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

filePreviewMode.ts

65 lines2.5 KB

1import type { AssetResource, ProjectReadFileError, ScopedThreadRef } from "@t3tools/contracts";
2import { mediaFileReference } from "@t3tools/client-runtime/media-reference";
3import { isHostPath, workspaceRelativeFilePath } from "@t3tools/shared/path";
4​
5export function resolveFilePreviewPath(path: string | null, cwd: string): string | null {
6 if (path === null) return null;
7 return path === "." || workspaceRelativeFilePath(path, cwd) === "." ? null : path;
8}
9​
10export const isMarkdownPreviewFile = (path: string): boolean =>
11 /\.(?:md|mdx|markdown|mdown|mkd)$/i.test(path);
12​
13export function filePreviewReadErrorMessage(error: ProjectReadFileError): string {
14 switch (error.failure) {
15 case "path_not_file":
16 return "The path is a directory or special file, not a regular file.";
17 case "binary_file":
18 return "The file is binary and cannot be displayed as text.";
19 case "workspace_path_outside_root":
20 return "The requested path is outside the workspace.";
21 case "resolved_path_outside_root":
22 return "The path resolves to a location outside the workspace.";
23 case "operation_failed":
24 return error.operation === "realpath-workspace-root"
25 ? "The workspace folder could not be accessed."
26 : "The file could not be accessed or read. It may be missing or inaccessible.";
27 default:
28 return error.message;
29 }
31​
32export function shouldShowFileExplorer(input: {
33 readonly relativePath: string | null;
34 readonly explorerOpen: boolean;
35 readonly attachmentOpen: boolean;
36}): boolean {
37 if (input.attachmentOpen || (input.relativePath && isHostPath(input.relativePath))) {
38 return false;
39 }
40 return input.explorerOpen || input.relativePath === null;
42​
43/**
44 * The server only signs `workspace-file` assets below the workspace root, so a
45 * file opened from outside it, such as an absolute link in the thread, goes
46 * through the host `media-file` resource the direct media viewer uses.
47 */
48export function workspaceAssetResource(input: {
49 readonly kind: "workspace-file" | "media-file";
50 readonly threadRef: ScopedThreadRef;
51 readonly draft: boolean;
52 readonly workspaceRoot: string;
53 readonly absolutePath: string;
54}): AssetResource {
55 if (input.draft) {
56 return { _tag: "draft-workspace-file", cwd: input.workspaceRoot, path: input.absolutePath };
57 }
58 const insideWorkspace =
59 mediaFileReference(input.absolutePath, input.workspaceRoot).relativePath !== undefined;
60 return {
61 _tag: insideWorkspace ? input.kind : "media-file",
62 threadId: input.threadRef.threadId,
63 path: input.absolutePath,
64 };