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