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

useFileMetadata.ts

65 lines2.1 KB

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