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