Open History to see the last commit
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;
39}
40
41function mediaFileName(source: MediaActionSource): string {
42 return (
43 (source.reference && mediaReferenceFileName(source.reference)) || source.name || source.kind
44 );
45}
46
47/** An explicit action may ask the server while its grant is still unresolved. */
48function allowsHostMedia(session: SessionGrantInput | null) {
49 return session === null || sessionGrantsScope(session, AuthFilesystemReadScope);
50}
51
52function canReadHostMedia(environmentId: EnvironmentId | null): boolean {
53 if (environmentId === null) return true;
54 const result = appAtomRegistry.get(environmentSession.sessionStateAtom(environmentId));
55 return result._tag !== "Failure" && allowsHostMedia(Option.getOrNull(AsyncResult.value(result)));
56}
57
58/** Explicit byte operations get fresh capabilities without replacing a player's active source. */
59/** Exported for tests that drive the byte operations without the menu. */
60export function useMediaActions(source: MediaActionSource) {
61 const hostEnvironmentId =
62 source.asset &&
63 (source.asset.resource._tag === "workspace-file" || source.asset.resource._tag === "media-file")
64 ? source.asset.environmentId
65 : null;
66 const fileSession = useEnvironmentQuery(
67 hostEnvironmentId === null ? null : environmentSession.sessionStateAtom(hostEnvironmentId),
68 );
69 const canReadMedia =
70 hostEnvironmentId === null ||
71 (fileSession.error === null && fileSession.data !== null && allowsHostMedia(fileSession.data));
72 const assertCanReadMedia = useCallback(() => {
73 if (!canReadHostMedia(hostEnvironmentId)) {
74 throw new Error("This connection cannot read host files.");
75 }
76 }, [hostEnvironmentId]);
77 const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
78 reportFailure: false,
79 refresh: true,
80 });
81 const actionUrl = useCallback(async () => {
82 assertCanReadMedia();
83 if (!source.asset) {
84 if (!source.src) throw new Error("This media is unavailable. Try reopening the preview.");
85 return source.src;
86 }
87 const { environmentId, resource } = source.asset;
88 const connection = readPreparedConnection(environmentId);
89 if (!connection) throw new Error("Reconnect to this environment and try again.");
90 const result = await createAssetUrl({ environmentId, input: { resource } });
91 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
92 assertCanReadMedia();
93 const url = resolveAssetUrl(connection.httpBaseUrl, result.value.relativeUrl);
94 if (!url) throw new Error("The environment returned an invalid media URL.");
95 return url;
96 }, [source, createAssetUrl, assertCanReadMedia]);
97 const save = useCallback(async () => {
98 await downloadMedia(await actionUrl(), mediaFileName(source));
99 }, [actionUrl, source]);
100 const copyImage = useCallback(async () => {
101 assertCanReadMedia();
102 if (!navigator.clipboard?.write || typeof ClipboardItem === "undefined") {
103 throw new Error(
104 "Image copying is unavailable. Use a secure browser connection or save the image.",
105 );
106 }
107 // Start the clipboard write in the user gesture; fetching/decoding may finish later.
108 await navigator.clipboard.write([
109 new ClipboardItem({ "image/png": actionUrl().then(readMediaPng) }),
110 ]);
111 }, [actionUrl, assertCanReadMedia]);
112 return { save, copyImage, canReadMedia, assertCanReadMedia };
113}
114
115/** Adds source-aware actions and a tooltip to the existing media element without a layout wrapper. */
116export function MediaActions({
117 source,
118 children,
119}: {
120 source: MediaActionSource;
121 children: ReactElement;
122}) {
123 const { save, copyImage, canReadMedia, assertCanReadMedia } = useMediaActions(source);
124 const [tooltipOpen, setTooltipOpen] = useState(false);
125 const menuOpen = useRef(false);
126 const reference = source.reference;
127 const tooltip = reference?.kind === "file" ? reference.path : (reference?.url ?? source.name);
128
129 const showMenu = async (position: { x: number; y: number }) => {
130 const api = readLocalApi();
131 if (!api || menuOpen.current) return;
132 menuOpen.current = true;
133 setTooltipOpen(false);
134 let failureTitle = "Could not open media menu";
135 let progressToast: ReturnType<typeof toastManager.add> | undefined;
136 try {
137 const noun = source.kind === "image" ? "image" : "video";
138 const unavailable = !canReadMedia || (source.src === null && source.asset === undefined);
139 const canCopyImage =
140 typeof navigator !== "undefined" &&
141 Boolean(navigator.clipboard?.write) &&
142 typeof ClipboardItem !== "undefined";
143 const items: ContextMenuItem<MediaActionId>[] = [];
144 if (reference?.kind === "file") {
145 items.push({ id: "copy-full-path", label: "Copy full path" });
146 if (reference.relativePath)
147 items.push({ id: "copy-relative-path", label: "Copy relative path" });
148 } else if (reference?.kind === "url") {
149 items.push({ id: "copy-url", label: "Copy URL" });
150 }
151 if (source.onOpenFile)
152 items.push({ id: "open-file", label: "Open in file viewer", disabled: !canReadMedia });
153 items.push({ id: "save", label: `Save ${noun}`, disabled: unavailable });
154 if (source.kind === "image") {
155 items.push({
156 id: "copy-image",
157 label: "Copy image",
158 disabled: unavailable || !canCopyImage,
159 });
160 }
161
162 const action = await api.contextMenu.show(items, position);
163 if (!action) return;
164 failureTitle = `Could not ${items.find((item) => item.id === action)?.label.toLowerCase() ?? "complete media action"}`;
165 const text =
166 action === "copy-full-path" && reference?.kind === "file"
167 ? reference.path
168 : action === "copy-relative-path" && reference?.kind === "file"
169 ? reference.relativePath
170 : action === "copy-url" && reference?.kind === "url"
171 ? reference.url
172 : undefined;
173 if (text !== undefined) {
174 await writeTextToClipboard(text, 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 } catch (error) {
194 const toast = stackedThreadToast({
195 type: "error",
196 title: failureTitle,
197 description: error instanceof Error ? error.message : "The media action failed.",
198 });
199 if (progressToast) toastManager.update(progressToast, toast);
200 else toastManager.add(toast);
201 } finally {
202 menuOpen.current = false;
203 }
204 };
205
206 return (
207 <Tooltip open={tooltipOpen} onOpenChange={setTooltipOpen}>
208 <TooltipTrigger
209 render={children}
210 tabIndex={0}
211 onContextMenu={(event) => {
212 if (event.defaultPrevented) return;
213 event.preventDefault();
214 event.stopPropagation();
215 const bounds = event.currentTarget.getBoundingClientRect();
216 void showMenu(
217 event.clientX === 0 && event.clientY === 0
218 ? { x: bounds.left, y: bounds.bottom }
219 : { x: event.clientX, y: event.clientY },
220 );
221 }}
222 onKeyDown={(event) => {
223 if (
224 event.defaultPrevented ||
225 !(event.key === "ContextMenu" || (event.shiftKey && event.key === "F10"))
226 )
227 return;
228 event.preventDefault();
229 event.stopPropagation();
230 const bounds = event.currentTarget.getBoundingClientRect();
231 void showMenu({ x: bounds.left, y: bounds.bottom });
232 }}
233 />
234 <TooltipPopup variant="code">{tooltip}</TooltipPopup>
235 </Tooltip>
236 );
237}