import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent, type MouseEvent, type HTMLAttributes } from "react";
import { File, FileArchive, FileAudio, FileChartColumn, FileCode2, FileImage, FileJson2, FileSpreadsheet, FileText, FileVideo2, type LucideIcon } from "lucide-react";
import { useTranslation } from "react-i18next";
import { FileActions, useFilePreviewLoader } from "@/components/FileActions";
import { inferMediaKind } from "@/lib/media";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
export type FileReferenceKind =
| "default"
| "archive"
| "audio"
| "css"
| "document"
| "html"
| "image"
| "javascript"
| "json"
| "markdown"
| "notebook"
| "presentation"
| "python"
| "react"
| "spreadsheet"
| "text"
| "typescript"
| "video";
interface FileReferenceChipProps {
path: string;
tooltipPath?: string;
display?: "name" | "path";
showIcon?: boolean;
truncateFromStart?: boolean;
active?: boolean;
className?: string;
textClassName?: string;
previewPath?: string;
onOpen?: (path: string) => void;
testId?: string;
}
export function FileReferenceChip({
path,
tooltipPath,
display = "name",
showIcon = true,
truncateFromStart = false,
active = false,
className,
textClassName,
previewPath,
onOpen,
testId = "inline-file-path",
}: FileReferenceChipProps) {
const { t } = useTranslation();
const [tooltipOpen, setTooltipOpen] = useState(false);
const { directory, name } = splitFilePath(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 Text = truncateFromStart ? StartTruncatedText : "span";
const onKeyDown = (event: KeyboardEvent) => {
if (event.key !== "Enter" && event.key !== " ") return;
openPreview(event);
};
return (
setTooltipOpen(false)}
className={cn("not-prose inline-flex max-w-full align-baseline leading-[inherit]", truncateFromStart && "min-w-0", className)}
>
{showIcon ? : null}
{display === "path" && directory ? (
<>
{directory}
{name}
>
) : (
displayText
)}
{truncateFromStart ? {fullPath.split(/([\\/])/).map((part, index) => (
{part}{/^[\\/]$/.test(part) ? : null}
))} : !imageQuickLook ? fullPath : null}
{imageQuickLook && tooltipOpen ? : null}
);
}
function StartTruncatedText({ children, className, ...props }: HTMLAttributes & { "data-sheen-text"?: string }) {
const container = useRef(null);
const content = useRef(null);
const [clipped, setClipped] = useState(false);
useLayoutEffect(() => {
let availableWidth = 0;
let contentWidth = 0;
const observer = new ResizeObserver((entries) => {
for (const entry of entries) {
const width = entry.borderBoxSize[0].inlineSize;
if (entry.target === container.current) availableWidth = width;
else contentWidth = width;
}
setClipped(contentWidth > availableWidth);
});
observer.observe(container.current!, { box: "border-box" });
observer.observe(content.current!, { box: "border-box" });
return () => observer.disconnect();
}, []);
return
{clipped ? … : null}
{children}
;
}
/** 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
{t("filePreview.failed", { defaultValue: "Could not preview this file." })}
;
return
{source ?
setResult({ load, source: null })} />
: }
;
}
export function isLikelyFilePath(value: string): boolean {
const raw = value.trim();
if (!raw || raw.includes("\n")) return false;
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(raw)) return false;
if (isFilePatternReference(raw)) return false;
if (!/[\\/]/.test(raw) && !/^(dockerfile|makefile|readme|package-lock\.json)$/i.test(raw)) {
return false;
}
const normalized = raw.replace(/\\/g, "/");
const name = normalized.split("/").filter(Boolean).pop() ?? normalized;
if (!name || name === "." || name === "..") return false;
if (/^(dockerfile|makefile|readme|package-lock\.json)$/i.test(name)) return true;
return /\.[a-z0-9][a-z0-9_-]{0,12}$/i.test(name);
}
export function isFilePatternReference(value: string): boolean {
return /[*?[\]{}]/.test(value.trim());
}
export function splitFilePath(path: string): { directory: string; name: string } {
const normalized = path.replace(/\\/g, "/");
const slash = normalized.lastIndexOf("/");
if (slash < 0) return { directory: "", name: path };
return {
directory: normalized.slice(0, slash + 1),
name: normalized.slice(slash + 1) || normalized,
};
}
export function fileKindForPath(path: string): FileReferenceKind {
const mediaKind = inferMediaKind({ url: path });
if (mediaKind === "image" || mediaKind === "video") return mediaKind;
const normalized = path.toLowerCase();
const name = normalized.split(/[\\/]/).pop() ?? normalized;
const ext = name.includes(".") ? name.split(".").pop() ?? "" : "";
if (name === "dockerfile") {
return "default";
}
switch (ext) {
case "zip":
case "7z":
case "rar":
case "tar":
case "gz":
case "bz2":
case "xz":
case "tgz":
return "archive";
case "mp3":
case "wav":
case "ogg":
case "m4a":
case "flac":
case "aac":
return "audio";
case "pdf":
case "doc":
case "docx":
case "odt":
case "rtf":
return "document";
case "xls":
case "xlsx":
case "csv":
case "tsv":
case "ods":
return "spreadsheet";
case "ppt":
case "pptx":
case "odp":
return "presentation";
case "avif":
return "image";
case "py":
case "pyi":
return "python";
case "jsx":
case "tsx":
return "react";
case "js":
case "mjs":
case "cjs":
return "javascript";
case "ts":
case "mts":
case "cts":
return "typescript";
case "html":
case "htm":
return "html";
case "css":
case "scss":
case "sass":
return "css";
case "json":
case "jsonl":
return "json";
case "md":
case "mdx":
return "markdown";
case "ipynb":
return "notebook";
case "txt":
case "log":
return "text";
default:
return "default";
}
}
const FILE_ICONS = {
default: File,
archive: FileArchive,
audio: FileAudio,
css: FileCode2,
document: FileText,
html: FileCode2,
image: FileImage,
javascript: FileCode2,
json: FileJson2,
markdown: FileText,
notebook: FileCode2,
presentation: FileChartColumn,
python: FileCode2,
react: FileCode2,
spreadsheet: FileSpreadsheet,
text: FileText,
typescript: FileCode2,
video: FileVideo2,
} satisfies Record;
export function fileIconForPath(path: string): LucideIcon {
return FILE_ICONS[fileKindForPath(path)];
}
export function FileReferenceIcon({ kind, className }: { kind: FileReferenceKind; className?: string }) {
const Icon = FILE_ICONS[kind];
return ;
}