SPB Git

Repository Public

MessageList.tsx 36.0 KB 822 lines tsx

1// Liste des conversations : recherche et filtres, barre contextuelle de sélection, lignes en cartes (pastille, aperçu, actions2// rapides au survol, gestes de glissement au doigt), liste virtualisée (fenêtres Email/query).3import { Suspense, lazy, memo, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent, type ReactNode } from "react"4import { fmtListDate, fmtNumber, t } from "../i18n"5import { KW, type Id } from "../jmap/types"6import { displayName, initials } from "../mail/address"7import { countLoaded, hasId, indexOfId } from "../mail/listmodel"8import { emptySearch, isEmptySearch, parseSearch, stringifySearch, type SearchQuery } from "../mail/search"9import { addressHue } from "../mail/unified"10import { S, currentAccount, folderOfView, routeHref } from "../state/app"11import { emptyFolder, ensureRange, folderLabel, markRead, moveTo, retryList, selectAll, setFlag, sortedFolders, toggleSelect, viewLabel } from "../state/mail"12import { PaletteButton } from "./PaletteButton"13import { requestRowContext, requestSnooze, useListHeaders, useListView, useRowGlyphs, useRowLabels, useSearchBar, useSelectionActions } from "../state/registry"14import { navigate, rememberSearch } from "../state/session"15import { shallowEqual, useStore } from "../state/store"16import { DRAG_TYPE } from "./Sidebar"17import { SyncIndicator } from "./SyncIndicator"18import { doArchive, doDelete, doJunk, openRow } from "./actions"19import { ErrorBoundary, Icon, IconButton, MenuButton, REDUCED_MOTION, confirmAsync, type IconName, type MenuItem } from "./kit"2021// ---------------------------------------------------------------- recherche22function SearchBar() {23  const query = useStore(S, (s) => (s.view === "search" ? s.query : ""))24  const mbIndex = useStore(S, (s) => (s.route.name === "mail" ? s.route.mbIndex : 0))25  const [text, setText] = useState(query)26  const [panel, setPanel] = useState(false)27  const [form, setForm] = useState<SearchQuery>(emptySearch())28  const ids = { from: useId(), to: useId(), subject: useId(), after: useId(), before: useId(), att: useId(), panel: useId() }29  useEffect(() => setText(query), [query])3031  const run = (q: string) => {32    const trimmed = q.trim()33    if (!trimmed) navigate(routeHref({ name: "mail", mbIndex, view: "inbox", threadId: null, q: "" }))34    else {35      rememberSearch(trimmed)36      navigate(routeHref({ name: "mail", mbIndex, view: "search", threadId: null, q: trimmed }))37    }38  }39  const parsed = useMemo(() => parseSearch(query), [query])40  const chips: { label: string; clear: Partial<SearchQuery> }[] = []41  if (parsed.from) chips.push({ label: `${t("search.from")} ${parsed.from}`, clear: { from: "" } })42  if (parsed.to) chips.push({ label: `${t("search.to")} ${parsed.to}`, clear: { to: "" } })43  if (parsed.subject) chips.push({ label: `${t("search.subject")} ${parsed.subject}`, clear: { subject: "" } })44  if (parsed.hasAttachment) chips.push({ label: t("search.hasAttachment"), clear: { hasAttachment: false } })45  if (parsed.after) chips.push({ label: `${t("search.after")} ${parsed.after}`, clear: { after: "" } })46  if (parsed.before) chips.push({ label: `${t("search.before")} ${parsed.before}`, clear: { before: "" } })4748  return (49    <div className="search">50      <form51        role="search"52        className="search-form"53        onSubmit={(e) => {54          e.preventDefault()55          setPanel(false)56          run(text)57        }}58      >59        <IconButton icon="menu" label={t("nav.open")} className="only-narrow" onClick={() => S.set({ navOpen: true })} />60        <label className="search-box">61          <span className="sr-only">{t("search.label")}</span>62          <Icon name="search" />63          <input64            id="search-input"65            type="search"66            value={text}67            onChange={(e) => setText(e.target.value)}68            placeholder={t("search.placeholder")}69            autoComplete="off"70            spellCheck={false}71            enterKeyHint="search"72            onKeyDown={(e) => {73              if (e.key === "Escape") {74                e.currentTarget.blur()75                if (text && !query) setText("")76              }77            }}78          />79        </label>80        {query ? <IconButton icon="close" label={t("search.clear")} onClick={() => run("")} /> : null}81        <PaletteButton />82        <IconButton83          icon="filter"84          label={t("search.filters")}85          pressed={panel}86          onClick={() => {87            setForm(parseSearch(text))88            setPanel((p) => !p)89          }}90        />91        <SyncIndicator compact />92      </form>93      {panel ? (94        <form95          className="search-panel"96          id={ids.panel}97          aria-label={t("search.filters")}98          onSubmit={(e) => {99            e.preventDefault()100            const q = stringifySearch(form)101            setText(q)102            setPanel(false)103            run(q)104          }}105        >106          <div className="field">107            <label htmlFor={ids.from}>{t("search.from")}</label>108            <input id={ids.from} className="input" value={form.from} onChange={(e) => setForm({ ...form, from: e.target.value })} />109          </div>110          <div className="field">111            <label htmlFor={ids.to}>{t("search.to")}</label>112            <input id={ids.to} className="input" value={form.to} onChange={(e) => setForm({ ...form, to: e.target.value })} />113          </div>114          <div className="field">115            <label htmlFor={ids.subject}>{t("search.subject")}</label>116            <input id={ids.subject} className="input" value={form.subject} onChange={(e) => setForm({ ...form, subject: e.target.value })} />117          </div>118          <div className="search-dates">119            <div className="field">120              <label htmlFor={ids.after}>{t("search.after")}</label>121              <input id={ids.after} className="input" type="date" value={form.after} onChange={(e) => setForm({ ...form, after: e.target.value })} />122            </div>123            <div className="field">124              <label htmlFor={ids.before}>{t("search.before")}</label>125              <input id={ids.before} className="input" type="date" value={form.before} onChange={(e) => setForm({ ...form, before: e.target.value })} />126            </div>127          </div>128          <label className="check" htmlFor={ids.att}>129            <input id={ids.att} type="checkbox" checked={form.hasAttachment} onChange={(e) => setForm({ ...form, hasAttachment: e.target.checked })} />130            <span>{t("search.hasAttachment")}</span>131          </label>132          <div className="row">133            <span className="spacer" />134            <button type="button" className="btn small" onClick={() => setForm({ ...emptySearch(), text: form.text })}>135              {t("search.reset")}136            </button>137            <button type="submit" className="btn primary small" disabled={isEmptySearch(form)}>138              {t("search.run")}139            </button>140          </div>141        </form>142      ) : null}143      {chips.length ? (144        <ul className="chips" aria-label={t("search.activeFilters")}>145          {chips.map((c) => (146            <li key={c.label} className="chip">147              <span className="truncate">{c.label}</span>148              <button type="button" aria-label={t("search.removeFilter", { label: c.label })} onClick={() => run(stringifySearch({ ...parsed, ...c.clear }))}>149                <Icon name="close" small />150              </button>151            </li>152          ))}153        </ul>154      ) : null}155    </div>156  )157}158159// ---------------------------------------------------------------- barre d'actions160/** La sélection contient-elle un message non lu ? Mémorisé sur (sélection, messages) : le sélecteur est relu à chaque mise à jour. */161let unreadMemo: { selected: ReadonlySet<Id>; emails: object; value: boolean } | null = null162function selectionHasUnread(s: { selected: ReadonlySet<Id>; emails: Record<Id, { keywords: Record<string, boolean> }> }): boolean {163  if (unreadMemo && unreadMemo.selected === s.selected && unreadMemo.emails === s.emails) return unreadMemo.value164  let value = false165  for (const id of s.selected)166    if (s.emails[id] && !s.emails[id].keywords[KW.seen]) {167      value = true168      break169    }170  unreadMemo = { selected: s.selected, emails: s.emails, value }171  return value172}173174function Toolbar() {175  // `countLoaded` est mémorisé par version de la liste : ce sélecteur, relu à chaque mise à jour du magasin, ne parcourt rien176  const { count, total, loaded, view, stale } = useStore(S, (s) => ({ count: s.selected.size, total: s.list.total, loaded: countLoaded(s.list.ids), view: s.view, stale: s.list.stale }), shallowEqual)177  const account = useStore(S, currentAccount)178  const mb = useStore(S, (s) => s.mb)179  const anyUnread = useStore(S, selectionHasUnread)180  const extra = useSelectionActions()181  const title = viewLabel(account, view)182  const allSelected = count > 0 && count >= loaded183  const box = useRef<HTMLInputElement>(null)184  useEffect(() => {185    if (box.current) box.current.indeterminate = count > 0 && !allSelected186  }, [count, allSelected])187  const selected = () => [...S.get().selected]188  const folders = sortedFolders(account)189  const moveItems: MenuItem[] = [...folders.system, ...folders.custom]190    .filter((f) => f.role !== "drafts" && f.id !== folderOfView(account, view)?.id)191    .map((f) => ({192      label: folderLabel(f),193      icon: "folder" as const,194      onSelect: () => {195        const ids = selected()196        S.set({ selected: new Set() })197        void moveTo(ids, f.id)198      },199    }))200  const current = folderOfView(account, view)201  const canEmpty = (view === "trash" || view === "junk") && current && (total ?? 0) > 0202  return (203    <div className={`list-toolbar${count ? " selecting" : ""}`} role="toolbar" aria-label={t("list.toolbar")}>204      <label className="check list-selectall" title={t("list.selectAll")}>205        <input ref={box} type="checkbox" checked={allSelected} onChange={(e) => selectAll(e.target.checked)} disabled={!loaded} />206        <span className="sr-only">{t("list.selectAll")}</span>207      </label>208      {count === 0 ? (209        <>210          <h1 className="list-title truncate">{title}</h1>211          <span className="muted small list-count" aria-live="polite">212            {total === null ? "" : t("list.count", { n: total, count: fmtNumber(total) })}213            {stale ? ` · ${t("offline.cached")}` : ""}214          </span>215          <span className="spacer" />216          {canEmpty && mb && current ? (217            <button218              type="button"219              className="btn small ghost"220              onClick={async () => {221                if (await confirmAsync({ title: t("list.emptyFolderTitle", { folder: title }), body: t("list.emptyFolderBody", { n: total ?? 0 }), confirmLabel: t("list.emptyFolder"), danger: true })) void emptyFolder(mb, current.id)222              }}223            >224              {t("list.emptyFolder")}225            </button>226          ) : null}227        </>228      ) : (229        <>230          <span className="list-selcount truncate" aria-live="polite">231            {t("list.selected", { n: count })}232          </span>233          <span className="spacer" />234          {/* les actions principales restent visibles à toute largeur de volet ; les autres sont dans le menu */}235          {anyUnread ? <IconButton icon="mail" label={t("action.markRead")} shortcut="Shift+I" onClick={() => void markRead(selected(), true)} /> : <IconButton icon="unread" label={t("action.markUnread")} shortcut="Shift+U" onClick={() => void markRead(selected(), false)} />}236          {view !== "archive" ? <IconButton icon="archive" label={t("action.archive")} shortcut="e" onClick={() => void doArchive()} /> : null}237          <MenuButton icon="move" label={t("action.move")} items={moveItems} />238          <IconButton icon="trash" label={view === "trash" || view === "drafts" ? t("action.deleteForever") : t("action.delete")} shortcut="#" onClick={() => void doDelete()} />239          {mb ? extra.map((a) => <IconButton key={a.id} icon={a.icon} label={a.label()} shortcut={a.shortcut} className="list-extra" onClick={() => a.run(selected(), mb)} />) : null}240          <MenuButton241            label={t("list.moreActions")}242            items={[243              { label: t("action.markRead"), icon: "mail", onSelect: () => void markRead(selected(), true) },244              { label: t("action.markUnread"), icon: "unread", onSelect: () => void markRead(selected(), false) },245              { label: t("action.flag"), icon: "star", onSelect: () => void setFlag(selected(), true) },246              { label: t("action.unflag"), icon: "star", onSelect: () => void setFlag(selected(), false) },247              { label: view === "junk" ? t("action.notJunk") : t("action.junk"), icon: "junk", onSelect: () => void doJunk(view !== "junk") },248              ...(mb ? extra.map((a) => ({ label: a.label(), icon: a.icon, onSelect: () => a.run(selected(), mb) })) : []),249            ]}250          />251          <IconButton icon="close" label={t("list.clearSelection")} className="list-clear" onClick={() => S.set({ selected: new Set() })} />252        </>253      )}254    </div>255  )256}257258// ---------------------------------------------------------------- gestes de glissement (doigt, stylet)259const SWIPE_ARM = 72260export interface SwipeActions {261  /** glissement vers la droite */262  lead: { icon: IconName; label: string; run: () => void }263  /** glissement court vers la gauche */264  trail: { icon: IconName; label: string; run: () => void }265  /** glissement long vers la gauche */266  trailLong: { icon: IconName; label: string; run: () => void }267}268/**269 * Glissement horizontal d'une ligne au doigt. La carte suit le doigt (transform seulement) ; au relâchement, l'action armée270 * s'exécute. Mouvement réduit : la carte ne bouge pas, seule l'étiquette de l'action apparaît. Le défilement vertical reste271 * natif (`touch-action: pan-y`) et un geste entamé verticalement n'arme jamais rien.272 */273export function useRowSwipe(actions: SwipeActions | null) {274  const card = useRef<HTMLSpanElement>(null)275  const st = useRef<{ id: number; x: number; y: number; dx: number; active: boolean; w: number } | null>(null)276  const swallowClick = useRef(false)277  const ref = useRef(actions)278  ref.current = actions279  const stage = (dx: number, w: number): string => (dx > 0 ? (dx >= SWIPE_ARM ? "lead-armed" : "lead") : -dx >= Math.max(SWIPE_ARM * 2, w * 0.55) ? "trail-long" : -dx >= SWIPE_ARM ? "trail-armed" : "trail")280  const finish = (row: HTMLElement, commit: boolean) => {281    const s = st.current282    st.current = null283    if (!s) return284    const where = s.active ? stage(s.dx, s.w) : ""285    row.classList.remove("swiping")286    row.removeAttribute("data-swipe")287    if (card.current) card.current.style.transform = ""288    if (!s.active) return289    swallowClick.current = true290    setTimeout(() => (swallowClick.current = false), 350)291    const a = ref.current292    if (!commit || !a) return293    if (where === "lead-armed") a.lead.run()294    else if (where === "trail-armed") a.trail.run()295    else if (where === "trail-long") a.trailLong.run()296  }297  const handlers = {298    onPointerDown: (e: ReactPointerEvent<HTMLElement>) => {299      if (!ref.current || (e.pointerType !== "touch" && e.pointerType !== "pen")) return300      st.current = { id: e.pointerId, x: e.clientX, y: e.clientY, dx: 0, active: false, w: e.currentTarget.clientWidth }301    },302    onPointerMove: (e: ReactPointerEvent<HTMLElement>) => {303      const s = st.current304      if (!s || s.id !== e.pointerId) return305      const dx = e.clientX - s.x306      const dy = e.clientY - s.y307      if (!s.active) {308        if (Math.abs(dy) > 10 && Math.abs(dy) > Math.abs(dx)) return void (st.current = null) // défilement vertical309        if (Math.abs(dx) < 12) return310        s.active = true311        try {312          e.currentTarget.setPointerCapture(e.pointerId)313        } catch {314          /* pointeur déjà relâché */315        }316        e.currentTarget.classList.add("swiping")317      }318      s.dx = dx319      e.currentTarget.setAttribute("data-swipe", stage(dx, s.w))320      if (card.current && !matchMedia(REDUCED_MOTION).matches) card.current.style.transform = `translateX(${Math.round(dx)}px)`321    },322    onPointerUp: (e: ReactPointerEvent<HTMLElement>) => finish(e.currentTarget, true),323    onPointerCancel: (e: ReactPointerEvent<HTMLElement>) => finish(e.currentTarget, false),324  }325  return { card, handlers, swallowClick }326}327328/** Fond d'une ligne glissée : l'action de chaque côté (décoratif : les mêmes actions existent au clavier et dans les barres). */329export function SwipeLayer({ actions }: { actions: SwipeActions }) {330  return (331    <span className="mrow-swipe" aria-hidden="true">332      <span className="mrow-swipe-lead">333        <Icon name={actions.lead.icon} />334        <span>{actions.lead.label}</span>335      </span>336      <span className="mrow-swipe-trail">337        <span className="mrow-swipe-short">338          <span>{actions.trail.label}</span>339          <Icon name={actions.trail.icon} />340        </span>341        <span className="mrow-swipe-long">342          <span>{actions.trailLong.label}</span>343          <Icon name={actions.trailLong.icon} />344        </span>345      </span>346    </span>347  )348}349350const canHover = () => typeof matchMedia === "function" && matchMedia("(hover: hover)").matches351352// ---------------------------------------------------------------- lignes353/** Colonne de tête d'une ligne : pastille d'initiales (si activée) qui cède la place à la case de sélection. */354export function RowLead({ address, name, selected, unread, onToggle }: { address: string; name: string; selected: boolean; unread: boolean; onToggle: (shift: boolean) => void }) {355  return (356    <span357      className="mrow-check"358      onClick={(e) => {359        e.stopPropagation()360        onToggle(e.shiftKey)361      }}362    >363      {unread ? <span className="dot" /> : null}364      <span className="avatar s mrow-avatar" style={{ "--h": addressHue(address) } as CSSProperties}>365        {initials({ email: address || "?", name })}366      </span>367      <span className={`box${selected ? " on" : ""}`}>{selected ? <Icon name="check" small /> : null}</span>368    </span>369  )370}371372const Row = memo(function Row({ id, index, top, total }: { id: Id; index: number; top: number; total: number }) {373  const email = useStore(S, (s) => s.emails[id])374  const selected = useStore(S, (s) => s.selected.has(id))375  const isCursor = useStore(S, (s) => s.cursor === id)376  const isOpen = useStore(S, (s) => !!s.open && s.open.mb === s.mb && !!s.emails[id] && s.open.threadId === s.emails[id].threadId)377  // seuls les messages que le lecteur montrera sont comptés (corbeille et brouillons écartés)378  const threadSize = useStore(S, (s) => (s.emails[id] ? (s.threadShown[s.emails[id].threadId] ?? s.threads[s.emails[id].threadId]?.length ?? 1) : 1))379  const outgoing = useStore(S, (s) => s.view === "sent" || s.view === "drafts")380  const view = useStore(S, (s) => s.view)381  const labelsOf = useRowLabels()382  const glyphsOf = useRowGlyphs()383  const unread = email ? !email.keywords[KW.seen] : false384  // gestes au doigt seulement : à la souris, les actions rapides au survol et le glisser-déposer vers un dossier les remplacent385  const actions: SwipeActions | null =386    email && !canHover()387      ? {388          lead: { icon: unread ? "mail" : "unread", label: unread ? t("action.markRead") : t("action.markUnread"), run: () => void markRead([id], unread) },389          trail: view === "archive" ? { icon: "trash", label: t("action.delete"), run: () => void doDelete({ ids: [id], exact: false }) } : { icon: "archive", label: t("action.archive"), run: () => void doArchive({ ids: [id], exact: false }) },390          trailLong: { icon: "snooze", label: t("action.snooze"), run: () => requestSnooze([id], S.get().mb) },391        }392      : null393  const swipe = useRowSwipe(actions)394  if (!email) return <SkeletonRow top={top} />395  const flagged = !!email.keywords[KW.flagged]396  const pinned = !!email.keywords[KW.pinned]397  const person = outgoing ? email.to?.[0] : email.from?.[0]398  const who = outgoing ? (email.to ?? []).map((a) => displayName(a)).join(", ") || t("list.noRecipient") : displayName(email.from?.[0]) || t("list.unknownSender")399  const subject = email.subject?.trim() || t("list.noSubject")400  const labels = labelsOf ? labelsOf(email) : []401  const glyphs = glyphsOf ? glyphsOf(email) : []402  const label = [unread ? t("list.unread") : "", who, subject, fmtListDate(email.receivedAt), email.hasAttachment ? t("list.hasAttachment") : "", flagged ? t("list.flagged") : "", pinned ? t("list.pinned") : "", threadSize > 1 ? t("list.threadCount", { n: threadSize }) : "", ...labels.map((l) => l.name), ...glyphs.map((g) => g.label)].filter(Boolean).join(", ")403  const quick = (run: () => void) => (e: React.MouseEvent) => {404    e.stopPropagation()405    run()406  }407  const target = { ids: [id], exact: false }408  return (409    <div410      id={`row-${id}`}411      role="option"412      aria-selected={selected}413      aria-setsize={total}414      aria-posinset={index + 1}415      data-id={id}416      className={`mrow${unread ? " unread" : ""}${selected ? " selected" : ""}${isCursor ? " cursor" : ""}${isOpen ? " open" : ""}`}417      style={{ transform: `translateY(${top}px)` }}418      draggable={canHover()}419      onDragStart={(e) => {420        const sel = S.get().selected421        const ids = sel.has(id) ? [...sel] : [id]422        e.dataTransfer.setData(DRAG_TYPE, JSON.stringify(ids))423        e.dataTransfer.setData("text/plain", subject)424        // « copyMove » : un dossier déplace, un libellé (dépôt en « copy ») s'ajoute sans déplacer425        e.dataTransfer.effectAllowed = "copyMove"426      }}427      onContextMenu={(e) => {428        // menu contextuel d'un module (libellés, veille…) ; sans module inscrit, celui du navigateur reste429        const sel = S.get().selected430        if (requestRowContext({ emailIds: sel.has(id) ? [...sel] : [id], mailboxId: S.get().mb, x: e.clientX, y: e.clientY })) e.preventDefault()431      }}432      onClick={(e) => {433        if (swipe.swallowClick.current) return434        if (e.metaKey || e.ctrlKey) toggleSelect(id)435        else if (e.shiftKey) toggleSelect(id, true)436        else openRow(id)437      }}438      {...swipe.handlers}439    >440      <span className="sr-only">{label}</span>441      {actions ? <SwipeLayer actions={actions} /> : null}442      <span className="mrow-card" aria-hidden="true" ref={swipe.card}>443        <RowLead address={person?.email ?? ""} name={person?.name ?? ""} selected={selected} unread={unread} onToggle={(shift) => toggleSelect(id, shift)} />444        <span className="mrow-main">445          <span className="mrow-top">446            <span className="mrow-from truncate">{who}</span>447            {threadSize > 1 ? <span className="mrow-n">{threadSize}</span> : null}448            <span className="mrow-icons">449              {labels.slice(0, 3).map((l) => (450                <span key={l.id} className="label-dot" style={{ background: l.color }} title={l.name} />451              ))}452              {glyphs.map((g) => (453                <span key={g.id} className={`mrow-glyph mrow-glyph-${g.id}`} title={g.label}>454                  <Icon name={g.icon} small />455                </span>456              ))}457              {pinned ? <Icon name="pin" small className="pin" /> : null}458              {email.hasAttachment ? <Icon name="attach" small /> : null}459              {email.keywords[KW.answered] ? <Icon name="reply" small /> : null}460            </span>461            <span className="mrow-date">{fmtListDate(email.receivedAt)}</span>462          </span>463          <span className="mrow-bottom">464            <span className="mrow-subject truncate">{subject}</span>465            <span className="mrow-preview">{email.preview}</span>466          </span>467        </span>468        <span className="mrow-quick">469          {view !== "archive" ? (470            <span className="mrow-q" title={t("action.archive")} onClick={quick(() => void doArchive(target))}>471              <Icon name="archive" small />472            </span>473          ) : null}474          <span className="mrow-q" title={view === "trash" || view === "drafts" ? t("action.deleteForever") : t("action.delete")} onClick={quick(() => void doDelete(target))}>475            <Icon name="trash" small />476          </span>477          <span className="mrow-q" title={t("action.snooze")} onClick={quick(() => requestSnooze([id], S.get().mb))}>478            <Icon name="snooze" small />479          </span>480          <span className="mrow-q" title={unread ? t("action.markRead") : t("action.markUnread")} onClick={quick(() => void markRead([id], unread))}>481            <Icon name={unread ? "mail" : "unread"} small />482          </span>483        </span>484        <span485          className={`mrow-star${flagged ? " on" : ""}`}486          title={flagged ? t("action.unflag") : t("action.flag")}487          onClick={(e) => {488            e.stopPropagation()489            void setFlag([id], !flagged)490          }}491        >492          <Icon name="star" />493        </span>494      </span>495    </div>496  )497})498499/**500 * Case de sélection et favori d'une ligne, exposés aux technologies d'assistance. Les éléments visibles (dans une `option`,501 * dont les enfants sont de pure présentation en ARIA) ne servent qu'au pointeur : ceux-ci sont de vrais contrôles, nommés,502 * avec leur état, placés hors de la liste. Au clavier, les mêmes actions se font par « x » et « s ».503 */504const RowControls = memo(function RowControls({ id }: { id: Id }) {505  const email = useStore(S, (s) => s.emails[id])506  const selected = useStore(S, (s) => s.selected.has(id))507  if (!email) return null508  const subject = email.subject?.trim() || t("list.noSubject")509  const flagged = !!email.keywords[KW.flagged]510  return (511    <li>512      <label>513        <input type="checkbox" tabIndex={-1} checked={selected} onChange={() => toggleSelect(id)} />514        {t("list.selectRow", { subject })}515      </label>516      <button type="button" tabIndex={-1} aria-pressed={flagged} onClick={() => void setFlag([id], !flagged)}>517        {t("list.starRow", { subject })}518      </button>519    </li>520  )521})522523export function SkeletonRow({ top }: { top: number }) {524  return (525    <div className="mrow skeleton-row" style={{ transform: `translateY(${top}px)` }} aria-hidden="true">526      <span className="mrow-card">527        <span className="mrow-check">528          <span className="skeleton mrow-avatar avatar s" />529        </span>530        <span className="mrow-main">531          <span className="mrow-top">532            <span className="skeleton" style={{ width: "38%", height: 11 }} />533          </span>534          <span className="mrow-bottom">535            <span className="skeleton" style={{ width: "82%", height: 11 }} />536          </span>537        </span>538      </span>539    </div>540  )541}542543/** Hauteur d'une ligne : elle dépend de la densité, du nombre de lignes d'aperçu et du point de rupture (jeton --row-h). */544export function useRowHeight(): number {545  const density = useStore(S, (s) => s.prefs.density)546  const preview = useStore(S, (s) => s.prefs.previewLines)547  const [h, setH] = useState(72)548  useLayoutEffect(() => {549    const read = () => setH(Number.parseFloat(getComputedStyle(document.documentElement).getPropertyValue("--row-h")) || 72)550    read()551    window.addEventListener("resize", read)552    return () => window.removeEventListener("resize", read)553  }, [density, preview])554  return h555}556557/** Lignes fantômes du premier chargement, à la hauteur de la densité active. */558export function SkeletonList() {559  const rowH = useRowHeight()560  return (561    <div className="mlist" aria-busy="true" aria-label={t("common.loading")}>562      <div className="mlist-inner" style={{ height: 8 * rowH }}>563        {Array.from({ length: 8 }, (_, i) => (564          <SkeletonRow key={i} top={i * rowH} />565        ))}566      </div>567    </div>568  )569}570571/** Ce qu'une liste virtualisée doit savoir de sa source (liste d'une boîte, ou vue « Toutes les boîtes »). */572export interface VirtualSource {573  ids: readonly (string | undefined)[]574  /** nombre de lignes à réserver (au moins `ids.length`) */575  total: number576  cursor: string | null577  /** nom lu par les lecteurs d'écran */578  label: string579  /** change quand la liste change : retour en haut */580  listKey: string581  ensureRange: (first: number, last: number) => void582  renderRow: (id: string, index: number, top: number, count: number) => ReactNode583  /** contrôles accessibles d'une ligne (sélection, favori), rendus hors de la liste */584  renderControls?: (id: string) => ReactNode585  onFocusEmpty: () => void586}587588/** Liste virtualisée : seules les lignes visibles (plus une marge) sont dans le DOM. */589export function VirtualRows({ ids, total, cursor, label, listKey, ensureRange: ensure, renderRow, renderControls, onFocusEmpty }: VirtualSource) {590  const rowH = useRowHeight()591  const ref = useRef<HTMLDivElement>(null)592  const [scrollTop, setScrollTop] = useState(0)593  const [height, setHeight] = useState(600)594  const raf = useRef(0)595596  useLayoutEffect(() => {597    const el = ref.current598    if (!el) return599    const ro = new ResizeObserver(() => setHeight(el.clientHeight))600    ro.observe(el)601    setHeight(el.clientHeight)602    return () => ro.disconnect()603  }, [])604  // nouvelle liste : retour en haut605  useLayoutEffect(() => {606    if (ref.current) ref.current.scrollTop = 0607    setScrollTop(0)608  }, [listKey])609610  const count = Math.max(total, ids.length)611  const first = Math.max(0, Math.floor(scrollTop / rowH) - 6)612  const last = Math.min(count - 1, Math.ceil((scrollTop + height) / rowH) + 6)613  const ensureRef = useRef(ensure)614  ensureRef.current = ensure615  useEffect(() => {616    if (count > 0) ensureRef.current(first, last)617  }, [first, last, count, listKey])618619  // le curseur clavier reste visible620  const idsRef = useRef(ids)621  idsRef.current = ids622  useEffect(() => {623    const el = ref.current624    if (!cursor || !el) return625    const i = indexOfId(idsRef.current, cursor)626    if (i < 0) return627    const top = i * rowH628    if (top < el.scrollTop) el.scrollTop = top629    else if (top + rowH > el.scrollTop + el.clientHeight) el.scrollTop = top + rowH - el.clientHeight630  }, [cursor, rowH])631632  // Focus venu d'un clic : pas de curseur posé d'office sur la première ligne. Sinon la liste, pour montrer ce curseur,633  // remonterait en haut entre l'appui et le relâchement du bouton, et le clic n'atteindrait plus la ligne visée.634  const byPointer = useRef(false)635636  const onScroll = useCallback(() => {637    cancelAnimationFrame(raf.current)638    raf.current = requestAnimationFrame(() => setScrollTop(ref.current?.scrollTop ?? 0))639  }, [])640641  const rows = []642  const controls = []643  for (let i = first; i <= last; i++) {644    const id = ids[i]645    rows.push(id ? renderRow(id, i, i * rowH, count) : <SkeletonRow key={`s${i}`} top={i * rowH} />)646    if (id && renderControls) controls.push(renderControls(id))647  }648  return (649    <div650      ref={ref}651      className="mlist"652      onScroll={onScroll}653      onPointerDownCapture={() => {654        byPointer.current = true655        setTimeout(() => (byPointer.current = false), 0)656      }}657    >658      <div659        // la clé rejoue la transition d'entrée à chaque changement de liste (dossier, recherche)660        key={listKey}661        id="message-list"662        role="listbox"663        aria-multiselectable="true"664        aria-label={label}665        aria-activedescendant={hasId(ids, cursor) ? `row-${cursor}` : undefined}666        tabIndex={0}667        className="mlist-inner"668        style={{ height: count * rowH }}669        onFocus={() => {670          if (!byPointer.current) onFocusEmpty()671        }}672      >673        {rows}674      </div>675      {controls.length ? (676        <ul className="sr-only" aria-label={t("list.rowControls")}>677          {controls}678        </ul>679      ) : null}680    </div>681  )682}683684function VirtualList() {685  const ids = useStore(S, (s) => s.list.ids)686  const total = useStore(S, (s) => s.list.total ?? s.list.ids.length)687  const cursor = useStore(S, (s) => s.cursor)688  const title = useStore(S, (s) => viewLabel(currentAccount(s), s.view))689  const listKey = useStore(S, (s) => s.list.key)690  return (691    <VirtualRows692      ids={ids}693      total={total}694      cursor={cursor}695      label={t("list.aria", { name: title })}696      listKey={listKey}697      ensureRange={ensureRange}698      renderRow={(id, i, top, count) => <Row key={id} id={id} index={i} top={top} total={count} />}699      renderControls={(id) => <RowControls key={id} id={id} />}700      onFocusEmpty={() => {701        if (!S.get().cursor) {702          const firstId = S.get().list.ids[0]703          if (firstId) S.set({ cursor: firstId })704        }705      }}706    />707  )708}709710function ListBody() {711  // `blank` : aucune ligne à montrer (pas encore chargée, ou liste réellement vide quand le total connu vaut zéro)712  const { loadingFirst, error, blank, empty, view, query } = useStore(S, (s) => ({ loadingFirst: s.list.loadingFirst, error: s.list.error, blank: s.list.ids.length === 0, empty: s.list.total === 0 && s.list.ids.length === 0, view: s.view, query: s.query }), shallowEqual)713  const accountError = useStore(S, (s) => (currentAccount(s)?.status === "error" ? (currentAccount(s)?.error ?? "unknown") : null))714  const noMailbox = useStore(S, (s) => s.me !== null && s.me.mailboxes.length === 0)715  if (noMailbox)716    return (717      <div className="empty">718        <Icon name="inbox" />719        <h2>{t("list.noMailboxTitle")}</h2>720        <p>{t("list.noMailboxBody")}</p>721      </div>722    )723  if (error && blank)724    return (725      <div className="empty" role="alert">726        <Icon name={error === "offline" ? "offline" : "warn"} />727        <h2>{t("list.errorTitle")}</h2>728        <p>{t(`error.${error}`)}</p>729        <button type="button" className="btn" onClick={retryList}>730          <Icon name="refresh" />731          <span>{t("common.retry")}</span>732        </button>733      </div>734    )735  if (loadingFirst && blank) return <SkeletonList />736  if (empty) {737    const searching = view === "search"738    return (739      <div className="empty">740        <Icon name={searching ? "search" : view === "trash" ? "trash" : view === "flagged" ? "star" : view === "pinned" ? "pin" : view === "drafts" ? "draft" : view === "sent" ? "sent" : view === "archive" ? "archive" : "inbox"} />741        <h2>{searching ? (query ? t("list.emptySearchTitle") : t("list.searchPromptTitle")) : t("list.emptyTitle")}</h2>742        <p>{searching ? (query ? t("list.emptySearchBody") : t("list.searchPromptBody")) : view === "inbox" ? t("list.emptyInbox") : t("list.emptyBody")}</p>743      </div>744    )745  }746  return (747    <>748      {error || accountError ? (749        <div className="banner warn list-banner" role="status">750          <Icon name="warn" small />751          <span className="spacer">{t(`error.${error ?? accountError ?? "unknown"}`)}</span>752          <button type="button" className="btn small" onClick={retryList}>753            {t("common.retry")}754          </button>755        </div>756      ) : null}757      <VirtualList />758    </>759  )760}761762const Unified = lazy(() => import("./Unified"))763764/** Bandeaux inscrits par les modules (pastilles d'aperçu) : entre la barre d'outils et les lignes. */765function ListHeaders() {766  const headers = useListHeaders()767  const live = useStore(S, (s) => headers.map((h) => (h.when(s) ? 1 : 0)).join(""))768  if (!headers.length) return null769  return (770    <ErrorBoundary compact>771      <Suspense fallback={null}>772        {headers.map((h, i) => (live[i] === "1" ? <h.component key={h.id} /> : null))}773      </Suspense>774    </ErrorBoundary>775  )776}777778export function MessageList() {779  const all = useStore(S, (s) => s.all)780  const View = useListView()781  const Search = useSearchBar()782  // vue inscrite par un module (résultats de la recherche du serveur) : elle remplace tout le volet, comme « Toutes les boîtes »783  if (View)784    return (785      <Suspense786        fallback={787          <section className="list-pane" id="list-pane" aria-busy="true" aria-label={t("list.region")}>788            <SkeletonList />789          </section>790        }791      >792        <View />793      </Suspense>794    )795  if (all)796    return (797      <Suspense798        fallback={799          <section className="list-pane" id="list-pane" aria-busy="true" aria-label={t("list.region")}>800            <SkeletonList />801          </section>802        }803      >804        <Unified />805      </Suspense>806    )807  return (808    <section className="list-pane" id="list-pane" aria-label={t("list.region")}>809      {Search ? (810        <Suspense fallback={<SearchBar />}>811          <Search />812        </Suspense>813      ) : (814        <SearchBar />815      )}816      <Toolbar />817      <ListHeaders />818      <ListBody />819    </section>820  )821}822
Files main
Menu

Theme