The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; |
| 2 | import { DownloadIcon, CopyIcon, CheckIcon, Code2Icon, EyeIcon, Table2Icon } from "lucide-react"; |
| 3 | import { msg, T, useGT, useMessages, Var } from "gt-react"; |
| 4 | import { m, type MessageResolver } from "~/i18n/messages"; |
| 5 | import { namedClipboardTarget, useCopyToClipboard } from "~/hooks/useCopyToClipboard"; |
| 6 | import { Spinner } from "~/components/ui/spinner"; |
| 7 | import { |
| 8 | type AssetResource, |
| 9 | AuthPreviewOperateScope, |
| 10 | type EditorId, |
| 11 | type EnvironmentId, |
| 12 | type ProjectId, |
| 13 | type ResolvedKeybindingsConfig, |
| 14 | type ScopedThreadRef, |
| 15 | } from "@t3tools/contracts"; |
| 16 | import { filePreviewDelimiter } from "@t3tools/shared/delimitedPreview"; |
| 17 | import { AuthFilesystemWriteScope } from "@t3tools/contracts"; |
| 18 | import { |
| 19 | isWorkspaceAudioPreviewPath, |
| 20 | isWorkspaceImagePreviewPath, |
| 21 | isWorkspaceFontPreviewPath, |
| 22 | isWorkspaceVideoPreviewPath, |
| 23 | officePreviewKind, |
| 24 | binaryPreviewKind, |
| 25 | } from "@t3tools/shared/filePreview"; |
| 26 | import { useAtomMount, useAtomValue } from "@effect/atom-react"; |
| 27 | import { Atom } from "effect/reactivity"; |
| 28 | import { |
| 29 | DEFAULT_TOKENIZE_MAX_LENGTH, |
| 30 | VirtualizedFile, |
| 31 | getFiletypeFromFileName, |
| 32 | type File as FileInstance, |
| 33 | type FileContents, |
| 34 | type PostRenderPhase, |
| 35 | type SelectedLineRange, |
| 36 | } from "@pierre/diffs"; |
| 37 | import { |
| 38 | Editor, |
| 39 | type EditorChangeEvent, |
| 40 | type EditorFactory, |
| 41 | type EditorOptions, |
| 42 | } from "@pierre/diffs/edit"; |
| 43 | import type { WorkerPoolManager } from "@pierre/diffs/worker"; |
| 44 | import { EditProvider, File, Virtualizer, useWorkerPool } from "@pierre/diffs/react"; |
| 45 | import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider"; |
| 46 | import { useFilesystemReadAccess } from "~/state/filesystem"; |
| 47 | import { |
| 48 | isAtomCommandInterrupted, |
| 49 | squashAtomCommandFailure, |
| 50 | } from "@t3tools/client-runtime/state/runtime"; |
| 51 | import { mediaFileReference } from "@t3tools/client-runtime/media-reference"; |
| 52 | import { FolderTree, Globe2, WrapTextIcon } from "lucide-react"; |
| 53 | import * as Schema from "effect/Schema"; |
| 54 | import { |
| 55 | lazy, |
| 56 | Suspense, |
| 57 | useEffect, |
| 58 | useEffectEvent, |
| 59 | useRef, |
| 60 | useState, |
| 61 | type KeyboardEvent as ReactKeyboardEvent, |
| 62 | } from "react"; |
| 63 | |
| 64 | import { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPreview"; |
| 65 | import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls"; |
| 66 | import { OpenInPicker } from "~/components/chat/OpenInPicker"; |
| 67 | import { MediaVideoPlayer } from "~/components/media/MediaVideoPlayer"; |
| 68 | import { MediaActions, type MediaActionSource } from "~/components/media/MediaActions"; |
| 69 | import { useRemoteOpenState } from "~/remoteOpen"; |
| 70 | import { useClientSettings } from "~/hooks/useSettings"; |
| 71 | import { useTheme } from "~/hooks/useTheme"; |
| 72 | import { useStableCallback } from "~/hooks/useStableCallback"; |
| 73 | import { getLocalStorageItem, setLocalStorageItem, useLocalStorage } from "~/hooks/useLocalStorage"; |
| 74 | import { resolveDiffThemeName } from "~/lib/diffRendering"; |
| 75 | import { PREFERRED_HIGHLIGHTER } from "~/lib/syntaxHighlighting"; |
| 76 | import { cn, isMacPlatform } from "~/lib/utils"; |
| 77 | import { requestWorkspaceFocus } from "~/lib/workspaceFocus"; |
| 78 | import type { ChatFileAttachment } from "~/types"; |
| 79 | import { isHostPath } from "@t3tools/shared/path"; |
| 80 | import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks"; |
| 81 | import { ScrollArea } from "~/components/ui/scroll-area"; |
| 82 | import { stackedThreadToast, toastManager } from "~/components/ui/toast"; |
| 83 | import { type DraftId, useComposerDraftStore } from "~/composerDraftStore"; |
| 84 | import { buildFileReviewComment, type ReviewCommentContext } from "~/reviewCommentContext"; |
| 85 | import { assetEnvironment } from "~/state/assets"; |
| 86 | import { usePreviewAvailable } from "~/browser/previewRuntime"; |
| 87 | import { useEnvironmentHttpBaseUrl, usePrimaryEnvironmentId } from "~/state/environments"; |
| 88 | import { hostEnvironmentIdAtom } from "~/state/primaryEnvironment"; |
| 89 | import { previewEnvironment } from "~/state/preview"; |
| 90 | import { serverEnvironment } from "~/state/server"; |
| 91 | import { useEnvironmentScope } from "~/state/session"; |
| 92 | import { useAtomCommand } from "~/state/use-atom-command"; |
| 93 | import { useAtomQueryRunner } from "~/state/use-atom-query-runner"; |
| 94 | |
| 95 | import { AttachmentFilePreview } from "./AttachmentFilePreview"; |
| 96 | import { AudioPreview } from "./AudioPreview"; |
| 97 | import { BrowserDocumentFrame, isPdfPreviewFile } from "./BrowserDocumentFrame"; |
| 98 | import { DelimitedTablePreview } from "./DelimitedTablePreview"; |
| 99 | import { PreviewImage } from "./PreviewImage"; |
| 100 | import FileBrowserPanel from "./FileBrowserPanel"; |
| 101 | import { FileExplorerPane } from "./FileExplorerPane"; |
| 102 | import { FileBreadcrumbs } from "./FileBreadcrumbs"; |
| 103 | import { breadcrumbPathOf, retainedBreadcrumbTrail, trailChildOf } from "./filePath"; |
| 104 | import { FileMarkdownPreview } from "./FileMarkdownPreview"; |
| 105 | import { |
| 106 | type FileCommentAnnotationEntry, |
| 107 | type FileCommentAnnotationGroup, |
| 108 | type FileCommentLineAnnotation, |
| 109 | formatFileCommentRange, |
| 110 | nextFileCommentId, |
| 111 | normalizeFileCommentRange, |
| 112 | remapFileCommentAnnotations, |
| 113 | promptFileCommentEntries, |
| 114 | } from "./fileCommentAnnotations"; |
| 115 | import { installFileEditorDismissal } from "./fileEditorDismissal"; |
| 116 | import { |
| 117 | FILE_LINK_REVEAL_ATTRIBUTE, |
| 118 | FILE_LINK_REVEAL_UNSAFE_CSS, |
| 119 | FILE_SURFACE_SUBHEADER_CLASS, |
| 120 | FileSurfaceAction, |
| 121 | FileSurfaceFailure, |
| 122 | FileSurfaceLoading, |
| 123 | } from "./fileSurfaceChrome"; |
| 124 | import SourceFilePreview from "./ReadOnlySourcePreview"; |
| 125 | import { resolveCenteredFileLineScrollTop } from "./fileLineReveal"; |
| 126 | import { DiffCommentAnnotation } from "../diffs/DiffCommentAnnotation"; |
| 127 | import { projectFileCacheKey } from "./fileContentRevision"; |
| 128 | import { |
| 129 | filePreviewReadErrorMessage, |
| 130 | isMarkdownPreviewFile, |
| 131 | resolveFilePreviewPath, |
| 132 | shouldShowFileExplorer, |
| 133 | workspaceAssetResource, |
| 134 | } from "./filePreviewMode"; |
| 135 | import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList"; |
| 136 | import { changeFileSaveSession, useFileSaveSession } from "./fileSaveSessions"; |
| 137 | import { revisionedQuery } from "~/state/revisionedQuery"; |
| 138 | import { |
| 139 | getOptimisticProjectFileQueryData, |
| 140 | getProjectFileContents, |
| 141 | getProjectFileQueryAtom, |
| 142 | setProjectFileQueryData, |
| 143 | useProjectFileQuery, |
| 144 | } from "./projectFilesQueryState"; |
| 145 | |
| 146 | const NO_FILE_REVISION_ATOM = Atom.make(null); |
| 147 | |
| 148 | interface FilePreviewPanelProps { |
| 149 | environmentId: EnvironmentId; |
| 150 | cwd: string; |
| 151 | projectName: string; |
| 152 | projectId?: ProjectId | undefined; |
| 153 | relativePath: string | null; |
| 154 | attachment?: ChatFileAttachment; |
| 155 | threadRef: ScopedThreadRef; |
| 156 | composerDraftTarget: ScopedThreadRef | DraftId; |
| 157 | keybindings: ResolvedKeybindingsConfig; |
| 158 | availableEditors: ReadonlyArray<EditorId>; |
| 159 | openInShortcutEnabled: boolean; |
| 160 | revealLine: number | null; |
| 161 | revealRequestId: number; |
| 162 | onOpenFile: (relativePath: string) => void; |
| 163 | onNavigateFolder: (relativePath: string, folderTrail: string, keepSource: boolean) => void; |
| 164 | /** Retained descendant breadcrumb path after navigating up; see navigateFolder. */ |
| 165 | folderTrail: string | undefined; |
| 166 | onPendingChange: (relativePath: string, pending: boolean) => void; |
| 167 | selectedFilePending: boolean; |
| 168 | workspaceMutationId: string | null; |
| 169 | } |
| 170 | |
| 171 | const MermaidFilePreview = lazy(() => |
| 172 | import("./MermaidFilePreview").then((module) => ({ default: module.MermaidFilePreview })), |
| 173 | ); |
| 174 | |
| 175 | const FILE_EXPLORER_STORAGE_KEY = "t3code.fileExplorerOpen"; |
| 176 | const RENDER_MARKDOWN_STORAGE_KEY = "t3code.renderMarkdown"; |
| 177 | const RENDER_BROWSER_FILE_STORAGE_KEY = "t3code.renderBrowserFile"; |
| 178 | const RENDER_TABLE_STORAGE_KEY = "t3code.renderTable"; |
| 179 | type FilePostRender = <LAnnotation>( |
| 180 | fileContainer: HTMLElement, |
| 181 | instance: FileInstance<LAnnotation, undefined>, |
| 182 | phase: PostRenderPhase, |
| 183 | ) => void; |
| 184 | |
| 185 | function WorkspaceImagePreview(props: { |
| 186 | readonly environmentId: EnvironmentId; |
| 187 | readonly threadRef: ScopedThreadRef; |
| 188 | readonly draft: boolean; |
| 189 | readonly absolutePath: string; |
| 190 | readonly workspaceRoot: string; |
| 191 | readonly alt: string; |
| 192 | readonly workspaceMutationId: string | null; |
| 193 | }) { |
| 194 | const resource = workspaceAssetResource({ |
| 195 | kind: |
| 196 | mediaFileReference(props.absolutePath, props.workspaceRoot).relativePath !== undefined |
| 197 | ? "workspace-file" |
| 198 | : "media-file", |
| 199 | threadRef: props.threadRef, |
| 200 | draft: props.draft, |
| 201 | workspaceRoot: props.workspaceRoot, |
| 202 | absolutePath: props.absolutePath, |
| 203 | }); |
| 204 | const assetUrl = useAssetUrlState(props.environmentId, resource); |
| 205 | const revisionSuffix = |
| 206 | props.workspaceMutationId === null |
| 207 | ? "" |
| 208 | : `${assetUrl._tag === "Success" && assetUrl.url.includes("?") ? "&" : "?"}workspace-revision=${encodeURIComponent(props.workspaceMutationId)}`; |
| 209 | const imageUrl = assetUrl._tag === "Success" ? `${assetUrl.url}${revisionSuffix}` : null; |
| 210 | const actionsSource: MediaActionSource = { |
| 211 | kind: "image", |
| 212 | name: props.alt, |
| 213 | src: imageUrl, |
| 214 | reference: mediaFileReference(props.absolutePath, props.workspaceRoot), |
| 215 | asset: { environmentId: props.environmentId, resource }, |
| 216 | }; |
| 217 | |
| 218 | if (assetUrl._tag === "Failure") { |
| 219 | return ( |
| 220 | <MediaActions source={actionsSource}> |
| 221 | <div className="flex min-h-0 flex-1 items-center justify-center px-6 text-center text-xs leading-relaxed text-destructive"> |
| 222 | <T>Unable to load workspace image.</T> |
| 223 | </div> |
| 224 | </MediaActions> |
| 225 | ); |
| 226 | } |
| 227 | |
| 228 | return assetUrl._tag === "Success" && imageUrl !== null ? ( |
| 229 | <MediaActions source={actionsSource}> |
| 230 | <div className="flex min-h-0 flex-1 flex-col overflow-hidden"> |
| 231 | <PreviewImage key={imageUrl} src={imageUrl} name={props.alt} /> |
| 232 | </div> |
| 233 | </MediaActions> |
| 234 | ) : ( |
| 235 | <div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground"> |
| 236 | <Spinner size="lg" /> |
| 237 | </div> |
| 238 | ); |
| 239 | } |
| 240 | |
| 241 | interface HtmlPreviewFrame { |
| 242 | readonly revision: string | null; |
| 243 | readonly url: string; |
| 244 | /** When the loaded page's grant is about to expire and a fresh URL has to replace it. */ |
| 245 | readonly renewAt: number; |
| 246 | } |
| 247 | |
| 248 | const HTML_PREVIEW_RENEW_BEFORE_EXPIRY_MS = 2 * 60_000; |
| 249 | // Grants last an hour. A client clock far from the server's would otherwise renew at once, forever. |
| 250 | const HTML_PREVIEW_MIN_GRANT_HOLD_MS = 3 * 60_000; |
| 251 | const HTML_PREVIEW_MAX_GRANT_HOLD_MS = 60 * 60_000; |
| 252 | |
| 253 | const htmlPreviewFrame = ( |
| 254 | minted: { readonly revision: string | null; readonly url: string; readonly expiresAt: number }, |
| 255 | now: number, |
| 256 | ): HtmlPreviewFrame => ({ |
| 257 | revision: minted.revision, |
| 258 | url: minted.url, |
| 259 | renewAt: Math.min( |
| 260 | Math.max( |
| 261 | minted.expiresAt - HTML_PREVIEW_RENEW_BEFORE_EXPIRY_MS, |
| 262 | now + HTML_PREVIEW_MIN_GRANT_HOLD_MS, |
| 263 | ), |
| 264 | now + HTML_PREVIEW_MAX_GRANT_HOLD_MS, |
| 265 | ), |
| 266 | }); |
| 267 | |
| 268 | export function WorkspaceBrowserPreview(props: { |
| 269 | readonly environmentId: EnvironmentId; |
| 270 | readonly threadRef: ScopedThreadRef; |
| 271 | readonly draft: boolean; |
| 272 | readonly absolutePath: string; |
| 273 | readonly workspaceRoot: string; |
| 274 | readonly title: string; |
| 275 | readonly workspaceMutationId: string | null; |
| 276 | }) { |
| 277 | const pdf = isPdfPreviewFile(props.absolutePath); |
| 278 | const resource = workspaceAssetResource({ |
| 279 | kind: pdf ? "media-file" : "workspace-file", |
| 280 | threadRef: props.threadRef, |
| 281 | draft: props.draft, |
| 282 | workspaceRoot: props.workspaceRoot, |
| 283 | absolutePath: props.absolutePath, |
| 284 | }); |
| 285 | // Each workspace mutation re-mints the URL: a file outside the workspace is signed by its |
| 286 | // inode, which an atomic replace changes. |
| 287 | const assetUrl = useAssetUrlState(props.environmentId, resource, props.workspaceMutationId); |
| 288 | const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource); |
| 289 | // Servers that report the file's revision let an unchanged page stay loaded; older ones only |
| 290 | // offer the workspace mutation, which changes after every command. |
| 291 | const fileRevision = assetUrl._tag === "Success" ? assetUrl.fileRevision : undefined; |
| 292 | const latestRevision = fileRevision ?? props.workspaceMutationId; |
| 293 | // The HTML frame keeps the URL it loaded, so it moves only once a re-minted URL has arrived. |
| 294 | const [frame, setFrame] = useState<HtmlPreviewFrame | null>(null); |
| 295 | const [endingGrant, setEndingGrant] = useState<string | null>(null); |
| 296 | const grantEnding = frame !== null && endingGrant === frame.url; |
| 297 | if ( |
| 298 | !pdf && |
| 299 | assetUrl._tag === "Success" && |
| 300 | (frame === null || |
| 301 | (!assetUrl.waiting && |
| 302 | (frame.revision !== latestRevision || (grantEnding && frame.url !== assetUrl.url)))) |
| 303 | ) { |
| 304 | const { url, expiresAt } = assetUrl; |
| 305 | setFrame(() => htmlPreviewFrame({ revision: latestRevision, url, expiresAt }, Date.now())); |
| 306 | } |
| 307 | const renewGrant = useEffectEvent((url: string) => { |
| 308 | setEndingGrant(url); |
| 309 | // A command may have minted the next URL already; otherwise ask for it. |
| 310 | if (assetUrl._tag === "Success" && assetUrl.url === url) { |
| 311 | void refreshAssetUrl().catch(() => undefined); |
| 312 | } |
| 313 | }); |
| 314 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- mints a fresh URL shortly before the loaded page's grant expires |
| 315 | useEffect(() => { |
| 316 | if (frame === null) return; |
| 317 | const timer = setTimeout(() => renewGrant(frame.url), frame.renewAt - Date.now()); |
| 318 | return () => clearTimeout(timer); |
| 319 | }, [frame]); |
| 320 | const revision = pdf ? latestRevision : (frame?.revision ?? latestRevision); |
| 321 | const url = |
| 322 | assetUrl._tag !== "Success" ? null : pdf ? assetUrl.url : (frame?.url ?? assetUrl.url); |
| 323 | const revisionSuffix = |
| 324 | revision === null |
| 325 | ? "" |
| 326 | : `${url?.includes("?") ? "&" : "?"}${fileRevision !== undefined ? "file" : "workspace"}-revision=${encodeURIComponent(revision)}`; |
| 327 | |
| 328 | if (assetUrl._tag === "Failure") { |
| 329 | return ( |
| 330 | <div className="flex min-h-0 flex-1 items-center justify-center px-6 text-center text-xs leading-relaxed text-destructive"> |
| 331 | <T>Unable to load file preview.</T> |
| 332 | </div> |
| 333 | ); |
| 334 | } |
| 335 | if ( |
| 336 | assetUrl._tag !== "Success" || |
| 337 | (pdf && assetUrl.fileRevision === undefined && assetUrl.waiting) |
| 338 | ) { |
| 339 | return ( |
| 340 | <div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground"> |
| 341 | <Spinner size="lg" /> |
| 342 | </div> |
| 343 | ); |
| 344 | } |
| 345 | const documentId = `${props.environmentId}:${resource._tag}:${props.threadRef.threadId}:${props.absolutePath}`; |
| 346 | return ( |
| 347 | <BrowserDocumentFrame |
| 348 | src={`${url}${revisionSuffix}`} |
| 349 | documentKey={`${documentId}:${revision}${pdf ? "" : `:${frame?.renewAt}`}`} |
| 350 | documentId={documentId} |
| 351 | title={props.title} |
| 352 | pdf={pdf} |
| 353 | pdfActions={ |
| 354 | <WorkspacePdfSaveAction |
| 355 | environmentId={props.environmentId} |
| 356 | resource={resource} |
| 357 | name={props.title} |
| 358 | /> |
| 359 | } |
| 360 | /> |
| 361 | ); |
| 362 | } |
| 363 | |
| 364 | function WorkspacePdfSaveAction(props: { |
| 365 | readonly environmentId: EnvironmentId; |
| 366 | readonly resource: AssetResource; |
| 367 | readonly name: string; |
| 368 | }) { |
| 369 | const gt = useGT(); |
| 370 | const [saving, setSaving] = useState(false); |
| 371 | const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, props.resource); |
| 372 | return ( |
| 373 | <FileSurfaceAction |
| 374 | label={saving ? gt("Preparing file…") : gt("Save file")} |
| 375 | disabled={saving} |
| 376 | onPress={() => { |
| 377 | setSaving(true); |
| 378 | void (async () => { |
| 379 | const url = await refreshAssetUrl(); |
| 380 | if (!url) throw new Error(gt("Reconnect to the environment and try again.")); |
| 381 | const response = await fetch(url); |
| 382 | if (!response.ok) throw new Error(gt("The file could not be loaded. Try again.")); |
| 383 | // Blob downloads keep desktop's custom app scheme from navigating to an external browser. |
| 384 | const downloadUrl = URL.createObjectURL(await response.blob()); |
| 385 | setTimeout(() => URL.revokeObjectURL(downloadUrl), 30_000); |
| 386 | const anchor = document.createElement("a"); |
| 387 | anchor.href = downloadUrl; |
| 388 | anchor.download = props.name.split(/[\\/]/).at(-1) || props.name; |
| 389 | anchor.click(); |
| 390 | })() |
| 391 | .catch((cause: unknown) => |
| 392 | toastManager.add({ |
| 393 | type: "error", |
| 394 | title: gt("Could not save file"), |
| 395 | description: thrownErrorMessage(cause, m) ?? gt("Please try again."), |
| 396 | }), |
| 397 | ) |
| 398 | .finally(() => setSaving(false)); |
| 399 | }} |
| 400 | > |
| 401 | <DownloadIcon className="size-3.5" /> |
| 402 | </FileSurfaceAction> |
| 403 | ); |
| 404 | } |
| 405 | |
| 406 | function WorkspaceVideoPreview(props: { |
| 407 | readonly environmentId: EnvironmentId; |
| 408 | readonly threadRef: ScopedThreadRef; |
| 409 | readonly draft: boolean; |
| 410 | readonly absolutePath: string; |
| 411 | readonly workspaceRoot: string; |
| 412 | readonly name: string; |
| 413 | readonly workspaceMutationId: string | null; |
| 414 | }) { |
| 415 | const resource = workspaceAssetResource({ |
| 416 | kind: "media-file", |
| 417 | threadRef: props.threadRef, |
| 418 | draft: props.draft, |
| 419 | workspaceRoot: props.workspaceRoot, |
| 420 | absolutePath: props.absolutePath, |
| 421 | }); |
| 422 | // Each workspace mutation re-mints the URL, so an edited file loads its new bytes. |
| 423 | const assetUrl = useAssetUrlState( |
| 424 | props.environmentId, |
| 425 | resource, |
| 426 | props.workspaceMutationId ?? undefined, |
| 427 | ); |
| 428 | const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource); |
| 429 | // Servers that report the file's revision let an unchanged file stay loaded; older ones |
| 430 | // only offer the workspace mutation, which changes after every command. The revision also |
| 431 | // goes in the URL, since two mints in the same millisecond sign identical URLs. |
| 432 | const fileRevision = assetUrl._tag === "Success" ? assetUrl.fileRevision : undefined; |
| 433 | const revision = fileRevision ?? props.workspaceMutationId; |
| 434 | const revisionSuffix = |
| 435 | revision === null |
| 436 | ? "" |
| 437 | : `${assetUrl._tag === "Success" && assetUrl.url.includes("?") ? "&" : "?"}${fileRevision !== undefined ? "file" : "workspace"}-revision=${encodeURIComponent(revision)}`; |
| 438 | const latestUrl = assetUrl._tag === "Success" ? `${assetUrl.url}${revisionSuffix}` : null; |
| 439 | |
| 440 | return ( |
| 441 | <div className="flex min-h-0 flex-1 items-center justify-center overflow-hidden p-4"> |
| 442 | <MediaVideoPlayer |
| 443 | src={latestUrl} |
| 444 | sourceFailed={assetUrl._tag === "Failure"} |
| 445 | label={props.name} |
| 446 | revision={revision} |
| 447 | preload="metadata" |
| 448 | className="flex h-full min-h-0 w-full max-w-5xl items-center justify-center" |
| 449 | videoClassName="aspect-auto max-h-full w-auto max-w-full" |
| 450 | onRetry={refreshAssetUrl} |
| 451 | actionsSource={{ |
| 452 | kind: "video", |
| 453 | name: props.name, |
| 454 | src: latestUrl, |
| 455 | reference: mediaFileReference(props.absolutePath, props.workspaceRoot), |
| 456 | asset: { environmentId: props.environmentId, resource }, |
| 457 | }} |
| 458 | /> |
| 459 | </div> |
| 460 | ); |
| 461 | } |
| 462 | |
| 463 | function WorkspaceAudioPreview(props: { |
| 464 | readonly environmentId: EnvironmentId; |
| 465 | readonly threadRef: ScopedThreadRef; |
| 466 | readonly draft: boolean; |
| 467 | readonly absolutePath: string; |
| 468 | readonly workspaceRoot: string; |
| 469 | readonly name: string; |
| 470 | readonly workspaceMutationId: string | null; |
| 471 | }) { |
| 472 | const gt = useGT(); |
| 473 | const resource = workspaceAssetResource({ |
| 474 | kind: "media-file", |
| 475 | threadRef: props.threadRef, |
| 476 | draft: props.draft, |
| 477 | workspaceRoot: props.workspaceRoot, |
| 478 | absolutePath: props.absolutePath, |
| 479 | }); |
| 480 | const assetUrl = useAssetUrlState( |
| 481 | props.environmentId, |
| 482 | resource, |
| 483 | props.workspaceMutationId ?? undefined, |
| 484 | ); |
| 485 | const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource); |
| 486 | const [failedUrl, setFailedUrl] = useState<string | null>(null); |
| 487 | const fileRevision = assetUrl._tag === "Success" ? assetUrl.fileRevision : undefined; |
| 488 | const revision = fileRevision ?? props.workspaceMutationId; |
| 489 | const revisionSuffix = |
| 490 | revision === null |
| 491 | ? "" |
| 492 | : `${assetUrl._tag === "Success" && assetUrl.url.includes("?") ? "&" : "?"}${fileRevision !== undefined ? "file" : "workspace"}-revision=${encodeURIComponent(revision)}`; |
| 493 | const url = assetUrl._tag === "Success" ? `${assetUrl.url}${revisionSuffix}` : null; |
| 494 | if (assetUrl._tag === "Failure" || (url !== null && failedUrl === url)) { |
| 495 | return ( |
| 496 | <FileSurfaceFailure |
| 497 | message={gt("Unable to load audio.")} |
| 498 | onRetry={() => { |
| 499 | setFailedUrl(null); |
| 500 | void refreshAssetUrl().catch(() => undefined); |
| 501 | }} |
| 502 | /> |
| 503 | ); |
| 504 | } |
| 505 | if (url === null) return <FileSurfaceLoading />; |
| 506 | return ( |
| 507 | <AudioPreview |
| 508 | src={url} |
| 509 | name={props.name} |
| 510 | revision={revision} |
| 511 | onError={() => setFailedUrl(url)} |
| 512 | /> |
| 513 | ); |
| 514 | } |
| 515 | |
| 516 | function WorkspaceDocumentPreview(props: { |
| 517 | readonly environmentId: EnvironmentId; |
| 518 | readonly threadRef: ScopedThreadRef; |
| 519 | readonly draft: boolean; |
| 520 | readonly document: boolean; |
| 521 | readonly absolutePath: string; |
| 522 | readonly workspaceRoot: string; |
| 523 | readonly name: string; |
| 524 | readonly workspaceMutationId: string | null; |
| 525 | readonly refreshRevision: number; |
| 526 | }) { |
| 527 | const resource = |
| 528 | props.draft && props.document |
| 529 | ? { |
| 530 | _tag: "draft-workspace-file" as const, |
| 531 | cwd: props.workspaceRoot, |
| 532 | path: props.absolutePath, |
| 533 | } |
| 534 | : { |
| 535 | _tag: "media-file" as const, |
| 536 | threadId: props.threadRef.threadId, |
| 537 | path: props.absolutePath, |
| 538 | ...(props.document ? {} : { disposition: "attachment" as const }), |
| 539 | }; |
| 540 | const gt = useGT(); |
| 541 | // Drafts keep reloading on every workspace mutation, as before. |
| 542 | const revisioned = resource._tag === "media-file"; |
| 543 | const assetUrl = useAssetUrlState( |
| 544 | props.environmentId, |
| 545 | revisioned ? resource : null, |
| 546 | props.workspaceMutationId ?? undefined, |
| 547 | ); |
| 548 | const resolved = |
| 549 | assetUrl._tag === "Success" ? (assetUrl.fileRevision ?? props.workspaceMutationId) : undefined; |
| 550 | // A reconnect reports Loading and keeps the last revision, so the open file stays loaded; |
| 551 | // a failure (say the file was deleted) remounts so the preview shows its error. |
| 552 | const [shown, setShown] = useState(resolved); |
| 553 | if (resolved !== undefined && resolved !== shown) setShown(resolved); |
| 554 | const revision = !revisioned |
| 555 | ? props.workspaceMutationId |
| 556 | : assetUrl._tag === "Failure" |
| 557 | ? `failure:${props.workspaceMutationId}` |
| 558 | : (resolved ?? shown); |
| 559 | // Waiting on the first revision keeps the preview from mounting twice when it opens. |
| 560 | if (revisioned && revision === undefined && assetUrl._tag === "Loading") { |
| 561 | return <FileSurfaceLoading />; |
| 562 | } |
| 563 | return ( |
| 564 | <AttachmentFilePreview |
| 565 | key={`${revision}:${props.refreshRevision}`} |
| 566 | name={props.name} |
| 567 | mimeType="application/octet-stream" |
| 568 | sizeBytes={0} |
| 569 | asset={{ environmentId: props.environmentId, resource }} |
| 570 | origin={gt("File", { $context: "label for a file opened from the workspace" })} |
| 571 | /> |
| 572 | ); |
| 573 | } |
| 574 | |
| 575 | function clampFileLine(contents: string, requestedLine: number): number { |
| 576 | let lineCount = 1; |
| 577 | for (let index = 0; index < contents.length; index += 1) { |
| 578 | const character = contents.charCodeAt(index); |
| 579 | if (character === 10) { |
| 580 | lineCount += 1; |
| 581 | } else if (character === 13) { |
| 582 | lineCount += 1; |
| 583 | if (contents.charCodeAt(index + 1) === 10) index += 1; |
| 584 | } |
| 585 | } |
| 586 | return Math.min(Math.max(1, requestedLine), lineCount); |
| 587 | } |
| 588 | |
| 589 | function updateFileLinkReveal(fileContainer: HTMLElement, line: number | null): void { |
| 590 | const root = fileContainer.shadowRoot ?? fileContainer; |
| 591 | for (const element of root.querySelectorAll<HTMLElement>(`[${FILE_LINK_REVEAL_ATTRIBUTE}]`)) { |
| 592 | element.removeAttribute(FILE_LINK_REVEAL_ATTRIBUTE); |
| 593 | } |
| 594 | if (line === null) return; |
| 595 | |
| 596 | root |
| 597 | .querySelector<HTMLElement>(`[data-line="${line}"]`) |
| 598 | ?.setAttribute(FILE_LINK_REVEAL_ATTRIBUTE, ""); |
| 599 | root |
| 600 | .querySelector<HTMLElement>(`[data-column-number="${line}"]`) |
| 601 | ?.setAttribute(FILE_LINK_REVEAL_ATTRIBUTE, ""); |
| 602 | } |
| 603 | |
| 604 | const REVEAL_MAX_ATTEMPTS = 30; |
| 605 | /** Hold the reveal target against late focus/restoration scroll resets. */ |
| 606 | const REVEAL_GUARD_FRAMES = 20; |
| 607 | const REVEAL_GUARD_TOLERANCE_PX = 2; |
| 608 | |
| 609 | interface FileRevealState { |
| 610 | frameId: number | null; |
| 611 | cancelGuard: (() => void) | null; |
| 612 | handledRequestId: number | null; |
| 613 | latestRequestId: number | null; |
| 614 | /** The path's code view offset when it last unmounted, restored when it is shown again. */ |
| 615 | scrollTop: number; |
| 616 | scrollContainer: HTMLElement | null; |
| 617 | restoreFrameId: number | null; |
| 618 | } |
| 619 | |
| 620 | function useFileLineReveal( |
| 621 | relativePath: string | null, |
| 622 | revealLine: number | null, |
| 623 | revealRequestId: number, |
| 624 | ): FilePostRender { |
| 625 | const [revealStatesByPath] = useState(() => new Map<string, FileRevealState>()); |
| 626 | |
| 627 | return (fileContainer, instance, phase) => { |
| 628 | if (relativePath === null) return; |
| 629 | |
| 630 | const existingState = revealStatesByPath.get(relativePath); |
| 631 | const state: FileRevealState = existingState ?? { |
| 632 | frameId: null, |
| 633 | cancelGuard: null, |
| 634 | handledRequestId: null, |
| 635 | latestRequestId: null, |
| 636 | scrollTop: 0, |
| 637 | scrollContainer: null, |
| 638 | restoreFrameId: null, |
| 639 | }; |
| 640 | if (!existingState) revealStatesByPath.set(relativePath, state); |
| 641 | |
| 642 | const cancelPendingReveal = () => { |
| 643 | if (state.frameId !== null) { |
| 644 | cancelAnimationFrame(state.frameId); |
| 645 | state.frameId = null; |
| 646 | } |
| 647 | state.cancelGuard?.(); |
| 648 | if (state.restoreFrameId !== null) { |
| 649 | cancelAnimationFrame(state.restoreFrameId); |
| 650 | state.restoreFrameId = null; |
| 651 | } |
| 652 | }; |
| 653 | |
| 654 | const scrollContainer = fileContainer.closest<HTMLElement>(".file-preview-virtualizer"); |
| 655 | |
| 656 | if (phase === "unmount") { |
| 657 | // A view torn down before its restore ran never showed the saved offset, so keep it. |
| 658 | const restorePending = state.restoreFrameId !== null; |
| 659 | cancelPendingReveal(); |
| 660 | if (scrollContainer && !restorePending) state.scrollTop = scrollContainer.scrollTop; |
| 661 | state.scrollContainer = null; |
| 662 | return; |
| 663 | } |
| 664 | |
| 665 | const contents = instance.file?.contents; |
| 666 | const targetLine = |
| 667 | revealLine === null || contents === undefined ? null : clampFileLine(contents, revealLine); |
| 668 | updateFileLinkReveal(fileContainer, targetLine); |
| 669 | |
| 670 | if (!(instance instanceof VirtualizedFile)) return; |
| 671 | |
| 672 | if (state.latestRequestId !== revealRequestId) { |
| 673 | cancelPendingReveal(); |
| 674 | state.latestRequestId = revealRequestId; |
| 675 | state.handledRequestId = null; |
| 676 | } |
| 677 | |
| 678 | if (scrollContainer && state.scrollContainer !== scrollContainer) { |
| 679 | state.scrollContainer = scrollContainer; |
| 680 | const savedScrollTop = state.scrollTop; |
| 681 | // A pending line reveal owns the scroll position. |
| 682 | if ( |
| 683 | savedScrollTop > 0 && |
| 684 | (revealLine === null || state.handledRequestId === revealRequestId) |
| 685 | ) { |
| 686 | const restoreScroll = (attempt: number) => { |
| 687 | state.restoreFrameId = requestAnimationFrame(() => { |
| 688 | state.restoreFrameId = null; |
| 689 | if (!scrollContainer.isConnected || scrollContainer.scrollTop !== 0) return; |
| 690 | // Wait for the virtualizer to size the file so the offset is not clamped. |
| 691 | const fits = |
| 692 | scrollContainer.scrollHeight - scrollContainer.clientHeight >= savedScrollTop; |
| 693 | if (fits || attempt >= REVEAL_MAX_ATTEMPTS) { |
| 694 | scrollContainer.scrollTop = savedScrollTop; |
| 695 | return; |
| 696 | } |
| 697 | restoreScroll(attempt + 1); |
| 698 | }); |
| 699 | }; |
| 700 | restoreScroll(0); |
| 701 | } |
| 702 | } |
| 703 | |
| 704 | if (revealLine === null) { |
| 705 | fileContainer.style.minHeight = ""; |
| 706 | return; |
| 707 | } |
| 708 | |
| 709 | if (!scrollContainer) return; |
| 710 | fileContainer.style.minHeight = `${Math.ceil( |
| 711 | Math.max(instance.height, scrollContainer.clientHeight), |
| 712 | )}px`; |
| 713 | |
| 714 | if (state.handledRequestId === revealRequestId || state.frameId !== null) { |
| 715 | return; |
| 716 | } |
| 717 | |
| 718 | const resolveScrollTarget = (line: number): number | null => { |
| 719 | const linePosition = instance.getLinePosition(line); |
| 720 | if (!linePosition) return null; |
| 721 | |
| 722 | const scrollContainerRect = scrollContainer.getBoundingClientRect(); |
| 723 | const fileTop = |
| 724 | scrollContainer.scrollTop + |
| 725 | fileContainer.getBoundingClientRect().top - |
| 726 | scrollContainerRect.top; |
| 727 | const root = fileContainer.shadowRoot ?? fileContainer; |
| 728 | const renderedLineElement = root.querySelector<HTMLElement>(`[data-line="${line}"]`); |
| 729 | const renderedLineRect = renderedLineElement?.getBoundingClientRect(); |
| 730 | |
| 731 | return resolveCenteredFileLineScrollTop({ |
| 732 | scrollTop: scrollContainer.scrollTop, |
| 733 | scrollHeight: scrollContainer.scrollHeight, |
| 734 | viewportTop: scrollContainerRect.top, |
| 735 | viewportHeight: scrollContainer.clientHeight, |
| 736 | fileTop, |
| 737 | estimatedLine: linePosition, |
| 738 | ...(renderedLineRect && renderedLineRect.height > 0 |
| 739 | ? { |
| 740 | renderedLine: { |
| 741 | top: renderedLineRect.top, |
| 742 | height: renderedLineRect.height, |
| 743 | }, |
| 744 | } |
| 745 | : {}), |
| 746 | }); |
| 747 | }; |
| 748 | |
| 749 | const guardScrollTarget = (line: number) => { |
| 750 | let framesLeft = REVEAL_GUARD_FRAMES; |
| 751 | let guardFrameId: number | null = null; |
| 752 | const cancelGuard = () => { |
| 753 | if (guardFrameId !== null) { |
| 754 | cancelAnimationFrame(guardFrameId); |
| 755 | guardFrameId = null; |
| 756 | } |
| 757 | scrollContainer.removeEventListener("wheel", cancelGuard); |
| 758 | scrollContainer.removeEventListener("touchstart", cancelGuard); |
| 759 | scrollContainer.removeEventListener("pointerdown", cancelGuard, true); |
| 760 | window.removeEventListener("keydown", cancelGuard, true); |
| 761 | if (state.cancelGuard === cancelGuard) state.cancelGuard = null; |
| 762 | }; |
| 763 | scrollContainer.addEventListener("wheel", cancelGuard, { passive: true }); |
| 764 | scrollContainer.addEventListener("touchstart", cancelGuard, { passive: true }); |
| 765 | // Capture gutter pointer events before Pierre stops propagation so comments can cancel the reveal |
| 766 | // guard. |
| 767 | scrollContainer.addEventListener("pointerdown", cancelGuard, { |
| 768 | passive: true, |
| 769 | capture: true, |
| 770 | }); |
| 771 | window.addEventListener("keydown", cancelGuard, true); |
| 772 | const holdTarget = () => { |
| 773 | guardFrameId = null; |
| 774 | framesLeft -= 1; |
| 775 | if (framesLeft <= 0 || !scrollContainer.isConnected) { |
| 776 | cancelGuard(); |
| 777 | return; |
| 778 | } |
| 779 | const targetTop = resolveScrollTarget(line); |
| 780 | if ( |
| 781 | targetTop !== null && |
| 782 | Math.abs(scrollContainer.scrollTop - targetTop) > REVEAL_GUARD_TOLERANCE_PX |
| 783 | ) { |
| 784 | scrollContainer.scrollTop = targetTop; |
| 785 | } |
| 786 | guardFrameId = requestAnimationFrame(holdTarget); |
| 787 | }; |
| 788 | guardFrameId = requestAnimationFrame(holdTarget); |
| 789 | state.cancelGuard = cancelGuard; |
| 790 | }; |
| 791 | |
| 792 | const scheduleReveal = (attempt: number) => { |
| 793 | state.frameId = requestAnimationFrame(() => { |
| 794 | state.frameId = null; |
| 795 | if (state.latestRequestId !== revealRequestId || !fileContainer.isConnected) { |
| 796 | return; |
| 797 | } |
| 798 | |
| 799 | // Wait for contents and metrics; missing data would clamp fresh-mount reveals to line 1 and mark them |
| 800 | // handled. |
| 801 | const currentContents = instance.file?.contents; |
| 802 | const line = |
| 803 | currentContents === undefined ? null : clampFileLine(currentContents, revealLine); |
| 804 | const targetTop = line === null ? null : resolveScrollTarget(line); |
| 805 | if (line === null || targetTop === null) { |
| 806 | if (attempt < REVEAL_MAX_ATTEMPTS) scheduleReveal(attempt + 1); |
| 807 | return; |
| 808 | } |
| 809 | updateFileLinkReveal(fileContainer, line); |
| 810 | |
| 811 | scrollContainer.scrollTop = targetTop; |
| 812 | state.handledRequestId = revealRequestId; |
| 813 | guardScrollTarget(line); |
| 814 | }); |
| 815 | }; |
| 816 | |
| 817 | scheduleReveal(0); |
| 818 | }; |
| 819 | } |
| 820 | |
| 821 | const EMPTY_REVIEW_COMMENTS: ReadonlyArray<ReviewCommentContext> = []; |
| 822 | |
| 823 | const createFileEditor: EditorFactory<FileCommentAnnotationGroup, undefined> = ( |
| 824 | editorType, |
| 825 | options, |
| 826 | editStateKey, |
| 827 | ) => new Editor(editorType, options, editStateKey); |
| 828 | type FileEditor = Editor<"file", FileCommentAnnotationGroup, undefined>; |
| 829 | |
| 830 | function editableFileContents( |
| 831 | environmentId: EnvironmentId, |
| 832 | cwd: string, |
| 833 | relativePath: string, |
| 834 | contents: string, |
| 835 | ): FileContents { |
| 836 | return { |
| 837 | name: relativePath, |
| 838 | contents, |
| 839 | cacheKey: `editor:${environmentId}:${projectFileCacheKey(cwd, relativePath, contents)}`, |
| 840 | }; |
| 841 | } |
| 842 | |
| 843 | function needsWorkerHighlight(workerPool: WorkerPoolManager | undefined, file: FileContents) { |
| 844 | if (workerPool?.isWorkingPool() !== true) return false; |
| 845 | if ((file.lang ?? getFiletypeFromFileName(file.name)) === "text") return false; |
| 846 | let lines = 1; |
| 847 | for ( |
| 848 | let index = file.contents.indexOf("\n"); |
| 849 | index !== -1; |
| 850 | index = file.contents.indexOf("\n", index + 1) |
| 851 | ) { |
| 852 | lines += 1; |
| 853 | } |
| 854 | return lines <= DEFAULT_TOKENIZE_MAX_LENGTH; |
| 855 | } |
| 856 | |
| 857 | /** Enable editing only after worker highlighting renders; active edit sessions highlight on the main |
| 858 | * thread. */ |
| 859 | function useEditableAfterHighlight(file: FileContents) { |
| 860 | const workerPool = useWorkerPool(); |
| 861 | const [highlightedFile, setHighlightedFile] = useState<FileContents | null>(null); |
| 862 | const needsHighlight = needsWorkerHighlight(workerPool, file); |
| 863 | const ready = !needsHighlight || highlightedFile === file; |
| 864 | |
| 865 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- primes the worker pool's highlight cache for this file and falls back to plain text if it fails |
| 866 | useEffect(() => { |
| 867 | if (ready || workerPool === undefined) return; |
| 868 | workerPool.primeFileHighlightCache(file).catch(() => setHighlightedFile(file)); |
| 869 | }, [file, ready, workerPool]); |
| 870 | |
| 871 | const onPostRender = (renderedFile: FileContents | undefined, phase: PostRenderPhase) => { |
| 872 | if (ready || phase === "unmount" || renderedFile?.cacheKey !== file.cacheKey) return; |
| 873 | // Cache results arrive just before instance rendering; seeing the cache during render means rows are |
| 874 | // highlighted. |
| 875 | if (workerPool?.getFileResultCache(file) !== undefined) setHighlightedFile(file); |
| 876 | }; |
| 877 | return { ready, onPostRender }; |
| 878 | } |
| 879 | |
| 880 | interface EditableFileSurfaceProps { |
| 881 | environmentId: EnvironmentId; |
| 882 | projectId?: ProjectId | undefined; |
| 883 | cwd: string; |
| 884 | relativePath: string; |
| 885 | composerDraftTarget: ScopedThreadRef | DraftId; |
| 886 | contents: string; |
| 887 | resolvedTheme: "light" | "dark"; |
| 888 | revealRequestId: number; |
| 889 | wordWrap: boolean; |
| 890 | onPostRender: FilePostRender; |
| 891 | onPendingChange: (relativePath: string, pending: boolean) => void; |
| 892 | onEditorChange: (editor: FileEditor | null) => void; |
| 893 | } |
| 894 | |
| 895 | interface FileSelectionOverride { |
| 896 | revealRequestId: number; |
| 897 | range: SelectedLineRange | null; |
| 898 | } |
| 899 | |
| 900 | function EditableFileSurface({ |
| 901 | environmentId, |
| 902 | projectId, |
| 903 | cwd, |
| 904 | relativePath, |
| 905 | composerDraftTarget, |
| 906 | contents, |
| 907 | resolvedTheme, |
| 908 | revealRequestId, |
| 909 | wordWrap, |
| 910 | onPostRender, |
| 911 | onPendingChange, |
| 912 | onEditorChange, |
| 913 | }: EditableFileSurfaceProps) { |
| 914 | const messages = useMessages(); |
| 915 | const addReviewComment = useComposerDraftStore((store) => store.addReviewComment); |
| 916 | const removeReviewComment = useComposerDraftStore((store) => store.removeReviewComment); |
| 917 | const promptCommentIds = new Set( |
| 918 | useComposerDraftStore( |
| 919 | (store) => |
| 920 | store.getComposerDraft(composerDraftTarget)?.reviewComments ?? EMPTY_REVIEW_COMMENTS, |
| 921 | ).map((comment) => comment.id), |
| 922 | ); |
| 923 | const [lineAnnotations, setLineAnnotations] = useState<FileCommentLineAnnotation[]>([]); |
| 924 | const [selectionOverride, setSelectionOverride] = useState<FileSelectionOverride | null>(null); |
| 925 | const selectedRange = |
| 926 | selectionOverride?.revealRequestId === revealRequestId ? selectionOverride.range : null; |
| 927 | const setSelectedRange = (range: SelectedLineRange | null) => { |
| 928 | setSelectionOverride({ revealRequestId, range }); |
| 929 | }; |
| 930 | const surfaceRef = useRef<HTMLDivElement>(null); |
| 931 | const selectionFrameRef = useRef<number | null>(null); |
| 932 | const saveTarget = { environmentId, cwd, relativePath }; |
| 933 | useFileSaveSession(saveTarget, onPendingChange); |
| 934 | // Retain file identity for echoed editor changes; only external changes replace the editor's draft. |
| 935 | const [externalFile, setExternalFile] = useState(() => |
| 936 | editableFileContents(environmentId, cwd, relativePath, contents), |
| 937 | ); |
| 938 | const [editedContents, setEditedContents] = useState<string | null>(null); |
| 939 | if (contents !== (editedContents ?? externalFile.contents)) { |
| 940 | setExternalFile(editableFileContents(environmentId, cwd, relativePath, contents)); |
| 941 | setEditedContents(null); |
| 942 | } |
| 943 | const { ready: editable, onPostRender: onEditablePostRender } = |
| 944 | useEditableAfterHighlight(externalFile); |
| 945 | const editorRef = useRef<FileEditor | null>(null); |
| 946 | const editorOptions: EditorOptions<"file", FileCommentAnnotationGroup, undefined> = { |
| 947 | onAttach: (editor) => { |
| 948 | editorRef.current = editor; |
| 949 | onEditorChange(editor); |
| 950 | }, |
| 951 | onComplete: () => { |
| 952 | editorRef.current = null; |
| 953 | onEditorChange(null); |
| 954 | }, |
| 955 | }; |
| 956 | |
| 957 | const handleEditChange = ({ |
| 958 | file, |
| 959 | lineAnnotations: nextLineAnnotations, |
| 960 | }: EditorChangeEvent<"file", FileCommentAnnotationGroup, undefined>) => { |
| 961 | if (file.contents === getProjectFileContents(environmentId, cwd, relativePath)) return; |
| 962 | setEditedContents(file.contents); |
| 963 | setProjectFileQueryData(environmentId, cwd, relativePath, file.contents); |
| 964 | changeFileSaveSession(saveTarget, file.contents); |
| 965 | if (!nextLineAnnotations) return; |
| 966 | const remapped = remapFileCommentAnnotations(nextLineAnnotations); |
| 967 | // The editor hands back the array it was given until an edit moves an annotation. |
| 968 | setLineAnnotations((current) => (current === nextLineAnnotations ? current : remapped)); |
| 969 | for (const annotation of remapped) { |
| 970 | for (const entry of annotation.metadata.entries) { |
| 971 | if (entry.kind !== "comment" || !promptCommentIds.has(entry.id)) continue; |
| 972 | addReviewComment( |
| 973 | composerDraftTarget, |
| 974 | buildFileReviewComment({ |
| 975 | id: entry.id, |
| 976 | filePath: relativePath, |
| 977 | startLine: entry.startLine, |
| 978 | endLine: entry.endLine, |
| 979 | text: entry.text, |
| 980 | contents: file.contents, |
| 981 | }), |
| 982 | ); |
| 983 | } |
| 984 | } |
| 985 | }; |
| 986 | |
| 987 | const removeAnnotationEntry = (entryId: string) => { |
| 988 | setSelectedRange(null); |
| 989 | removeReviewComment(composerDraftTarget, entryId); |
| 990 | setLineAnnotations((current) => { |
| 991 | return current.flatMap((annotation) => { |
| 992 | const entries = annotation.metadata.entries.filter((entry) => entry.id !== entryId); |
| 993 | return entries.length > 0 ? [{ ...annotation, metadata: { entries } }] : []; |
| 994 | }); |
| 995 | }); |
| 996 | }; |
| 997 | |
| 998 | const submitAnnotationEntry = (entryId: string, text: string) => { |
| 999 | setSelectedRange(null); |
| 1000 | const entry = lineAnnotations |
| 1001 | .flatMap((annotation) => annotation.metadata.entries) |
| 1002 | .find((candidate) => candidate.id === entryId); |
| 1003 | if (entry) { |
| 1004 | addReviewComment( |
| 1005 | composerDraftTarget, |
| 1006 | buildFileReviewComment({ |
| 1007 | id: entry.id, |
| 1008 | filePath: relativePath, |
| 1009 | startLine: entry.startLine, |
| 1010 | endLine: entry.endLine, |
| 1011 | text, |
| 1012 | contents, |
| 1013 | }), |
| 1014 | ); |
| 1015 | } |
| 1016 | setLineAnnotations((current) => |
| 1017 | current.map((annotation) => ({ |
| 1018 | ...annotation, |
| 1019 | metadata: { |
| 1020 | entries: annotation.metadata.entries.map((annotationEntry) => |
| 1021 | annotationEntry.id === entryId |
| 1022 | ? { ...annotationEntry, kind: "comment", text } |
| 1023 | : annotationEntry, |
| 1024 | ), |
| 1025 | }, |
| 1026 | })), |
| 1027 | ); |
| 1028 | }; |
| 1029 | |
| 1030 | const beginComment = (range: SelectedLineRange) => { |
| 1031 | editorRef.current?.setSelections([]); |
| 1032 | editorRef.current?.blur(); |
| 1033 | const { startLine, endLine } = normalizeFileCommentRange(range); |
| 1034 | const draftEntry: FileCommentAnnotationEntry = { |
| 1035 | id: nextFileCommentId(), |
| 1036 | kind: "draft", |
| 1037 | startLine, |
| 1038 | endLine, |
| 1039 | text: "", |
| 1040 | }; |
| 1041 | setLineAnnotations((current) => { |
| 1042 | const withoutDraft = current.flatMap((annotation) => { |
| 1043 | const entries = annotation.metadata.entries.filter((entry) => entry.kind !== "draft"); |
| 1044 | return entries.length > 0 ? [{ ...annotation, metadata: { entries } }] : []; |
| 1045 | }); |
| 1046 | const existingIndex = withoutDraft.findIndex( |
| 1047 | (annotation) => annotation.lineNumber === endLine, |
| 1048 | ); |
| 1049 | if (existingIndex < 0) { |
| 1050 | return [ |
| 1051 | ...withoutDraft, |
| 1052 | { |
| 1053 | lineNumber: endLine, |
| 1054 | metadata: { entries: [draftEntry] }, |
| 1055 | }, |
| 1056 | ]; |
| 1057 | } |
| 1058 | return withoutDraft.map((annotation, index) => |
| 1059 | index === existingIndex |
| 1060 | ? { |
| 1061 | ...annotation, |
| 1062 | metadata: { entries: [...annotation.metadata.entries, draftEntry] }, |
| 1063 | } |
| 1064 | : annotation, |
| 1065 | ); |
| 1066 | }); |
| 1067 | }; |
| 1068 | const hasOpenCommentForm = lineAnnotations.some((annotation) => |
| 1069 | annotation.metadata.entries.some((entry) => entry.kind === "draft"), |
| 1070 | ); |
| 1071 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- installs selection dismissal listeners on the editor surface DOM node |
| 1072 | useEffect(() => { |
| 1073 | const root = surfaceRef.current; |
| 1074 | if (!root) return; |
| 1075 | return installFileEditorDismissal({ |
| 1076 | root, |
| 1077 | editor: { setSelections: (selections) => editorRef.current?.setSelections(selections) }, |
| 1078 | isBlocked: () => hasOpenCommentForm, |
| 1079 | onDismiss: () => setSelectedRange(null), |
| 1080 | }); |
| 1081 | }, [hasOpenCommentForm, setSelectedRange]); |
| 1082 | const handleLineSelectionEnd = (range: SelectedLineRange | null) => { |
| 1083 | setSelectedRange(range); |
| 1084 | if (range) { |
| 1085 | beginComment(range); |
| 1086 | } |
| 1087 | }; |
| 1088 | |
| 1089 | const handlePostRender: FilePostRender = (fileContainer, instance, phase) => { |
| 1090 | onPostRender(fileContainer, instance, phase); |
| 1091 | onEditablePostRender(instance.file, phase); |
| 1092 | |
| 1093 | if (selectionFrameRef.current !== null) { |
| 1094 | cancelAnimationFrame(selectionFrameRef.current); |
| 1095 | selectionFrameRef.current = null; |
| 1096 | } |
| 1097 | if (phase === "unmount") return; |
| 1098 | |
| 1099 | selectionFrameRef.current = requestAnimationFrame(() => { |
| 1100 | selectionFrameRef.current = null; |
| 1101 | if (!fileContainer.isConnected) return; |
| 1102 | instance.setSelectedLines(selectedRange, { notify: false }); |
| 1103 | }); |
| 1104 | }; |
| 1105 | |
| 1106 | return ( |
| 1107 | <EditProvider createEditor={createFileEditor}> |
| 1108 | <div ref={surfaceRef} className="flex min-h-0 flex-1"> |
| 1109 | <Virtualizer |
| 1110 | className="file-preview-virtualizer min-h-0 flex-1 overflow-auto" |
| 1111 | config={{ |
| 1112 | overscrollSize: 600, |
| 1113 | intersectionObserverMargin: 1200, |
| 1114 | }} |
| 1115 | > |
| 1116 | <File<FileCommentAnnotationGroup> |
| 1117 | file={externalFile} |
| 1118 | edit={editable} |
| 1119 | editorOptions={editorOptions} |
| 1120 | onEditChange={handleEditChange} |
| 1121 | options={{ |
| 1122 | disableFileHeader: true, |
| 1123 | enableGutterUtility: !hasOpenCommentForm, |
| 1124 | enableLineSelection: !hasOpenCommentForm, |
| 1125 | onGutterUtilityClick: setSelectedRange, |
| 1126 | onLineSelectionChange: setSelectedRange, |
| 1127 | onLineSelectionEnd: handleLineSelectionEnd, |
| 1128 | overflow: wordWrap ? "wrap" : "scroll", |
| 1129 | theme: resolveDiffThemeName(resolvedTheme), |
| 1130 | preferredHighlighter: PREFERRED_HIGHLIGHTER, |
| 1131 | themeType: resolvedTheme, |
| 1132 | unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS, |
| 1133 | onPostRender: handlePostRender, |
| 1134 | }} |
| 1135 | selectedLines={selectedRange} |
| 1136 | lineAnnotations={lineAnnotations} |
| 1137 | renderAnnotation={(annotation) => { |
| 1138 | // Sent comments stay annotated so a failed send can restore them at remapped lines. |
| 1139 | const entries = promptFileCommentEntries( |
| 1140 | annotation.metadata.entries, |
| 1141 | promptCommentIds, |
| 1142 | ); |
| 1143 | if (entries.length === 0) return null; |
| 1144 | return ( |
| 1145 | <div className="py-1"> |
| 1146 | {entries.map((entry) => ( |
| 1147 | <DiffCommentAnnotation |
| 1148 | key={entry.id} |
| 1149 | environmentId={environmentId} |
| 1150 | projectId={projectId} |
| 1151 | ownerKey={JSON.stringify([ |
| 1152 | environmentId, |
| 1153 | composerDraftTarget, |
| 1154 | relativePath, |
| 1155 | entry.id, |
| 1156 | ])} |
| 1157 | kind={entry.kind} |
| 1158 | rangeLabel={formatFileCommentRange(entry.startLine, entry.endLine, messages)} |
| 1159 | text={entry.text} |
| 1160 | onCancel={() => removeAnnotationEntry(entry.id)} |
| 1161 | onComment={(text) => submitAnnotationEntry(entry.id, text)} |
| 1162 | onDelete={() => removeAnnotationEntry(entry.id)} |
| 1163 | /> |
| 1164 | ))} |
| 1165 | </div> |
| 1166 | ); |
| 1167 | }} |
| 1168 | className="min-h-full" |
| 1169 | /> |
| 1170 | </Virtualizer> |
| 1171 | </div> |
| 1172 | </EditProvider> |
| 1173 | ); |
| 1174 | } |
| 1175 | |
| 1176 | function selectRenderedContentOnSelectAll(event: ReactKeyboardEvent<HTMLElement>) { |
| 1177 | const mac = isMacPlatform(navigator.platform); |
| 1178 | const selectAll = |
| 1179 | event.key.toLowerCase() === "a" && |
| 1180 | (mac ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey) && |
| 1181 | !event.shiftKey && |
| 1182 | !event.altKey; |
| 1183 | // React bubbles keys from portaled children (the image dialog) through this surface. |
| 1184 | if ( |
| 1185 | !selectAll || |
| 1186 | !(event.target instanceof Node) || |
| 1187 | !event.currentTarget.contains(event.target) |
| 1188 | ) { |
| 1189 | return; |
| 1190 | } |
| 1191 | event.preventDefault(); |
| 1192 | window.getSelection()?.selectAllChildren(event.currentTarget); |
| 1193 | } |
| 1194 | |
| 1195 | function RenderedMarkdownSurface({ |
| 1196 | environmentId, |
| 1197 | cwd, |
| 1198 | relativePath, |
| 1199 | contents, |
| 1200 | threadRef, |
| 1201 | workspaceMutationId, |
| 1202 | readOnly, |
| 1203 | onPendingChange, |
| 1204 | }: Omit< |
| 1205 | EditableFileSurfaceProps, |
| 1206 | | "resolvedTheme" |
| 1207 | | "composerDraftTarget" |
| 1208 | | "revealLine" |
| 1209 | | "revealRequestId" |
| 1210 | | "wordWrap" |
| 1211 | | "onPostRender" |
| 1212 | | "onEditorChange" |
| 1213 | > & { |
| 1214 | threadRef: ScopedThreadRef; |
| 1215 | readOnly: boolean; |
| 1216 | workspaceMutationId: string | null; |
| 1217 | }) { |
| 1218 | const saveTarget = { environmentId, cwd, relativePath }; |
| 1219 | useFileSaveSession(saveTarget, onPendingChange); |
| 1220 | |
| 1221 | return ( |
| 1222 | <ScrollArea className="min-h-0 flex-1" onKeyDown={selectRenderedContentOnSelectAll}> |
| 1223 | <FileMarkdownPreview |
| 1224 | text={contents} |
| 1225 | cwd={cwd} |
| 1226 | relativePath={relativePath} |
| 1227 | threadRef={threadRef} |
| 1228 | workspaceMutationId={workspaceMutationId} |
| 1229 | onTaskListChange={ |
| 1230 | readOnly |
| 1231 | ? undefined |
| 1232 | : ({ markerOffset, checked }) => { |
| 1233 | const currentContents = |
| 1234 | getOptimisticProjectFileQueryData(environmentId, cwd, relativePath)?.contents ?? |
| 1235 | contents; |
| 1236 | const nextContents = setMarkdownTaskChecked(currentContents, markerOffset, checked); |
| 1237 | if (nextContents === currentContents) return; |
| 1238 | setProjectFileQueryData(environmentId, cwd, relativePath, nextContents); |
| 1239 | changeFileSaveSession(saveTarget, nextContents); |
| 1240 | } |
| 1241 | } |
| 1242 | /> |
| 1243 | </ScrollArea> |
| 1244 | ); |
| 1245 | } |
| 1246 | |
| 1247 | function renderedToggleLabel( |
| 1248 | mode: "markdown" | "mermaid" | "html" | "table", |
| 1249 | rendered: boolean, |
| 1250 | resolve: MessageResolver, |
| 1251 | ): string { |
| 1252 | if (mode === "mermaid") |
| 1253 | return rendered ? resolve(msg("Show Mermaid source")) : resolve(msg("Show rendered diagram")); |
| 1254 | if (mode === "markdown") |
| 1255 | return rendered ? resolve(msg("Show markdown source")) : resolve(msg("Show rendered markdown")); |
| 1256 | if (mode === "table") return rendered ? resolve(msg("Show source")) : resolve(msg("Show table")); |
| 1257 | return rendered ? resolve(msg("Show HTML source")) : resolve(msg("Show rendered page")); |
| 1258 | } |
| 1259 | |
| 1260 | function initialExplorerOpen(): boolean { |
| 1261 | try { |
| 1262 | return getLocalStorageItem(FILE_EXPLORER_STORAGE_KEY, Schema.Boolean) ?? true; |
| 1263 | } catch (error) { |
| 1264 | console.error(error); |
| 1265 | return true; |
| 1266 | } |
| 1267 | } |
| 1268 | |
| 1269 | export default function FilePreviewPanel({ |
| 1270 | environmentId, |
| 1271 | cwd, |
| 1272 | projectName, |
| 1273 | projectId, |
| 1274 | relativePath: requestedPath, |
| 1275 | attachment, |
| 1276 | threadRef, |
| 1277 | composerDraftTarget, |
| 1278 | keybindings, |
| 1279 | availableEditors, |
| 1280 | openInShortcutEnabled, |
| 1281 | revealLine, |
| 1282 | revealRequestId, |
| 1283 | onOpenFile, |
| 1284 | onNavigateFolder, |
| 1285 | folderTrail, |
| 1286 | onPendingChange, |
| 1287 | selectedFilePending, |
| 1288 | workspaceMutationId, |
| 1289 | }: FilePreviewPanelProps) { |
| 1290 | const relativePath = |
| 1291 | attachment === undefined ? resolveFilePreviewPath(requestedPath, cwd) : requestedPath; |
| 1292 | const draft = typeof composerDraftTarget === "string"; |
| 1293 | const gt = useGT(); |
| 1294 | const m = useMessages(); |
| 1295 | const { resolvedTheme } = useTheme(); |
| 1296 | const defaultWordWrap = useClientSettings((settings) => settings.wordWrap); |
| 1297 | const [wordWrapOverride, setWordWrapOverride] = useState<boolean | null>(null); |
| 1298 | const wordWrap = wordWrapOverride ?? defaultWordWrap; |
| 1299 | const canOperatePreview = useEnvironmentScope(environmentId, AuthPreviewOperateScope); |
| 1300 | const primaryEnvironmentId = usePrimaryEnvironmentId(); |
| 1301 | const hostEnvironmentId = useAtomValue(hostEnvironmentIdAtom); |
| 1302 | const remoteOpenState = useRemoteOpenState(environmentId); |
| 1303 | const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId)); |
| 1304 | const environmentHttpBaseUrl = useEnvironmentHttpBaseUrl(environmentId); |
| 1305 | const previewAvailable = usePreviewAvailable(environmentId); |
| 1306 | const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, { |
| 1307 | reportFailure: false, |
| 1308 | refresh: true, |
| 1309 | }); |
| 1310 | const openPreview = useAtomCommand(previewEnvironment.open, { |
| 1311 | reportFailure: false, |
| 1312 | }); |
| 1313 | const isVideo = relativePath !== null && isWorkspaceVideoPreviewPath(relativePath); |
| 1314 | const isAudio = relativePath !== null && !isVideo && isWorkspaceAudioPreviewPath(relativePath); |
| 1315 | const isImage = relativePath !== null && !isVideo && isWorkspaceImagePreviewPath(relativePath); |
| 1316 | const isMedia = isImage || isVideo || isAudio; |
| 1317 | const isPdf = relativePath !== null && isPdfPreviewFile(relativePath); |
| 1318 | const isDocument = |
| 1319 | relativePath !== null && |
| 1320 | (binaryPreviewKind({ name: relativePath }) !== null || |
| 1321 | officePreviewKind({ name: relativePath }) !== null || |
| 1322 | isWorkspaceFontPreviewPath(relativePath)); |
| 1323 | const isHtml = relativePath !== null && !isPdf && isBrowserPreviewFile(relativePath); |
| 1324 | const isHostFile = |
| 1325 | attachment !== undefined || (relativePath !== null && isHostPath(relativePath)); |
| 1326 | const fileAccess = useFilesystemReadAccess(environmentId, m); |
| 1327 | const { canReadFiles } = fileAccess; |
| 1328 | const canWriteFiles = useEnvironmentScope(environmentId, AuthFilesystemWriteScope); |
| 1329 | const file = useProjectFileQuery( |
| 1330 | environmentId, |
| 1331 | cwd, |
| 1332 | relativePath, |
| 1333 | attachment === undefined && relativePath !== null, |
| 1334 | m, |
| 1335 | ); |
| 1336 | const [fileRefreshRevision, setFileRefreshRevision] = useState(0); |
| 1337 | const attemptedPath = file.readError?.resolvedPath ?? file.readError?.operationPath; |
| 1338 | // Folder links fail file reads; retain mutation refresh to detect conversion to files. Host folders own |
| 1339 | // roots; folderTrail keeps descendants. |
| 1340 | const breadcrumbPath = |
| 1341 | attachment !== undefined ? null : (relativePath ?? (folderTrail === undefined ? null : "")); |
| 1342 | // Reset crumbs when a host trail reaches the workspace root and no longer passes through the current path. |
| 1343 | const breadcrumbTrail = |
| 1344 | breadcrumbPath === null ? null : retainedBreadcrumbTrail(folderTrail, breadcrumbPath); |
| 1345 | // A trail implies a folder before reads settle, preventing file-preview flashes while navigating up. |
| 1346 | const isFolder = |
| 1347 | attachment === undefined && |
| 1348 | (file.isNotFile || (folderTrail !== undefined && file.data === null && file.error === null)); |
| 1349 | const hostFolderPath = isFolder && isHostFile ? relativePath : null; |
| 1350 | // A chat-linked folder reads as a file until its read settles, and revealing a |
| 1351 | // folder selects it in its parent instead of opening it, so reveal waits. |
| 1352 | const revealsInFileManager = |
| 1353 | !isFolder && |
| 1354 | (file.data !== null || file.error !== null) && |
| 1355 | serverConfig?.shellRevealInFileManager === true; |
| 1356 | // Everything preview-related keys off previewPath; a folder has no preview. |
| 1357 | const previewPath = isFolder ? null : relativePath; |
| 1358 | const [explorerOpen, setExplorerOpen] = useState(initialExplorerOpen); |
| 1359 | const showExplorer = shouldShowFileExplorer({ |
| 1360 | relativePath: previewPath, |
| 1361 | explorerOpen, |
| 1362 | attachmentOpen: attachment !== undefined, |
| 1363 | }); |
| 1364 | const [renderMarkdownPreferred, setRenderMarkdownPreferred] = useLocalStorage( |
| 1365 | RENDER_MARKDOWN_STORAGE_KEY, |
| 1366 | false, |
| 1367 | Schema.Boolean, |
| 1368 | ); |
| 1369 | const [renderBrowserFilePreferred, setRenderBrowserFilePreferred] = useLocalStorage( |
| 1370 | RENDER_BROWSER_FILE_STORAGE_KEY, |
| 1371 | true, |
| 1372 | Schema.Boolean, |
| 1373 | ); |
| 1374 | const [renderTablePreferred, setRenderTablePreferred] = useLocalStorage( |
| 1375 | RENDER_TABLE_STORAGE_KEY, |
| 1376 | true, |
| 1377 | Schema.Boolean, |
| 1378 | ); |
| 1379 | // Reveal ids restart at one per file; pair with the path so dismissal cannot swallow another file's reveal. |
| 1380 | const [handledReveal, setHandledReveal] = useState<{ path: string; requestId: number } | null>( |
| 1381 | null, |
| 1382 | ); |
| 1383 | const breadcrumbRef = useRef<HTMLDivElement>(null); |
| 1384 | const isMarkdown = previewPath ? isMarkdownPreviewFile(previewPath) : false; |
| 1385 | const isMermaid = previewPath !== null && /\.(mmd|mermaid)$/i.test(previewPath); |
| 1386 | const [renderMermaidPreferred, setRenderMermaidPreferred] = useLocalStorage( |
| 1387 | "t3code.renderMermaid", |
| 1388 | true, |
| 1389 | Schema.Boolean, |
| 1390 | ); |
| 1391 | const tableDelimiter = |
| 1392 | previewPath && attachment === undefined ? filePreviewDelimiter({ name: previewPath }) : null; |
| 1393 | const revealHandled = |
| 1394 | revealLine === null || |
| 1395 | (handledReveal?.path === relativePath && handledReveal.requestId === revealRequestId); |
| 1396 | const renderMarkdown = isMarkdown && renderMarkdownPreferred && revealHandled; |
| 1397 | const renderMermaid = isMermaid && renderMermaidPreferred && revealHandled; |
| 1398 | const renderBrowserFile = isPdf || (isHtml && renderBrowserFilePreferred && revealHandled); |
| 1399 | const renderTable = tableDelimiter !== null && renderTablePreferred && revealHandled; |
| 1400 | const renderedMode = isMermaid |
| 1401 | ? ("mermaid" as const) |
| 1402 | : isMarkdown |
| 1403 | ? ("markdown" as const) |
| 1404 | : tableDelimiter |
| 1405 | ? ("table" as const) |
| 1406 | : isHtml |
| 1407 | ? ("html" as const) |
| 1408 | : null; |
| 1409 | const canToggleRendered = |
| 1410 | previewPath !== null && attachment === undefined && renderedMode !== null; |
| 1411 | const showsRawText = |
| 1412 | previewPath !== null && |
| 1413 | file.data !== null && |
| 1414 | !(isMarkdown && renderMarkdown) && |
| 1415 | !renderMermaid && |
| 1416 | !(tableDelimiter && renderTable) && |
| 1417 | !renderBrowserFile && |
| 1418 | !isDocument; |
| 1419 | const mayOpenEditor = |
| 1420 | previewPath !== null && |
| 1421 | !isHostFile && |
| 1422 | canWriteFiles && |
| 1423 | file.error === null && |
| 1424 | !file.data?.truncated && |
| 1425 | !isMedia && |
| 1426 | !isDocument && |
| 1427 | !renderBrowserFile && |
| 1428 | !renderMermaid && |
| 1429 | !(isMarkdown && renderMarkdown) && |
| 1430 | !(tableDelimiter && renderTable); |
| 1431 | const copyableContents = |
| 1432 | previewPath !== null && |
| 1433 | !isMedia && |
| 1434 | !isDocument && |
| 1435 | !isPdf && |
| 1436 | file.data && |
| 1437 | !file.data.truncated && |
| 1438 | file.data.contents.length > 0 |
| 1439 | ? file.data.contents |
| 1440 | : null; |
| 1441 | const { copyToClipboard, isCopied } = useCopyToClipboard({ |
| 1442 | target: namedClipboardTarget(previewPath ?? ""), |
| 1443 | onError: (error) => |
| 1444 | toastManager.add({ |
| 1445 | type: "error", |
| 1446 | title: gt("Could not copy file"), |
| 1447 | description: error.message, |
| 1448 | }), |
| 1449 | }); |
| 1450 | const contentFocusRef = useRef<HTMLDivElement>(null); |
| 1451 | const fileEditorRef = useRef<FileEditor | null>(null); |
| 1452 | const focusEditorFromContent = () => { |
| 1453 | const editor = fileEditorRef.current; |
| 1454 | if (!editor || document.activeElement !== contentFocusRef.current) return; |
| 1455 | // Without a caret the editor focuses with no selection, so no caret shows and typing |
| 1456 | // lands on whatever the browser selection held. |
| 1457 | const hasCaret = Boolean(editor.getViewState().selections?.length); |
| 1458 | editor.focus( |
| 1459 | hasCaret |
| 1460 | ? { preventScroll: true } |
| 1461 | : { preventScroll: true, lineNumber: revealLine ?? "first-visible" }, |
| 1462 | ); |
| 1463 | }; |
| 1464 | const handleEditorChange = (editor: FileEditor | null) => { |
| 1465 | fileEditorRef.current = editor; |
| 1466 | focusEditorFromContent(); |
| 1467 | }; |
| 1468 | const handleEditorChangeStable = useStableCallback(handleEditorChange); |
| 1469 | const focusEditorOnTreeRowClickOrEnter = (event: { |
| 1470 | nativeEvent: Event; |
| 1471 | altKey: boolean; |
| 1472 | ctrlKey: boolean; |
| 1473 | metaKey: boolean; |
| 1474 | shiftKey: boolean; |
| 1475 | }) => { |
| 1476 | if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return; |
| 1477 | const row = event.nativeEvent |
| 1478 | .composedPath() |
| 1479 | .find( |
| 1480 | (node): node is Element => |
| 1481 | node instanceof Element && node.matches('[role="treeitem"][data-item-path]'), |
| 1482 | ); |
| 1483 | const path = row?.getAttribute("data-item-path"); |
| 1484 | if (!path || path.endsWith("/")) return; |
| 1485 | requestWorkspaceFocus({ area: "panel", selector: "[data-file-content-focus]" }); |
| 1486 | }; |
| 1487 | const rendered = isMermaid |
| 1488 | ? renderMermaid |
| 1489 | : isMarkdown |
| 1490 | ? renderMarkdown |
| 1491 | : tableDelimiter |
| 1492 | ? renderTable |
| 1493 | : renderBrowserFile; |
| 1494 | const setRenderedPreferred = isMermaid |
| 1495 | ? setRenderMermaidPreferred |
| 1496 | : isMarkdown |
| 1497 | ? setRenderMarkdownPreferred |
| 1498 | : tableDelimiter |
| 1499 | ? setRenderTablePreferred |
| 1500 | : setRenderBrowserFilePreferred; |
| 1501 | const canOpenInBrowser = |
| 1502 | canOperatePreview && |
| 1503 | previewPath !== null && |
| 1504 | attachment === undefined && |
| 1505 | !isVideo && |
| 1506 | previewAvailable && |
| 1507 | isBrowserPreviewFile(previewPath); |
| 1508 | // Navigating up preserves the file tab; retain the trail's path spelling to find its folder tab. |
| 1509 | const navigateToFolder = (crumbPath: string) => { |
| 1510 | const path = |
| 1511 | breadcrumbTrail !== null && breadcrumbPathOf(breadcrumbTrail) === crumbPath |
| 1512 | ? breadcrumbTrail |
| 1513 | : crumbPath; |
| 1514 | onNavigateFolder(path, retainedBreadcrumbTrail(breadcrumbTrail ?? undefined, path), !isFolder); |
| 1515 | }; |
| 1516 | const absolutePath = |
| 1517 | breadcrumbPath === "" |
| 1518 | ? cwd |
| 1519 | : relativePath && attachment === undefined |
| 1520 | ? resolvePathLinkTarget(relativePath, cwd) |
| 1521 | : null; |
| 1522 | const onFilePostRender = useFileLineReveal(relativePath, revealLine, revealRequestId); |
| 1523 | // Mounting the file read under the workspace mutation id refetches it after each mutation. |
| 1524 | useAtomMount( |
| 1525 | canReadFiles && |
| 1526 | attachment === undefined && |
| 1527 | relativePath !== null && |
| 1528 | // Skip mutation reads for media and documents; folders still detect conversion to files. |
| 1529 | (isFolder || (!isMedia && !isPdf && !isDocument)) && |
| 1530 | !selectedFilePending |
| 1531 | ? revisionedQuery( |
| 1532 | getProjectFileQueryAtom(environmentId, cwd, relativePath), |
| 1533 | workspaceMutationId, |
| 1534 | ) |
| 1535 | : NO_FILE_REVISION_ATOM, |
| 1536 | ); |
| 1537 | |
| 1538 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- scrolls the breadcrumb DOM so the deepest and current crumbs are in view after commit |
| 1539 | useEffect(() => { |
| 1540 | const crumbs = breadcrumbRef.current?.querySelectorAll<HTMLElement>("[data-file-crumb]"); |
| 1541 | // Show the deepest crumb when it fits, but never at the cost of the current one. |
| 1542 | crumbs?.[crumbs.length - 1]?.scrollIntoView({ block: "nearest", inline: "end" }); |
| 1543 | breadcrumbRef.current |
| 1544 | ?.querySelector<HTMLElement>("[data-current-file-crumb='true']") |
| 1545 | ?.scrollIntoView({ block: "nearest", inline: "nearest" }); |
| 1546 | // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A new path or trail re-renders the crumbs, so the current one scrolls back into view. |
| 1547 | }, [breadcrumbPath, breadcrumbTrail]); |
| 1548 | |
| 1549 | const toggleExplorer = () => { |
| 1550 | setExplorerOpen((current) => { |
| 1551 | const next = !current; |
| 1552 | try { |
| 1553 | setLocalStorageItem(FILE_EXPLORER_STORAGE_KEY, next, Schema.Boolean); |
| 1554 | } catch (error) { |
| 1555 | console.error(error); |
| 1556 | } |
| 1557 | return next; |
| 1558 | }); |
| 1559 | }; |
| 1560 | |
| 1561 | const handleOpenInBrowser = () => { |
| 1562 | if (!canReadFiles || !canOperatePreview || !absolutePath || !environmentHttpBaseUrl) return; |
| 1563 | void (async () => { |
| 1564 | const result = await openFileInPreview({ |
| 1565 | threadRef, |
| 1566 | filePath: absolutePath, |
| 1567 | workspaceRoot: cwd, |
| 1568 | httpBaseUrl: environmentHttpBaseUrl, |
| 1569 | createAssetUrl, |
| 1570 | openPreview, |
| 1571 | }); |
| 1572 | if (result._tag === "Success" || isAtomCommandInterrupted(result)) { |
| 1573 | return; |
| 1574 | } |
| 1575 | const error = squashAtomCommandFailure(result); |
| 1576 | toastManager.add( |
| 1577 | stackedThreadToast({ |
| 1578 | type: "error", |
| 1579 | title: gt("Unable to open file in browser"), |
| 1580 | description: thrownErrorMessage(error, m) ?? gt("An error occurred."), |
| 1581 | }), |
| 1582 | ); |
| 1583 | })(); |
| 1584 | }; |
| 1585 | |
| 1586 | if (attachment === undefined && !canReadFiles) { |
| 1587 | if (fileAccess.isPending) { |
| 1588 | return ( |
| 1589 | <div className="flex min-h-0 flex-1 items-center justify-center gap-2 text-sm text-muted-foreground"> |
| 1590 | <Spinner className="size-4" /> |
| 1591 | <T>Checking file access...</T> |
| 1592 | </div> |
| 1593 | ); |
| 1594 | } |
| 1595 | return ( |
| 1596 | <div className="p-4 text-sm text-muted-foreground"> |
| 1597 | {fileAccess.error ?? gt("This connection cannot read host files.")} |
| 1598 | </div> |
| 1599 | ); |
| 1600 | } |
| 1601 | |
| 1602 | return ( |
| 1603 | <div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-background"> |
| 1604 | {breadcrumbPath !== null && breadcrumbTrail !== null ? ( |
| 1605 | <div className={FILE_SURFACE_SUBHEADER_CLASS} data-surface-subheader> |
| 1606 | <ScrollArea |
| 1607 | radius="none" |
| 1608 | ref={breadcrumbRef} |
| 1609 | hideScrollbars |
| 1610 | scrollFade |
| 1611 | className="min-w-0 flex-1" |
| 1612 | data-file-breadcrumbs |
| 1613 | > |
| 1614 | <div className="flex h-full w-max min-w-full items-center text-xs"> |
| 1615 | <FileBreadcrumbs |
| 1616 | cwd={cwd} |
| 1617 | environmentId={environmentId} |
| 1618 | onNavigateFolder={navigateToFolder} |
| 1619 | onOpenFile={onOpenFile} |
| 1620 | projectName={projectName} |
| 1621 | relativePath={breadcrumbPath} |
| 1622 | trail={breadcrumbTrail} |
| 1623 | workspaceMutationId={workspaceMutationId} |
| 1624 | /> |
| 1625 | </div> |
| 1626 | </ScrollArea> |
| 1627 | {absolutePath && |
| 1628 | (environmentId === primaryEnvironmentId || |
| 1629 | environmentId === hostEnvironmentId || |
| 1630 | remoteOpenState.mode !== "local-exec") ? ( |
| 1631 | <OpenInPicker |
| 1632 | environmentId={environmentId} |
| 1633 | keybindings={keybindings} |
| 1634 | availableEditors={availableEditors} |
| 1635 | enableShortcut={openInShortcutEnabled} |
| 1636 | openInCwd={absolutePath} |
| 1637 | openInCwdIsFile={file.isFile} |
| 1638 | compact |
| 1639 | revealFileManager={revealsInFileManager} |
| 1640 | /> |
| 1641 | ) : null} |
| 1642 | {canToggleRendered && renderedMode ? ( |
| 1643 | <FileSurfaceAction |
| 1644 | label={renderedToggleLabel(renderedMode, rendered, m)} |
| 1645 | pressed={rendered} |
| 1646 | onPress={() => { |
| 1647 | const pressed = !rendered; |
| 1648 | setRenderedPreferred(pressed); |
| 1649 | setHandledReveal( |
| 1650 | pressed && relativePath !== null |
| 1651 | ? { path: relativePath, requestId: revealRequestId } |
| 1652 | : null, |
| 1653 | ); |
| 1654 | }} |
| 1655 | > |
| 1656 | {rendered ? ( |
| 1657 | <Code2Icon className="size-3.5" /> |
| 1658 | ) : renderedMode === "table" ? ( |
| 1659 | <Table2Icon className="size-3.5" /> |
| 1660 | ) : ( |
| 1661 | <EyeIcon className="size-3.5" /> |
| 1662 | )} |
| 1663 | </FileSurfaceAction> |
| 1664 | ) : null} |
| 1665 | {showsRawText ? ( |
| 1666 | <FileSurfaceAction |
| 1667 | label={wordWrap ? gt("Disable word wrap") : gt("Enable word wrap")} |
| 1668 | pressed={wordWrap} |
| 1669 | onPress={() => setWordWrapOverride(!wordWrap)} |
| 1670 | > |
| 1671 | <WrapTextIcon className="size-3.5" /> |
| 1672 | </FileSurfaceAction> |
| 1673 | ) : null} |
| 1674 | {copyableContents !== null ? ( |
| 1675 | <FileSurfaceAction |
| 1676 | label={isCopied ? gt("Copied") : gt("Copy contents")} |
| 1677 | onPress={() => copyToClipboard(copyableContents, undefined)} |
| 1678 | > |
| 1679 | {isCopied ? <CheckIcon className="size-3.5" /> : <CopyIcon className="size-3.5" />} |
| 1680 | </FileSurfaceAction> |
| 1681 | ) : null} |
| 1682 | {canOpenInBrowser ? ( |
| 1683 | <FileSurfaceAction |
| 1684 | label={gt("Open file in preview browser")} |
| 1685 | onPress={handleOpenInBrowser} |
| 1686 | > |
| 1687 | <Globe2 className="size-3.5" /> |
| 1688 | </FileSurfaceAction> |
| 1689 | ) : null} |
| 1690 | {!isHostFile && previewPath !== null ? ( |
| 1691 | <FileSurfaceAction |
| 1692 | label={explorerOpen ? gt("Hide file explorer") : gt("Show file explorer")} |
| 1693 | pressed={explorerOpen} |
| 1694 | onPress={toggleExplorer} |
| 1695 | > |
| 1696 | <FolderTree className="size-3.5" /> |
| 1697 | </FileSurfaceAction> |
| 1698 | ) : null} |
| 1699 | </div> |
| 1700 | ) : null} |
| 1701 | {relativePath && !attachment && !isHostFile && !canWriteFiles && !fileAccess.isPending ? ( |
| 1702 | <div className="shrink-0 border-b px-3 py-1.5 text-2xs text-muted-foreground"> |
| 1703 | <T>Read-only connection. Unsaved edits are kept until write access returns.</T> |
| 1704 | </div> |
| 1705 | ) : null} |
| 1706 | {previewPath && |
| 1707 | attachment === undefined && |
| 1708 | !isMedia && |
| 1709 | !renderBrowserFile && |
| 1710 | file.data?.truncated && |
| 1711 | (draft || isMarkdown || isMermaid || isHtml) ? ( |
| 1712 | <div className="shrink-0 border-b border-warning/20 bg-warning-surface px-3 py-1.5 text-2xs text-warning-foreground"> |
| 1713 | {gt( |
| 1714 | "{count, plural, one {Preview limited to the first 1 MB of a {formatted} byte file.} other {Preview limited to the first 1 MB of a {formatted} byte file.}}", |
| 1715 | { count: file.data.byteLength, formatted: file.data.byteLength.toLocaleString() }, |
| 1716 | )} |
| 1717 | </div> |
| 1718 | ) : null} |
| 1719 | <div className="flex min-h-0 flex-1 overflow-hidden"> |
| 1720 | <div |
| 1721 | className={cn("min-w-0 flex-1 flex-col overflow-hidden", previewPath ? "flex" : "hidden")} |
| 1722 | > |
| 1723 | {mayOpenEditor ? ( |
| 1724 | // Panel focus lands here and passes to the editor once it attaches. sr-only keeps the |
| 1725 | // 1px box workspace focus needs, and clips it so clicks in the file never reach it. |
| 1726 | // The hand-off waits a microtask: workspace focus checks that focus stayed here. |
| 1727 | <div |
| 1728 | ref={contentFocusRef} |
| 1729 | tabIndex={-1} |
| 1730 | data-workspace-focus-default |
| 1731 | data-file-content-focus |
| 1732 | aria-label={gt("File contents")} |
| 1733 | className="sr-only" |
| 1734 | onFocus={() => queueMicrotask(focusEditorFromContent)} |
| 1735 | /> |
| 1736 | ) : null} |
| 1737 | {isFolder ? null : relativePath && attachment ? ( |
| 1738 | <AttachmentFilePreview |
| 1739 | key={`${environmentId}:${attachment.id}`} |
| 1740 | name={attachment.name} |
| 1741 | mimeType={attachment.mimeType} |
| 1742 | sizeBytes={attachment.sizeBytes} |
| 1743 | asset={{ environmentId, attachmentId: attachment.id }} |
| 1744 | htmlRender={attachment.htmlRender === true} |
| 1745 | threadRef={threadRef} |
| 1746 | /> |
| 1747 | ) : relativePath && isVideo && absolutePath ? ( |
| 1748 | <WorkspaceVideoPreview |
| 1749 | key={`${environmentId}:${threadRef.threadId}:${absolutePath}`} |
| 1750 | environmentId={environmentId} |
| 1751 | threadRef={threadRef} |
| 1752 | draft={draft} |
| 1753 | absolutePath={absolutePath} |
| 1754 | workspaceRoot={cwd} |
| 1755 | name={relativePath} |
| 1756 | workspaceMutationId={workspaceMutationId} |
| 1757 | /> |
| 1758 | ) : relativePath && isAudio && absolutePath ? ( |
| 1759 | <WorkspaceAudioPreview |
| 1760 | key={`${environmentId}:${threadRef.threadId}:${absolutePath}`} |
| 1761 | environmentId={environmentId} |
| 1762 | threadRef={threadRef} |
| 1763 | draft={draft} |
| 1764 | absolutePath={absolutePath} |
| 1765 | workspaceRoot={cwd} |
| 1766 | name={relativePath} |
| 1767 | workspaceMutationId={workspaceMutationId} |
| 1768 | /> |
| 1769 | ) : relativePath && isImage && absolutePath ? ( |
| 1770 | <WorkspaceImagePreview |
| 1771 | key={absolutePath} |
| 1772 | environmentId={environmentId} |
| 1773 | threadRef={threadRef} |
| 1774 | draft={draft} |
| 1775 | absolutePath={absolutePath} |
| 1776 | workspaceRoot={cwd} |
| 1777 | alt={relativePath} |
| 1778 | workspaceMutationId={workspaceMutationId} |
| 1779 | /> |
| 1780 | ) : relativePath && renderBrowserFile && absolutePath ? ( |
| 1781 | <WorkspaceBrowserPreview |
| 1782 | key={absolutePath} |
| 1783 | environmentId={environmentId} |
| 1784 | threadRef={threadRef} |
| 1785 | draft={draft} |
| 1786 | absolutePath={absolutePath} |
| 1787 | workspaceRoot={cwd} |
| 1788 | title={relativePath} |
| 1789 | workspaceMutationId={workspaceMutationId} |
| 1790 | /> |
| 1791 | ) : relativePath && |
| 1792 | absolutePath && |
| 1793 | file.data?.truncated && |
| 1794 | !isDocument && |
| 1795 | !draft && |
| 1796 | !isMarkdown && |
| 1797 | !isMermaid && |
| 1798 | !isHtml ? ( |
| 1799 | <WorkspaceLargeTextPreview |
| 1800 | key={`${absolutePath}:${renderTable}:${fileRefreshRevision}`} |
| 1801 | environmentId={environmentId} |
| 1802 | threadRef={threadRef} |
| 1803 | absolutePath={absolutePath} |
| 1804 | name={relativePath} |
| 1805 | delimiter={renderTable ? tableDelimiter : null} |
| 1806 | workspaceMutationId={workspaceMutationId} |
| 1807 | revealLine={revealLine} |
| 1808 | revealRequestId={revealRequestId} |
| 1809 | wordWrap={wordWrap} |
| 1810 | /> |
| 1811 | ) : relativePath && |
| 1812 | absolutePath && |
| 1813 | (isDocument || file.readError?.failure === "binary_file") ? ( |
| 1814 | <WorkspaceDocumentPreview |
| 1815 | key={`${environmentId}:${absolutePath}`} |
| 1816 | environmentId={environmentId} |
| 1817 | threadRef={threadRef} |
| 1818 | draft={draft} |
| 1819 | document={isDocument} |
| 1820 | absolutePath={absolutePath} |
| 1821 | workspaceRoot={cwd} |
| 1822 | name={relativePath.split(/[\\/]/).at(-1) || relativePath} |
| 1823 | workspaceMutationId={workspaceMutationId} |
| 1824 | refreshRevision={fileRefreshRevision} |
| 1825 | /> |
| 1826 | ) : relativePath && file.error && file.data === null ? ( |
| 1827 | <div |
| 1828 | role="alert" |
| 1829 | className="scrollbar-gutter-both flex min-h-0 flex-1 flex-col overflow-auto" |
| 1830 | > |
| 1831 | <div className="my-auto flex shrink-0 flex-col gap-3 px-6 py-6 text-center text-xs leading-relaxed"> |
| 1832 | <p className="text-destructive"> |
| 1833 | {file.readError ? filePreviewReadErrorMessage(file.readError, m) : file.error} |
| 1834 | </p> |
| 1835 | {attemptedPath ? ( |
| 1836 | <p className="text-muted-foreground"> |
| 1837 | <T> |
| 1838 | Attempted path |
| 1839 | <code className="block break-all font-mono text-foreground select-all"> |
| 1840 | <Var>{attemptedPath}</Var> |
| 1841 | </code> |
| 1842 | </T> |
| 1843 | </p> |
| 1844 | ) : null} |
| 1845 | {!isHostFile ? ( |
| 1846 | <p className="text-muted-foreground"> |
| 1847 | <T> |
| 1848 | Workspace folder:{" "} |
| 1849 | <code className="break-all font-mono select-all"> |
| 1850 | <Var>{file.readError?.cwd ?? cwd}</Var> |
| 1851 | </code> |
| 1852 | . Check the link's path or locate the file in Files. |
| 1853 | </T> |
| 1854 | </p> |
| 1855 | ) : null} |
| 1856 | </div> |
| 1857 | </div> |
| 1858 | ) : relativePath && file.data === null ? ( |
| 1859 | <div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground"> |
| 1860 | <Spinner size="lg" /> |
| 1861 | </div> |
| 1862 | ) : relativePath && file.data ? ( |
| 1863 | renderMermaid ? ( |
| 1864 | <Suspense fallback={<FileSurfaceLoading />}> |
| 1865 | <MermaidFilePreview text={file.data.contents} /> |
| 1866 | </Suspense> |
| 1867 | ) : isMarkdown && renderMarkdown ? ( |
| 1868 | <RenderedMarkdownSurface |
| 1869 | key={relativePath} |
| 1870 | environmentId={environmentId} |
| 1871 | cwd={cwd} |
| 1872 | relativePath={relativePath} |
| 1873 | threadRef={threadRef} |
| 1874 | contents={file.data.contents} |
| 1875 | workspaceMutationId={workspaceMutationId} |
| 1876 | readOnly={file.data.truncated || isHostFile || !canWriteFiles} |
| 1877 | onPendingChange={onPendingChange} |
| 1878 | /> |
| 1879 | ) : tableDelimiter && renderTable ? ( |
| 1880 | <DelimitedTablePreview |
| 1881 | key={relativePath} |
| 1882 | name={relativePath} |
| 1883 | text={file.data.contents} |
| 1884 | delimiter={tableDelimiter} |
| 1885 | /> |
| 1886 | ) : file.data.truncated || isHostFile || !canWriteFiles ? ( |
| 1887 | <SourceFilePreview |
| 1888 | name={relativePath} |
| 1889 | text={file.data.contents} |
| 1890 | cacheKey={projectFileCacheKey(cwd, relativePath, file.data.contents)} |
| 1891 | onPostRender={onFilePostRender} |
| 1892 | wordWrap={wordWrap} |
| 1893 | /> |
| 1894 | ) : ( |
| 1895 | <DiffWorkerPoolProvider> |
| 1896 | <EditableFileSurface |
| 1897 | key={`${relativePath}:${resolvedTheme}`} |
| 1898 | environmentId={environmentId} |
| 1899 | projectId={projectId} |
| 1900 | cwd={cwd} |
| 1901 | relativePath={relativePath} |
| 1902 | composerDraftTarget={composerDraftTarget} |
| 1903 | contents={file.data.contents} |
| 1904 | resolvedTheme={resolvedTheme} |
| 1905 | revealRequestId={revealRequestId} |
| 1906 | wordWrap={wordWrap} |
| 1907 | onPostRender={onFilePostRender} |
| 1908 | onPendingChange={onPendingChange} |
| 1909 | onEditorChange={handleEditorChangeStable} |
| 1910 | /> |
| 1911 | </DiffWorkerPoolProvider> |
| 1912 | ) |
| 1913 | ) : null} |
| 1914 | </div> |
| 1915 | {showExplorer ? ( |
| 1916 | <FileExplorerPane resizable={Boolean(previewPath)}> |
| 1917 | <div |
| 1918 | className="contents" |
| 1919 | onClick={focusEditorOnTreeRowClickOrEnter} |
| 1920 | onKeyDown={(event) => { |
| 1921 | if (event.key === "Enter") focusEditorOnTreeRowClickOrEnter(event); |
| 1922 | }} |
| 1923 | > |
| 1924 | <FileBrowserPanel |
| 1925 | key={`${environmentId}:${hostFolderPath ?? cwd}`} |
| 1926 | environmentId={environmentId} |
| 1927 | cwd={hostFolderPath ?? cwd} |
| 1928 | projectName={hostFolderPath ?? projectName} |
| 1929 | hostFolder={hostFolderPath !== null} |
| 1930 | selectedPath={ |
| 1931 | hostFolderPath === null |
| 1932 | ? relativePath |
| 1933 | : trailChildOf(hostFolderPath, breadcrumbTrail ?? hostFolderPath) |
| 1934 | } |
| 1935 | selectedPathRevealId={revealRequestId} |
| 1936 | onOpenFile={onOpenFile} |
| 1937 | answersPanelFind={!previewPath} |
| 1938 | workspaceMutationId={workspaceMutationId} |
| 1939 | {...(previewPath && !isMedia && !isPdf |
| 1940 | ? { |
| 1941 | onRefreshSelectedFile: () => { |
| 1942 | if (!isDocument) file.refresh(); |
| 1943 | setFileRefreshRevision((value) => value + 1); |
| 1944 | }, |
| 1945 | } |
| 1946 | : {})} |
| 1947 | /> |
| 1948 | </div> |
| 1949 | </FileExplorerPane> |
| 1950 | ) : null} |
| 1951 | </div> |
| 1952 | </div> |
| 1953 | ); |
| 1954 | } |
| 1955 | |
| 1956 | const LargeTextViewer = lazy(() => import("./LargeTextViewer")); |
| 1957 | export function WorkspaceLargeTextPreview(props: { |
| 1958 | environmentId: EnvironmentId; |
| 1959 | threadRef: ScopedThreadRef; |
| 1960 | absolutePath: string; |
| 1961 | name: string; |
| 1962 | delimiter: "," | "\t" | null; |
| 1963 | workspaceMutationId: string | null; |
| 1964 | revealLine: number | null; |
| 1965 | revealRequestId: number; |
| 1966 | wordWrap: boolean; |
| 1967 | }) { |
| 1968 | const resource = { |
| 1969 | _tag: "media-file", |
| 1970 | threadId: props.threadRef.threadId, |
| 1971 | path: props.absolutePath, |
| 1972 | disposition: "attachment", |
| 1973 | } as const; |
| 1974 | const gt = useGT(); |
| 1975 | const copyContents = useRef<(() => Promise<string>) | null>(null); |
| 1976 | const { copyToClipboard, isCopied } = useCopyToClipboard({ |
| 1977 | target: namedClipboardTarget(props.name), |
| 1978 | }); |
| 1979 | const [saving, setSaving] = useState(false); |
| 1980 | const [revision, setRevision] = useState(0); |
| 1981 | const showError = (cause: unknown) => { |
| 1982 | toastManager.add({ |
| 1983 | type: "error", |
| 1984 | title: gt("Could not read file"), |
| 1985 | description: thrownErrorMessage(cause, m) ?? gt("Try again."), |
| 1986 | }); |
| 1987 | }; |
| 1988 | // Each workspace mutation re-mints the URL, so an edited file loads its new bytes. |
| 1989 | const assetUrl = useAssetUrlState( |
| 1990 | props.environmentId, |
| 1991 | resource, |
| 1992 | props.workspaceMutationId ?? undefined, |
| 1993 | ); |
| 1994 | const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource); |
| 1995 | const contentRevision = JSON.stringify([ |
| 1996 | props.environmentId, |
| 1997 | resource, |
| 1998 | assetUrl._tag === "Success" ? (assetUrl.fileRevision ?? props.workspaceMutationId) : null, |
| 1999 | revision, |
| 2000 | ]); |
| 2001 | const [loaded, setLoaded] = useState<{ revision: string; url: string } | null>(null); |
| 2002 | if (assetUrl._tag === "Success" && loaded?.revision !== contentRevision) { |
| 2003 | setLoaded({ revision: contentRevision, url: assetUrl.url }); |
| 2004 | } |
| 2005 | if (assetUrl._tag === "Failure") |
| 2006 | return ( |
| 2007 | <FileSurfaceFailure |
| 2008 | message={gt("Unable to load file preview.")} |
| 2009 | onRetry={() => { |
| 2010 | setRevision((value) => value + 1); |
| 2011 | void refreshAssetUrl().catch(showError); |
| 2012 | }} |
| 2013 | /> |
| 2014 | ); |
| 2015 | if (assetUrl._tag !== "Success" || loaded === null) |
| 2016 | return ( |
| 2017 | <div className="p-6 text-xs text-muted-foreground"> |
| 2018 | <T>Loading…</T> |
| 2019 | </div> |
| 2020 | ); |
| 2021 | const src = `${loaded.url}${loaded.url.includes("?") ? "&" : "?"}revision=${encodeURIComponent(loaded.revision)}`; |
| 2022 | return ( |
| 2023 | <> |
| 2024 | <div className={FILE_SURFACE_SUBHEADER_CLASS}> |
| 2025 | <span className="min-w-0 flex-1 text-xs text-muted-foreground"> |
| 2026 | <T>Full file</T> |
| 2027 | </span> |
| 2028 | <FileSurfaceAction |
| 2029 | label={isCopied ? gt("Copied") : gt("Copy contents")} |
| 2030 | onPress={() => { |
| 2031 | const copy = copyContents.current; |
| 2032 | if (!copy) return; |
| 2033 | void copy() |
| 2034 | .then((text) => copyToClipboard(text, undefined)) |
| 2035 | .catch(showError); |
| 2036 | }} |
| 2037 | > |
| 2038 | {isCopied ? <CheckIcon className="size-3.5" /> : <CopyIcon className="size-3.5" />} |
| 2039 | </FileSurfaceAction> |
| 2040 | <FileSurfaceAction |
| 2041 | label={saving ? gt("Preparing file…") : gt("Save file")} |
| 2042 | disabled={saving} |
| 2043 | onPress={() => { |
| 2044 | setSaving(true); |
| 2045 | void (async () => { |
| 2046 | const url = await refreshAssetUrl(); |
| 2047 | if (!url) throw new Error(gt("Reconnect to the environment and try again.")); |
| 2048 | const response = await fetch(url); |
| 2049 | if (!response.ok) throw new Error(gt("The file could not be loaded. Try again.")); |
| 2050 | const downloadUrl = URL.createObjectURL(await response.blob()); |
| 2051 | setTimeout(() => URL.revokeObjectURL(downloadUrl), 30_000); |
| 2052 | const anchor = document.createElement("a"); |
| 2053 | anchor.href = downloadUrl; |
| 2054 | anchor.download = props.name.split(/[\\/]/).at(-1) || props.name; |
| 2055 | anchor.click(); |
| 2056 | })() |
| 2057 | .catch(showError) |
| 2058 | .finally(() => setSaving(false)); |
| 2059 | }} |
| 2060 | > |
| 2061 | <DownloadIcon className="size-3.5" /> |
| 2062 | </FileSurfaceAction> |
| 2063 | </div> |
| 2064 | <Suspense |
| 2065 | fallback={ |
| 2066 | <div className="p-6 text-xs text-muted-foreground"> |
| 2067 | <T>Loading…</T> |
| 2068 | </div> |
| 2069 | } |
| 2070 | > |
| 2071 | <LargeTextViewer |
| 2072 | key={`${src}:${revision}`} |
| 2073 | name={props.name} |
| 2074 | copyContents={copyContents} |
| 2075 | onRetry={() => { |
| 2076 | void refreshAssetUrl() |
| 2077 | .then(() => setRevision((value) => value + 1)) |
| 2078 | .catch(showError); |
| 2079 | }} |
| 2080 | src={src} |
| 2081 | delimiter={props.delimiter} |
| 2082 | revealLine={props.revealLine} |
| 2083 | revealRequestId={props.revealRequestId} |
| 2084 | wordWrap={props.wordWrap} |
| 2085 | /> |
| 2086 | </Suspense> |
| 2087 | </> |
| 2088 | ); |
| 2089 | } |