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

preload-workspace-file.ts

82 lines2.4 KB

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