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