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