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