Repository Public
1// SP Mail Next — fiche de l'expéditeur dans le lecteur : bouton à côté de l'expéditeur, petite fenêtre (ajouter / ouvrir la fiche, favori, VIP, rechercher ses messages).2import { useEffect, useId, useLayoutEffect, useRef, useState, type CSSProperties } from "react"3import { t } from "../../i18n"4import { isAbort } from "../../next/api"5import { createContact, findByEmail, saveSuggestion, updateContact, type Contact } from "../../next/contacts"6import { nextHref, operator, searchHref } from "../../next/nav"7import type { ReaderPanelProps } from "../../state/registry"8import { linkProps } from "../../state/session"9import { Icon, Spinner } from "../kit"10import { ContactAvatar, attempt, useOnline } from "./ContactBits"1112type Lookup = { status: "loading" } | { status: "ready"; contact: Contact | null } | { status: "error" }1314function Popover({ name, email, anchor, onClose }: { name: string; email: string; anchor: HTMLElement; onClose: () => void }) {15 const [look, setLook] = useState<Lookup>({ status: "loading" })16 const [round, setRound] = useState(0)17 const [pos, setPos] = useState<CSSProperties>({ visibility: "hidden" })18 const ref = useRef<HTMLDivElement>(null)19 const online = useOnline()20 const titleId = useId()21 useEffect(() => {22 const ctrl = new AbortController()23 setLook({ status: "loading" })24 findByEmail(email, ctrl.signal).then(25 (contact) => !ctrl.signal.aborted && setLook({ status: "ready", contact }),26 (e: unknown) => !ctrl.signal.aborted && !isAbort(e) && setLook({ status: "error" }),27 )28 return () => ctrl.abort()29 }, [email, round])30 // placée sous le bouton, ramenée dans la fenêtre31 useLayoutEffect(() => {32 const place = () => {33 const a = anchor.getBoundingClientRect()34 const w = ref.current?.offsetWidth ?? 30035 const h = ref.current?.offsetHeight ?? 20036 const left = Math.max(8, Math.min(a.left, innerWidth - w - 8))37 const below = a.bottom + 638 const top = below + h > innerHeight - 8 ? Math.max(8, a.top - h - 6) : below39 setPos({ left, top })40 }41 place()42 addEventListener("resize", place)43 return () => removeEventListener("resize", place)44 }, [anchor, look.status])45 useEffect(() => {46 ref.current?.focus()47 const away = (e: MouseEvent) => {48 if (!ref.current?.contains(e.target as Node) && !anchor.contains(e.target as Node)) onClose()49 }50 const key = (e: KeyboardEvent) => {51 if (e.key !== "Escape") return52 e.stopPropagation()53 onClose()54 anchor.focus()55 }56 const scrolled = (e: Event) => {57 if (!ref.current?.contains(e.target as Node)) onClose()58 }59 document.addEventListener("mousedown", away)60 document.addEventListener("keydown", key, true)61 document.addEventListener("scroll", scrolled, true)62 return () => {63 document.removeEventListener("mousedown", away)64 document.removeEventListener("keydown", key, true)65 document.removeEventListener("scroll", scrolled, true)66 }67 }, [anchor, onClose])6869 const contact = look.status === "ready" ? look.contact : null70 const set = (c: Contact) => setLook({ status: "ready", contact: c })71 const off = online ? undefined : t("nx.offline")72 /** Favori / VIP sur un expéditeur encore inconnu : la fiche est créée avec le réglage voulu. */73 const flag = (patch: { favorite?: boolean; vip?: boolean }) =>74 void attempt(async () => set(contact ? await updateContact(contact.id, patch) : await createContact({ name, emails: [{ email }], ...patch })))75 const add = () => void attempt(async () => set(contact ? await saveSuggestion(contact.id) : await createContact({ name, emails: [{ email }] })), t("nx.contacts.added"))76 const shown = contact ?? { name, emails: [{ email, label: null }], phones: [], avatar_color: "" }77 return (78 <div ref={ref} className="nx-pop nx-ct-pop" role="dialog" aria-labelledby={titleId} tabIndex={-1} style={pos}>79 <div className="nx-ct-pop-head">80 <ContactAvatar contact={shown} />81 <span className="nx-item-main">82 <strong id={titleId} className="truncate">83 {contact?.name || name || email}84 </strong>85 <span className="small truncate">{email}</span>86 </span>87 </div>88 {look.status === "loading" ? (89 <div className="nx-ct-pop-body">90 <Spinner label={t("nx.loading")} />91 </div>92 ) : look.status === "error" ? (93 <div className="nx-ct-pop-body" role="alert">94 <p className="nx-note">{online ? t("nx.contacts.loadFailed") : t("nx.offline")}</p>95 <button type="button" className="btn small" onClick={() => setRound((n) => n + 1)}>96 {t("nx.retry")}97 </button>98 </div>99 ) : (100 <div className="nx-ct-pop-menu" role="group" aria-label={t("nx.contacts.sender.actions")}>101 {contact && contact.kind === "saved" ? (102 <a {...linkProps(nextHref("contacts", contact.id))}>103 <Icon name="user" small />104 <span className="truncate">{t("nx.contacts.sender.open")}</span>105 </a>106 ) : (107 <button type="button" disabled={!online} title={off} onClick={add}>108 <Icon name="userPlus" small />109 <span className="truncate">{t("nx.contacts.addToContacts")}</span>110 </button>111 )}112 <button type="button" aria-pressed={contact?.favorite ?? false} disabled={!online} title={off} onClick={() => flag({ favorite: !(contact?.favorite ?? false) })}>113 <Icon name="star" small />114 <span className="truncate">{t("nx.contacts.favorite")}</span>115 {contact?.favorite ? <Icon name="check" small className="nx-ct-pop-check" /> : null}116 </button>117 <button type="button" aria-pressed={contact?.vip ?? false} disabled={!online} title={off} onClick={() => flag({ vip: !(contact?.vip ?? false) })}>118 <Icon name="crown" small />119 <span className="truncate">{t("nx.contacts.vipLong")}</span>120 {contact?.vip ? <Icon name="check" small className="nx-ct-pop-check" /> : null}121 </button>122 <div className="sep" role="separator" />123 <a {...linkProps(searchHref(operator("from", email), { all: true }))}>124 <Icon name="search" small />125 <span className="truncate">{t("nx.contacts.searchFrom")}</span>126 </a>127 </div>128 )}129 </div>130 )131}132133/** Emplacement `sender` du lecteur : un bouton discret à côté de l'expéditeur du message déplié. */134export default function SenderButton({ email }: ReaderPanelProps) {135 const [open, setOpen] = useState(false)136 const btn = useRef<HTMLButtonElement>(null)137 const from = email?.from?.[0]138 const addr = from?.email?.trim().toLowerCase() ?? ""139 if (!addr) return null140 const label = t("nx.contacts.sender.button", { name: from?.name || addr })141 return (142 <>143 <button ref={btn} type="button" className="icon-btn nx-ct-senderbtn" aria-label={label} title={label} aria-haspopup="dialog" aria-expanded={open} onClick={() => setOpen((o) => !o)}>144 <Icon name="user" />145 </button>146 {open && btn.current ? <Popover name={from?.name?.trim() ?? ""} email={addr} anchor={btn.current} onClose={() => setOpen(false)} /> : null}147 </>148 )149}150