Open History to see the last commit
1import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions";
2import {
3 isAtomCommandInterrupted,
4 squashAtomCommandFailure,
5 type AtomCommandResult,
6} from "@t3tools/client-runtime/state/runtime";
7import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
8import { memo, type MouseEvent as ReactMouseEvent } from "react";
9
10import { readLocalApi } from "../../localApi";
11import { cn } from "../../lib/utils";
12import { shouldOpenMarkdownFileLinkInEditor } from "../../markdown-links";
13import type { markdownFileCopyPaths } from "../../markdownFileHostPath";
14import { documentChipKindForFileName } from "../../pierre-icons";
15import { ContextChip } from "../ContextChip";
16import { stackedThreadToast, toastManager } from "../ui/toast";
17import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
18import { FileTagChipContent } from "./FileTagChip";
19import {
20 hasMarkdownFilePrimaryAction,
21 markdownFileCopyMenuItems,
22 shouldUseMarkdownFileBrowserPrimaryAction,
23} from "./MarkdownFileLink.logic";
24import { reportMarkdownActionFailure } from "./markdownActionFailure";
25import { WorkspaceEntryTooltip } from "./WorkspaceEntryIcon";
26
27interface MarkdownFileLinkProps {
28 environmentId: EnvironmentId | null;
29 href: string;
30 targetPath: string;
31 iconPath: string;
32 workspaceRelativePath: string | null;
33 panelPath: string | null;
34 line?: number | undefined;
35 label: string;
36 copyMarkdown: string;
37 theme: "light" | "dark";
38 threadRef?: ScopedThreadRef | undefined;
39 onOpen?: (() => Promise<AtomCommandResult<unknown, unknown>>) | undefined;
40 onOpenInPanel: (panelPath: string, line: number | undefined) => void;
41 resolveCopyPaths: () => Promise<ReturnType<typeof markdownFileCopyPaths>>;
42 openInEditorMenuLabel: string;
43 onOpenInBrowser?: (() => Promise<AtomCommandResult<unknown, unknown>>) | undefined;
44 onOpenMedia?: (() => void) | undefined;
45 onReveal?: (() => Promise<AtomCommandResult<unknown, unknown>>) | undefined;
46 revealLabel?: string | undefined;
47}
48
49const MARKDOWN_FILE_LINK_CLASS_NAME = "chat-markdown-file-link";
50
51export const MarkdownFileLink = memo(function MarkdownFileLink({
52 environmentId,
53 href,
54 targetPath,
55 iconPath,
56 workspaceRelativePath,
57 panelPath,
58 line,
59 label,
60 copyMarkdown,
61 theme,
62 threadRef,
63 onOpen,
64 onOpenInPanel,
65 openInEditorMenuLabel,
66 onOpenInBrowser,
67 onOpenMedia,
68 onReveal,
69 revealLabel,
70 resolveCopyPaths,
71}: MarkdownFileLinkProps) {
72 const handleOpenInEditor = () => {
73 if (!onOpen) {
74 return;
75 }
76 void (async () => {
77 try {
78 const result = await onOpen();
79 if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
80 return;
81 }
82 reportMarkdownActionFailure(
83 { operation: "open-file-in-editor", target: targetPath },
84 result.cause,
85 );
86 const error = squashAtomCommandFailure(result);
87 toastManager.add(
88 stackedThreadToast({
89 type: "error",
90 title: "Unable to open file",
91 description: error instanceof Error ? error.message : "An error occurred.",
92 }),
93 );
94 } catch (cause) {
95 reportMarkdownActionFailure(
96 { operation: "open-file-in-editor", target: targetPath },
97 cause,
98 );
99 toastManager.add(
100 stackedThreadToast({
101 type: "error",
102 title: "Unable to open file",
103 description: cause instanceof Error ? cause.message : "An error occurred.",
104 }),
105 );
106 }
107 })();
108 };
109
110 const handleOpenInFilePreview = () => {
111 if (threadRef && panelPath) {
112 onOpenInPanel(panelPath, line);
113 return;
114 }
115 if (onOpenMedia) {
116 onOpenMedia();
117 return;
118 }
119 handleOpenInEditor();
120 };
121
122 const handleOpenInBrowser = () => {
123 if (!onOpenInBrowser) {
124 return;
125 }
126 void (async () => {
127 try {
128 const result = await onOpenInBrowser();
129 if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
130 return;
131 }
132 reportMarkdownActionFailure(
133 { operation: "open-file-in-browser", target: targetPath },
134 result.cause,
135 );
136 const error = squashAtomCommandFailure(result);
137 toastManager.add(
138 stackedThreadToast({
139 type: "error",
140 title: "Unable to open file in browser",
141 description: error instanceof Error ? error.message : "An error occurred.",
142 }),
143 );
144 } catch (cause) {
145 reportMarkdownActionFailure(
146 { operation: "open-file-in-browser", target: targetPath },
147 cause,
148 );
149 toastManager.add(
150 stackedThreadToast({
151 type: "error",
152 title: "Unable to open file in browser",
153 description: cause instanceof Error ? cause.message : "An error occurred.",
154 }),
155 );
156 }
157 })();
158 };
159
160 const handleRevealInFileManager = () => {
161 if (!onReveal) {
162 return;
163 }
164 void (async () => {
165 try {
166 const result = await onReveal();
167 if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
168 return;
169 }
170 reportMarkdownActionFailure(
171 { operation: "reveal-file-in-file-manager", target: targetPath },
172 result.cause,
173 );
174 const error = squashAtomCommandFailure(result);
175 toastManager.add(
176 stackedThreadToast({
177 type: "error",
178 title: "Unable to reveal file",
179 description: error instanceof Error ? error.message : "An error occurred.",
180 }),
181 );
182 } catch (cause) {
183 reportMarkdownActionFailure(
184 { operation: "reveal-file-in-file-manager", target: targetPath },
185 cause,
186 );
187 toastManager.add(
188 stackedThreadToast({
189 type: "error",
190 title: "Unable to reveal file",
191 description: cause instanceof Error ? cause.message : "An error occurred.",
192 }),
193 );
194 }
195 })();
196 };
197
198 const handleCopy = (resolveValue: () => Promise<string>, title: string) => {
199 if (typeof window === "undefined" || !navigator.clipboard?.writeText) {
200 toastManager.add(
201 stackedThreadToast({
202 type: "error",
203 title: `Failed to copy ${title.toLowerCase()}`,
204 description: "Clipboard API unavailable.",
205 }),
206 );
207 return;
208 }
209
210 const value = resolveValue().then((text) => formatFilePathForClipboard(text, targetPath));
211 // Start the write before workspace lookup finishes so Safari retains the user gesture.
212 const write =
213 typeof navigator.clipboard.write === "function" && typeof ClipboardItem !== "undefined"
214 ? navigator.clipboard.write([
215 new ClipboardItem({
216 "text/plain": value.then((text) => new Blob([text], { type: "text/plain" })),
217 }),
218 ])
219 : value.then((text) => navigator.clipboard.writeText(text));
220 void Promise.all([write, value]).then(
221 ([, text]) => {
222 toastManager.add({
223 type: "success",
224 title: `${title} copied`,
225 description: text,
226 });
227 },
228 (error) => {
229 reportMarkdownActionFailure(
230 { operation: "copy-file-path", target: targetPath, copyTarget: title },
231 error,
232 );
233 toastManager.add(
234 stackedThreadToast({
235 type: "error",
236 title: `Failed to copy ${title.toLowerCase()}`,
237 description: error instanceof Error ? error.message : "An error occurred.",
238 }),
239 );
240 },
241 );
242 };
243
244 const showFileContextMenu = async (position: { x: number; y: number }) => {
245 const api = readLocalApi();
246 if (!api) return;
247
248 try {
249 const copyItems = markdownFileCopyMenuItems({ targetPath, workspaceRelativePath });
250 const clicked = await api.contextMenu.show(
251 [
252 ...(onOpenMedia ? ([{ id: "preview-media", label: "Preview media" }] as const) : []),
253 ...(onOpen ? ([{ id: "open", label: openInEditorMenuLabel }] as const) : []),
254 ...(onOpenInBrowser
255 ? ([{ id: "open-in-browser", label: "Open in integrated browser" }] as const)
256 : []),
257 ...(onReveal && revealLabel ? ([{ id: "reveal", label: revealLabel }] as const) : []),
258 ...copyItems.map(({ id, label }) => ({ id, label })),
259 ] as const,
260 position,
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);
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 iconPath,
320 canOpenInEditor,
321 canOpenInBrowser,
322 canOpenInPanel,
323 });
324 const chipKind = documentChipKindForFileName(iconPath) ?? "mention";
325
326 return (
327 <Tooltip>
328 <TooltipTrigger
329 render={
330 hasPrimaryAction ? (
331 <ContextChip
332 kind={chipKind}
333 dir="ltr"
334 render={<a href={href} />}
335 className={MARKDOWN_FILE_LINK_CLASS_NAME}
336 data-markdown-copy={copyMarkdown}
337 onClick={(event) => {
338 event.preventDefault();
339 event.stopPropagation();
340 if (onOpen && shouldOpenMarkdownFileLinkInEditor(event)) {
341 handleOpenInEditor();
342 return;
343 }
344 if (useBrowserPrimaryAction) {
345 handleOpenInBrowser();
346 return;
347 }
348 handleOpenInFilePreview();
349 }}
350 onContextMenu={handleContextMenu}
351 >
352 <FileTagChipContent
353 path={iconPath}
354 environmentId={environmentId}
355 label={label}
356 theme={theme}
357 />
358 </ContextChip>
359 ) : (
360 <ContextChip
361 kind={chipKind}
362 dir="ltr"
363 render={<button type="button" />}
364 aria-label={`File options for ${label}`}
365 aria-haspopup="menu"
366 className={cn(MARKDOWN_FILE_LINK_CLASS_NAME, "select-text")}
367 data-markdown-copy={copyMarkdown}
368 onClick={handleContextMenu}
369 onContextMenu={handleContextMenu}
370 >
371 <FileTagChipContent
372 path={iconPath}
373 environmentId={environmentId}
374 label={label}
375 theme={theme}
376 />
377 </ContextChip>
378 )
379 }
380 />
381 <TooltipPopup side="top" variant="code">
382 <div className="overflow-x-auto whitespace-nowrap scrollbar-thumb-border/78 scrollbar-track-transparent [scrollbar-width:thin] [&::-webkit-scrollbar]:h-1.5 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-border/78 [&::-webkit-scrollbar-track]:bg-transparent">
383 <WorkspaceEntryTooltip path={iconPath} label={targetPath} environmentId={environmentId} />
384 </div>
385 </TooltipPopup>
386 </Tooltip>
387 );
388}, areMarkdownFileLinkPropsEqual);
389
390function areMarkdownFileLinkPropsEqual(
391 previous: Readonly<MarkdownFileLinkProps>,
392 next: Readonly<MarkdownFileLinkProps>,
393): boolean {
394 return (
395 previous.href === next.href &&
396 previous.targetPath === next.targetPath &&
397 previous.iconPath === next.iconPath &&
398 previous.environmentId === next.environmentId &&
399 previous.workspaceRelativePath === next.workspaceRelativePath &&
400 previous.panelPath === next.panelPath &&
401 previous.line === next.line &&
402 previous.label === next.label &&
403 previous.copyMarkdown === next.copyMarkdown &&
404 previous.theme === next.theme &&
405 previous.threadRef === next.threadRef &&
406 previous.onOpen === next.onOpen &&
407 previous.onOpenInPanel === next.onOpenInPanel &&
408 previous.openInEditorMenuLabel === next.openInEditorMenuLabel &&
409 previous.onOpenInBrowser === next.onOpenInBrowser &&
410 previous.onOpenMedia === next.onOpenMedia &&
411 previous.onReveal === next.onReveal &&
412 previous.resolveCopyPaths === next.resolveCopyPaths &&
413 previous.revealLabel === next.revealLabel
414 );
415}