sailfork / t3code-github / apps/ mobile/ src/ features/ files/ preload-workspace-file.ts

import { AuthFilesystemReadScope } from "@t3tools/contracts";
import { readEnvironmentScope } from "../../state/session";
import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId } from "@t3tools/contracts";
import {
  isWorkspaceBrowserPreviewPath,
  isWorkspaceImagePreviewPath,
} from "@t3tools/shared/filePreview";

import { appAtomRegistry } from "../../state/atom-registry";
import { projectEnvironment } from "../../state/projects";
import { isVideoPreviewFile } from "./filePath";
import { prepareSourceFileDocument } from "./source-file-document";
import { sourceHighlightAtom } from "./sourceHighlightingState";
import type { HighlightScheme } from "../../lib/highlights";

const inFlightPreloads = new Map<string, Promise<void>>();
const MAX_HIGHLIGHT_PRELOAD_CHARACTERS = 256 * 1024;

function preloadKey(input: {
  readonly cwd: string;
  readonly environmentId: EnvironmentId;
  readonly relativePath: string;
}): string {
  return JSON.stringify([input.environmentId, input.cwd, input.relativePath]);
}

export function preloadWorkspaceFileContents(input: {
  readonly cwd: string;
  readonly environmentId: EnvironmentId;
  readonly relativePath: string;
  readonly theme: HighlightScheme;
}): void {
  if (
    !readEnvironmentScope(input.environmentId, AuthFilesystemReadScope) ||
    isWorkspaceBrowserPreviewPath(input.relativePath) ||
    isWorkspaceImagePreviewPath(input.relativePath) ||
    isVideoPreviewFile(input.relativePath)
  ) {
    return;
  }

  const key = preloadKey(input);
  if (inFlightPreloads.has(key)) {
    return;
  }

  const preload = executeAtomQuery(
    appAtomRegistry,
    projectEnvironment.readFile({
      environmentId: input.environmentId,
      input: { cwd: input.cwd, relativePath: input.relativePath },
    }),
    {
      label: "workspace file preload",
      reportDefect: false,
      reportFailure: false,
    },
  )
    .then(async (result) => {
      if (result._tag === "Success") {
        const document = prepareSourceFileDocument(result.value.contents);
        if (document.contents.length <= MAX_HIGHLIGHT_PRELOAD_CHARACTERS) {
          await executeAtomQuery(
            appAtomRegistry,
            sourceHighlightAtom({
              path: input.relativePath,
              contents: document.contents,
              theme: input.theme,
            }),
            {
              label: "workspace source highlight preload",
              reportDefect: false,
              reportFailure: false,
            },
          );
        }
      }
    })
    .finally(() => {
      inFlightPreloads.delete(key);
    });

  inFlightPreloads.set(key, preload);
}