The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { memo, useRef, useState, type ReactNode, type KeyboardEvent } from "react"; |
| 2 | import { flushSync } from "react-dom"; |
| 3 | import { T, useGT } from "gt-react"; |
| 4 | import { |
| 5 | ArrowLeftIcon, |
| 6 | ChevronLeftIcon, |
| 7 | ChevronRightIcon, |
| 8 | ImageIcon, |
| 9 | TextIcon, |
| 10 | } from "lucide-react"; |
| 11 | import { Button } from "../ui/button"; |
| 12 | import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog"; |
| 13 | import type { ExpandedImageItem, ExpandedImagePreview } from "./ExpandedImagePreview"; |
| 14 | import { resolveExternalWebLinkHost } from "./externalLinkContextMenu"; |
| 15 | import { useAssetUrlRefresh, useAssetUrlState } from "../../assets/assetUrls"; |
| 16 | import { OpenMediaLink } from "../media/OpenMediaLink"; |
| 17 | import { MediaActions, type MediaActionSource } from "../media/MediaActions"; |
| 18 | import { MediaVideoPlayer } from "../media/MediaVideoPlayer"; |
| 19 | import { isContextMenuOpen } from "../../contextMenuFallback"; |
| 20 | import { |
| 21 | SnapShotAccessibilityData, |
| 22 | SnapShotCopyButton, |
| 23 | SnapShotContentsButton, |
| 24 | snapShotAccessibilityDetails, |
| 25 | } from "./SnapShotAttachmentDetails"; |
| 26 | import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; |
| 27 | import { ZoomableImage, type ZoomableImageHandle } from "./ZoomableImage"; |
| 28 | import { composerFloatingLayerProps } from "./composerEventScope"; |
| 29 | import { useAtomValue } from "@effect/atom-react"; |
| 30 | import { Atom } from "effect/reactivity"; |
| 31 | import { appAtomRegistry } from "~/rpc/atomRegistry"; |
| 32 | import { expandedImageKey } from "./ExpandedImagePreview"; |
| 33 | import { registerThreadOverlay } from "./threadOverlayRetention"; |
| 34 | import { mediaReferenceFileName } from "@t3tools/client-runtime/media-reference"; |
| 35 | import { mediaMimeType, mediaMimeTypeFromExtension } from "@t3tools/shared/mediaPreview"; |
| 36 | |
| 37 | interface ExpandedImageDialogProps { |
| 38 | preview: ExpandedImagePreview; |
| 39 | onClose: () => void; |
| 40 | } |
| 41 | |
| 42 | const EXPANDED_MEDIA_STATE_CLASS_NAME = |
| 43 | "flex aspect-auto h-48 min-h-0 w-[min(var(--media-width),32rem)] flex-col items-center justify-center gap-3 rounded-lg border border-border/70 bg-black p-6 text-center text-sm text-white shadow-2xl"; |
| 44 | |
| 45 | function ExpandedMediaFailure({ children }: { children: ReactNode }) { |
| 46 | return ( |
| 47 | <div role="alert" className={EXPANDED_MEDIA_STATE_CLASS_NAME}> |
| 48 | {children} |
| 49 | </div> |
| 50 | ); |
| 51 | } |
| 52 | |
| 53 | function itemMimeType(item: ExpandedImageItem): string | undefined { |
| 54 | if (item.mimeType) return item.mimeType; |
| 55 | const reference = item.actionsSource?.reference; |
| 56 | const fileName = reference && mediaReferenceFileName(reference); |
| 57 | if (fileName) { |
| 58 | return mediaMimeTypeFromExtension(fileName.slice(fileName.lastIndexOf("."))) ?? undefined; |
| 59 | } |
| 60 | return mediaMimeType(item.src ?? "") ?? undefined; |
| 61 | } |
| 62 | |
| 63 | function ExpandedVideo({ item }: { readonly item: ExpandedImageItem }) { |
| 64 | const asset = item.actionsSource?.asset; |
| 65 | const assetUrl = useAssetUrlState(asset?.environmentId ?? null, asset?.resource ?? null); |
| 66 | const refreshAssetUrl = useAssetUrlRefresh(asset?.environmentId ?? null, asset?.resource ?? null); |
| 67 | const src = asset |
| 68 | ? assetUrl._tag === "Success" |
| 69 | ? assetUrl.url + (item.srcFragment ?? "") |
| 70 | : null |
| 71 | : item.src; |
| 72 | return ( |
| 73 | <MediaVideoPlayer |
| 74 | src={src} |
| 75 | label={item.name} |
| 76 | sourceFailed={assetUrl._tag === "Failure"} |
| 77 | originalUrl={item.originalUrl} |
| 78 | preload="metadata" |
| 79 | autoPlay={item.autoPlay ?? true} |
| 80 | className="block max-h-[var(--media-height)] max-w-[var(--media-width)] text-center" |
| 81 | videoClassName="aspect-auto max-h-[var(--media-height)] w-auto max-w-[var(--media-width)] rounded-lg border border-border/70 shadow-2xl" |
| 82 | stateClassName={EXPANDED_MEDIA_STATE_CLASS_NAME} |
| 83 | onRetry={asset ? refreshAssetUrl : undefined} |
| 84 | /> |
| 85 | ); |
| 86 | } |
| 87 | |
| 88 | export const ExpandedImageDialog = memo(function ExpandedImageDialog({ |
| 89 | preview, |
| 90 | onClose, |
| 91 | }: ExpandedImageDialogProps) { |
| 92 | const gt = useGT(); |
| 93 | const [imageOffset, setImageOffset] = useState(0); |
| 94 | const [failedImageSrc, setFailedImageSrc] = useState<string | null>(null); |
| 95 | const [accessibilityDetailsSrc, setAccessibilityDetailsSrc] = useState<string | null>(null); |
| 96 | const zoomableImageRef = useRef<ZoomableImageHandle>(null); |
| 97 | const [returnFocus] = useState(() => { |
| 98 | const target = document.activeElement instanceof HTMLElement ? document.activeElement : null; |
| 99 | return { target, focusVisible: target?.matches(":focus-visible") ?? false }; |
| 100 | }); |
| 101 | // The host unmounts the dialog outright, so Base UI never runs finalFocus. Without |
| 102 | // this, focus stays on the removed dialog, and the composer that owned the opener |
| 103 | // reads that as a blur and rests. Preserve mouse focus when Escape closes it. |
| 104 | const close = () => { |
| 105 | flushSync(onClose); |
| 106 | const { target, focusVisible } = returnFocus; |
| 107 | if (target?.isConnected) target.focus({ preventScroll: true, focusVisible }); |
| 108 | }; |
| 109 | const closeButtonRef = useRef<HTMLButtonElement>(null); |
| 110 | const imageCount = preview.images.length; |
| 111 | const index = |
| 112 | imageCount > 0 ? (((preview.index + imageOffset) % imageCount) + imageCount) % imageCount : 0; |
| 113 | const item = preview.images[index]; |
| 114 | const source: MediaActionSource = item?.actionsSource ?? { |
| 115 | kind: item?.type === "video" ? "video" : "image", |
| 116 | name: item?.name ?? gt("Media"), |
| 117 | src: item?.src ?? null, |
| 118 | }; |
| 119 | const openFile = source.onOpenFile; |
| 120 | const actionsSource: MediaActionSource = openFile |
| 121 | ? { |
| 122 | ...source, |
| 123 | onOpenFile: () => { |
| 124 | openFile(); |
| 125 | close(); |
| 126 | }, |
| 127 | } |
| 128 | : source; |
| 129 | |
| 130 | const navigateImage = (direction: -1 | 1) => { |
| 131 | setImageOffset((current) => current + direction); |
| 132 | }; |
| 133 | |
| 134 | const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => { |
| 135 | if (event.defaultPrevented || isContextMenuOpen() || event.target instanceof HTMLVideoElement) |
| 136 | return; |
| 137 | if (zoomableImageRef.current?.pan(event.key)) { |
| 138 | event.preventDefault(); |
| 139 | event.stopPropagation(); |
| 140 | return; |
| 141 | } |
| 142 | if (preview.images.length <= 1) return; |
| 143 | if (event.key === "ArrowLeft") { |
| 144 | event.preventDefault(); |
| 145 | event.stopPropagation(); |
| 146 | navigateImage(-1); |
| 147 | return; |
| 148 | } |
| 149 | if (event.key !== "ArrowRight") return; |
| 150 | event.preventDefault(); |
| 151 | event.stopPropagation(); |
| 152 | navigateImage(1); |
| 153 | }; |
| 154 | |
| 155 | if (!item) return null; |
| 156 | const isVideo = item.type === "video"; |
| 157 | const openOriginalLink = |
| 158 | item.originalUrl && resolveExternalWebLinkHost(item.originalUrl) !== null ? ( |
| 159 | <OpenMediaLink originalUrl={item.originalUrl} /> |
| 160 | ) : null; |
| 161 | const accessibilityDetails = item.source ? snapShotAccessibilityDetails(item.source) : undefined; |
| 162 | const showingAccessibilityDetails = |
| 163 | Boolean(accessibilityDetails) && accessibilityDetailsSrc === item.src; |
| 164 | const contentsLabel = showingAccessibilityDetails |
| 165 | ? gt("Show screenshot") |
| 166 | : accessibilityDetails?.format === "json" |
| 167 | ? gt("Show accessibility JSON") |
| 168 | : gt("Show extracted text"); |
| 169 | |
| 170 | return ( |
| 171 | <Dialog |
| 172 | open |
| 173 | onOpenChange={(open, eventDetails) => { |
| 174 | if (open) return; |
| 175 | // Escape belongs to an open context menu first. |
| 176 | if (eventDetails.reason === "escape-key" && isContextMenuOpen()) { |
| 177 | eventDetails.cancel(); |
| 178 | return; |
| 179 | } |
| 180 | close(); |
| 181 | }} |
| 182 | > |
| 183 | <DialogPopup |
| 184 | {...composerFloatingLayerProps} |
| 185 | variant="media" |
| 186 | mediaControlsPlacement="inside" |
| 187 | showCloseButton={false} |
| 188 | bottomStickOnMobile={false} |
| 189 | className="row-start-1 h-full max-h-[92vh] w-[92vw] max-w-[92vw] items-center justify-center overflow-visible [--media-width:92vw] [--media-height:min(calc((100vh-var(--native-titlebar-height,0px))*0.86),calc(100vh-var(--native-titlebar-height,0px)-160px))] sm:[--media-width:calc(92vw-96px)]" |
| 190 | onKeyDown={onKeyDown} |
| 191 | initialFocus={closeButtonRef} |
| 192 | finalFocus={() => returnFocus.target} |
| 193 | onClick={(event) => { |
| 194 | if (event.target === event.currentTarget) close(); |
| 195 | }} |
| 196 | > |
| 197 | <DialogTitle className="sr-only"> |
| 198 | {isVideo ? gt("Expanded video preview") : gt("Expanded image preview")} |
| 199 | </DialogTitle> |
| 200 | <Button |
| 201 | type="button" |
| 202 | ref={closeButtonRef} |
| 203 | size="sm" |
| 204 | variant="media-close" |
| 205 | className="absolute left-0 top-0 z-20 max-[8rem]:left-1/2 max-[8rem]:-translate-x-1/2" |
| 206 | onClick={close} |
| 207 | aria-label={isVideo ? gt("Back, close video preview") : gt("Back, close image preview")} |
| 208 | > |
| 209 | <ArrowLeftIcon aria-hidden="true" /> |
| 210 | <T>Back</T> |
| 211 | </Button> |
| 212 | {preview.images.length > 1 && ( |
| 213 | <Button |
| 214 | type="button" |
| 215 | size="icon" |
| 216 | variant="media-navigation" |
| 217 | className="left-0 top-auto bottom-0 translate-y-0 sm:top-1/2 sm:bottom-auto sm:-translate-y-1/2" |
| 218 | aria-label={gt("Previous media")} |
| 219 | onClick={() => navigateImage(-1)} |
| 220 | > |
| 221 | <ChevronLeftIcon className="size-5" /> |
| 222 | </Button> |
| 223 | )} |
| 224 | <MediaActions source={actionsSource} showTooltip={false}> |
| 225 | <div className="relative isolate z-10 flex max-h-full max-w-[var(--media-width)] flex-col items-center"> |
| 226 | {item.type === "video" ? ( |
| 227 | <ExpandedVideo key={index} item={item} /> |
| 228 | ) : showingAccessibilityDetails ? ( |
| 229 | accessibilityDetails ? ( |
| 230 | <SnapShotAccessibilityData |
| 231 | details={accessibilityDetails} |
| 232 | className="h-[min(var(--media-height),40rem)] w-[min(var(--media-width),42rem)] transition-opacity duration-140 ease-out starting:opacity-0 rounded-lg border border-border/70 bg-background p-4 text-xs leading-5 shadow-2xl motion-reduce:transition-none" |
| 233 | /> |
| 234 | ) : null |
| 235 | ) : item.src === null || failedImageSrc === item.src ? ( |
| 236 | <ExpandedMediaFailure> |
| 237 | <p> |
| 238 | {openOriginalLink |
| 239 | ? gt("This image could not be loaded.") |
| 240 | : gt("Image unavailable. The file may have been moved or deleted.")} |
| 241 | </p> |
| 242 | {openOriginalLink} |
| 243 | </ExpandedMediaFailure> |
| 244 | ) : ( |
| 245 | <ZoomableImage |
| 246 | ref={zoomableImageRef} |
| 247 | key={`${index}:${item.src}`} |
| 248 | src={item.src} |
| 249 | name={item.name} |
| 250 | mimeType={itemMimeType(item)} |
| 251 | onError={() => setFailedImageSrc(item.src)} |
| 252 | /> |
| 253 | )} |
| 254 | <div className="mt-2 flex max-w-[var(--media-width)] items-center justify-center gap-1.5 text-xs text-white/80 max-sm:px-10"> |
| 255 | <span className="truncate" aria-live="polite" aria-atomic="true"> |
| 256 | {item.name} |
| 257 | {preview.images.length > 1 ? ` (${index + 1}/${preview.images.length})` : ""} |
| 258 | </span> |
| 259 | {accessibilityDetails && item.source ? ( |
| 260 | <Tooltip> |
| 261 | <TooltipTrigger |
| 262 | render={ |
| 263 | <Button |
| 264 | aria-label={contentsLabel} |
| 265 | aria-pressed={showingAccessibilityDetails} |
| 266 | onClick={() => |
| 267 | setAccessibilityDetailsSrc(showingAccessibilityDetails ? null : item.src) |
| 268 | } |
| 269 | size="icon-micro" |
| 270 | variant="overlay" |
| 271 | /> |
| 272 | } |
| 273 | > |
| 274 | {showingAccessibilityDetails ? ( |
| 275 | <ImageIcon className="size-3" aria-hidden="true" /> |
| 276 | ) : ( |
| 277 | <TextIcon className="size-3" aria-hidden="true" /> |
| 278 | )} |
| 279 | </TooltipTrigger> |
| 280 | <TooltipPopup side="top">{contentsLabel}</TooltipPopup> |
| 281 | </Tooltip> |
| 282 | ) : item.source ? ( |
| 283 | <SnapShotContentsButton source={item.source} side="top" /> |
| 284 | ) : null} |
| 285 | {item.onCopySnapshot && ( |
| 286 | <div className="-my-1.5"> |
| 287 | <SnapShotCopyButton onCopy={item.onCopySnapshot} /> |
| 288 | </div> |
| 289 | )} |
| 290 | </div> |
| 291 | </div> |
| 292 | </MediaActions> |
| 293 | {preview.images.length > 1 && ( |
| 294 | <Button |
| 295 | type="button" |
| 296 | size="icon" |
| 297 | variant="media-navigation" |
| 298 | className="right-0 top-auto bottom-0 translate-y-0 sm:top-1/2 sm:bottom-auto sm:-translate-y-1/2" |
| 299 | aria-label={gt("Next media")} |
| 300 | onClick={() => navigateImage(1)} |
| 301 | > |
| 302 | <ChevronRightIcon className="size-5" /> |
| 303 | </Button> |
| 304 | )} |
| 305 | </DialogPopup> |
| 306 | </Dialog> |
| 307 | ); |
| 308 | }); |
| 309 | |
| 310 | // Keep preview state outside ChatView to isolate dialog renders. |
| 311 | type ExpandedImagePreviewState = { |
| 312 | readonly threadKey: string; |
| 313 | readonly preview: ExpandedImagePreview; |
| 314 | } | null; |
| 315 | |
| 316 | const expandedImagePreviewAtom = Atom.make<ExpandedImagePreviewState>(null).pipe( |
| 317 | Atom.keepAlive, |
| 318 | Atom.withLabel("chat:expanded-image-preview"), |
| 319 | ); |
| 320 | |
| 321 | function ownedSrc(state: ExpandedImagePreviewState): string | null { |
| 322 | const item = state?.preview.images[state.preview.index]; |
| 323 | return item?.ownsSrc === true ? item.src : null; |
| 324 | } |
| 325 | |
| 326 | // The preview owns a blob URL made for it, so whatever replaces it releases that URL. |
| 327 | function setExpandedImagePreview(next: ExpandedImagePreviewState): void { |
| 328 | const previous = ownedSrc(appAtomRegistry.get(expandedImagePreviewAtom)); |
| 329 | appAtomRegistry.set(expandedImagePreviewAtom, next); |
| 330 | if (previous !== null && previous !== ownedSrc(next)) URL.revokeObjectURL(previous); |
| 331 | } |
| 332 | |
| 333 | export function openExpandedImagePreview(threadKey: string, preview: ExpandedImagePreview): void { |
| 334 | setExpandedImagePreview({ threadKey, preview }); |
| 335 | } |
| 336 | |
| 337 | function closeExpandedImagePreview(): void { |
| 338 | setExpandedImagePreview(null); |
| 339 | } |
| 340 | |
| 341 | // Leaving the thread's route (or the chat view) drops its preview. |
| 342 | registerThreadOverlay((threadKey) => { |
| 343 | const current = appAtomRegistry.get(expandedImagePreviewAtom); |
| 344 | if (current !== null && current.threadKey !== threadKey) closeExpandedImagePreview(); |
| 345 | }); |
| 346 | |
| 347 | export function ExpandedImageDialogHost({ threadKey }: { readonly threadKey: string }) { |
| 348 | const state = useAtomValue(expandedImagePreviewAtom); |
| 349 | const preview = state?.threadKey === threadKey ? state.preview : null; |
| 350 | if (preview === null) return null; |
| 351 | return ( |
| 352 | <ExpandedImageDialog |
| 353 | key={expandedImageKey(preview)} |
| 354 | preview={preview} |
| 355 | onClose={closeExpandedImagePreview} |
| 356 | /> |
| 357 | ); |
| 358 | } |