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

mediaActions.ts

236 lines9.1 KB

1import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
2import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
3import * as Dialog from "../components/ui/Dialog";
4import type { MediaActionsSource } from "../lib/mediaActionsSource";
5import { useNavigation } from "@react-navigation/native";
6import { msg, useGT } from "gt-react-native";
7import { m } from "../i18n/messages";
8import {
9 formatFilePathForClipboard,
10 type MediaActionId,
11} from "@t3tools/client-runtime/media-actions";
12import {
13 AuthFilesystemReadScope,
14 type EnvironmentId,
15 sessionGrantsScope,
16 type SessionGrantInput,
17} from "@t3tools/contracts";
18import { normalizeNativeMarkdownUrl } from "../lib/markdownLinks";
19import { AsyncResult } from "effect/reactivity";
20import * as Haptics from "expo-haptics";
21import { useEffect, useRef, useState } from "react";
22​
23import { useRefreshAssetUrl } from "./assets";
24import { appAtomRegistry } from "./atom-registry";
25import { useEnvironmentQuery } from "./query";
26import { environmentSession } from "./session";
27import {
28 downloadAndShareAttachment,
29 downloadAttachmentForPreview,
30 shareLocalAttachment,
31} from "../lib/attachmentDownload";
32import { copyTextWithHaptic } from "../lib/copyTextWithHaptic";
33import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
34import { canSaveImageToLibrary, saveImageToLibrary } from "../lib/saveImageToLibrary";
35​
36function allowsHostMedia(session: SessionGrantInput | null) {
37 return session === null || sessionGrantsScope(session, AuthFilesystemReadScope);
39​
40function canReadHostMedia(environmentId: EnvironmentId | null): boolean {
41 if (environmentId === null) return true;
42 const result = appAtomRegistry.get(environmentSession.sessionStateAtom(environmentId));
43 return result._tag !== "Failure" && allowsHostMedia(AsyncResult.getOrElse(result, () => null));
45​
46export function useMediaActions(
47 source: MediaActionsSource | undefined,
48 onOpenFile?: () => void,
49 options?: { readonly getSaveImageSignal: () => AbortSignal },
50) {
51 const navigation = useNavigation();
52 const gt = useGT();
53 const hostEnvironmentId =
54 source &&
55 "resource" in source &&
56 (source.resource._tag === "workspace-file" || source.resource._tag === "media-file")
57 ? source.environmentId
58 : null;
59 const fileSession = useEnvironmentQuery(
60 hostEnvironmentId === null ? null : environmentSession.sessionStateAtom(hostEnvironmentId),
61 );
62 const canReadMedia =
63 hostEnvironmentId === null ||
64 (fileSession.error === null && fileSession.data !== null && allowsHostMedia(fileSession.data));
65 const refresh = useRefreshAssetUrl(
66 source && "environmentId" in source ? source.environmentId : null,
67 source && "resource" in source ? source.resource : null,
68 );
69 const controller = useRef<AbortController | null>(null);
70 const [busy, setBusy] = useState<"share" | "save-image" | null>(null);
71 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- cancels page-owned work and stops updating busy state on unmount
72 useEffect(() => () => controller.current?.abort(), []);
73​
74 const run = (
75 kind: "share" | "save-image",
76 task: (source: MediaActionsSource, signal: AbortSignal) => Promise<void>,
77 ) => {
78 if (!source || controller.current || !canReadHostMedia(hostEnvironmentId)) return;
79 const request = new AbortController();
80 controller.current = request;
81 setBusy(kind);
82 const signal = kind === "save-image" && options ? options.getSaveImageSignal() : request.signal;
83 return task(source, signal)
84 .catch((error: unknown) => {
85 if (!signal.aborted) {
86 Dialog.alert(
87 kind === "share" ? m(msg("Could not share file")) : m(msg("Could not save image")),
88 errorDisplayMessage(error, m) ?? m(msg("Try again.")),
89 );
90 }
91 })
92 .finally(() => {
93 if (controller.current === request) {
94 controller.current = null;
95 if (!request.signal.aborted) setBusy(null);
96 }
97 });
98 };
99​
100 const hostUri = async (source: MediaActionsSource, signal: AbortSignal) => {
101 const uri = "uri" in source ? normalizeNativeMarkdownUrl(source.uri) : await refresh();
102 if (signal.aborted || !canReadHostMedia(hostEnvironmentId)) return null;
103 if (uri === null) {
104 throw new Error(m(msg("The file could not be loaded. Reconnect and try again.")));
105 }
106 return uri;
107 };
108​
109 const share = () =>
110 run("share", async (source, signal) => {
111 if ("attachment" in source) {
112 const preview = await loadLocalAttachmentPreview(source.attachment, signal);
113 if (!preview) return;
114 const shared = await settlePromise(() => preview.share(signal, source.sourceIdentifier));
115 preview.dispose();
116 if (AsyncResult.isFailure(shared)) throw squashAtomCommandFailure(shared);
117 return;
118 }
119 const uri = await hostUri(source, signal);
120 if (uri === null) return;
121 const input = {
122 attachment: { name: source.name, mimeType: source.mimeType },
123 signal,
124 sourceIdentifier: source.sourceIdentifier,
125 };
126 if (/^(file|content):/i.test(uri)) await shareLocalAttachment({ ...input, uri });
127 else await downloadAndShareAttachment({ ...input, url: uri });
128 });
129​
130 const localImageFile = async (source: MediaActionsSource, signal: AbortSignal) => {
131 if ("attachment" in source) return loadLocalAttachmentPreview(source.attachment, signal);
132 const uri = await hostUri(source, signal);
133 if (uri === null) return null;
134 if (/^(file|content):/i.test(uri)) return { uri, dispose: () => {} };
135 return downloadAttachmentForPreview({
136 url: uri,
137 attachment: { name: source.name, mimeType: source.mimeType },
138 signal,
139 });
140 };
141​
142 const saveImage = () =>
143 run("save-image", async (source, signal) => {
144 const file = await localImageFile(source, signal);
145 if (!file) return;
146 const saved = signal.aborted
147 ? null
148 : await settlePromise(() => saveImageToLibrary(file.uri, source.mimeType, source.name));
149 file.dispose();
150 if (saved === null) return;
151 if (AsyncResult.isFailure(saved)) throw squashAtomCommandFailure(saved);
152 void Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {});
153 });
154​
155 const reference = source?.reference;
156 const relativePath = reference?.kind === "file" ? reference.relativePath : undefined;
157 const threadId = source && "threadId" in source ? source.threadId : undefined;
158 const actions: { id: MediaActionId; title: string; run: () => void; disabled?: boolean }[] =
159 source
160 ? [
161 ...(reference?.kind === "file"
162 ? [
163 {
164 id: "copy-full-path" as const,
165 title: gt("Copy full path"),
166 run: () => copyTextWithHaptic(formatFilePathForClipboard(reference.path)),
167 },
168 ]
169 : []),
170 ...(relativePath && reference?.kind === "file"
171 ? [
172 {
173 id: "copy-relative-path" as const,
174 title: gt("Copy relative path"),
175 run: () =>
176 copyTextWithHaptic(formatFilePathForClipboard(relativePath, reference.path)),
177 },
178 ]
179 : []),
180 ...(reference?.kind === "url"
181 ? [
182 {
183 id: "copy-url" as const,
184 title: gt("Copy URL"),
185 run: () => copyTextWithHaptic(reference.url),
186 },
187 ]
188 : []),
189 ...(relativePath && "environmentId" in source && threadId !== undefined
190 ? [
191 {
192 id: "open-file" as const,
193 title: gt("Open in file viewer"),
194 disabled: !canReadMedia,
195 run: () => {
196 if (!canReadHostMedia(hostEnvironmentId)) return;
197 onOpenFile?.();
198 navigation.navigate("ThreadFile", {
199 environmentId: String(source.environmentId),
200 threadId: String(threadId),
201 path: relativePath.split("/"),
202 });
203 },
204 },
205 ]
206 : []),
207 ...(canSaveImageToLibrary(source.mimeType)
208 ? [
209 {
210 id: "save-image" as const,
211 title: busy === "save-image" ? gt("Saving image…") : gt("Save image"),
212 run: saveImage,
213 disabled: busy !== null || !canReadMedia,
214 },
215 ]
216 : []),
217 {
218 id: "save" as const,
219 title:
220 busy === "share"
221 ? gt("Opening share sheet…")
222 : canSaveImageToLibrary(source.mimeType)
223 ? gt("Share", { $context: "verb, opens the system share sheet" })
224 : gt("Save or share"),
225 run: share,
226 disabled: busy !== null || !canReadMedia,
227 },
228 ]
229 : [];
230 return {
231 title: reference?.kind === "file" ? reference.path : reference?.url,
232 actions,
233 sharing: busy === "share",
234 share,
235 };