SPB Git

Repository Public

PreviewDialog.tsx 7.2 KB 153 lines tsx

1// SP Mail Next — aperçu d'une pièce jointe (galerie et lecteur) : image sûre, texte brut borné ; PDF et autres formats : téléchargement (avec la raison).2import { useEffect, useId, useState } from "react"3import { fmtDateTime, getLang, t } from "../../i18n"4import { formatSize } from "../../mail/attachments"5import { PV, TEXT_PREVIEW_BYTES, closePreview, decodeTextPreview, kindGlyph, stepPreview, type PreviewItem } from "../../next/attachments"6import { messageHref } from "../../next/nav"7import { S } from "../../state/app"8import { linkProps } from "../../state/session"9import { shallowEqual, useStore } from "../../state/store"10import { Icon, IconButton, Spinner, useModal } from "../kit"11import { attachToNewMessage } from "./AttachmentActions"1213/** Lit au plus `limit` octets de la réponse puis coupe le flux. */14async function readBounded(url: string, limit: number, signal: AbortSignal): Promise<Uint8Array> {15  const r = await fetch(url, { credentials: "same-origin", cache: "no-store", signal })16  if (!r.ok) throw new Error(String(r.status))17  const reader = r.body?.getReader()18  if (!reader) return new Uint8Array(await r.arrayBuffer()).subarray(0, limit + 1)19  const chunks: Uint8Array[] = []20  let size = 021  while (size <= limit) {22    const { done, value } = await reader.read()23    if (done) break24    chunks.push(value)25    size += value.length26  }27  void reader.cancel().catch(() => {})28  const out = new Uint8Array(size)29  let at = 030  for (const c of chunks) {31    out.set(c, at)32    at += c.length33  }34  return out35}3637function Fallback({ item, text }: { item: PreviewItem; text: string }) {38  return (39    <div className="nx-empty nx-pv-fallback">40      <Icon name={item.mode === "pdf" ? "file" : kindGlyph("other")} />41      <p>{text}</p>42      <a className="btn primary" href={item.downloadUrl} download={item.name}>43        <Icon name="download" />44        <span>{t("nx.attachments.download")}</span>45      </a>46    </div>47  )48}4950function ImageView({ item }: { item: PreviewItem }) {51  const [failed, setFailed] = useState(false)52  if (failed || !item.inlineUrl) return <Fallback item={item} text={t("nx.attachments.preview.failed")} />53  return <img className="nx-pv-img" src={item.inlineUrl} alt={item.name} decoding="async" onError={() => setFailed(true)} />54}5556function TextView({ item }: { item: PreviewItem }) {57  const [state, setState] = useState<{ status: "loading" } | { status: "error" } | { status: "ready"; text: string; truncated: boolean }>({ status: "loading" })58  useEffect(() => {59    const ctrl = new AbortController()60    setState({ status: "loading" })61    readBounded(item.downloadUrl, TEXT_PREVIEW_BYTES, ctrl.signal).then(62      (bytes) => !ctrl.signal.aborted && setState({ status: "ready", ...decodeTextPreview(bytes, item.size) }),63      () => !ctrl.signal.aborted && setState({ status: "error" }),64    )65    return () => ctrl.abort()66  }, [item.key, item.downloadUrl, item.size])67  if (state.status === "loading") return <Spinner label={t("nx.loading")} />68  if (state.status === "error") return <Fallback item={item} text={t("nx.attachments.preview.failed")} />69  return (70    <div className="nx-pv-textwrap">71      {/* texte seul : jamais interprété comme du HTML */}72      <pre className="nx-pv-text" tabIndex={0} aria-label={t("nx.attachments.preview.textOf", { name: item.name })}>73        {state.text}74      </pre>75      {state.truncated ? <p className="nx-note">{t("nx.attachments.preview.truncated", { size: formatSize(TEXT_PREVIEW_BYTES, getLang()) })}</p> : null}76    </div>77  )78}7980/**81 * PDF : téléchargement seulement. La politique de sécurité de l'application (aucun cadre, aucun module) interdit une visionneuse82 * dans la page — et elle n'est pas assouplie pour cela. Le dialogue dit pourquoi, en une ligne.83 */84function PdfView({ item }: { item: PreviewItem }) {85  return <Fallback item={item} text={t("nx.attachments.preview.pdfDownloadOnly")} />86}8788export default function PreviewDialog() {89  const { items, index } = useStore(PV, (s) => ({ items: s.items, index: s.index }), shallowEqual)90  const online = useStore(S, (s) => s.online)91  const ref = useModal(closePreview)92  const titleId = useId()93  const item = items[index]94  useEffect(() => {95    const onKey = (e: KeyboardEvent) => {96      if (e.altKey || e.ctrlKey || e.metaKey) return97      const el = e.target as HTMLElement | null98      if (el && (el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.tagName === "PRE")) return99      if (e.key === "ArrowRight") (e.preventDefault(), stepPreview(1))100      else if (e.key === "ArrowLeft") (e.preventDefault(), stepPreview(-1))101    }102    document.addEventListener("keydown", onKey)103    return () => document.removeEventListener("keydown", onKey)104  }, [])105  if (!item) return null106  const meta = [formatSize(item.size, getLang()), item.from, item.receivedAt ? fmtDateTime(item.receivedAt) : ""].filter(Boolean).join(" · ")107  return (108    <div className="overlay nx-pv-overlay" onMouseDown={(e) => e.target === e.currentTarget && closePreview()}>109      <div ref={ref} className="nx-pv" role="dialog" aria-modal="true" aria-labelledby={titleId} tabIndex={-1} data-mode={item.mode}>110        <header className="nx-pv-head">111          <div className="nx-item-main">112            <h2 id={titleId} className="truncate" title={item.name}>113              {item.name}114            </h2>115            <span className="small truncate">{meta}</span>116          </div>117          {items.length > 1 ? (118            <>119              <span className="nx-meta" aria-live="polite">120                {t("nx.attachments.preview.position", { i: index + 1, n: items.length })}121              </span>122              <IconButton icon="chevronRight" className="nx-pv-prev" label={t("nx.attachments.preview.prev")} shortcut="←" disabled={index === 0} onClick={() => stepPreview(-1)} />123              <IconButton icon="chevronRight" label={t("nx.attachments.preview.next")} shortcut="→" disabled={index === items.length - 1} onClick={() => stepPreview(1)} />124            </>125          ) : null}126          <a className="icon-btn" href={item.downloadUrl} download={item.name} aria-label={t("nx.attachments.downloadNamed", { name: item.name })} title={t("nx.attachments.download")}>127            <Icon name="download" />128          </a>129          <IconButton130            icon="forward"131            label={t("nx.attachments.attachNew")}132            disabled={!online}133            onClick={() => {134              const one = item135              closePreview()136              void attachToNewMessage([one])137            }}138          />139          {item.threadId ? (140            <a {...linkProps(messageHref(item.mailboxId, item.threadId))} className="icon-btn" aria-label={t("nx.attachments.openMessage")} title={t("nx.attachments.openMessage")} onClickCapture={closePreview}>141              <Icon name="mail" />142            </a>143          ) : null}144          <IconButton icon="close" label={t("common.close")} onClick={closePreview} />145        </header>146        <div className="nx-pv-body" key={item.key}>147          {item.mode === "image" ? <ImageView item={item} /> : item.mode === "text" ? <TextView item={item} /> : item.mode === "pdf" ? <PdfView item={item} /> : <Fallback item={item} text={t("nx.attachments.preview.none")} />}148        </div>149      </div>150    </div>151  )152}153
Files main
Menu

Theme