SPB Git

Repository Public

RowMenu.tsx 6.9 KB 142 lines tsx

1// SP Mail Next — menu contextuel d'une ligne (clic droit, appui long) : actions courantes puis entrées des modules (libellés,2// veille, rappel). Menu positionné sous le pointeur, gardé dans la fenêtre, entièrement utilisable au clavier.3import { useEffect, useLayoutEffect, useRef, useState } from "react"4import { t } from "../../i18n"5import { KW } from "../../jmap/types"6import { closeRowMenu, rowMenuGroups, RowMenuUi, targetCount, type RowMenuItem, type Targets } from "../../next/rowmenu"7import { S } from "../../state/app"8import { useStore } from "../../state/store"9import { U, moveRows, rowsPinned, setPinnedRows, setRead, setStarred, unifiedRowIds } from "../../state/unified"10import { doArchive, doDelete, doMarkRead, doToggleFlag, doTogglePin } from "../actions"11import { Icon } from "../kit"12import "./labels.css"1314/** « Toutes les boîtes » : mêmes actions, appliquées aux lignes de la vue unifiée (boîte par boîte). */15function unifiedItems(targets: Targets): RowMenuItem[][] {16  const ids = unifiedRowIds(targets.groups)17  if (!ids.length) return []18  const u = U.get()19  const rows = u.list.rows.filter((m) => ids.includes(m.id))20  const unread = rows.some((m) => m.unread)21  const flagged = rows.length > 0 && rows.every((m) => m.starred)22  const pinned = rowsPinned(ids)23  return [24    [25      { id: "read", icon: unread ? "mail" : "unread", label: unread ? t("action.markRead") : t("action.markUnread"), run: () => void setRead(ids, unread) },26      { id: "flag", icon: "star", label: flagged ? t("action.unflag") : t("action.flag"), run: () => void setStarred(ids, !flagged) },27      { id: "pin", icon: "pin", label: pinned ? t("action.unpin") : t("action.pin"), run: () => void setPinnedRows(ids, !pinned) },28    ],29    u.view === "drafts"30      ? []31      : [32          { id: "archive", icon: "archive", label: t("action.archive"), run: () => void moveRows(ids, "archive") },33          { id: "delete", icon: "trash", label: t("action.delete"), danger: true, run: () => void moveRows(ids, "trash") },34        ],35  ].filter((g) => g.length > 0) as RowMenuItem[][]36}37/** Actions d'origine de la liste, pour les lignes de la boîte affichée. */38function baseItems(targets: Targets): RowMenuItem[][] {39  const s = S.get()40  const g = targets.groups[0]41  if (targets.unified) return unifiedItems(targets)42  if (!g || g.mailboxId !== s.mb) return []43  const tg = { ids: g.emailIds, exact: targets.exact }44  const emails = g.emailIds.map((id) => s.emails[id] ?? s.open?.emails[id]).filter((e) => !!e)45  const unread = emails.some((e) => !e.keywords[KW.seen])46  const flagged = emails.length > 0 && emails.every((e) => e.keywords[KW.flagged])47  const pinned = emails.length > 0 && emails.every((e) => e.keywords[KW.pinned])48  return [49    [50      { id: "read", icon: unread ? "mail" : "unread", label: unread ? t("action.markRead") : t("action.markUnread"), run: () => void doMarkRead(unread, tg) },51      { id: "flag", icon: "star", label: flagged ? t("action.unflag") : t("action.flag"), run: () => void doToggleFlag(tg) },52      { id: "pin", icon: "pin", label: pinned ? t("action.unpin") : t("action.pin"), run: () => void doTogglePin(tg) },53    ],54    [55      ...(s.view !== "archive" ? [{ id: "archive", icon: "archive" as const, label: t("action.archive"), run: () => void doArchive(tg) }] : []),56      { id: "delete", icon: "trash", label: s.view === "trash" || s.view === "drafts" ? t("action.deleteForever") : t("action.delete"), danger: true, run: () => void doDelete(tg) },57    ],58  ]59}6061function Menu({ x, y, targets }: { x: number; y: number; targets: Targets }) {62  const ref = useRef<HTMLDivElement>(null)63  const [pos, setPos] = useState({ left: x, top: y, ready: false })64  const groups = [...baseItems(targets), ...rowMenuGroups(targets)]65  const n = targetCount(targets)66  const close = (refocus = true) => {67    closeRowMenu()68    if (refocus) document.getElementById("message-list")?.focus({ preventScroll: true })69  }70  useLayoutEffect(() => {71    const el = ref.current72    if (!el) return73    const r = el.getBoundingClientRect()74    setPos({ left: Math.max(8, Math.min(x, window.innerWidth - r.width - 8)), top: Math.max(8, Math.min(y, window.innerHeight - r.height - 8)), ready: true })75  }, [x, y])76  // le focus ne peut entrer qu'une fois le menu visible (placé)77  useEffect(() => {78    if (pos.ready) ref.current?.querySelector<HTMLElement>("button:not([disabled])")?.focus({ preventScroll: true })79  }, [pos.ready])80  useEffect(() => {81    const away = (e: Event) => {82      if (!ref.current?.contains(e.target as Node)) close(false)83    }84    const gone = () => close(false)85    document.addEventListener("pointerdown", away, true)86    window.addEventListener("resize", gone)87    window.addEventListener("blur", gone)88    document.addEventListener("scroll", gone, true)89    return () => {90      document.removeEventListener("pointerdown", away, true)91      window.removeEventListener("resize", gone)92      window.removeEventListener("blur", gone)93      document.removeEventListener("scroll", gone, true)94    }95  }, [])96  const onKey = (e: React.KeyboardEvent) => {97    if (e.key === "Escape" || e.key === "Tab") {98      e.preventDefault()99      e.stopPropagation()100      return close()101    }102    if (e.key !== "ArrowDown" && e.key !== "ArrowUp" && e.key !== "Home" && e.key !== "End") return103    e.preventDefault()104    const buttons = Array.from(ref.current?.querySelectorAll<HTMLElement>("button:not([disabled])") ?? [])105    const i = buttons.indexOf(document.activeElement as HTMLElement)106    const next = e.key === "Home" ? 0 : e.key === "End" ? buttons.length - 1 : (i + (e.key === "ArrowDown" ? 1 : -1) + buttons.length) % buttons.length107    buttons[next]?.focus()108  }109  if (!groups.length) return null110  return (111    <div ref={ref} className="menu nx-rowmenu" role="menu" aria-label={n > 1 ? t("nx.rowmenu.labelMany", { n }) : t("nx.rowmenu.label")} data-testid="row-menu" style={{ left: pos.left, top: pos.top, visibility: pos.ready ? "visible" : "hidden" }} onKeyDown={onKey} onContextMenu={(e) => e.preventDefault()}>112      {groups.map((items, gi) => (113        <div key={gi} role="group" className="nx-rowmenu-group">114          {gi > 0 ? <div className="sep" role="separator" /> : null}115          {items.map((it) => (116            <button117              key={it.id}118              type="button"119              role="menuitem"120              disabled={it.disabled}121              className={it.danger ? "danger" : undefined}122              onClick={() => {123                close(false)124                it.run()125              }}126            >127              <Icon name={it.icon} small />128              <span className="truncate">{it.label}</span>129            </button>130          ))}131        </div>132      ))}133    </div>134  )135}136137export default function RowMenu() {138  const open = useStore(RowMenuUi, (s) => s.open)139  if (!open) return null140  return <Menu key={`${open.x}:${open.y}:${open.targets.groups[0]?.emailIds[0] ?? ""}`} x={open.x} y={open.y} targets={open.targets} />141}142
Files main
Menu

Theme