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

MarkdownFileLink.tsx

470 lines15.2 KB

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