SPB Git

Repository Public

Frame.tsx 3.7 KB 96 lines tsx

1// Cadre d'aperçu d'un modèle : <iframe sandbox> sans scripts ni même origine, document construit par templates/srcdoc.ts.2// Les images distantes (https) du modèle sont récupérées par la page via le mandataire /api/img, puis injectées en data:.3import { useEffect, useMemo, useState } from "react"4import { getLang } from "../../i18n"5import type { ColorScheme } from "../../templates/darkmode"6import { buildPreviewDocument, proxyUrl } from "../../templates/srcdoc"78// ---------------------------------------------------------------- images du modèle (cache de la session)9const imageCache = new Map<string, string>()10const failed = new Set<string>()11const inflight = new Map<string, Promise<void>>()12const MAX_CACHED = 2401314function loadImage(url: string): Promise<void> {15  let p = inflight.get(url)16  if (p) return p17  p = (async () => {18    try {19      const r = await fetch(proxyUrl(url), { credentials: "same-origin" })20      if (!r.ok) throw new Error(String(r.status))21      const blob = await r.blob()22      if (!/^image\/(png|jpeg|gif|webp)$/.test(blob.type)) throw new Error("type")23      const data = await new Promise<string | null>((resolve) => {24        const fr = new FileReader()25        fr.onload = () => resolve(typeof fr.result === "string" ? fr.result : null)26        fr.onerror = () => resolve(null)27        fr.readAsDataURL(blob)28      })29      if (!data) throw new Error("read")30      if (imageCache.size >= MAX_CACHED) imageCache.delete(imageCache.keys().next().value as string)31      imageCache.set(url, data)32    } catch {33      failed.add(url)34    } finally {35      inflight.delete(url)36    }37  })()38  inflight.set(url, p)39  return p40}4142export interface FrameProps {43  /** HTML du modèle (rendu ou brut) — jamais inséré ailleurs que dans le cadre isolé */44  html: string45  title: string46  scheme?: ColorScheme47  /** miniature : inerte, sans défilement, masquée aux lecteurs d'écran */48  thumbnail?: boolean49  width: number50  height: number51  /** facteur d'échelle appliqué au cadre (1 = taille réelle) */52  scale?: number53  onInfo?: (info: { hasDark: boolean; images: number }) => void54}5556export function TemplateFrame({ html, title, scheme = "light", thumbnail, width, height, scale = 1, onInfo }: FrameProps) {57  const [tick, setTick] = useState(0)58  const doc = useMemo(59    () => buildPreviewDocument(html, { scheme, thumbnail, images: imageCache, lang: getLang() }),60    // `tick` : une image de plus est arrivée dans le cache61    // eslint-disable-next-line react-hooks/exhaustive-deps62    [html, scheme, thumbnail, tick],63  )64  useEffect(() => {65    onInfo?.({ hasDark: doc.hasDark, images: doc.remoteImages.length })66    const missing = doc.remoteImages.filter((u) => !imageCache.has(u) && !failed.has(u)).slice(0, 40)67    if (!missing.length) return68    let alive = true69    let next = 070    const worker = async () => {71      while (alive && next < missing.length) await loadImage(missing[next++])72    }73    void Promise.all(Array.from({ length: 4 }, worker)).then(() => {74      if (alive) setTick((x) => x + 1)75    })76    return () => {77      alive = false78    }79    // eslint-disable-next-line react-hooks/exhaustive-deps80  }, [doc])81  const s = Math.max(0.05, scale)82  return (83    <div className={`tpl-frame${thumbnail ? " thumb" : ""}`} style={{ width: Math.round(width * s), height: Math.round(height * s) }} data-scheme={scheme}>84      <iframe85        title={title}86        sandbox={thumbnail ? "" : "allow-popups allow-popups-to-escape-sandbox"}87        referrerPolicy="no-referrer"88        srcDoc={doc.srcdoc}89        tabIndex={thumbnail ? -1 : 0}90        aria-hidden={thumbnail ? true : undefined}91        style={{ width, height, transform: s === 1 ? undefined : `scale(${s})` }}92      />93    </div>94  )95}96
Files main
Menu

Theme