Open History to see the last commit
1import { useNativeFileDrag } from "../../useNativeFileDrag";
2import { useFileMetadata } from "../../hooks/useFileMetadata";
3import { useAssetUrlState } from "../../assets/assetUrls";
4import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions";
5import {
6 isAtomCommandInterrupted,
7 squashAtomCommandFailure,
8 type AtomCommandResult,
9} from "@t3tools/client-runtime/state/runtime";
10import type { ContextMenuSource, EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
11import { memo, useState, type MouseEvent as ReactMouseEvent } from "react";
12import { useGT } from "gt-react";
13import { FolderIcon } from "lucide-react";
14
15import { contextMenuSourceOf, openContextMenuFromKeyboard } from "../../contextMenuSource";
16import { readLocalApi } from "../../localApi";
17import { cn } from "../../lib/utils";
18import { shouldOpenMarkdownFileLinkInEditor } from "../../markdown-links";
19import type { markdownFileCopyPaths } from "../../markdownFileHostPath";
20import { documentChipKindForFileName } from "../../pierre-icons";
21import { ContextChip } from "../ContextChip";
22import { stackedThreadToast, toastManager } from "../ui/toast";
23import { SharedTooltipTrigger, useSharedTooltip, withSharedTooltip } from "../ui/shared-tooltip";
24import { FileTagChipContent } from "./FileTagChip";
25import {
26 hasMarkdownFilePrimaryAction,
27 markdownFileCopyMenuItems,
28 shouldUseMarkdownFileBrowserPrimaryAction,
29} from "./MarkdownFileLink.logic";
30import { reportMarkdownActionFailure } from "./markdownActionFailure";
31import { WorkspaceEntryTooltip } from "./WorkspaceEntryIcon";
32
33interface MarkdownFileLinkProps {
34 environmentId: EnvironmentId | null;
35 href: string;
36 targetPath: string;
37 iconPath: string;
38 isAppBundle?: boolean;
39 workspaceRelativePath: string | null;
40 panelPath: string | null;
41 line?: number | undefined;
42 label: string;
43 copyMarkdown: string;
44 theme: "light" | "dark";
45 threadRef?: ScopedThreadRef | undefined;
46 onOpen?: (() => Promise<AtomCommandResult<unknown, unknown>>) | undefined;
47 onOpenInPanel: (panelPath: string, line: number | undefined) => void;
48 resolveDragPath: () => Promise<string>;
49 resolveCopyPaths: () => Promise<ReturnType<typeof markdownFileCopyPaths>>;
50 openInEditorMenuLabel: string;
51 onOpenInBrowser?: (() => Promise<AtomCommandResult<unknown, unknown>>) | undefined;
52 onOpenMedia?: (() => void) | undefined;
53 onReveal?: (() => Promise<AtomCommandResult<unknown, unknown>>) | undefined;
54 revealLabel?: string | undefined;
55 onDownload?: (() => void) | undefined;
56}
57
58const MARKDOWN_FILE_LINK_CLASS_NAME = "chat-markdown-file-link";
59
60export const MarkdownFileLink = memo(function MarkdownFileLink({
61 environmentId,
62 href,
63 targetPath,
64 iconPath,
65 isAppBundle = false,
66 workspaceRelativePath,
67 panelPath,
68 line,
69 label,
70 copyMarkdown,
71 theme,
72 threadRef,
73 onOpen,
74 onOpenInPanel,
75 openInEditorMenuLabel,
76 onOpenInBrowser,
77 onOpenMedia,
78 onReveal,
79 revealLabel,
80 onDownload,
81 resolveCopyPaths,
82 resolveDragPath,
83}: MarkdownFileLinkProps) {
84 const gt = useGT();
85 const nativeDrag = useNativeFileDrag(environmentId, resolveDragPath);
86 const isDirectory = useFileMetadata(environmentId, iconPath)?.kind === "directory";
87 const handleOpenInEditor = () => {
88 if (!onOpen) {
89 return;
90 }
91 void (async () => {
92 try {
93 const result = await onOpen();
94 if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
95 return;
96 }
97 reportMarkdownActionFailure(
98 { operation: "open-file-in-editor", target: targetPath },
99 result.cause,
100 );
101 const error = squashAtomCommandFailure(result);
102 toastManager.add(
103 stackedThreadToast({
104 type: "error",
105 title: gt`Unable to open file`,
106 description: error instanceof Error ? error.message : gt`An error occurred.`,
107 }),
108 );
109 } catch (cause) {
110 reportMarkdownActionFailure(
111 { operation: "open-file-in-editor", target: targetPath },
112 cause,
113 );
114 toastManager.add(
115 stackedThreadToast({
116 type: "error",
117 title: gt`Unable to open file`,
118 description: cause instanceof Error ? cause.message : gt`An error occurred.`,
119 }),
120 );
121 }
122 })();
123 };
124
125 const handleOpenInFilePreview = () => {
126 if (threadRef && panelPath) {
127 onOpenInPanel(panelPath, line);
128 return;
129 }
130 if (onOpenMedia) {
131 onOpenMedia();
132 return;
133 }
134 handleOpenInEditor();
135 };
136
137 const handleOpenInBrowser = () => {
138 if (!onOpenInBrowser) {
139 return;
140 }
141 void (async () => {
142 try {
143 const result = await onOpenInBrowser();
144 if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
145 return;
146 }
147 reportMarkdownActionFailure(
148 { operation: "open-file-in-browser", target: targetPath },
149 result.cause,
150 );
151 const error = squashAtomCommandFailure(result);
152 toastManager.add(
153 stackedThreadToast({
154 type: "error",
155 title: gt`Unable to open file in browser`,
156 description: error instanceof Error ? error.message : gt`An error occurred.`,
157 }),
158 );
159 } catch (cause) {
160 reportMarkdownActionFailure(
161 { operation: "open-file-in-browser", target: targetPath },
162 cause,
163 );
164 toastManager.add(
165 stackedThreadToast({
166 type: "error",
167 title: gt`Unable to open file in browser`,
168 description: cause instanceof Error ? cause.message : gt`An error occurred.`,
169 }),
170 );
171 }
172 })();
173 };
174
175 const handleRevealInFileManager = () => {
176 if (!onReveal) {
177 return;
178 }
179 void (async () => {
180 try {
181 const result = await onReveal();
182 if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
183 return;
184 }
185 reportMarkdownActionFailure(
186 { operation: "reveal-file-in-file-manager", target: targetPath },
187 result.cause,
188 );
189 const error = squashAtomCommandFailure(result);
190 toastManager.add(
191 stackedThreadToast({
192 type: "error",
193 title: gt`Unable to reveal file`,
194 description: error instanceof Error ? error.message : gt`An error occurred.`,
195 }),
196 );
197 } catch (cause) {
198 reportMarkdownActionFailure(
199 { operation: "reveal-file-in-file-manager", target: targetPath },
200 cause,
201 );
202 toastManager.add(
203 stackedThreadToast({
204 type: "error",
205 title: gt`Unable to reveal file`,
206 description: cause instanceof Error ? cause.message : gt`An error occurred.`,
207 }),
208 );
209 }
210 })();
211 };
212
213 const handleCopy = (resolveValue: () => Promise<string>, title: string) => {
214 const failureTitle =
215 title === "Relative path" ? gt`Failed to copy relative path` : gt`Failed to copy full path`;
216 if (typeof window === "undefined" || !navigator.clipboard?.writeText) {
217 toastManager.add(
218 stackedThreadToast({
219 type: "error",
220 title: failureTitle,
221 description: gt`Clipboard API unavailable.`,
222 }),
223 );
224 return;
225 }
226
227 const value = resolveValue().then((text) => formatFilePathForClipboard(text, targetPath));
228 // Start the write before workspace lookup finishes so Safari retains the user gesture.
229 const write =
230 typeof navigator.clipboard.write === "function" && typeof ClipboardItem !== "undefined"
231 ? navigator.clipboard.write([
232 new ClipboardItem({
233 "text/plain": value.then((text) => new Blob([text], { type: "text/plain" })),
234 }),
235 ])
236 : value.then((text) => navigator.clipboard.writeText(text));
237 void Promise.all([write, value]).catch((error) => {
238 reportMarkdownActionFailure(
239 { operation: "copy-file-path", target: targetPath, copyTarget: title },
240 error,
241 );
242 toastManager.add(
243 stackedThreadToast({
244 type: "error",
245 title: failureTitle,
246 description: error instanceof Error ? error.message : gt`An error occurred.`,
247 }),
248 );
249 });
250 };
251
252 const showFileContextMenu = async (
253 position: { x: number; y: number },
254 source: ContextMenuSource,
255 ) => {
256 const api = readLocalApi();
257 if (!api) return;
258
259 try {
260 const copyItems = markdownFileCopyMenuItems({ targetPath, workspaceRelativePath });
261 const clicked = await api.contextMenu.show(
262 [
263 ...(onOpenMedia ? ([{ id: "preview-media", label: gt`Preview media` }] as const) : []),
264 ...(onOpen ? ([{ id: "open", label: openInEditorMenuLabel }] as const) : []),
265 ...(onOpenInBrowser
266 ? ([{ id: "open-in-browser", label: gt`Open in integrated browser` }] as const)
267 : []),
268 ...(onReveal && revealLabel ? ([{ id: "reveal", label: revealLabel }] as const) : []),
269 ...(onDownload && !isDirectory
270 ? ([
271 { id: "download", label: gt({ context: "verb, saves a file" })`Download` },
272 ] as const)
273 : []),
274 ...copyItems.map(({ id, label }) => ({ id, label })),
275 ] as const,
276 position,
277 source,
278 );
279
280 if (clicked === "preview-media") {
281 onOpenMedia?.();
282 return;
283 }
284 if (clicked === "open") {
285 handleOpenInEditor();
286 return;
287 }
288 if (clicked === "open-in-browser") {
289 handleOpenInBrowser();
290 return;
291 }
292 if (clicked === "reveal") {
293 handleRevealInFileManager();
294 return;
295 }
296 if (clicked === "download") {
297 onDownload?.();
298 return;
299 }
300 if (clicked === "copy-relative" || clicked === "copy-full") {
301 handleCopy(
302 () =>
303 resolveCopyPaths().then((paths) =>
304 clicked === "copy-relative" ? paths.relativePath : paths.fullPath,
305 ),
306 clicked === "copy-relative" ? "Relative path" : "Full path",
307 );
308 }
309 } catch (cause) {
310 reportMarkdownActionFailure(
311 { operation: "show-file-context-menu", target: targetPath },
312 cause,
313 );
314 }
315 };
316
317 const handleContextMenu = (event: ReactMouseEvent<HTMLElement>) => {
318 event.preventDefault();
319 event.stopPropagation();
320 const position =
321 event.clientX === 0 && event.clientY === 0
322 ? (() => {
323 const bounds = event.currentTarget.getBoundingClientRect();
324 return { x: bounds.left, y: bounds.bottom };
325 })()
326 : { x: event.clientX, y: event.clientY };
327 void showFileContextMenu(position, contextMenuSourceOf(event));
328 };
329
330 const canOpenInEditor = onOpen !== undefined;
331 const canOpenInBrowser = onOpenInBrowser !== undefined;
332 const canOpenInPanel = threadRef !== undefined && Boolean(panelPath);
333 const hasPrimaryAction = hasMarkdownFilePrimaryAction({
334 canOpenInEditor,
335 canOpenInBrowser,
336 canOpenInPanel,
337 canOpenMedia: onOpenMedia !== undefined,
338 });
339 const useBrowserPrimaryAction = shouldUseMarkdownFileBrowserPrimaryAction({
340 canOpenInEditor,
341 canOpenInBrowser,
342 canOpenInPanel,
343 });
344 const chipKind = documentChipKindForFileName(iconPath) ?? "mention";
345
346 const tooltipContent = (
347 <WorkspaceEntryTooltip path={iconPath} label={targetPath} environmentId={environmentId} />
348 );
349 const sharedTooltip = useSharedTooltip({
350 render: () => tooltipContent,
351 contentKey: `${iconPath}\u0000${targetPath}`,
352 variant: "code",
353 });
354 const chip = hasPrimaryAction ? (
355 <ContextChip
356 {...nativeDrag}
357 kind={chipKind}
358 dir="ltr"
359 render={<a href={href} />}
360 className={MARKDOWN_FILE_LINK_CLASS_NAME}
361 data-markdown-copy={copyMarkdown}
362 onClick={(event) => {
363 event.preventDefault();
364 event.stopPropagation();
365 if (onOpen && shouldOpenMarkdownFileLinkInEditor(event)) {
366 handleOpenInEditor();
367 return;
368 }
369 if (useBrowserPrimaryAction) {
370 handleOpenInBrowser();
371 return;
372 }
373 handleOpenInFilePreview();
374 }}
375 onAuxClick={(event) => {
376 // Middle-clicking an <a> skips onClick and would open href as a broken app route.
377 if (event.button === 1) event.preventDefault();
378 }}
379 onContextMenu={handleContextMenu}
380 onKeyDown={openContextMenuFromKeyboard}
381 >
382 <FileTagChipContent
383 icon={
384 isAppBundle ? <AppBundleIcon environmentId={environmentId} path={iconPath} /> : undefined
385 }
386 path={iconPath}
387 environmentId={environmentId}
388 label={label}
389 theme={theme}
390 />
391 </ContextChip>
392 ) : (
393 <ContextChip
394 {...nativeDrag}
395 kind={chipKind}
396 dir="ltr"
397 render={<button type="button" />}
398 aria-label={gt`File options for ${{ label }}`}
399 aria-haspopup="menu"
400 className={cn(MARKDOWN_FILE_LINK_CLASS_NAME, "select-text")}
401 data-markdown-copy={copyMarkdown}
402 onClick={handleContextMenu}
403 onContextMenu={handleContextMenu}
404 onKeyDown={openContextMenuFromKeyboard}
405 >
406 <FileTagChipContent
407 icon={
408 isAppBundle ? <AppBundleIcon environmentId={environmentId} path={iconPath} /> : undefined
409 }
410 path={iconPath}
411 environmentId={environmentId}
412 label={label}
413 theme={theme}
414 />
415 </ContextChip>
416 );
417 if (sharedTooltip) return withSharedTooltip(chip, sharedTooltip);
418 return (
419 <SharedTooltipTrigger
420 render={chip}
421 label={tooltipContent}
422 variant="code"
423 className="pointer-events-auto"
424 />
425 );
426}, areMarkdownFileLinkPropsEqual);
427
428function areMarkdownFileLinkPropsEqual(
429 previous: Readonly<MarkdownFileLinkProps>,
430 next: Readonly<MarkdownFileLinkProps>,
431): boolean {
432 return (
433 previous.href === next.href &&
434 previous.targetPath === next.targetPath &&
435 previous.iconPath === next.iconPath &&
436 previous.environmentId === next.environmentId &&
437 previous.workspaceRelativePath === next.workspaceRelativePath &&
438 previous.panelPath === next.panelPath &&
439 previous.line === next.line &&
440 previous.label === next.label &&
441 previous.copyMarkdown === next.copyMarkdown &&
442 previous.theme === next.theme &&
443 previous.threadRef === next.threadRef &&
444 previous.isAppBundle === next.isAppBundle &&
445 previous.onOpen === next.onOpen &&
446 previous.onOpenInPanel === next.onOpenInPanel &&
447 previous.openInEditorMenuLabel === next.openInEditorMenuLabel &&
448 previous.onOpenInBrowser === next.onOpenInBrowser &&
449 previous.onOpenMedia === next.onOpenMedia &&
450 previous.onReveal === next.onReveal &&
451 previous.resolveCopyPaths === next.resolveCopyPaths &&
452 previous.resolveDragPath === next.resolveDragPath &&
453 previous.revealLabel === next.revealLabel &&
454 previous.onDownload === next.onDownload
455 );
456}
457
458function AppBundleIcon(props: { environmentId: EnvironmentId | null; path: string }) {
459 const asset = useAssetUrlState(props.environmentId, {
460 _tag: "native-app-icon",
461 app: { _tag: "app-path", path: props.path },
462 });
463 const [failedUrl, setFailedUrl] = useState<string | null>(null);
464 const [loadedUrl, setLoadedUrl] = useState<string | null>(null);
465 const url = asset._tag === "Success" && asset.url !== failedUrl ? asset.url : null;
466 const loaded = url !== null && loadedUrl === url;
467 return (
468 <span
469 data-app-bundle-icon=""
470 aria-hidden="true"
471 className="relative me-[0.2em] inline-block size-[1em] align-[calc((1cap-1em)/2)]"
472 >
473 <FolderIcon className={cn("size-full text-icon-muted", loaded && "invisible")} />
474 {url !== null && (
475 <img
476 src={url}
477 alt=""
478 className={cn("absolute inset-0 size-full object-contain", !loaded && "invisible")}
479 onLoad={() => setLoadedUrl(url)}
480 onError={() => setFailedUrl(url)}
481 />
482 )}
483 </span>
484 );
485}