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

mediaActions.ts

164 lines6.2 KB

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