import { useCallback, useEffect, useMemo, useState } from 'react' import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import { ImageLightbox } from './ImageLightbox.tsx' import type { ImageLightboxLabels } from './ImageLightbox.tsx' import css from './MessageImage.module.css' /** Loads a session-authorized durable image URL. */ export type ImageLoader = (attachment: ImageAttachmentRef) => Promise /** Message-image strings the owner resolves from its own locale namespace. */ export interface MessageImageLabels { /** Fallback display name for an unnamed image. */ image: string /** Thumbnail tooltip inviting the original-image preview. */ open: string /** Accessible thumbnail label; receives the image's display name. */ openNamed: (label: string) => string /** Loading placeholder shown until bytes resolve. */ loading: string /** Retry-control label shown when the load fails. */ loadFailed: string /** Lightbox strings forwarded to the opened preview. */ lightbox: ImageLightboxLabels } /** * Compact history renderer with retryable loading and click-to-open original * preview. * * @param props.attachment - the durable image reference to load and bound. * @param props.load - session-authorized URL loader. * @param props.labels - resolved strings (tooltip, loading, retry, lightbox). * @returns the bounded thumbnail button, or the retry control on failure. */ export function MessageImage({ attachment, load, labels }: { attachment: ImageAttachmentRef load: ImageLoader labels: MessageImageLabels }) { const [src, setSrc] = useState(null) const [error, setError] = useState(false) const [open, setOpen] = useState(false) // Retry re-arms the one load effect below, so every attempt — first load or // retry — runs under the same liveness guard and the same reset. const [attempt, setAttempt] = useState(0) const request = useCallback(() => { setAttempt(a => a + 1) }, []) const close = useCallback(() => { setOpen(false) }, []) const size = useMemo(() => { const scale = Math.min(1, 240 / attachment.width, 240 / attachment.height) return { width: Math.max(1, Math.round(attachment.width * scale)), height: Math.max(1, Math.round(attachment.height * scale)) } }, [attachment.height, attachment.width]) useEffect(() => { let live = true setError(false) setSrc(null) void load(attachment).then((url) => { if (live) setSrc(url) }).catch(() => { if (live) setError(true) }) return () => { live = false } }, [attachment, load, attempt]) const label = attachment.name ?? labels.image if (error) return return ( <> {open && src !== null && } ) } /** Wrapping image group shared by user and assistant history. */ export function ImageGallery({ images, load, align, labels }: { images: readonly { attachment: ImageAttachmentRef }[] load: ImageLoader align: 'start' | 'end' labels: MessageImageLabels }) { if (images.length === 0) return null return (
{images.map((image, index) => ( ))}
) }