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

useFileChipShare.ts

69 lines2.7 KB

1import * as Dialog from "../../components/ui/Dialog";
2import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
3import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
4import * as Option from "effect/Option";
5import { useCallback, useEffect, useLayoutEffect, useRef } from "react";
6​
7import { downloadAndShareAttachment } from "../../lib/attachmentDownload";
8import { assetEnvironment } from "../../state/assets";
9import { usePreparedConnection } from "../../state/session";
10import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
11import { fileChipShareSource, type FileChipTarget } from "./fileChipMenu";
12​
13export function useFileChipShare(
14 environmentId: EnvironmentId,
15 threadId: ThreadId,
16 sourceIdentifier: string,
17) {
18 const connection = usePreparedConnection(environmentId);
19 const httpBaseUrl = Option.isSome(connection) ? connection.value.httpBaseUrl : null;
20 const createUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
21 refresh: true,
22 reportFailure: false,
23 });
24 const connectionRef = useRef(httpBaseUrl);
25 useLayoutEffect(() => {
26 connectionRef.current = httpBaseUrl;
27 }, [httpBaseUrl]);
28 const requestRef = useRef<AbortController | null>(null);
29 useEffect(() => () => requestRef.current?.abort(), []);
30​
31 const share = useCallback(
32 (target: FileChipTarget) => {
33 const source = fileChipShareSource(target, threadId);
34 if (!source || requestRef.current) return;
35 const request = new AbortController();
36 requestRef.current = request;
37 const httpBaseUrl = connectionRef.current;
38 void (async () => {
39 if (httpBaseUrl === null) throw new Error("Reconnect to the environment and try again.");
40 const result = await createUrl({ environmentId, input: { resource: source.resource } });
41 if (request.signal.aborted) return;
42 const url =
43 result._tag === "Success" ? resolveAssetUrl(httpBaseUrl, result.value.relativeUrl) : null;
44 if (url === null) throw new Error("The file could not be loaded. Reconnect and try again.");
45 await downloadAndShareAttachment({
46 url,
47 attachment: source,
48 signal: request.signal,
49 sourceIdentifier,
50 });
51 })()
52 .catch((error: unknown) => {
53 if (!request.signal.aborted) {
54 Dialog.alert(
55 "Could not share file",
56 error instanceof Error ? error.message : "Try again.",
57 );
58 }
59 })
60 .finally(() => {
61 if (requestRef.current === request) {
62 requestRef.current = null;
63 }
64 });
65 },
66 [createUrl, environmentId, sourceIdentifier, threadId],
67 );
68 return share;