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

useFileMetadata.ts

75 lines2.5 KB

1import {
2 AuthFilesystemReadScope,
3 type EnvironmentId,
4 type ScopedThreadRef,
5} from "@t3tools/contracts";
6import {
7 joinPath,
8 parseFileUrlHref,
9 resolvePathLinkTarget,
10 splitFilePathPosition,
11} from "@t3tools/shared/fileLinks";
12import {
13 isAbsolutePath,
14 isNetworkPath,
15 isWindowsAbsolutePath,
16 normalizeProjectPathForComparison,
17} from "@t3tools/shared/path";
18import { safeDecodeURIComponent } from "@t3tools/shared/markdownLinks";
19import { useContext } from "react";
20​
21import { useEnvironmentScope } from "../state/session";
22import { projectEnvironment } from "../state/projects";
23import { useEnvironmentQuery } from "../state/query";
24import { FileMetadataThreadContext } from "./FileMetadataThreadProvider";
25​
26export function getFileMetadataQueryAtom(
27 environmentId: EnvironmentId,
28 path: string,
29 cwd?: string,
30 threadRef?: ScopedThreadRef | null,
31 literal = false,
32) {
33 const uri = /^file:\/\//iu.test(path) ? parseFileUrlHref(path) : null;
34 const hostPath = literal ? path : splitFilePathPosition(path).path;
35 const targetPath = normalizeProjectPathForComparison(
36 uri
37 ? safeDecodeURIComponent(uri.path)
38 : hostPath.startsWith("~/") || !cwd
39 ? hostPath
40 : // A POSIX name may end in `:<digits>`; Windows names cannot contain `:`.
41 literal && !isWindowsAbsolutePath(cwd)
42 ? isAbsolutePath(hostPath)
43 ? hostPath
44 : joinPath(cwd, hostPath.replace(/^(?:\.\/)+/, ""), "/")
45 : resolvePathLinkTarget(hostPath, cwd),
46 );
47 const absolute = isAbsolutePath(targetPath) || targetPath.startsWith("~/");
48 return (
49 // Servers stat what they are asked about, and a network path leaks the
50 // Windows user's NTLM credentials to its host before any chip is clicked.
51 absolute && !isNetworkPath(targetPath) && targetPath.length <= 512
52 ? projectEnvironment.fileMetadata({
53 environmentId,
54 input: {
55 path: targetPath,
56 ...(threadRef?.environmentId === environmentId ? { threadId: threadRef.threadId } : {}),
57 },
58 })
59 : null
60 );
62​
63export function useFileMetadata(
64 environmentId: EnvironmentId | null | undefined,
65 path: string,
66 cwd?: string,
67) {
68 const canRead = useEnvironmentScope(environmentId ?? null, AuthFilesystemReadScope);
69 const threadRef = useContext(FileMetadataThreadContext);
70 return useEnvironmentQuery(
71 environmentId && canRead
72 ? getFileMetadataQueryAtom(environmentId, path, cwd, threadRef, true)
73 : null,
74 ).data;