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

MarkdownFileLink.tsx

450 lines14.3 KB

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