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

MediaActions.tsx

192 lines7.7 KB

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