Open History to see the last commit
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 { useEffect, 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 requestRef = useRef<AbortController | null>(null);
25 useEffect(() => () => requestRef.current?.abort(), []);
26
27 return (target: FileChipTarget) => {
28 const source = fileChipShareSource(target, threadId);
29 if (!source || requestRef.current) return;
30 const request = new AbortController();
31 requestRef.current = request;
32 void (async () => {
33 if (httpBaseUrl === null) throw new Error("Reconnect to the environment and try again.");
34 const result = await createUrl({ environmentId, input: { resource: source.resource } });
35 if (request.signal.aborted) return;
36 const url =
37 result._tag === "Success" ? resolveAssetUrl(httpBaseUrl, result.value.relativeUrl) : null;
38 if (url === null) throw new Error("The file could not be loaded. Reconnect and try again.");
39 await downloadAndShareAttachment({
40 url,
41 attachment: source,
42 signal: request.signal,
43 sourceIdentifier,
44 });
45 })()
46 .catch((error: unknown) => {
47 if (!request.signal.aborted) {
48 Dialog.alert(
49 "Could not share file",
50 error instanceof Error ? error.message : "Try again.",
51 );
52 }
53 })
54 .finally(() => {
55 if (requestRef.current === request) {
56 requestRef.current = null;
57 }
58 });
59 };
60}