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