The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; |
| 2 | import { |
| 3 | formatFilePathForClipboard, |
| 4 | type MediaActionId, |
| 5 | } from "@t3tools/client-runtime/media-actions"; |
| 6 | import { |
| 7 | mediaReferenceFileName, |
| 8 | type MediaReference, |
| 9 | } from "@t3tools/client-runtime/media-reference"; |
| 10 | import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets"; |
| 11 | import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; |
| 12 | import { |
| 13 | AuthFilesystemReadScope, |
| 14 | type AssetResource, |
| 15 | type ContextMenuItem, |
| 16 | type EnvironmentId, |
| 17 | sessionGrantsScope, |
| 18 | type SessionGrantInput, |
| 19 | } from "@t3tools/contracts"; |
| 20 | import { AsyncResult } from "effect/reactivity"; |
| 21 | import { msg } from "gt-react"; |
| 22 | import { useRef, useState, type ReactElement } from "react"; |
| 23 | |
| 24 | import { writeTextToClipboard } from "../../hooks/useCopyToClipboard"; |
| 25 | import { readLocalApi } from "../../localApi"; |
| 26 | import { appAtomRegistry } from "../../rpc/atomRegistry"; |
| 27 | import { assetEnvironment } from "../../state/assets"; |
| 28 | import { useEnvironmentQuery } from "../../state/query"; |
| 29 | import { environmentSession, readPreparedConnection } from "../../state/session"; |
| 30 | import { m } from "../../i18n/messages"; |
| 31 | import { useAtomQueryRunner } from "../../state/use-atom-query-runner"; |
| 32 | import { stackedThreadToast, toastManager } from "../ui/toast"; |
| 33 | import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; |
| 34 | import { downloadMedia, readMediaPng } from "./mediaContent"; |
| 35 | |
| 36 | export interface MediaActionSource { |
| 37 | readonly kind: "image" | "video"; |
| 38 | readonly name: string; |
| 39 | readonly src: string | null; |
| 40 | readonly reference?: MediaReference; |
| 41 | readonly asset?: { readonly environmentId: EnvironmentId; readonly resource: AssetResource }; |
| 42 | readonly onOpenFile?: () => void; |
| 43 | } |
| 44 | |
| 45 | function mediaFileName(source: MediaActionSource): string { |
| 46 | return ( |
| 47 | (source.reference && mediaReferenceFileName(source.reference)) || source.name || source.kind |
| 48 | ); |
| 49 | } |
| 50 | |
| 51 | function allowsHostMedia(session: SessionGrantInput | null) { |
| 52 | return session === null || sessionGrantsScope(session, AuthFilesystemReadScope); |
| 53 | } |
| 54 | |
| 55 | function canReadHostMedia(environmentId: EnvironmentId | null): boolean { |
| 56 | if (environmentId === null) return true; |
| 57 | const result = appAtomRegistry.get(environmentSession.sessionStateAtom(environmentId)); |
| 58 | return result._tag !== "Failure" && allowsHostMedia(AsyncResult.getOrElse(result, () => null)); |
| 59 | } |
| 60 | |
| 61 | export function useMediaActions(source: MediaActionSource) { |
| 62 | const hostEnvironmentId = |
| 63 | source.asset && |
| 64 | (source.asset.resource._tag === "workspace-file" || source.asset.resource._tag === "media-file") |
| 65 | ? source.asset.environmentId |
| 66 | : null; |
| 67 | const fileSession = useEnvironmentQuery( |
| 68 | hostEnvironmentId === null ? null : environmentSession.sessionStateAtom(hostEnvironmentId), |
| 69 | ); |
| 70 | const canReadMedia = |
| 71 | hostEnvironmentId === null || |
| 72 | (fileSession.error === null && fileSession.data !== null && allowsHostMedia(fileSession.data)); |
| 73 | const assertCanReadMedia = () => { |
| 74 | if (!canReadHostMedia(hostEnvironmentId)) { |
| 75 | throw new Error(m(msg("This connection cannot read host files."))); |
| 76 | } |
| 77 | }; |
| 78 | const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, { |
| 79 | reportFailure: false, |
| 80 | refresh: true, |
| 81 | }); |
| 82 | const actionUrl = async () => { |
| 83 | assertCanReadMedia(); |
| 84 | if (!source.asset) { |
| 85 | if (!source.src) { |
| 86 | throw new Error(m(msg("This media is unavailable. Try reopening the preview."))); |
| 87 | } |
| 88 | return source.src; |
| 89 | } |
| 90 | const { environmentId, resource } = source.asset; |
| 91 | const connection = readPreparedConnection(environmentId); |
| 92 | if (!connection) throw new Error(m(msg("Reconnect to this environment and try again."))); |
| 93 | const result = await createAssetUrl({ environmentId, input: { resource } }); |
| 94 | if (result._tag === "Failure") throw squashAtomCommandFailure(result); |
| 95 | assertCanReadMedia(); |
| 96 | const url = resolveAssetUrl(connection.httpBaseUrl, result.value.relativeUrl); |
| 97 | if (!url) throw new Error(m(msg("The environment returned an invalid media URL."))); |
| 98 | return url; |
| 99 | }; |
| 100 | const save = async () => { |
| 101 | await downloadMedia(await actionUrl(), mediaFileName(source)); |
| 102 | }; |
| 103 | const copyImage = async () => { |
| 104 | assertCanReadMedia(); |
| 105 | if (!navigator.clipboard?.write || typeof ClipboardItem === "undefined") { |
| 106 | throw new Error( |
| 107 | m(msg("Image copying is unavailable. Use a secure browser connection or save the image.")), |
| 108 | ); |
| 109 | } |
| 110 | // Start the clipboard write in the user gesture; fetching/decoding may finish later. |
| 111 | await navigator.clipboard.write([ |
| 112 | new ClipboardItem({ "image/png": actionUrl().then(readMediaPng) }), |
| 113 | ]); |
| 114 | }; |
| 115 | return { save, copyImage, canReadMedia, assertCanReadMedia }; |
| 116 | } |
| 117 | |
| 118 | export function MediaActions({ |
| 119 | source, |
| 120 | children, |
| 121 | showTooltip = true, |
| 122 | }: { |
| 123 | source: MediaActionSource; |
| 124 | children: ReactElement; |
| 125 | showTooltip?: boolean; |
| 126 | }) { |
| 127 | const { save, copyImage, canReadMedia, assertCanReadMedia } = useMediaActions(source); |
| 128 | const [tooltipOpen, setTooltipOpen] = useState(false); |
| 129 | const menuOpen = useRef(false); |
| 130 | const reference = source.reference; |
| 131 | const tooltip = reference?.kind === "file" ? reference.path : (reference?.url ?? source.name); |
| 132 | |
| 133 | const showMenu = async (position: { x: number; y: number }) => { |
| 134 | const api = readLocalApi(); |
| 135 | if (!api || menuOpen.current) return; |
| 136 | menuOpen.current = true; |
| 137 | setTooltipOpen(false); |
| 138 | let failureTitle = m(msg("Could not open media menu")); |
| 139 | let progressToast: ReturnType<typeof toastManager.add> | undefined; |
| 140 | const result = await settlePromise(async () => { |
| 141 | const isImage = source.kind === "image"; |
| 142 | const unavailable = !canReadMedia || (source.src === null && source.asset === undefined); |
| 143 | const canCopyImage = |
| 144 | typeof navigator !== "undefined" && |
| 145 | Boolean(navigator.clipboard?.write) && |
| 146 | typeof ClipboardItem !== "undefined"; |
| 147 | const items: ContextMenuItem<MediaActionId>[] = []; |
| 148 | if (reference?.kind === "file") { |
| 149 | items.push({ id: "copy-full-path", label: m(msg("Copy full path")) }); |
| 150 | if (reference.relativePath) |
| 151 | items.push({ id: "copy-relative-path", label: m(msg("Copy relative path")) }); |
| 152 | } else if (reference?.kind === "url") { |
| 153 | items.push({ id: "copy-url", label: m(msg("Copy URL")) }); |
| 154 | } |
| 155 | if (source.onOpenFile) |
| 156 | items.push({ |
| 157 | id: "open-file", |
| 158 | label: m(msg("Open in file viewer")), |
| 159 | disabled: !canReadMedia, |
| 160 | }); |
| 161 | items.push({ |
| 162 | id: "save", |
| 163 | label: isImage ? m(msg("Save image")) : m(msg("Save video")), |
| 164 | disabled: unavailable, |
| 165 | }); |
| 166 | if (source.kind === "image") { |
| 167 | items.push({ |
| 168 | id: "copy-image", |
| 169 | label: m(msg("Copy image")), |
| 170 | disabled: unavailable || !canCopyImage, |
| 171 | }); |
| 172 | } |
| 173 | |
| 174 | const action = await api.contextMenu.show(items, position); |
| 175 | if (!action) return; |
| 176 | failureTitle = |
| 177 | action === "copy-full-path" |
| 178 | ? m(msg("Could not copy full path")) |
| 179 | : action === "copy-relative-path" |
| 180 | ? m(msg("Could not copy relative path")) |
| 181 | : action === "copy-url" |
| 182 | ? m(msg("Could not copy url")) |
| 183 | : action === "open-file" |
| 184 | ? m(msg("Could not open in file viewer")) |
| 185 | : action === "save" |
| 186 | ? isImage |
| 187 | ? m(msg("Could not save image")) |
| 188 | : m(msg("Could not save video")) |
| 189 | : action === "copy-image" |
| 190 | ? m(msg("Could not copy image")) |
| 191 | : m(msg("Could not complete media action")); |
| 192 | const text = |
| 193 | action === "copy-full-path" && reference?.kind === "file" |
| 194 | ? reference.path |
| 195 | : action === "copy-relative-path" && reference?.kind === "file" |
| 196 | ? reference.relativePath |
| 197 | : action === "copy-url" && reference?.kind === "url" |
| 198 | ? reference.url |
| 199 | : undefined; |
| 200 | if (text !== undefined) { |
| 201 | const clipboardText = |
| 202 | reference?.kind === "file" ? formatFilePathForClipboard(text, reference.path) : text; |
| 203 | await writeTextToClipboard( |
| 204 | clipboardText, |
| 205 | reference?.kind === "file" |
| 206 | ? { |
| 207 | target: "file path", |
| 208 | unavailableMessage: msg("Clipboard API is unavailable while copying file path."), |
| 209 | failureMessage: msg("Failed to copy file path to the clipboard."), |
| 210 | } |
| 211 | : { |
| 212 | target: "URL", |
| 213 | unavailableMessage: msg("Clipboard API is unavailable while copying URL."), |
| 214 | failureMessage: msg("Failed to copy URL to the clipboard."), |
| 215 | }, |
| 216 | ); |
| 217 | } else if (action === "open-file") { |
| 218 | assertCanReadMedia(); |
| 219 | source.onOpenFile?.(); |
| 220 | } else if (action === "save" || action === "copy-image") { |
| 221 | progressToast = toastManager.add({ |
| 222 | type: "loading", |
| 223 | title: |
| 224 | action === "save" |
| 225 | ? isImage |
| 226 | ? m(msg("Preparing image download…")) |
| 227 | : m(msg("Preparing video download…")) |
| 228 | : m(msg("Copying image…")), |
| 229 | }); |
| 230 | await (action === "save" ? save() : copyImage()); |
| 231 | toastManager.close(progressToast); |
| 232 | } |
| 233 | }); |
| 234 | if (AsyncResult.isFailure(result)) { |
| 235 | const error = squashAtomCommandFailure(result); |
| 236 | const toast = stackedThreadToast({ |
| 237 | type: "error", |
| 238 | title: failureTitle, |
| 239 | description: thrownErrorMessage(error, m) ?? m(msg("The media action failed.")), |
| 240 | }); |
| 241 | if (progressToast) toastManager.update(progressToast, toast); |
| 242 | else toastManager.add(toast); |
| 243 | } |
| 244 | menuOpen.current = false; |
| 245 | }; |
| 246 | |
| 247 | return ( |
| 248 | <Tooltip disabled={!showTooltip} open={tooltipOpen} onOpenChange={setTooltipOpen}> |
| 249 | <TooltipTrigger |
| 250 | render={children} |
| 251 | tabIndex={0} |
| 252 | onContextMenu={(event) => { |
| 253 | if (event.defaultPrevented) return; |
| 254 | event.preventDefault(); |
| 255 | event.stopPropagation(); |
| 256 | const bounds = event.currentTarget.getBoundingClientRect(); |
| 257 | void showMenu( |
| 258 | event.clientX === 0 && event.clientY === 0 |
| 259 | ? { x: bounds.left, y: bounds.bottom } |
| 260 | : { x: event.clientX, y: event.clientY }, |
| 261 | ); |
| 262 | }} |
| 263 | onKeyDown={(event) => { |
| 264 | if ( |
| 265 | event.defaultPrevented || |
| 266 | !(event.key === "ContextMenu" || (event.shiftKey && event.key === "F10")) |
| 267 | ) |
| 268 | return; |
| 269 | event.preventDefault(); |
| 270 | event.stopPropagation(); |
| 271 | const bounds = event.currentTarget.getBoundingClientRect(); |
| 272 | void showMenu({ x: bounds.left, y: bounds.bottom }); |
| 273 | }} |
| 274 | /> |
| 275 | <TooltipPopup variant="code">{tooltip}</TooltipPopup> |
| 276 | </Tooltip> |
| 277 | ); |
| 278 | } |