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

filePreviewMode.ts

60 lines2.3 KB

1import { workspaceRelativeFilePath } from "@t3tools/client-runtime/markdown-links";
2import type { ProjectReadFileError } from "@t3tools/contracts";
3import { isAbsolutePath } from "~/terminal-links";
4​
5/** Resolve workspace links before choosing between the explorer and a file preview. */
6export function resolveFilePreviewPath(path: string | null, cwd: string): string | null {
7 if (path === null) return null;
8 return path === "." || workspaceRelativeFilePath(path, cwd) === "." ? null : path;
9}
10​
11export const isMarkdownPreviewFile = (path: string): boolean => /\.(?:md|mdx)$/i.test(path);
12​
13/** Describe existing failure codes without exposing the underlying platform cause. */
14export function filePreviewReadErrorMessage(error: ProjectReadFileError): string {
15 switch (error.failure) {
16 case "path_not_file":
17 return "The path is a directory or special file, not a regular file.";
18 case "binary_file":
19 return "The file is binary and cannot be displayed as text.";
20 case "workspace_path_outside_root":
21 return "The requested path is outside the workspace.";
22 case "resolved_path_outside_root":
23 return "The path resolves to a location outside the workspace.";
24 case "operation_failed":
25 // A realpath failure can mean a missing path, permissions, or another I/O error.
26 return error.operation === "realpath-workspace-root"
27 ? "The workspace folder could not be accessed."
28 : "The file could not be accessed or read. It may be missing or inaccessible.";
29 default:
30 return error.message;
31 }
33​
34export function shouldShowFileExplorer(input: {
35 readonly relativePath: string | null;
36 readonly explorerOpen: boolean;
37 readonly attachmentOpen: boolean;
38}): boolean {
39 if (input.attachmentOpen || (input.relativePath && isAbsolutePath(input.relativePath))) {
40 return false;
41 }
42 return input.explorerOpen || input.relativePath === null;
44​
45export function setMarkdownTaskChecked(
46 markdown: string,
47 markerOffset: number,
48 checked: boolean,
49): string {
50 if (
51 markerOffset < 0 ||
52 markdown[markerOffset] !== "[" ||
53 !/[ xX]/.test(markdown[markerOffset + 1] ?? "") ||
54 markdown[markerOffset + 2] !== "]"
55 ) {
56 return markdown;
57 }
58​
59 return `${markdown.slice(0, markerOffset + 1)}${checked ? "x" : " "}${markdown.slice(markerOffset + 2)}`;