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

MediaActions.tsx

237 lines9.3 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}: {
117 source: MediaActionSource;
118 children: ReactElement;
119}) {
120 const { save, copyImage, canReadMedia, assertCanReadMedia } = useMediaActions(source);
121 const [tooltipOpen, setTooltipOpen] = useState(false);
122 const menuOpen = useRef(false);
123 const reference = source.reference;
124 const tooltip = reference?.kind === "file" ? reference.path : (reference?.url ?? source.name);
125​
126 const showMenu = async (position: { x: number; y: number }) => {
127 const api = readLocalApi();
128 if (!api || menuOpen.current) return;
129 menuOpen.current = true;
130 setTooltipOpen(false);
131 let failureTitle = "Could not open media menu";
132 let progressToast: ReturnType<typeof toastManager.add> | undefined;
133 const result = await settlePromise(async () => {
134 const noun = source.kind === "image" ? "image" : "video";
135 const unavailable = !canReadMedia || (source.src === null && source.asset === undefined);
136 const canCopyImage =
137 typeof navigator !== "undefined" &&
138 Boolean(navigator.clipboard?.write) &&
139 typeof ClipboardItem !== "undefined";
140 const items: ContextMenuItem<MediaActionId>[] = [];
141 if (reference?.kind === "file") {
142 items.push({ id: "copy-full-path", label: "Copy full path" });
143 if (reference.relativePath)
144 items.push({ id: "copy-relative-path", label: "Copy relative path" });
145 } else if (reference?.kind === "url") {
146 items.push({ id: "copy-url", label: "Copy URL" });
147 }
148 if (source.onOpenFile)
149 items.push({ id: "open-file", label: "Open in file viewer", disabled: !canReadMedia });
150 items.push({ id: "save", label: `Save ${noun}`, disabled: unavailable });
151 if (source.kind === "image") {
152 items.push({
153 id: "copy-image",
154 label: "Copy image",
155 disabled: unavailable || !canCopyImage,
156 });
157 }
158​
159 const action = await api.contextMenu.show(items, position);
160 if (!action) return;
161 failureTitle = `Could not ${items.find((item) => item.id === action)?.label.toLowerCase() ?? "complete media action"}`;
162 const text =
163 action === "copy-full-path" && reference?.kind === "file"
164 ? reference.path
165 : action === "copy-relative-path" && reference?.kind === "file"
166 ? reference.relativePath
167 : action === "copy-url" && reference?.kind === "url"
168 ? reference.url
169 : undefined;
170 if (text !== undefined) {
171 const clipboardText =
172 reference?.kind === "file" ? formatFilePathForClipboard(text, reference.path) : text;
173 await writeTextToClipboard(clipboardText, reference?.kind === "file" ? "file path" : "URL");
174 toastManager.add({
175 type: "success",
176 title: action === "copy-url" ? "URL copied" : "Path copied",
177 });
178 } else if (action === "open-file") {
179 assertCanReadMedia();
180 source.onOpenFile?.();
181 } else if (action === "save" || action === "copy-image") {
182 progressToast = toastManager.add({
183 type: "loading",
184 title: action === "save" ? `Preparing ${noun} download…` : "Copying image…",
185 });
186 await (action === "save" ? save() : copyImage());
187 toastManager.update(progressToast, {
188 type: "success",
189 title: action === "save" ? "Download started" : "Image copied",
190 });
191 }
192 });
193 if (AsyncResult.isFailure(result)) {
194 const error = squashAtomCommandFailure(result);
195 const toast = stackedThreadToast({
196 type: "error",
197 title: failureTitle,
198 description: error instanceof Error ? error.message : "The media action failed.",
199 });
200 if (progressToast) toastManager.update(progressToast, toast);
201 else toastManager.add(toast);
202 }
203 menuOpen.current = false;
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 );