SPB Git

Repository Public

GalleryScreen.tsx 11.6 KB 251 lines tsx

1// SP Mail Next — galerie des pièces jointes : grille de tuiles (vignette pour les images sûres, glyphe sinon), filtres, sélection multiple → ZIP, aperçu.2import { useEffect, useRef, useState } from "react"3import { fmtListDate, fmtDateTime, getLang, t } from "../../i18n"4import { attachmentRisk, formatSize } from "../../mail/attachments"5import {6  ATTACHMENT_KINDS, GA, ZIP_MAX_ITEMS, attachmentKey, clearSelected, downloadZip, emptyGalleryFilter, extensionLabel, inlineUrl, isFiltered, kindGlyph, loadGallery, loadMoreGallery, openPreview, previewOf,7  selectedItems, setGalleryFilter, toggleKind, toggleSelected, zipProblem, type AttachmentItem, type DateFilter, type SizeFilter,8} from "../../next/attachments"9import { messageHref } from "../../next/nav"10import { S, toast } from "../../state/app"11import { linkProps } from "../../state/session"12import { shallowEqual, useStore } from "../../state/store"13import { Icon, Spinner } from "../kit"14import { attachToNewMessage, attachmentError } from "./AttachmentActions"1516const SIZES: SizeFilter[] = ["any", "small", "medium", "large", "huge"]17const DATES: DateFilter[] = ["any", "7d", "30d", "90d", "1y"]1819function Tile({ a, index, selected, all }: { a: AttachmentItem; index: number; selected: boolean; all: AttachmentItem[] }) {20  const thumb = inlineUrl(a)21  const [broken, setBroken] = useState(false)22  const risk = attachmentRisk(a.name, a.type)23  const who = a.from[0]?.name || a.from[0]?.email || ""24  const ext = extensionLabel(a.name)25  return (26    <li className={`nx-ga-tile${selected ? " selected" : ""}`} data-kind={a.kind}>27      <button type="button" className="nx-ga-thumb" aria-label={t("nx.attachments.previewNamed", { name: a.name })} onClick={() => openPreview(all.map(previewOf), index)}>28        {thumb && !broken ? (29          <img src={thumb} alt="" loading="lazy" decoding="async" onError={() => setBroken(true)} />30        ) : (31          <span className="nx-ga-glyph">32            <Icon name={kindGlyph(a.kind)} />33            {ext ? <span className="nx-ga-ext">{ext}</span> : null}34          </span>35        )}36      </button>37      <label className="nx-ga-check">38        <input type="checkbox" checked={selected} onChange={() => toggleSelected(attachmentKey(a))} aria-label={t("nx.attachments.selectNamed", { name: a.name })} />39      </label>40      <div className="nx-ga-info">41        <span className="nx-ga-name truncate" title={a.name}>42          {a.name}43        </span>44        <span className="nx-ga-meta truncate">45          {formatSize(a.size, getLang())}46          {who ? ` · ${who}` : ""}47        </span>48        <span className="nx-ga-foot">49          <time className="nx-meta" dateTime={a.received_at} title={fmtDateTime(a.received_at)}>50            {fmtListDate(a.received_at)}51          </time>52          {risk ? (53            <span className="badge danger" title={t("reader.riskBanner")}>54              <Icon name="warn" small />55              <span className="sr-only">{t("reader.riskType")}</span>56            </span>57          ) : null}58          <span className="spacer" />59          <a {...linkProps(messageHref(a.mailbox_id, a.thread_id))} className="icon-btn" aria-label={t("nx.attachments.openMessageNamed", { name: a.name })} title={a.subject ? t("nx.attachments.openMessageOf", { subject: a.subject }) : t("nx.attachments.openMessage")}>60            <Icon name="mail" />61          </a>62          <a className="icon-btn" href={a.download_url} download={a.name} aria-label={t("nx.attachments.downloadNamed", { name: a.name })} title={t("nx.attachments.download")}>63            <Icon name="download" />64          </a>65        </span>66      </div>67    </li>68  )69}7071function Skeleton() {72  return (73    <ul className="nx-ga-grid" aria-hidden="true">74      {Array.from({ length: 12 }, (_, i) => (75        <li key={i} className="nx-ga-tile">76          <span className="skeleton nx-ga-thumb" />77          <div className="nx-ga-info">78            <span className="skeleton nx-ga-skel" style={{ width: `${50 + ((i * 13) % 40)}%` }} />79            <span className="skeleton nx-ga-skel thin" style={{ width: "40%" }} />80          </div>81        </li>82      ))}83    </ul>84  )85}8687export default function GalleryScreen() {88  const st = useStore(GA, (s) => ({ items: s.items, next: s.next, status: s.status, error: s.error, loadingMore: s.loadingMore, filter: s.filter, selected: s.selected }), shallowEqual)89  const mailboxes = useStore(S, (s) => s.me?.mailboxes ?? [])90  const online = useStore(S, (s) => s.online)91  const [q, setQ] = useState(st.filter.q)92  const [from, setFrom] = useState(st.filter.from)93  const [zipping, setZipping] = useState(false)94  const sentinel = useRef<HTMLDivElement>(null)9596  useEffect(() => {97    void loadGallery()98  }, [])99  useEffect(() => {100    const f = GA.get().filter101    if (q.trim() === f.q.trim() && from.trim() === f.from.trim()) return102    const timer = setTimeout(() => setGalleryFilter({ q, from }), 300)103    return () => clearTimeout(timer)104  }, [q, from])105  useEffect(() => {106    const node = sentinel.current107    if (!node || !st.next || typeof IntersectionObserver === "undefined") return108    const io = new IntersectionObserver((entries) => entries.some((e) => e.isIntersecting) && void loadMoreGallery(), { rootMargin: "400px" })109    io.observe(node)110    return () => io.disconnect()111  }, [st.next, st.items.length])112113  const chosen = selectedItems(st)114  const problem = zipProblem(chosen)115  const zip = async () => {116    if (problem === "too_many") return void toast({ kind: "error", text: t("nx.attachments.err.zipTooMany", { n: ZIP_MAX_ITEMS }) })117    if (problem === "too_large") return void toast({ kind: "error", text: t("nx.attachments.err.zipTooLarge") })118    if (problem) return119    if (!S.get().online) return void toast({ kind: "error", text: t("nx.offline") })120    setZipping(true)121    try {122      const name = await downloadZip(chosen)123      toast({ kind: "success", text: t("nx.attachments.zipReady", { name }) })124      clearSelected()125    } catch (e) {126      toast({ kind: "error", text: attachmentError(e), actionLabel: t("nx.retry"), action: () => void zip() })127    } finally {128      setZipping(false)129    }130  }131  const reset = () => {132    setQ("")133    setFrom("")134    setGalleryFilter(emptyGalleryFilter())135  }136  const filtered = isFiltered(st.filter)137  return (138    <div className="nx-page wide nx-ga">139      <div className="nx-head">140        <h1>{t("nx.attachments.title")}</h1>141        {st.status === "ready" && st.items.length ? <span className="nx-sub">{t("nx.attachments.count", { n: st.items.length })}{st.next ? "+" : ""}</span> : null}142        <span className="spacer" />143        {chosen.length ? (144          <div className="nx-toolbar nx-ga-selection" role="group" aria-label={t("nx.attachments.selection")}>145            <span className="nx-sub" aria-live="polite">146              {t("nx.attachments.selected", { n: chosen.length })} · {formatSize(chosen.reduce((n, a) => n + a.size, 0), getLang())}147            </span>148            <button type="button" className="btn primary" disabled={zipping || !online} title={online ? undefined : t("nx.offline")} onClick={() => void zip()}>149              {zipping ? <span className="spinner" aria-hidden="true" /> : <Icon name="zip" />}150              <span>{t("nx.attachments.zip")}</span>151            </button>152            <button type="button" className="btn" disabled={!online} title={online ? undefined : t("nx.offline")} onClick={() => void attachToNewMessage(chosen.map(previewOf)).then((n) => n && clearSelected())}>153              <Icon name="forward" />154              <span>{t("nx.attachments.attachNew")}</span>155            </button>156            <button type="button" className="btn ghost" onClick={clearSelected}>157              {t("nx.attachments.clearSelection")}158            </button>159          </div>160        ) : null}161      </div>162163      <div className="nx-ga-filters" role="search" aria-label={t("nx.attachments.filters")}>164        <div className="nx-ga-search">165          <Icon name="search" small />166          <input className="input" type="search" value={q} onChange={(e) => setQ(e.target.value)} placeholder={t("nx.attachments.search")} aria-label={t("nx.attachments.search")} maxLength={200} autoComplete="off" spellCheck={false} />167        </div>168        <input className="input nx-ga-from" type="search" value={from} onChange={(e) => setFrom(e.target.value)} placeholder={t("nx.attachments.from")} aria-label={t("nx.attachments.from")} maxLength={200} autoComplete="off" spellCheck={false} />169        <select className="select" aria-label={t("nx.attachments.size")} value={st.filter.size} onChange={(e) => setGalleryFilter({ size: e.target.value as SizeFilter })}>170          {SIZES.map((s) => (171            <option key={s} value={s}>172              {t(`nx.attachments.size.${s}`)}173            </option>174          ))}175        </select>176        <select className="select" aria-label={t("nx.attachments.date")} value={st.filter.date} onChange={(e) => setGalleryFilter({ date: e.target.value as DateFilter })}>177          {DATES.map((d) => (178            <option key={d} value={d}>179              {t(`nx.attachments.date.${d}`)}180            </option>181          ))}182        </select>183        {mailboxes.length > 1 ? (184          <select className="select" aria-label={t("nx.attachments.mailbox")} value={st.filter.mailbox ?? ""} onChange={(e) => setGalleryFilter({ mailbox: e.target.value || null })}>185            <option value="">{t("nx.allMailboxes")}</option>186            {mailboxes.map((m) => (187              <option key={m.id} value={m.id}>188                {m.address}189              </option>190            ))}191          </select>192        ) : null}193        {filtered ? (194          <button type="button" className="btn ghost" onClick={reset}>195            {t("nx.attachments.reset")}196          </button>197        ) : null}198      </div>199      <div className="nx-ga-kinds" role="group" aria-label={t("nx.attachments.kind")}>200        {ATTACHMENT_KINDS.map((k) => (201          <button key={k} type="button" className="nx-chip" aria-pressed={st.filter.kinds.includes(k)} onClick={() => toggleKind(k)}>202            <Icon name={kindGlyph(k)} />203            {t(`nx.attachments.kind.${k}`)}204          </button>205        ))}206      </div>207208      {st.status === "loading" || st.status === "idle" ? (209        <Skeleton />210      ) : st.status === "error" ? (211        <div className="nx-empty" role="alert">212          <Icon name="warn" />213          <p>{st.error === "offline" ? t("nx.offline") : st.error === "rate_limited" ? t("nx.error.rateLimited") : t("nx.attachments.loadFailed")}</p>214          <button type="button" className="btn" onClick={() => void loadGallery()}>215            {t("nx.retry")}216          </button>217        </div>218      ) : st.items.length === 0 ? (219        <div className="nx-empty">220          <Icon name="attach" />221          <p>{filtered ? t("nx.attachments.noMatch") : t("nx.attachments.empty")}</p>222          {filtered ? (223            <button type="button" className="btn" onClick={reset}>224              {t("nx.attachments.reset")}225            </button>226          ) : null}227        </div>228      ) : (229        <>230          <ul className="nx-ga-grid" aria-label={t("nx.attachments.title")}>231            {st.items.map((a, i) => (232              <Tile key={attachmentKey(a)} a={a} index={i} all={st.items} selected={st.selected.has(attachmentKey(a))} />233            ))}234          </ul>235          {st.next ? (236            <div ref={sentinel} className="nx-ga-more">237              {st.loadingMore ? (238                <Spinner label={t("nx.loading")} />239              ) : (240                <button type="button" className="btn small" onClick={() => void loadMoreGallery()}>241                  {t("nx.attachments.loadMore")}242                </button>243              )}244            </div>245          ) : null}246        </>247      )}248    </div>249  )250}251
Files main
Menu

Theme