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

MediaActions.tsx

233 lines9.3 KB

1import type { MediaActionId } from "@t3tools/client-runtime/media-actions";
2import {
3 mediaReferenceFileName,
4 type MediaReference,
5} from "@t3tools/client-runtime/media-reference";
6import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
7import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
8import {
9 AuthFilesystemReadScope,
10 type AssetResource,
11 type AuthSessionState,
12 type ContextMenuItem,
13 type EnvironmentId,
14 sessionGrantsScope,
15 type SessionGrantInput,
16} from "@t3tools/contracts";
17import * as Option from "effect/Option";
18import { AsyncResult } from "effect/reactivity";
19import { useCallback, useRef, useState, type ReactElement } from "react";
20​
21import { writeTextToClipboard } from "../../hooks/useCopyToClipboard";
22import { readLocalApi } from "../../localApi";
23import { appAtomRegistry } from "../../rpc/atomRegistry";
24import { assetEnvironment } from "../../state/assets";
25import { useEnvironmentQuery } from "../../state/query";
26import { environmentSession, readPreparedConnection } from "../../state/session";
27import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
28import { stackedThreadToast, toastManager } from "../ui/toast";
29import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
30import { downloadMedia, readMediaPng } from "./mediaContent";
31​
32export interface MediaActionSource {
33 readonly kind: "image" | "video";
34 readonly name: string;
35 readonly src: string | null;
36 readonly reference?: MediaReference;
37 readonly asset?: { readonly environmentId: EnvironmentId; readonly resource: AssetResource };
38 readonly onOpenFile?: () => void;
40​
41function mediaFileName(source: MediaActionSource): string {
42 return (
43 (source.reference && mediaReferenceFileName(source.reference)) || source.name || source.kind
44 );
46​
47function allowsHostMedia(session: SessionGrantInput | null) {
48 return session === null || sessionGrantsScope(session, AuthFilesystemReadScope);
50​
51function canReadHostMedia(environmentId: EnvironmentId | null): boolean {
52 if (environmentId === null) return true;
53 const result = appAtomRegistry.get(environmentSession.sessionStateAtom(environmentId));
54 return result._tag !== "Failure" && allowsHostMedia(Option.getOrNull(AsyncResult.value(result)));
56​
57export function useMediaActions(source: MediaActionSource) {
58 const hostEnvironmentId =
59 source.asset &&
60 (source.asset.resource._tag === "workspace-file" || source.asset.resource._tag === "media-file")
61 ? source.asset.environmentId
62 : null;
63 const fileSession = useEnvironmentQuery(
64 hostEnvironmentId === null ? null : environmentSession.sessionStateAtom(hostEnvironmentId),
65 );
66 const canReadMedia =
67 hostEnvironmentId === null ||
68 (fileSession.error === null && fileSession.data !== null && allowsHostMedia(fileSession.data));
69 const assertCanReadMedia = useCallback(() => {
70 if (!canReadHostMedia(hostEnvironmentId)) {
71 throw new Error("This connection cannot read host files.");
72 }
73 }, [hostEnvironmentId]);
74 const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
75 reportFailure: false,
76 refresh: true,
77 });
78 const actionUrl = useCallback(async () => {
79 assertCanReadMedia();
80 if (!source.asset) {
81 if (!source.src) throw new Error("This media is unavailable. Try reopening the preview.");
82 return source.src;
83 }
84 const { environmentId, resource } = source.asset;
85 const connection = readPreparedConnection(environmentId);
86 if (!connection) throw new Error("Reconnect to this environment and try again.");
87 const result = await createAssetUrl({ environmentId, input: { resource } });
88 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
89 assertCanReadMedia();
90 const url = resolveAssetUrl(connection.httpBaseUrl, result.value.relativeUrl);
91 if (!url) throw new Error("The environment returned an invalid media URL.");
92 return url;
93 }, [source, createAssetUrl, assertCanReadMedia]);
94 const save = useCallback(async () => {
95 await downloadMedia(await actionUrl(), mediaFileName(source));
96 }, [actionUrl, source]);
97 const copyImage = useCallback(async () => {
98 assertCanReadMedia();
99 if (!navigator.clipboard?.write || typeof ClipboardItem === "undefined") {
100 throw new Error(
101 "Image copying is unavailable. Use a secure browser connection or save the image.",
102 );
103 }
104 // Start the clipboard write in the user gesture; fetching/decoding may finish later.
105 await navigator.clipboard.write([
106 new ClipboardItem({ "image/png": actionUrl().then(readMediaPng) }),
107 ]);
108 }, [actionUrl, assertCanReadMedia]);
109 return { save, copyImage, canReadMedia, assertCanReadMedia };
111​
112export function MediaActions({
113 source,
114 children,
115}: {
116 source: MediaActionSource;
117 children: ReactElement;
118}) {
119 const { save, copyImage, canReadMedia, assertCanReadMedia } = useMediaActions(source);
120 const [tooltipOpen, setTooltipOpen] = useState(false);
121 const menuOpen = useRef(false);
122 const reference = source.reference;
123 const tooltip = reference?.kind === "file" ? reference.path : (reference?.url ?? source.name);
124​
125 const showMenu = async (position: { x: number; y: number }) => {
126 const api = readLocalApi();
127 if (!api || menuOpen.current) return;
128 menuOpen.current = true;
129 setTooltipOpen(false);
130 let failureTitle = "Could not open media menu";
131 let progressToast: ReturnType<typeof toastManager.add> | undefined;
132 try {
133 const noun = source.kind === "image" ? "image" : "video";
134 const unavailable = !canReadMedia || (source.src === null && source.asset === undefined);
135 const canCopyImage =
136 typeof navigator !== "undefined" &&
137 Boolean(navigator.clipboard?.write) &&
138 typeof ClipboardItem !== "undefined";
139 const items: ContextMenuItem<MediaActionId>[] = [];
140 if (reference?.kind === "file") {
141 items.push({ id: "copy-full-path", label: "Copy full path" });
142 if (reference.relativePath)
143 items.push({ id: "copy-relative-path", label: "Copy relative path" });
144 } else if (reference?.kind === "url") {
145 items.push({ id: "copy-url", label: "Copy URL" });
146 }
147 if (source.onOpenFile)
148 items.push({ id: "open-file", label: "Open in file viewer", disabled: !canReadMedia });
149 items.push({ id: "save", label: `Save ${noun}`, disabled: unavailable });
150 if (source.kind === "image") {
151 items.push({
152 id: "copy-image",
153 label: "Copy image",
154 disabled: unavailable || !canCopyImage,
155 });
156 }
157​
158 const action = await api.contextMenu.show(items, position);
159 if (!action) return;
160 failureTitle = `Could not ${items.find((item) => item.id === action)?.label.toLowerCase() ?? "complete media action"}`;
161 const text =
162 action === "copy-full-path" && reference?.kind === "file"
163 ? reference.path
164 : action === "copy-relative-path" && reference?.kind === "file"
165 ? reference.relativePath
166 : action === "copy-url" && reference?.kind === "url"
167 ? reference.url
168 : undefined;
169 if (text !== undefined) {
170 await writeTextToClipboard(text, reference?.kind === "file" ? "file path" : "URL");
171 toastManager.add({
172 type: "success",
173 title: action === "copy-url" ? "URL copied" : "Path copied",
174 });
175 } else if (action === "open-file") {
176 assertCanReadMedia();
177 source.onOpenFile?.();
178 } else if (action === "save" || action === "copy-image") {
179 progressToast = toastManager.add({
180 type: "loading",
181 title: action === "save" ? `Preparing ${noun} download…` : "Copying image…",
182 });
183 await (action === "save" ? save() : copyImage());
184 toastManager.update(progressToast, {
185 type: "success",
186 title: action === "save" ? "Download started" : "Image copied",
187 });
188 }
189 } catch (error) {
190 const toast = stackedThreadToast({
191 type: "error",
192 title: failureTitle,
193 description: error instanceof Error ? error.message : "The media action failed.",
194 });
195 if (progressToast) toastManager.update(progressToast, toast);
196 else toastManager.add(toast);
197 } finally {
198 menuOpen.current = false;
199 }
200 };
201​
202 return (
203 <Tooltip open={tooltipOpen} onOpenChange={setTooltipOpen}>
204 <TooltipTrigger
205 render={children}
206 tabIndex={0}
207 onContextMenu={(event) => {
208 if (event.defaultPrevented) return;
209 event.preventDefault();
210 event.stopPropagation();
211 const bounds = event.currentTarget.getBoundingClientRect();
212 void showMenu(
213 event.clientX === 0 && event.clientY === 0
214 ? { x: bounds.left, y: bounds.bottom }
215 : { x: event.clientX, y: event.clientY },
216 );
217 }}
218 onKeyDown={(event) => {
219 if (
220 event.defaultPrevented ||
221 !(event.key === "ContextMenu" || (event.shiftKey && event.key === "F10"))
222 )
223 return;
224 event.preventDefault();
225 event.stopPropagation();
226 const bounds = event.currentTarget.getBoundingClientRect();
227 void showMenu({ x: bounds.left, y: bounds.bottom });
228 }}
229 />
230 <TooltipPopup variant="code">{tooltip}</TooltipPopup>
231 </Tooltip>
232 );