Open History to see the last commit
1import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
2import * as Dialog from "../components/ui/Dialog";
3import type { MediaActionsSource } from "../lib/mediaActionsSource";
4import { useNavigation } from "@react-navigation/native";
5import {
6 formatFilePathForClipboard,
7 type MediaActionId,
8} from "@t3tools/client-runtime/media-actions";
9import {
10 AuthFilesystemReadScope,
11 type EnvironmentId,
12 sessionGrantsScope,
13 type SessionGrantInput,
14} from "@t3tools/contracts";
15import { normalizeNativeMarkdownUrl } from "../lib/markdownLinks";
16import { AsyncResult } from "effect/reactivity";
17import { useEffect, useRef, useState } from "react";
18
19import { useRefreshAssetUrl } from "./assets";
20import { appAtomRegistry } from "./atom-registry";
21import { useEnvironmentQuery } from "./query";
22import { environmentSession } from "./session";
23import { downloadAndShareAttachment, shareLocalAttachment } from "../lib/attachmentDownload";
24import { copyTextWithHaptic } from "../lib/copyTextWithHaptic";
25import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
26
27function allowsHostMedia(session: SessionGrantInput | null) {
28 return session === null || sessionGrantsScope(session, AuthFilesystemReadScope);
29}
30
31function canReadHostMedia(environmentId: EnvironmentId | null): boolean {
32 if (environmentId === null) return true;
33 const result = appAtomRegistry.get(environmentSession.sessionStateAtom(environmentId));
34 return result._tag !== "Failure" && allowsHostMedia(AsyncResult.getOrElse(result, () => null));
35}
36
37export function useMediaActions(source: MediaActionsSource | undefined, onOpenFile?: () => void) {
38 const navigation = useNavigation();
39 const hostEnvironmentId =
40 source &&
41 "resource" in source &&
42 (source.resource._tag === "workspace-file" || source.resource._tag === "media-file")
43 ? source.environmentId
44 : null;
45 const fileSession = useEnvironmentQuery(
46 hostEnvironmentId === null ? null : environmentSession.sessionStateAtom(hostEnvironmentId),
47 );
48 const canReadMedia =
49 hostEnvironmentId === null ||
50 (fileSession.error === null && fileSession.data !== null && allowsHostMedia(fileSession.data));
51 const refresh = useRefreshAssetUrl(
52 source && "environmentId" in source ? source.environmentId : null,
53 source && "resource" in source ? source.resource : null,
54 );
55 const controller = useRef<AbortController | null>(null);
56 const [sharing, setSharing] = useState(false);
57 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- aborts the in-flight media share when the component unmounts
58 useEffect(() => () => controller.current?.abort(), []);
59
60 const share = () => {
61 if (!source || controller.current || !canReadHostMedia(hostEnvironmentId)) return;
62 const request = new AbortController();
63 controller.current = request;
64 setSharing(true);
65 return (async () => {
66 if ("attachment" in source) {
67 const preview = await loadLocalAttachmentPreview(source.attachment, request.signal);
68 if (!preview) return;
69 const shared = await settlePromise(() =>
70 preview.share(request.signal, source.sourceIdentifier),
71 );
72 preview.dispose();
73 if (AsyncResult.isFailure(shared)) throw squashAtomCommandFailure(shared);
74 return;
75 }
76 const uri = "uri" in source ? normalizeNativeMarkdownUrl(source.uri) : await refresh();
77 if (request.signal.aborted || !canReadHostMedia(hostEnvironmentId)) return;
78 if (uri === null) throw new Error("The file could not be loaded. Reconnect and try again.");
79 const input = {
80 attachment: { name: source.name, mimeType: source.mimeType },
81 signal: request.signal,
82 sourceIdentifier: source.sourceIdentifier,
83 };
84 if (/^(file|content):/i.test(uri)) await shareLocalAttachment({ ...input, uri });
85 else await downloadAndShareAttachment({ ...input, url: uri });
86 })()
87 .catch((error: unknown) => {
88 if (!request.signal.aborted) {
89 Dialog.alert(
90 "Could not share file",
91 error instanceof Error ? error.message : "Try again.",
92 );
93 }
94 })
95 .finally(() => {
96 if (controller.current === request) {
97 controller.current = null;
98 if (!request.signal.aborted) setSharing(false);
99 }
100 });
101 };
102
103 const reference = source?.reference;
104 const relativePath = reference?.kind === "file" ? reference.relativePath : undefined;
105 const threadId = source && "threadId" in source ? source.threadId : undefined;
106 const actions: { id: MediaActionId; title: string; run: () => void; disabled?: boolean }[] =
107 source
108 ? [
109 ...(reference?.kind === "file"
110 ? [
111 {
112 id: "copy-full-path" as const,
113 title: "Copy full path",
114 run: () => copyTextWithHaptic(formatFilePathForClipboard(reference.path)),
115 },
116 ]
117 : []),
118 ...(relativePath && reference?.kind === "file"
119 ? [
120 {
121 id: "copy-relative-path" as const,
122 title: "Copy relative path",
123 run: () =>
124 copyTextWithHaptic(formatFilePathForClipboard(relativePath, reference.path)),
125 },
126 ]
127 : []),
128 ...(reference?.kind === "url"
129 ? [
130 {
131 id: "copy-url" as const,
132 title: "Copy URL",
133 run: () => copyTextWithHaptic(reference.url),
134 },
135 ]
136 : []),
137 ...(relativePath && "environmentId" in source && threadId !== undefined
138 ? [
139 {
140 id: "open-file" as const,
141 title: "Open in file viewer",
142 disabled: !canReadMedia,
143 run: () => {
144 if (!canReadHostMedia(hostEnvironmentId)) return;
145 onOpenFile?.();
146 navigation.navigate("ThreadFile", {
147 environmentId: String(source.environmentId),
148 threadId: String(threadId),
149 path: relativePath.split("/"),
150 });
151 },
152 },
153 ]
154 : []),
155 {
156 id: "save" as const,
157 title: sharing ? "Opening share sheet…" : "Save or share",
158 run: share,
159 disabled: sharing || !canReadMedia,
160 },
161 ]
162 : [];
163 return {
164 title: reference?.kind === "file" ? reference.path : reference?.url,
165 actions,
166 sharing,
167 share,
168 };
169}