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