SPB Git

Repository Public

Sidebar.tsx 19.6 KB 387 lines tsx

1// Barre latérale : boîte courante (avec sélecteur), entrées et dossiers système, dossiers intelligents et libellés (points2// d'extension), arborescence des dossiers personnels, autres boîtes, pied (stockage, synchronisation, réglages, compte).3// Réductible à une colonne d'icônes sur grand écran ; tiroir sur tablette et téléphone.4import { Suspense, lazy, useState } from "react"5import { getLang, t } from "../i18n"6import { errorDetail } from "../jmap/errors"7import type { Id, Mailbox } from "../jmap/types"8import { formatSize } from "../mail/attachments"9import { S, folderByRole, routeHref, toast, viewOfFolder, type Account, type AppState } from "../state/app"10import { composeNew } from "../state/composer"11import { createFolder, deleteFolder, folderDepth, folderLabel, initAccount, moveTo, renameFolder, sortedFolders } from "../state/mail"12import { useSidebarAction, useSidebarEntries, type SidebarEntry, type SidebarSlot } from "../state/registry"13import { linkProps, navigate, signOut, toggleFolderCollapsed, updateDevice } from "../state/session"14import { shallowEqual, useStore } from "../state/store"15import { SyncIndicator } from "./SyncIndicator"16import { AdminAlertBadge } from "./admin/AlertBadge"17import { Avatar, ConfirmDialog, Icon, IconButton, MenuButton, PromptDialog, type IconName } from "./kit"1819const MailboxOrderDialog = lazy(() => import("./MailboxOrder"))2021const DRAG_TYPE = "application/x-spmail-ids"22const ROLE_ICON: Record<string, IconName> = { inbox: "inbox", drafts: "draft", sent: "sent", archive: "archive", junk: "junk", trash: "trash" }2324interface NavItemProps {25  href: string26  icon: IconName27  label: string28  count?: number29  active: boolean30  strong?: boolean31  dropFolder?: Id32  depth?: number33  menu?: React.ReactNode34  /** pastille d'adresse à la place de l'icône (autres boîtes) */35  avatar?: string36  /** pastille de couleur (libellés) */37  color?: string38  /** bouton replier / déplier d'un dossier parent */39  twist?: React.ReactNode40  /** dépôt de conversations pris en charge par un module (libellés) */41  onDropIds?: (ids: Id[]) => void42}4344function NavItem({ href, icon, label, count, active, strong, dropFolder, depth = 0, menu, avatar, color, twist, onDropIds }: NavItemProps) {45  const [over, setOver] = useState(false)46  const drop = dropFolder || onDropIds47    ? {48        onDragOver: (e: React.DragEvent) => {49          if (!e.dataTransfer.types.includes(DRAG_TYPE)) return50          e.preventDefault()51          e.dataTransfer.dropEffect = dropFolder ? "move" : "copy"52          setOver(true)53        },54        onDragLeave: () => setOver(false),55        onDrop: (e: React.DragEvent) => {56          setOver(false)57          const raw = e.dataTransfer.getData(DRAG_TYPE)58          if (!raw) return59          e.preventDefault()60          try {61            const ids = JSON.parse(raw) as Id[]62            S.set({ selected: new Set() })63            if (dropFolder) void moveTo(ids, dropFolder)64            else onDropIds?.(ids)65          } catch {66            /* données de glisser-déposer illisibles */67          }68        },69      }70    : {}71  return (72    <li className={`nav-item${over ? " drop-over" : ""}${twist ? " has-twist" : ""}`} {...drop}>73      {twist}74      <a {...linkProps(href)} aria-current={active ? "page" : undefined} style={depth ? { paddingLeft: 12 + depth * 14 } : undefined} title={label}>75        {avatar !== undefined ? <Avatar addr={{ email: avatar }} small /> : color ? <span className="label-dot" style={{ background: color }} aria-hidden="true" /> : <Icon name={icon} />}76        <span className="truncate nav-label">{label}</span>77        {count ? (78          <span className={`nav-count${strong ? " strong" : ""}`}>79            <span aria-hidden="true">{count > 9999 ? "9999+" : count}</span>80            <span className="sr-only">{strong ? t("nav.unreadCount", { n: count }) : t("nav.totalCount", { n: count })}</span>81          </span>82        ) : null}83      </a>84      {menu}85    </li>86  )87}8889/** Entrées inscrites par d'autres modules (state/registry.ts) : « Command Center », dossiers intelligents, libellés. */90function ExtensionGroup({ slot, heading }: { slot: SidebarSlot; heading?: string }) {91  const entries = useSidebarEntries(slot)92  // un seul abonnement pour les compteurs et l'état actif de toutes les entrées93  const live = useStore(S, (s: AppState) => entries.map((e) => `${e.count?.(s) ?? 0}:${e.active?.(s) ? 1 : 0}`).join("|"))94  const action = useSidebarAction(slot)95  if (!entries.length && !action) return null96  const state = live.split("|")97  return (98    <>99      {heading ? (100        <div className="nav-heading">101          <span>{heading}</span>102          {action ? <IconButton icon={action.icon} label={action.label()} onClick={action.run} /> : null}103        </div>104      ) : null}105      <ul className={`nav-group nav-ext nav-ext-${slot}`} data-slot={slot}>106        {entries.map((e: SidebarEntry, i) => {107          const [count, active] = (state[i] ?? "0:0").split(":")108          return <NavItem key={e.id} href={e.href} icon={e.icon} label={e.label()} color={e.color} count={Number(count) || undefined} strong active={active === "1"} onDropIds={e.onDropIds} menu={e.menu ? <MenuButton label={t("folder.actions", { name: e.label() })} className="nav-menu" items={e.menu()} /> : undefined} />109        })}110      </ul>111    </>112  )113}114115function QuotaBar({ account }: { account: Account | undefined }) {116  const q = account?.quota.find((x) => x.resourceType === "octets" && x.hardLimit > 0)117  if (!q) return null118  const pct = Math.min(100, Math.round((q.used / q.hardLimit) * 100))119  const lang = getLang()120  return (121    <div className="quota" title={t("quota.title")}>122      <div className="row small">123        <span className="muted">{t("quota.label")}</span>124        <span className="spacer" />125        <span className="quota-usage">{t("quota.usage", { used: formatSize(q.used, lang), total: formatSize(q.hardLimit, lang) })}</span>126      </div>127      <progress value={pct} max={100} aria-label={t("quota.aria", { pct })} className={pct >= 90 ? "danger" : ""} />128    </div>129  )130}131132/** Dossiers personnels en arbre : un parent replié masque ses descendants (choix propre à l'appareil). */133function visibleTree(a: Account | undefined, custom: Mailbox[], collapsed: readonly string[]): { folder: Mailbox; depth: number; parent: boolean }[] {134  const hidden = new Set<Id>()135  const parents = new Set(custom.map((f) => f.parentId).filter((x): x is Id => !!x))136  const out: { folder: Mailbox; depth: number; parent: boolean }[] = []137  // `custom` est trié par chemin : un parent précède toujours ses enfants138  for (const f of custom) {139    if (f.parentId && (hidden.has(f.parentId) || collapsed.includes(f.parentId))) {140      hidden.add(f.id)141      continue142    }143    out.push({ folder: f, depth: folderDepth(a, f), parent: parents.has(f.id) })144  }145  return out146}147148export function Sidebar() {149  const me = useStore(S, (s) => s.me)150  const mb = useStore(S, (s) => s.mb)151  const view = useStore(S, (s) => s.view)152  const accounts = useStore(S, (s) => s.accounts)153  const mailRoute = useStore(S, (s) => s.route.name === "mail" && !s.route.all)154  const allView = useStore(S, (s) => (s.route.name === "mail" && s.route.all ? s.route.view : null))155  const subset = useStore(S, (s) => s.prefs.unifiedMailboxes)156  const pending = useStore(S, (s) => s.pendingApprovals)157  const collapsed = useStore(S, (s) => s.device.sidebarCollapsed)158  const foldersCollapsed = useStore(S, (s) => s.device.foldersCollapsed)159  const stats = useStore(S, (s) => ({ handle: s.me?.user.display_name ?? "", admin: s.me?.user.role === "admin" }), shallowEqual)160  const [dialog, setDialog] = useState<{ kind: "create" } | { kind: "rename"; folder: Mailbox } | { kind: "delete"; folder: Mailbox } | null>(null)161  const [ordering, setOrdering] = useState(false)162  if (!me) return null163  const href = (mbIndex: number, v: string) => routeHref({ name: "mail", mbIndex, view: v, threadId: null, q: "" })164  const uhref = (v: string) => routeHref({ name: "mail", all: true, mbIndex: 0, view: v, threadId: null, q: "" })165  const fail = (e: unknown): void => void toast({ kind: "error", text: t("error.actionFailed"), detail: errorDetail(e) || undefined })166167  return (168    <nav className="sidebar" aria-label={t("nav.label")} id="sidebar">169      <div className="sidebar-head">170        <span className="brand">171          <span className="brand-mark" aria-hidden="true">172            <Icon name="mail" />173          </span>174          <span className="brand-name">SP Mail</span>175        </span>176        <IconButton icon="command" label={t("palette.open")} className="sidebar-tool" shortcut="⌘K" onClick={() => S.set({ paletteOpen: true, navOpen: false })} />177        <button type="button" className="icon-btn sidebar-tool only-wide" aria-label={collapsed ? t("nav.expand") : t("nav.collapse")} title={`${collapsed ? t("nav.expand") : t("nav.collapse")} ([)`} aria-expanded={!collapsed} aria-controls="sidebar" onClick={() => updateDevice({ sidebarCollapsed: !collapsed })}>178          <Icon name="panel" />179        </button>180        <IconButton icon="close" label={t("nav.close")} className="only-narrow" onClick={() => S.set({ navOpen: false })} />181      </div>182      <button183        type="button"184        className="btn primary compose-btn"185        onClick={() => {186          S.set({ navOpen: false })187          composeNew()188        }}189        title={`${t("compose.new")} (c)`}190      >191        <Icon name="edit" />192        <span className="nav-label">{t("compose.new")}</span>193      </button>194195      <div className="sidebar-scroll">196        {me.mailboxes.length === 0 ? <p className="muted small sidebar-note">{t("nav.noMailbox")}</p> : null}197        <ExtensionGroup slot="primary" />198        {me.mailboxes.length > 1 ? (199          // comme une boîte : une ligne quand elle n'est pas affichée, ses vues quand elle l'est200          <ul className="nav-group nav-unified" aria-label={allView ? t("nav.unifiedGroup") : undefined}>201            <NavItem202              href={uhref("inbox")}203              icon="inbox"204              label={t("nav.unified")}205              count={me.mailboxes.reduce((n, m) => n + ((subset.length && !subset.includes(m.id) ? 0 : folderByRole(accounts[m.id], "inbox")?.unreadThreads) ?? 0), 0)}206              strong207              active={allView === "inbox"}208            />209            {allView ? (210              <>211                <NavItem href={uhref("unread")} icon="unread" label={t("view.unread")} active={allView === "unread"} depth={1} />212                <NavItem href={uhref("starred")} icon="star" label={t("view.flagged")} active={allView === "starred"} depth={1} />213                <NavItem href={uhref("drafts")} icon="draft" label={t("folder.drafts")} active={allView === "drafts"} depth={1} />214                <NavItem href={uhref("sent")} icon="sent" label={t("folder.sent")} active={allView === "sent"} depth={1} />215                <NavItem href={uhref("scheduled")} icon="clock" label={t("unified.scheduled")} active={allView === "scheduled"} depth={1} />216              </>217            ) : null}218          </ul>219        ) : null}220        {/* « Toutes les boîtes » : les dossiers intelligents (recherches enregistrées, veille) y restent à portée */}221        {allView ? <ExtensionGroup slot="smart" heading={t("nav.smart")} /> : null}222        {me.mailboxes.map((m, i) => {223          const a = accounts[m.id]224          const active = m.id === mb && !allView225          const inbox = folderByRole(a, "inbox")226          if (!active)227            return (228              <ul key={m.id} className="nav-group nav-mailbox">229                <NavItem href={href(i, "inbox")} icon="mail" avatar={m.address} label={m.address} count={inbox?.unreadThreads} strong active={false} />230              </ul>231            )232          const { system, custom } = sortedFolders(a)233          const systemByRole = new Map(system.map((f) => [f.role ?? "", f]))234          const roles = ["inbox", "drafts", "sent", "archive", "junk", "trash"]235          return (236            <section key={m.id} className="nav-account" aria-label={m.address}>237              <div className="nav-account-head">238                <Avatar addr={{ email: m.address, name: m.display_name }} small />239                <h2 className="nav-account-title truncate" title={m.address}>240                  {m.address}241                </h2>242                {a?.status === "loading" ? <span className="spinner" aria-hidden="true" /> : null}243                {a?.status === "error" ? <IconButton icon="refresh" label={t("common.retry")} onClick={() => void initAccount(m.id)} /> : null}244                {me.mailboxes.length > 1 ? (245                  <MenuButton246                    label={t("nav.switchMailbox")}247                    icon="chevron"248                    className="nav-switch"249                    items={[250                      { heading: t("nav.mailboxes") },251                      ...me.mailboxes.map((x, j) => ({ label: x.address, icon: "mail" as const, checked: x.id === m.id, onSelect: () => navigate(href(j, "inbox")) })),252                      "sep",253                      { label: t("mailbox.order.open"), icon: "list" as const, onSelect: () => setOrdering(true) },254                    ]}255                  />256                ) : null}257              </div>258              <ul className="nav-group">259                {roles.slice(0, 1).map((role) => {260                  const f = systemByRole.get(role)261                  return <NavItem key={role} href={href(i, role)} icon={ROLE_ICON[role]} label={t("folder.inbox")} count={f?.unreadThreads} strong active={mailRoute && view === role} dropFolder={f?.id} />262                })}263                <NavItem href={href(i, "unread")} icon="unread" label={t("view.unread")} active={mailRoute && view === "unread"} />264                <NavItem href={href(i, "flagged")} icon="star" label={t("view.flagged")} active={mailRoute && view === "flagged"} />265                <NavItem href={href(i, "pinned")} icon="pin" label={t("view.pinned")} active={mailRoute && view === "pinned"} />266                {roles.slice(1).map((role) => {267                  const f = systemByRole.get(role)268                  const count = role === "drafts" ? f?.totalEmails : role === "junk" ? f?.unreadThreads : undefined269                  return <NavItem key={role} href={href(i, role)} icon={ROLE_ICON[role]} label={f ? folderLabel(f) : t(`folder.${role}` as "folder.sent")} count={count} strong={role === "junk"} active={mailRoute && view === role} dropFolder={f?.id} />270                })}271              </ul>272              <ExtensionGroup slot="smart" heading={t("nav.smart")} />273              <ExtensionGroup slot="labels" heading={t("nav.labels")} />274              <div className="nav-heading">275                <span>{t("nav.folders")}</span>276                <IconButton icon="plus" label={t("folder.create")} onClick={() => setDialog({ kind: "create" })} disabled={a?.status !== "ready"} />277              </div>278              <ul className="nav-group nav-tree">279                {visibleTree(a, custom, foldersCollapsed).map(({ folder: f, depth, parent }) => {280                  const open = !foldersCollapsed.includes(f.id)281                  return (282                    <NavItem283                      key={f.id}284                      href={href(i, viewOfFolder(f))}285                      icon="folder"286                      label={f.name}287                      count={f.unreadThreads}288                      strong289                      depth={depth}290                      active={mailRoute && view === `f:${f.id}`}291                      dropFolder={f.id}292                      twist={293                        parent ? (294                          <button type="button" className="nav-twist" style={{ left: 2 + depth * 14 }} aria-expanded={open} aria-label={open ? t("folder.collapse", { name: f.name }) : t("folder.expand", { name: f.name })} onClick={() => toggleFolderCollapsed(f.id)}>295                            <Icon name={open ? "chevron" : "chevronRight"} small />296                          </button>297                        ) : undefined298                      }299                      menu={300                        <MenuButton301                          label={t("folder.actions", { name: f.name })}302                          className="nav-menu"303                          items={[304                            { label: t("folder.rename"), icon: "edit", onSelect: () => setDialog({ kind: "rename", folder: f }) },305                            { label: t("folder.delete"), icon: "trash", danger: true, onSelect: () => setDialog({ kind: "delete", folder: f }) },306                          ]}307                        />308                      }309                    />310                  )311                })}312                {custom.length === 0 ? <li className="muted small sidebar-note">{t("nav.noFolders")}</li> : null}313              </ul>314            </section>315          )316        })}317      </div>318319      <div className="sidebar-foot">320        <QuotaBar account={mb ? accounts[mb] : undefined} />321        <SyncIndicator />322        <ul className="nav-group">323          <li className="nav-item">324            <a {...linkProps("/templates")} title={t("nav.templates")}>325              <Icon name="template" />326              <span className="nav-label">{t("nav.templates")}</span>327            </a>328          </li>329          <li className="nav-item">330            <a {...linkProps("/settings/profile")} title={t("nav.settings")}>331              <Icon name="settings" />332              <span className="nav-label">{t("nav.settings")}</span>333            </a>334          </li>335          {stats.admin ? (336            <li className="nav-item">337              <a {...linkProps("/admin/overview")} className="nav-admin" title={t("nav.admin")}>338                <Icon name="shield" />339                <span className="nav-label">{t("nav.admin")}</span>340                {pending ? (341                  <span className="nav-count strong" data-testid="sidebar-approvals">342                    <span aria-hidden="true">{pending}</span>343                    <span className="sr-only">{t("nav.pendingApprovals", { n: pending })}</span>344                  </span>345                ) : null}346                <AdminAlertBadge />347              </a>348            </li>349          ) : null}350        </ul>351        <div className="sidebar-user">352          <Avatar addr={{ email: me.user.handle, name: stats.handle }} small />353          <span className="truncate nav-label sidebar-user-name" title={stats.handle}>354            {stats.handle}355          </span>356          <IconButton icon="help" label={t("nav.shortcuts")} shortcut="?" onClick={() => S.set({ helpOpen: true, navOpen: false })} />357          <IconButton icon="signout" label={t("nav.signOut")} onClick={() => void signOut()} />358        </div>359      </div>360361      {ordering ? (362        <Suspense fallback={null}>363          <MailboxOrderDialog onClose={() => setOrdering(false)} />364        </Suspense>365      ) : null}366      {dialog?.kind === "create" && mb ? (367        <PromptDialog title={t("folder.create")} label={t("folder.name")} confirmLabel={t("common.create")} onClose={() => setDialog(null)} onSubmit={(name) => createFolder(mb, name).then(() => undefined, fail)} />368      ) : null}369      {dialog?.kind === "rename" && mb ? (370        <PromptDialog title={t("folder.rename")} label={t("folder.name")} initial={dialog.folder.name} confirmLabel={t("common.save")} onClose={() => setDialog(null)} onSubmit={(name) => renameFolder(mb, dialog.folder.id, name).catch(fail)} />371      ) : null}372      {dialog?.kind === "delete" && mb ? (373        <ConfirmDialog374          title={t("folder.delete")}375          body={t("folder.deleteBody", { name: dialog.folder.name, n: dialog.folder.totalEmails })}376          confirmLabel={t("common.delete")}377          danger378          onClose={() => setDialog(null)}379          onConfirm={() => deleteFolder(mb, dialog.folder.id).catch(fail)}380        />381      ) : null}382    </nav>383  )384}385386export { DRAG_TYPE }387
Files main
Menu

Theme