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

MediaActions.tsx

239 lines9.4 KB

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