import { useNativeFileDrag } from "../../useNativeFileDrag"; import { useAssetUrlState } from "../../assets/assetUrls"; import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions"; import { isAtomCommandInterrupted, squashAtomCommandFailure, type AtomCommandResult, } from "@t3tools/client-runtime/state/runtime"; import type { ContextMenuSource, EnvironmentId, ScopedThreadRef } from "@t3tools/contracts"; import { memo, useState, type MouseEvent as ReactMouseEvent } from "react"; import { useGT } from "gt-react"; import { FolderIcon } from "lucide-react"; import { contextMenuSourceOf } from "../../contextMenuSource"; import { beginLayoutContentDrag } from "../../layout/layoutDrag"; import { readLocalApi } from "../../localApi"; import { cn } from "../../lib/utils"; import { fileSurface } from "../../rightPanelStore"; import { shouldOpenMarkdownFileLinkInEditor } from "../../markdown-links"; import type { markdownFileCopyPaths } from "../../markdownFileHostPath"; import { documentChipKindForFileName } from "../../pierre-icons"; import { ContextChip } from "../ContextChip"; import { stackedThreadToast, toastManager } from "../ui/toast"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { FileTagChipContent } from "./FileTagChip"; import { hasMarkdownFilePrimaryAction, markdownFileCopyMenuItems, shouldUseMarkdownFileBrowserPrimaryAction, } from "./MarkdownFileLink.logic"; import { reportMarkdownActionFailure } from "./markdownActionFailure"; import { WorkspaceEntryTooltip } from "./WorkspaceEntryIcon"; interface MarkdownFileLinkProps { environmentId: EnvironmentId | null; href: string; targetPath: string; iconPath: string; isAppBundle?: boolean; workspaceRelativePath: string | null; panelPath: string | null; line?: number | undefined; label: string; copyMarkdown: string; theme: "light" | "dark"; threadRef?: ScopedThreadRef | undefined; onOpen?: (() => Promise>) | undefined; onOpenInPanel: (panelPath: string, line: number | undefined) => void; resolveDragPath: () => Promise; resolvePanelPath: (panelPath: string) => string | Promise; resolveCopyPaths: () => Promise>; openInEditorMenuLabel: string; onOpenInBrowser?: (() => Promise>) | undefined; onOpenMedia?: (() => void) | undefined; onReveal?: (() => Promise>) | undefined; revealLabel?: string | undefined; } const MARKDOWN_FILE_LINK_CLASS_NAME = "chat-markdown-file-link"; export const MarkdownFileLink = memo(function MarkdownFileLink({ environmentId, href, targetPath, iconPath, isAppBundle = false, workspaceRelativePath, panelPath, line, label, copyMarkdown, theme, threadRef, onOpen, onOpenInPanel, resolvePanelPath, openInEditorMenuLabel, onOpenInBrowser, onOpenMedia, onReveal, revealLabel, resolveCopyPaths, resolveDragPath, }: MarkdownFileLinkProps) { const gt = useGT(); const nativeDrag = useNativeFileDrag(environmentId, resolveDragPath); const handleOpenInEditor = () => { if (!onOpen) { return; } void (async () => { try { const result = await onOpen(); if (result._tag === "Success" || isAtomCommandInterrupted(result)) { return; } reportMarkdownActionFailure( { operation: "open-file-in-editor", target: targetPath }, result.cause, ); const error = squashAtomCommandFailure(result); toastManager.add( stackedThreadToast({ type: "error", title: gt("Unable to open file"), description: error instanceof Error ? error.message : gt("An error occurred."), }), ); } catch (cause) { reportMarkdownActionFailure( { operation: "open-file-in-editor", target: targetPath }, cause, ); toastManager.add( stackedThreadToast({ type: "error", title: gt("Unable to open file"), description: cause instanceof Error ? cause.message : gt("An error occurred."), }), ); } })(); }; const handleOpenInFilePreview = () => { if (threadRef && panelPath) { onOpenInPanel(panelPath, line); return; } if (onOpenMedia) { onOpenMedia(); return; } handleOpenInEditor(); }; const handleOpenInBrowser = () => { if (!onOpenInBrowser) { return; } void (async () => { try { const result = await onOpenInBrowser(); if (result._tag === "Success" || isAtomCommandInterrupted(result)) { return; } reportMarkdownActionFailure( { operation: "open-file-in-browser", target: targetPath }, result.cause, ); const error = squashAtomCommandFailure(result); toastManager.add( stackedThreadToast({ type: "error", title: gt("Unable to open file in browser"), description: error instanceof Error ? error.message : gt("An error occurred."), }), ); } catch (cause) { reportMarkdownActionFailure( { operation: "open-file-in-browser", target: targetPath }, cause, ); toastManager.add( stackedThreadToast({ type: "error", title: gt("Unable to open file in browser"), description: cause instanceof Error ? cause.message : gt("An error occurred."), }), ); } })(); }; const handleRevealInFileManager = () => { if (!onReveal) { return; } void (async () => { try { const result = await onReveal(); if (result._tag === "Success" || isAtomCommandInterrupted(result)) { return; } reportMarkdownActionFailure( { operation: "reveal-file-in-file-manager", target: targetPath }, result.cause, ); const error = squashAtomCommandFailure(result); toastManager.add( stackedThreadToast({ type: "error", title: gt("Unable to reveal file"), description: error instanceof Error ? error.message : gt("An error occurred."), }), ); } catch (cause) { reportMarkdownActionFailure( { operation: "reveal-file-in-file-manager", target: targetPath }, cause, ); toastManager.add( stackedThreadToast({ type: "error", title: gt("Unable to reveal file"), description: cause instanceof Error ? cause.message : gt("An error occurred."), }), ); } })(); }; const handleCopy = (resolveValue: () => Promise, title: string) => { const failureTitle = title === "Relative path" ? gt("Failed to copy relative path") : gt("Failed to copy full path"); if (typeof window === "undefined" || !navigator.clipboard?.writeText) { toastManager.add( stackedThreadToast({ type: "error", title: failureTitle, description: gt("Clipboard API unavailable."), }), ); return; } const value = resolveValue().then((text) => formatFilePathForClipboard(text, targetPath)); // Start the write before workspace lookup finishes so Safari retains the user gesture. const write = typeof navigator.clipboard.write === "function" && typeof ClipboardItem !== "undefined" ? navigator.clipboard.write([ new ClipboardItem({ "text/plain": value.then((text) => new Blob([text], { type: "text/plain" })), }), ]) : value.then((text) => navigator.clipboard.writeText(text)); void Promise.all([write, value]).catch((error) => { reportMarkdownActionFailure( { operation: "copy-file-path", target: targetPath, copyTarget: title }, error, ); toastManager.add( stackedThreadToast({ type: "error", title: failureTitle, description: error instanceof Error ? error.message : gt("An error occurred."), }), ); }); }; const showFileContextMenu = async ( position: { x: number; y: number }, source: ContextMenuSource, ) => { const api = readLocalApi(); if (!api) return; try { const copyItems = markdownFileCopyMenuItems({ targetPath, workspaceRelativePath }); const clicked = await api.contextMenu.show( [ ...(onOpenMedia ? ([{ id: "preview-media", label: gt("Preview media") }] as const) : []), ...(onOpen ? ([{ id: "open", label: openInEditorMenuLabel }] as const) : []), ...(onOpenInBrowser ? ([{ id: "open-in-browser", label: gt("Open in integrated browser") }] as const) : []), ...(onReveal && revealLabel ? ([{ id: "reveal", label: revealLabel }] as const) : []), ...copyItems.map(({ id, label }) => ({ id, label })), ] as const, position, source, ); if (clicked === "preview-media") { onOpenMedia?.(); return; } if (clicked === "open") { handleOpenInEditor(); return; } if (clicked === "open-in-browser") { handleOpenInBrowser(); return; } if (clicked === "reveal") { handleRevealInFileManager(); return; } if (clicked === "copy-relative" || clicked === "copy-full") { handleCopy( () => resolveCopyPaths().then((paths) => clicked === "copy-relative" ? paths.relativePath : paths.fullPath, ), clicked === "copy-relative" ? "Relative path" : "Full path", ); } } catch (cause) { reportMarkdownActionFailure( { operation: "show-file-context-menu", target: targetPath }, cause, ); } }; const handleContextMenu = (event: ReactMouseEvent) => { event.preventDefault(); event.stopPropagation(); const position = event.clientX === 0 && event.clientY === 0 ? (() => { const bounds = event.currentTarget.getBoundingClientRect(); return { x: bounds.left, y: bounds.bottom }; })() : { x: event.clientX, y: event.clientY }; void showFileContextMenu(position, contextMenuSourceOf(event)); }; const canOpenInEditor = onOpen !== undefined; const canOpenInBrowser = onOpenInBrowser !== undefined; const canOpenInPanel = threadRef !== undefined && Boolean(panelPath); const hasPrimaryAction = hasMarkdownFilePrimaryAction({ canOpenInEditor, canOpenInBrowser, canOpenInPanel, canOpenMedia: onOpenMedia !== undefined, }); const useBrowserPrimaryAction = shouldUseMarkdownFileBrowserPrimaryAction({ canOpenInEditor, canOpenInBrowser, canOpenInPanel, }); const chipKind = documentChipKindForFileName(iconPath) ?? "mention"; const layoutDragThreadRef = threadRef && panelPath && !useBrowserPrimaryAction && !nativeDrag.draggable ? threadRef : null; return ( } className={MARKDOWN_FILE_LINK_CLASS_NAME} data-markdown-copy={copyMarkdown} onClick={(event) => { event.preventDefault(); event.stopPropagation(); if (onOpen && shouldOpenMarkdownFileLinkInEditor(event)) { handleOpenInEditor(); return; } if (useBrowserPrimaryAction) { handleOpenInBrowser(); return; } handleOpenInFilePreview(); }} onContextMenu={handleContextMenu} onPointerDown={(event) => { if (!layoutDragThreadRef || !panelPath) return; beginLayoutContentDrag(event, { kind: "surface", threadRef: layoutDragThreadRef, surface: fileSurface(panelPath, line ?? null, 0), resolve: async () => fileSurface(await resolvePanelPath(panelPath), line ?? null, 0), }); }} > ) : undefined } path={iconPath} environmentId={environmentId} label={label} theme={theme} /> ) : ( } aria-label={gt("File options for {label}", { label })} aria-haspopup="menu" className={cn(MARKDOWN_FILE_LINK_CLASS_NAME, "select-text")} data-markdown-copy={copyMarkdown} onClick={handleContextMenu} onContextMenu={handleContextMenu} > ) : undefined } path={iconPath} environmentId={environmentId} label={label} theme={theme} /> ) } /> ); }, areMarkdownFileLinkPropsEqual); function areMarkdownFileLinkPropsEqual( previous: Readonly, next: Readonly, ): boolean { return ( previous.href === next.href && previous.targetPath === next.targetPath && previous.iconPath === next.iconPath && previous.environmentId === next.environmentId && previous.workspaceRelativePath === next.workspaceRelativePath && previous.panelPath === next.panelPath && previous.line === next.line && previous.label === next.label && previous.copyMarkdown === next.copyMarkdown && previous.theme === next.theme && previous.threadRef === next.threadRef && previous.isAppBundle === next.isAppBundle && previous.onOpen === next.onOpen && previous.onOpenInPanel === next.onOpenInPanel && previous.resolvePanelPath === next.resolvePanelPath && previous.openInEditorMenuLabel === next.openInEditorMenuLabel && previous.onOpenInBrowser === next.onOpenInBrowser && previous.onOpenMedia === next.onOpenMedia && previous.onReveal === next.onReveal && previous.resolveCopyPaths === next.resolveCopyPaths && previous.resolveDragPath === next.resolveDragPath && previous.revealLabel === next.revealLabel ); } function AppBundleIcon(props: { environmentId: EnvironmentId | null; path: string }) { const asset = useAssetUrlState(props.environmentId, { _tag: "native-app-icon", app: { _tag: "app-path", path: props.path }, }); const [failedUrl, setFailedUrl] = useState(null); const [loadedUrl, setLoadedUrl] = useState(null); const url = asset._tag === "Success" && asset.url !== failedUrl ? asset.url : null; const loaded = url !== null && loadedUrl === url; return ( ); }