Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

MarkdownFileLink.tsx

413 lines13.3 KB

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