The best way to control Claude Code, Codex and more from any computer or phone

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