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";
10
11import { contextMenuSourceOf } from "../../contextMenuSource";
12import { readLocalApi } from "../../localApi";
13import { cn } from "../../lib/utils";
14import { shouldOpenMarkdownFileLinkInEditor } from "../../markdown-links";
15import type { markdownFileCopyPaths } from "../../markdownFileHostPath";
16import { documentChipKindForFileName } from "../../pierre-icons";
17import { ContextChip } from "../ContextChip";
18import { stackedThreadToast, toastManager } from "../ui/toast";
19import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
20import { FileTagChipContent } from "./FileTagChip";
21import {
22 hasMarkdownFilePrimaryAction,
23 markdownFileCopyMenuItems,
24 shouldUseMarkdownFileBrowserPrimaryAction,
25} from "./MarkdownFileLink.logic";
26import { reportMarkdownActionFailure } from "./markdownActionFailure";
27import { WorkspaceEntryIcon, WorkspaceEntryTooltip } from "./WorkspaceEntryIcon";
28
29interface MarkdownFileLinkProps {
30 environmentId: EnvironmentId | null;
31 href: string;
32 targetPath: string;
33 iconPath: string;
34 isAppBundle?: boolean;
35 workspaceRelativePath: string | null;
36 panelPath: string | null;
37 line?: number | undefined;
38 label: string;
39 copyMarkdown: string;
40 theme: "light" | "dark";
41 threadRef?: ScopedThreadRef | undefined;
42 onOpen?: (() => Promise<AtomCommandResult<unknown, unknown>>) | undefined;
43 onOpenInPanel: (panelPath: string, line: number | undefined) => void;
44 resolveCopyPaths: () => Promise<ReturnType<typeof markdownFileCopyPaths>>;
45 openInEditorMenuLabel: string;
46 onOpenInBrowser?: (() => Promise<AtomCommandResult<unknown, unknown>>) | undefined;
47 onOpenMedia?: (() => void) | undefined;
48 onReveal?: (() => Promise<AtomCommandResult<unknown, unknown>>) | undefined;
49 revealLabel?: string | undefined;
50}
51
52const MARKDOWN_FILE_LINK_CLASS_NAME = "chat-markdown-file-link";
53
54export const MarkdownFileLink = memo(function MarkdownFileLink({
55 environmentId,
56 href,
57 targetPath,
58 iconPath,
59 isAppBundle = false,
60 workspaceRelativePath,
61 panelPath,
62 line,
63 label,
64 copyMarkdown,
65 theme,
66 threadRef,
67 onOpen,
68 onOpenInPanel,
69 openInEditorMenuLabel,
70 onOpenInBrowser,
71 onOpenMedia,
72 onReveal,
73 revealLabel,
74 resolveCopyPaths,
75}: MarkdownFileLinkProps) {
76 const handleOpenInEditor = () => {
77 if (!onOpen) {
78 return;
79 }
80 void (async () => {
81 try {
82 const result = await onOpen();
83 if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
84 return;
85 }
86 reportMarkdownActionFailure(
87 { operation: "open-file-in-editor", target: targetPath },
88 result.cause,
89 );
90 const error = squashAtomCommandFailure(result);
91 toastManager.add(
92 stackedThreadToast({
93 type: "error",
94 title: "Unable to open file",
95 description: error instanceof Error ? error.message : "An error occurred.",
96 }),
97 );
98 } catch (cause) {
99 reportMarkdownActionFailure(
100 { operation: "open-file-in-editor", target: targetPath },
101 cause,
102 );
103 toastManager.add(
104 stackedThreadToast({
105 type: "error",
106 title: "Unable to open file",
107 description: cause instanceof Error ? cause.message : "An error occurred.",
108 }),
109 );
110 }
111 })();
112 };
113
114 const handleOpenInFilePreview = () => {
115 if (threadRef && panelPath) {
116 onOpenInPanel(panelPath, line);
117 return;
118 }
119 if (onOpenMedia) {
120 onOpenMedia();
121 return;
122 }
123 handleOpenInEditor();
124 };
125
126 const handleOpenInBrowser = () => {
127 if (!onOpenInBrowser) {
128 return;
129 }
130 void (async () => {
131 try {
132 const result = await onOpenInBrowser();
133 if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
134 return;
135 }
136 reportMarkdownActionFailure(
137 { operation: "open-file-in-browser", target: targetPath },
138 result.cause,
139 );
140 const error = squashAtomCommandFailure(result);
141 toastManager.add(
142 stackedThreadToast({
143 type: "error",
144 title: "Unable to open file in browser",
145 description: error instanceof Error ? error.message : "An error occurred.",
146 }),
147 );
148 } catch (cause) {
149 reportMarkdownActionFailure(
150 { operation: "open-file-in-browser", target: targetPath },
151 cause,
152 );
153 toastManager.add(
154 stackedThreadToast({
155 type: "error",
156 title: "Unable to open file in browser",
157 description: cause instanceof Error ? cause.message : "An error occurred.",
158 }),
159 );
160 }
161 })();
162 };
163
164 const handleRevealInFileManager = () => {
165 if (!onReveal) {
166 return;
167 }
168 void (async () => {
169 try {
170 const result = await onReveal();
171 if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
172 return;
173 }
174 reportMarkdownActionFailure(
175 { operation: "reveal-file-in-file-manager", target: targetPath },
176 result.cause,
177 );
178 const error = squashAtomCommandFailure(result);
179 toastManager.add(
180 stackedThreadToast({
181 type: "error",
182 title: "Unable to reveal file",
183 description: error instanceof Error ? error.message : "An error occurred.",
184 }),
185 );
186 } catch (cause) {
187 reportMarkdownActionFailure(
188 { operation: "reveal-file-in-file-manager", target: targetPath },
189 cause,
190 );
191 toastManager.add(
192 stackedThreadToast({
193 type: "error",
194 title: "Unable to reveal file",
195 description: cause instanceof Error ? cause.message : "An error occurred.",
196 }),
197 );
198 }
199 })();
200 };
201
202 const handleCopy = (resolveValue: () => Promise<string>, title: string) => {
203 if (typeof window === "undefined" || !navigator.clipboard?.writeText) {
204 toastManager.add(
205 stackedThreadToast({
206 type: "error",
207 title: `Failed to copy ${title.toLowerCase()}`,
208 description: "Clipboard API unavailable.",
209 }),
210 );
211 return;
212 }
213
214 const value = resolveValue().then((text) => formatFilePathForClipboard(text, targetPath));
215 // Start the write before workspace lookup finishes so Safari retains the user gesture.
216 const write =
217 typeof navigator.clipboard.write === "function" && typeof ClipboardItem !== "undefined"
218 ? navigator.clipboard.write([
219 new ClipboardItem({
220 "text/plain": value.then((text) => new Blob([text], { type: "text/plain" })),
221 }),
222 ])
223 : value.then((text) => navigator.clipboard.writeText(text));
224 void Promise.all([write, value]).catch((error) => {
225 reportMarkdownActionFailure(
226 { operation: "copy-file-path", target: targetPath, copyTarget: title },
227 error,
228 );
229 toastManager.add(
230 stackedThreadToast({
231 type: "error",
232 title: `Failed to copy ${title.toLowerCase()}`,
233 description: error instanceof Error ? error.message : "An error occurred.",
234 }),
235 );
236 });
237 };
238
239 const showFileContextMenu = async (
240 position: { x: number; y: number },
241 source: ContextMenuSource,
242 ) => {
243 const api = readLocalApi();
244 if (!api) return;
245
246 try {
247 const copyItems = markdownFileCopyMenuItems({ targetPath, workspaceRelativePath });
248 const clicked = await api.contextMenu.show(
249 [
250 ...(onOpenMedia ? ([{ id: "preview-media", label: "Preview media" }] as const) : []),
251 ...(onOpen ? ([{ id: "open", label: openInEditorMenuLabel }] as const) : []),
252 ...(onOpenInBrowser
253 ? ([{ id: "open-in-browser", label: "Open in integrated browser" }] as const)
254 : []),
255 ...(onReveal && revealLabel ? ([{ id: "reveal", label: revealLabel }] as const) : []),
256 ...copyItems.map(({ id, label }) => ({ id, label })),
257 ] as const,
258 position,
259 source,
260 );
261
262 if (clicked === "preview-media") {
263 onOpenMedia?.();
264 return;
265 }
266 if (clicked === "open") {
267 handleOpenInEditor();
268 return;
269 }
270 if (clicked === "open-in-browser") {
271 handleOpenInBrowser();
272 return;
273 }
274 if (clicked === "reveal") {
275 handleRevealInFileManager();
276 return;
277 }
278 if (clicked === "copy-relative" || clicked === "copy-full") {
279 handleCopy(
280 () =>
281 resolveCopyPaths().then((paths) =>
282 clicked === "copy-relative" ? paths.relativePath : paths.fullPath,
283 ),
284 clicked === "copy-relative" ? "Relative path" : "Full path",
285 );
286 }
287 } catch (cause) {
288 reportMarkdownActionFailure(
289 { operation: "show-file-context-menu", target: targetPath },
290 cause,
291 );
292 }
293 };
294
295 const handleContextMenu = (event: ReactMouseEvent<HTMLElement>) => {
296 event.preventDefault();
297 event.stopPropagation();
298 const position =
299 event.clientX === 0 && event.clientY === 0
300 ? (() => {
301 const bounds = event.currentTarget.getBoundingClientRect();
302 return { x: bounds.left, y: bounds.bottom };
303 })()
304 : { x: event.clientX, y: event.clientY };
305 void showFileContextMenu(position, contextMenuSourceOf(event));
306 };
307
308 const canOpenInEditor = onOpen !== undefined;
309 const canOpenInBrowser = onOpenInBrowser !== undefined;
310 const canOpenInPanel = threadRef !== undefined && Boolean(panelPath);
311 const hasPrimaryAction = hasMarkdownFilePrimaryAction({
312 canOpenInEditor,
313 canOpenInBrowser,
314 canOpenInPanel,
315 canOpenMedia: onOpenMedia !== undefined,
316 });
317 const useBrowserPrimaryAction = shouldUseMarkdownFileBrowserPrimaryAction({
318 iconPath,
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} theme={theme} />
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} theme={theme} />
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: {
426 environmentId: EnvironmentId | null;
427 path: string;
428 theme: "light" | "dark";
429}) {
430 const asset = useAssetUrlState(props.environmentId, {
431 _tag: "native-app-icon",
432 app: { _tag: "app-path", path: props.path },
433 });
434 const [failedUrl, setFailedUrl] = useState<string | null>(null);
435 if (asset._tag !== "Success" || asset.url === failedUrl) {
436 return <WorkspaceEntryIcon {...props} />;
437 }
438 return (
439 <img
440 src={asset.url}
441 alt=""
442 className="size-4 shrink-0 object-contain"
443 onError={() => setFailedUrl(asset.url)}
444 />
445 );
446}