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