1import { AuthFilesystemReadScope } from "@t3tools/contracts";
2import { readEnvironmentScope } from "../../state/session";
3import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
4import type { EnvironmentId } from "@t3tools/contracts";
5import {
6 isWorkspaceBrowserPreviewPath,
7 isWorkspaceImagePreviewPath,
8} from "@t3tools/shared/filePreview";
9
10import { appAtomRegistry } from "../../state/atom-registry";
11import { projectEnvironment } from "../../state/projects";
12import { isVideoPreviewFile } from "./filePath";
13import { prepareSourceFileDocument } from "./source-file-document";
14import { sourceHighlightAtom } from "./sourceHighlightingState";
15import type { ReviewDiffTheme } from "../review/shikiReviewHighlighter";
16
17const inFlightPreloads = new Map<string, Promise<void>>();
18const MAX_HIGHLIGHT_PRELOAD_CHARACTERS = 256 * 1024;
19
20function preloadKey(input: {
21 readonly cwd: string;
22 readonly environmentId: EnvironmentId;
23 readonly relativePath: string;
24}): string {
25 return JSON.stringify([input.environmentId, input.cwd, input.relativePath]);
26}
27
28export function preloadWorkspaceFileContents(input: {
29 readonly cwd: string;
30 readonly environmentId: EnvironmentId;
31 readonly relativePath: string;
32 readonly theme: ReviewDiffTheme;
33}): void {
34 if (
35 !readEnvironmentScope(input.environmentId, AuthFilesystemReadScope) ||
36 isWorkspaceBrowserPreviewPath(input.relativePath) ||
37 isWorkspaceImagePreviewPath(input.relativePath) ||
38 isVideoPreviewFile(input.relativePath)
39 ) {
40 return;
41 }
42
43 const key = preloadKey(input);
44 if (inFlightPreloads.has(key)) {
45 return;
46 }
47
48 const preload = executeAtomQuery(
49 appAtomRegistry,
50 projectEnvironment.readFile({
51 environmentId: input.environmentId,
52 input: { cwd: input.cwd, relativePath: input.relativePath },
53 }),
54 {
55 label: "workspace file preload",
56 reportDefect: false,
57 reportFailure: false,
58 },
59 )
60 .then(async (result) => {
61 if (result._tag === "Success") {
62 const document = prepareSourceFileDocument(result.value.contents);
63 if (document.contents.length <= MAX_HIGHLIGHT_PRELOAD_CHARACTERS) {
64 await executeAtomQuery(
65 appAtomRegistry,
66 sourceHighlightAtom({
67 path: input.relativePath,
68 contents: document.contents,
69 theme: input.theme,
70 }),
71 {
72 label: "workspace source highlight preload",
73 reportDefect: false,
74 reportFailure: false,
75 },
76 );
77 }
78 }
79 })
80 .finally(() => {
81 inFlightPreloads.delete(key);
82 });
83
84 inFlightPreloads.set(key, preload);
85}