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

useFileMetadata.ts

55 lines1.9 KB

1import {
2 AuthFilesystemReadScope,
3 type EnvironmentId,
4 type ScopedThreadRef,
5} from "@t3tools/contracts";
6import { resolvePathLinkTarget, splitFilePathPosition } from "@t3tools/shared/fileLinks";
7import {
8 isAbsolutePath,
9 isNetworkPath,
10 normalizeProjectPathForComparison,
11} from "@t3tools/shared/path";
12import { useContext } from "react";
13​
14import { useEnvironmentScope } from "../state/session";
15import { projectEnvironment } from "../state/projects";
16import { useEnvironmentQuery } from "../state/query";
17import { FileMetadataThreadContext } from "./FileMetadataThreadProvider";
18​
19export function getFileMetadataQueryAtom(
20 environmentId: EnvironmentId,
21 path: string,
22 cwd?: string,
23 threadRef?: ScopedThreadRef | null,
24) {
25 const hostPath = splitFilePathPosition(path).path;
26 const targetPath = normalizeProjectPathForComparison(
27 hostPath.startsWith("~/") || !cwd ? hostPath : resolvePathLinkTarget(hostPath, cwd),
28 );
29 const absolute = isAbsolutePath(targetPath) || targetPath.startsWith("~/");
30 return (
31 // Servers stat what they are asked about, and a network path leaks the
32 // Windows user's NTLM credentials to its host before any chip is clicked.
33 absolute && !isNetworkPath(targetPath) && targetPath.length <= 512
34 ? projectEnvironment.fileMetadata({
35 environmentId,
36 input: {
37 path: targetPath,
38 ...(threadRef?.environmentId === environmentId ? { threadId: threadRef.threadId } : {}),
39 },
40 })
41 : null
42 );
44​
45export function useFileMetadata(
46 environmentId: EnvironmentId | null | undefined,
47 path: string,
48 cwd?: string,
49) {
50 const canRead = useEnvironmentScope(environmentId ?? null, AuthFilesystemReadScope);
51 const threadRef = useContext(FileMetadataThreadContext);
52 return useEnvironmentQuery(
53 environmentId && canRead ? getFileMetadataQueryAtom(environmentId, path, cwd, threadRef) : null,
54 ).data;