Files
DeepTutor/web/components/common/MarkdownImage.tsx
2026-12-02 05:30:31 -05:00

97 lines
3.0 KiB
TypeScript

'use client'
import { useState, type ImgHTMLAttributes } from 'react'
import { ImageOff } from 'lucide-react'
import { useTranslation } from 'react-i18next'
/** Only http(s) images outside this origin need consent. */
export function isExternalImageSource(src: string): boolean {
// A relative reference always resolves against this page on server and client.
if (!/^(?:[a-z][a-z\d+.-]*:|[/\\]{2})/i.test(src.trim())) return false
try {
const url = new URL(
src,
typeof window === 'undefined' ? 'http://localhost' : window.location.href
)
return (
(url.protocol === 'http:' || url.protocol === 'https:') &&
(typeof window === 'undefined' || url.origin !== window.location.origin)
)
} catch {
return false
}
}
/**
* A markdown image that never contacts a third-party host until the reader
* asks for it.
*
* External images are common in model answers (web-search figures, copied
* URLs), but loading one on render leaks the reader's IP and the surrounding
* page as a referrer. The placeholder reserves a stable 16:9 box, so the
* eventual image cannot shift the transcript; local and workspace images keep
* the normal inline path.
*/
export default function MarkdownImage({
src,
alt = '',
className = '',
...props
}: ImgHTMLAttributes<HTMLImageElement> & { src?: string }) {
const { t } = useTranslation()
const [allowedSource, setAllowedSource] = useState<string | null>(null)
const label = t('Load external image')
if (!src) return null
const external = isExternalImageSource(src)
if (external && allowedSource !== src) {
let host = src
try {
host = new URL(src).hostname
} catch {}
return (
<button
type="button"
onClick={() => setAllowedSource(src)}
aria-label={`${label}: ${alt || host}`}
className="my-4 flex aspect-video w-full max-w-[640px] flex-col items-center justify-center gap-2 rounded-lg border border-dashed border-[var(--border)] bg-[var(--muted)]/35 px-4 text-[var(--muted-foreground)] transition-colors hover:border-[var(--ring)] hover:text-[var(--foreground)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--ring)]"
>
<ImageOff size={20} strokeWidth={1.6} aria-hidden="true" />
<span className="text-[12.5px] font-medium">{label}</span>
<span className="max-w-full truncate text-[11px] opacity-75">{alt || host}</span>
</button>
)
}
if (external) {
return (
<span className="my-4 block aspect-video w-full max-w-[640px] overflow-hidden rounded-lg border border-[var(--border)]">
<img
{...props}
src={src}
alt={alt}
loading="lazy"
decoding="async"
referrerPolicy="no-referrer"
className="h-full w-full object-contain"
/>
</span>
)
}
return (
<img
{...props}
src={src}
alt={alt}
loading="lazy"
decoding="async"
referrerPolicy="no-referrer"
className={className}
/>
)
}