import {
useCallback,
useEffect,
useMemo,
useRef,
useState,
type KeyboardEvent as ReactKeyboardEvent,
type PointerEvent as ReactPointerEvent,
type ReactNode,
} from "react";
import { useQuery, type UseQueryResult } from "@tanstack/react-query";
import {
AlertTriangle,
ArrowLeft,
Ban,
Check,
Cloud,
Copy,
Eye,
FileCode2,
FileSearch,
FolderOpen,
FolderSearch,
Link2,
Loader2,
Lock,
RefreshCcw,
X,
} from "lucide-react";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { fileResourcesApi } from "@/api/file-resources";
import { ApiError } from "@/api/client";
import { queryKeys } from "@/lib/queryKeys";
import {
useRequiredFileViewer,
type FileViewerUrlState,
} from "@/context/FileViewerContext";
import { WorkspaceFileBrowser } from "@/components/WorkspaceFileBrowser";
import { WorkspaceFileMarkdownBody } from "@/components/WorkspaceFileMarkdownBody";
import type {
ResolvedWorkspaceResource,
WorkspaceFileContent,
WorkspaceFileSelector,
} from "@paperclipai/shared";
const FILE_VIEWER_LABELLED_BY_ID = "paperclip-file-viewer-title";
const FILE_VIEWER_DESCRIBED_BY_ID = "paperclip-file-viewer-description";
const MIN_FILE_TREE_WIDTH = 220;
const MAX_FILE_TREE_WIDTH = 520;
interface FileViewerErrorShape {
status: number;
code: string;
message: string;
}
function normalizeError(error: unknown): FileViewerErrorShape {
if (error instanceof ApiError) {
const body = (error.body ?? null) as { error?: string; code?: string } | null;
const code = typeof body?.code === "string" ? body.code : "";
return {
status: error.status,
code,
message: typeof body?.error === "string" ? body.error : error.message,
};
}
if (error instanceof Error) {
return { status: 0, code: "", message: error.message };
}
return { status: 0, code: "", message: "Something went wrong." };
}
function formatBytes(size: number | null | undefined): string | null {
if (typeof size !== "number" || !Number.isFinite(size) || size < 0) return null;
if (size < 1024) return `${size} B`;
if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`;
return `${(size / (1024 * 1024)).toFixed(1)} MB`;
}
function splitContentIntoLines(data: string): string[] {
if (data === "") return [""];
const normalized = data.replace(/\r\n?/g, "\n");
const lines = normalized.split("\n");
if (lines.length > 0 && lines[lines.length - 1] === "") {
lines.pop();
}
return lines.length > 0 ? lines : [""];
}
function basename(path: string): string {
const idx = path.lastIndexOf("/");
return idx < 0 ? path : path.slice(idx + 1);
}
function middleTruncatePath(path: string, maxLen = 80): string {
if (path.length <= maxLen) return path;
const head = path.slice(0, Math.floor(maxLen / 2) - 1);
const tail = path.slice(path.length - (maxLen - head.length - 1));
return `${head}…${tail}`;
}
function isMarkdownResource(resource: ResolvedWorkspaceResource): boolean {
const contentType = resource.contentType?.toLowerCase() ?? "";
if (contentType.includes("markdown")) return true;
const path = (resource.displayPath || resource.title).toLowerCase();
return /\.(md|markdown|mdown|mkdn|mkd)$/.test(path);
}
async function copyTextWithFallback(text: string) {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text);
return;
}
const textarea = document.createElement("textarea");
textarea.value = text;
textarea.style.position = "fixed";
textarea.style.left = "-9999px";
document.body.appendChild(textarea);
try {
textarea.select();
const success = document.execCommand("copy");
if (!success) throw new Error("execCommand copy failed");
} finally {
document.body.removeChild(textarea);
}
}
export function describeDenial(code: string, fallback: string): { title: string; body: string; icon: ReactNode } {
const lower = code.toLowerCase();
if (lower.includes("policy") || lower.includes("denied") || lower.includes("sensitive")) {
return {
icon: ,
title: "Viewer blocked for this file",
body: "This file is not available through the viewer because it may contain sensitive data.",
};
}
if (lower.includes("outside") || lower.includes("traversal")) {
return {
icon: ,
title: "Path is outside the workspace",
body: "The viewer can only open files that live under the issue's workspace.",
};
}
if (lower.includes("archive") || lower.includes("cleaned")) {
return {
icon: ,
title: "Workspace is no longer available",
body: "The isolated worktree for this issue has been cleaned up, so files cannot be previewed.",
};
}
if (lower.includes("remote")) {
return {
icon: ,
title: "Remote workspace preview not supported",
body: "This workspace is hosted remotely and is not available for inline preview yet.",
};
}
if (lower.includes("too_large") || lower.includes("size")) {
return {
icon: ,
title: "File is too large to preview",
body: "This file exceeds the supported preview size.",
};
}
if (lower.includes("binary") || lower.includes("unsupported")) {
return {
icon: ,
title: "Preview not supported for this file type",
body: "This file does not have a text, image, or video preview available.",
};
}
return {
icon: ,
title: "Can't preview this file",
body: fallback || "The viewer was unable to load this file.",
};
}
function FileViewerStateView({
icon,
title,
body,
secondary,
actions,
}: {
icon: ReactNode;
title: string;
body?: string;
secondary?: ReactNode;
actions?: ReactNode;
}) {
return (
{icon}
{title}
{body ?
{body}
: null}
{secondary}
{actions ?
{actions}
: null}
);
}
export function FileViewerMetadataRow({
resolvedResource,
state,
}: {
resolvedResource?: ResolvedWorkspaceResource;
state: FileViewerUrlState | null;
}) {
return (
{resolvedResource ? (
<>
{resolvedResource.previewKind ? {resolvedResource.previewKind} : null}
{formatBytes(resolvedResource.byteSize) ? (
<>
·
{formatBytes(resolvedResource.byteSize)}
>
) : null}
{state?.line ? (
<>
·
Line {state.line}
{state.column ? `, Col ${state.column}` : ""}
>
) : null}
>
) : state ? (
) : null}
);
}
interface FileContentViewerProps {
content: WorkspaceFileContent;
highlightedLine: number | null;
onLoaded?: (summary: string) => void;
}
type MarkdownPreviewMode = "raw" | "rendered";
export function FileContentViewer({ content, highlightedLine, onLoaded }: FileContentViewerProps) {
const { resource } = content;
const isMarkdown = resource.previewKind === "text" && content.content.encoding === "utf8" && isMarkdownResource(resource);
const [markdownMode, setMarkdownMode] = useState("rendered");
const lines = useMemo(() => {
if (resource.previewKind === "text") {
return splitContentIntoLines(content.content.data);
}
return null;
}, [content.content.data, resource.previewKind]);
const codeScrollRef = useRef(null);
const highlightedLineRef = useRef(null);
useEffect(() => {
setMarkdownMode(isMarkdown ? "rendered" : "raw");
}, [isMarkdown, resource.displayPath, resource.title, resource.contentType]);
useEffect(() => {
if (!lines) return;
onLoaded?.(`File loaded, ${lines.length} ${lines.length === 1 ? "line" : "lines"}.`);
}, [lines, onLoaded]);
useEffect(() => {
if (markdownMode !== "raw") return;
if (!highlightedLine || !highlightedLineRef.current) return;
highlightedLineRef.current.scrollIntoView({ block: "center", behavior: "auto" });
}, [highlightedLine, markdownMode]);
if (resource.previewKind === "image") {
const dataUrl = content.content.encoding === "base64"
? `data:${resource.contentType ?? "application/octet-stream"};base64,${content.content.data}`
: null;
if (!dataUrl) {
return (
}
title="Image preview unavailable"
/>
);
}
return (
);
}
if (resource.previewKind === "video") {
const dataUrl = content.content.encoding === "base64"
? `data:${resource.contentType ?? "application/octet-stream"};base64,${content.content.data}`
: null;
if (!dataUrl) {
return (
}
title="Video preview unavailable"
/>
);
}
return (
);
}
if (resource.previewKind === "unsupported" || !lines) {
return (
}
title="Preview not supported for this file type"
body={resource.contentType ? `Content type: ${resource.contentType}` : undefined}
/>
);
}
const gutterWidth = `calc(${Math.max(4, String(lines.length).length)}ch + 2rem)`;
const rawSourceView = (
{lines.map((lineText, index) => {
const lineNumber = index + 1;
const isHighlighted = lineNumber === highlightedLine;
return (
{lineNumber}
{lineText.length === 0 ? "" : lineText}
);
})}
);
if (!isMarkdown) {
return rawSourceView;
}
return (
{markdownMode === "raw" ? (
rawSourceView
) : (
{content.content.data}
)}
);
}
function LoadingView({ elapsedMs }: { elapsedMs: number }) {
if (elapsedMs < 100) {
return ;
}
if (elapsedMs < 400) {
return (
Loading file preview
{Array.from({ length: 10 }).map((_, index) => (
))}
);
}
return (
);
}
interface FileViewerSheetProps {
issueId: string;
companyId?: string | null;
/** When not provided, the sheet defaults to the context state. */
state?: FileViewerUrlState | null;
/** When true, renders the "Open file" prompt when no file is selected but sheet is open. */
showPromptWhenEmpty?: boolean;
/** Whether the sheet is open. Defaults to `state !== null`. */
open?: boolean;
onOpenChange?: (open: boolean) => void;
}
export function FileViewerSheet({
issueId,
companyId,
state: stateProp,
showPromptWhenEmpty = false,
open: openProp,
onOpenChange,
}: FileViewerSheetProps) {
const viewer = useRequiredFileViewer();
const state = typeof stateProp !== "undefined" ? stateProp : viewer.state;
// Browse mode: no file selected, but the sheet was opened to browse/search.
const browseMode = state === null && (showPromptWhenEmpty || viewer.browse);
// True when the current file was reached from the browse list (drill-down).
const cameFromBrowse = state !== null && viewer.browse;
const computedOpen =
typeof openProp === "boolean" ? openProp : state !== null || showPromptWhenEmpty || viewer.browse;
const [elapsedMs, setElapsedMs] = useState(0);
const [copiedField, setCopiedField] = useState<"content" | "link" | null>(null);
const [copyingField, setCopyingField] = useState<"content" | "link" | null>(null);
const [copyFeedback, setCopyFeedback] = useState("");
const [announcement, setAnnouncement] = useState("");
const [fileTreeWidth, setFileTreeWidth] = useState(288);
const copyFeedbackTimerRef = useRef(null);
const resizeCleanupRef = useRef<(() => void) | null>(null);
useEffect(() => {
if (!state) {
setElapsedMs(0);
return;
}
const now = Date.now();
setElapsedMs(0);
const interval = window.setInterval(() => {
setElapsedMs(Date.now() - now);
}, 75);
return () => window.clearInterval(interval);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [state?.path, state?.workspace, state?.projectId, state?.workspaceId]);
const resolveQuery = useQuery({
queryKey: state
? queryKeys.issues.fileResource(issueId, state)
: ["issues", "file-resources", issueId, "resolve", "__closed__"],
queryFn: () => fileResourcesApi.resolve(issueId, state!),
enabled: !!state && computedOpen,
retry: false,
staleTime: 30_000,
});
const resolvedResource: ResolvedWorkspaceResource | undefined = resolveQuery.data;
const canPreview = resolvedResource?.capabilities.preview ?? false;
const contentQuery = useQuery({
queryKey: state
? queryKeys.issues.fileResourceContent(issueId, state)
: ["issues", "file-resources", issueId, "content", "__closed__"],
queryFn: () => fileResourcesApi.content(issueId, state!),
enabled: !!state && computedOpen && canPreview,
retry: false,
staleTime: 30_000,
});
useEffect(() => {
if (resolveQuery.isError) {
const normalized = normalizeError(resolveQuery.error);
setAnnouncement(normalized.message || "Unable to load file.");
}
}, [resolveQuery.isError, resolveQuery.error]);
useEffect(() => {
if (contentQuery.isError) {
const normalized = normalizeError(contentQuery.error);
setAnnouncement(normalized.message || "Unable to load file content.");
}
}, [contentQuery.isError, contentQuery.error]);
useEffect(() => () => {
if (copyFeedbackTimerRef.current) window.clearTimeout(copyFeedbackTimerRef.current);
resizeCleanupRef.current?.();
}, []);
const handleOpenChange = useCallback(
(next: boolean) => {
if (onOpenChange) {
onOpenChange(next);
return;
}
if (!next) viewer.close();
},
[onOpenChange, viewer],
);
const handleBrowseOpen = useCallback(
(ref: {
path: string;
workspace: WorkspaceFileSelector;
line?: number | null;
column?: number | null;
projectId?: string | null;
workspaceId?: string | null;
browseFolderPath?: string | null;
browseQuery?: string | null;
}) => {
viewer.open(
{
path: ref.path,
line: ref.line ?? null,
column: ref.column ?? null,
workspace: ref.workspace,
projectId: ref.projectId ?? null,
workspaceId: ref.workspaceId ?? null,
},
{
fromBrowse: true,
browseState: {
folderPath: ref.browseFolderPath ?? null,
q: ref.browseQuery ?? null,
},
},
);
},
[viewer],
);
const handleBrowseStateChange = useCallback(
(next: {
q: string | null;
folderPath: string | null;
projectId: string | null;
workspaceId: string | null;
}) => {
viewer.updateBrowseState(next);
},
[viewer],
);
const showCopyFeedback = useCallback((field: "content" | "link" | null, message: string) => {
setCopiedField(field);
setCopyFeedback(message);
setAnnouncement(message);
if (copyFeedbackTimerRef.current) window.clearTimeout(copyFeedbackTimerRef.current);
copyFeedbackTimerRef.current = window.setTimeout(() => {
setCopiedField((current) => (current === field ? null : current));
setCopyFeedback("");
copyFeedbackTimerRef.current = null;
}, 1800);
}, []);
const copyToClipboard = useCallback(async (value: string, field: "content" | "link", message: string) => {
try {
setCopyingField(field);
await copyTextWithFallback(value);
showCopyFeedback(field, message);
} catch {
showCopyFeedback(null, "Copy failed");
} finally {
setCopyingField((current) => (current === field ? null : current));
}
}, [showCopyFeedback]);
const handleCopyContent = useCallback(() => {
if (!state) return;
void (async () => {
let content = contentQuery.data;
if (!content && canPreview) {
const result = await contentQuery.refetch();
content = result.data;
}
if (!content) {
showCopyFeedback(null, "File contents unavailable");
return;
}
const message = content.content.encoding === "base64" ? "Copied file data" : "Copied contents";
await copyToClipboard(content.content.data, "content", message);
})();
}, [canPreview, contentQuery, copyToClipboard, showCopyFeedback, state]);
const handleCopyLink = useCallback(() => {
if (typeof window === "undefined") return;
void copyToClipboard(window.location.href, "link", "Copied link");
}, [copyToClipboard]);
const handleRetry = useCallback(() => {
void resolveQuery.refetch();
if (canPreview) void contentQuery.refetch();
}, [canPreview, contentQuery, resolveQuery]);
const handleResizeStart = useCallback((event: ReactPointerEvent) => {
event.preventDefault();
resizeCleanupRef.current?.();
const startX = event.clientX;
const startWidth = fileTreeWidth;
const handlePointerMove = (moveEvent: PointerEvent) => {
const nextWidth = Math.min(
MAX_FILE_TREE_WIDTH,
Math.max(MIN_FILE_TREE_WIDTH, startWidth + moveEvent.clientX - startX),
);
setFileTreeWidth(nextWidth);
};
const cleanup = () => {
document.removeEventListener("pointermove", handlePointerMove);
document.removeEventListener("pointerup", cleanup);
resizeCleanupRef.current = null;
};
resizeCleanupRef.current = cleanup;
document.addEventListener("pointermove", handlePointerMove);
document.addEventListener("pointerup", cleanup, { once: true });
}, [fileTreeWidth]);
const handleResizeKeyDown = useCallback((event: ReactKeyboardEvent) => {
if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;
event.preventDefault();
setFileTreeWidth((current) => {
const delta = event.key === "ArrowLeft" ? -24 : 24;
return Math.min(MAX_FILE_TREE_WIDTH, Math.max(MIN_FILE_TREE_WIDTH, current + delta));
});
}, []);
const title = state ? basename(state.path) : "Browse workspace";
const description = state
? middleTruncatePath(state.path)
: "Search and preview files from this issue's workspace.";
const showDescription = state ? description !== title : true;
return (
);
}
interface FileViewerBodyProps {
resolveQuery: UseQueryResult;
contentQuery: UseQueryResult;
elapsedMs: number;
canPreview: boolean;
highlightedLine: number | null;
onRetry: () => void;
onSetAnnouncement: (message: string) => void;
onFallbackToProject: null | (() => void);
}
function FileViewerBody({
resolveQuery,
contentQuery,
elapsedMs,
canPreview,
highlightedLine,
onRetry,
onSetAnnouncement,
onFallbackToProject,
}: FileViewerBodyProps) {
if (resolveQuery.isFetching && !resolveQuery.data) {
return ;
}
if (resolveQuery.isError) {
const normalized = normalizeError(resolveQuery.error);
if (normalized.status === 404) {
return (
}
title="File not found"
body="That file was not found in the active workspace."
actions={
<>
{onFallbackToProject ? (
) : null}
>
}
/>
);
}
if (normalized.status === 422) {
return (
}
title="No workspace available"
body="This issue does not have a workspace that supports preview yet."
/>
);
}
const denial = describeDenial(normalized.code, normalized.message);
return (
Retry
}
/>
);
}
const resource = resolveQuery.data;
if (!resource) return null;
if (resource.kind === "remote_resource") {
return (
}
title="Remote workspace preview coming soon"
body="This workspace is hosted remotely; inline previews are not supported yet."
/>
);
}
if (!canPreview) {
const denial = describeDenial(resource.denialReason ?? "", "");
return ;
}
if (contentQuery.isFetching && !contentQuery.data) {
return ;
}
if (contentQuery.isError) {
const normalized = normalizeError(contentQuery.error);
const denial = describeDenial(normalized.code, normalized.message);
return (
Retry
}
/>
);
}
if (!contentQuery.data) return null;
return (
);
}