Repository Public
1// Champ de destinataires : pastilles, autocomplétion (contacts du serveur, groupes, historique local en repli), collage de listes, glisser entre champs.2import { useEffect, useLayoutEffect, useRef, useState } from "react"3import { t } from "../../i18n"4import { displayName, formatAddress, isValidEmail, sameEmail, type Addr } from "../../mail/address"5import { parseRecipients } from "../../mail/compose"6import { S } from "../../state/app"7import { useStore } from "../../state/store"8import { Icon } from "../kit"9import { D, filterLocalContacts, groupMembers, suggestContacts, type ContactGroup, type ContactSuggestion } from "./data"10import { CmpIcon } from "./icons"11import "./compose.css"1213export type RecipientFieldName = "to" | "cc" | "bcc"14type Option = { kind: "contact"; addr: ContactSuggestion } | { kind: "group"; group: ContactGroup }15const DRAG_TYPE = "application/x-spmail-recipient"16/** Pastille en cours de glissement (le contenu d'un glisser n'est pas lisible pendant le survol). */17let dragging: { scope: string; field: string } | null = null1819export interface RecipientFieldProps {20 label: string21 value: Addr[]22 onChange: (v: Addr[]) => void23 inputId: string24 autoFocus?: boolean25 /** correspondants de l'historique d'envoi : repli quand le serveur de contacts ne répond pas */26 suggestions?: Addr[]27 /** nom du champ et portée (brouillon) : permettent de glisser une pastille vers un autre champ de la même rédaction */28 field?: RecipientFieldName29 scope?: string30 /** adresses présentes plus d'une fois dans le message (en minuscules) */31 duplicates?: readonly string[]32 /** déplace la pastille vers le champ suivant / précédent (Alt+↓ / Alt+↑) */33 onMove?: (addr: Addr, index: number, dir: 1 | -1) => void34}3536export function RecipientInput({ label, value, onChange, suggestions, autoFocus, inputId, field = "to", scope, duplicates, onMove }: RecipientFieldProps) {37 const [text, setText] = useState("")38 const [active, setActive] = useState(-1)39 const [open, setOpen] = useState(false)40 const [invalid, setInvalid] = useState(false)41 const [remote, setRemote] = useState<{ q: string; data: ContactSuggestion[] } | null>(null)42 const [over, setOver] = useState(false)43 const [announce, setAnnounce] = useState("")44 const input = useRef<HTMLInputElement>(null)45 const chips = useRef<HTMLUListElement>(null)46 const groups = useStore(D, (d) => d.groups)47 const online = useStore(S, (s) => s.online)48 const listId = `${inputId}-list`49 const q = text.trim()5051 // suggestions du serveur : attendues un court instant après la frappe, annulées si la saisie change52 useEffect(() => {53 if (q.length < 1 || !online) return54 const ctrl = new AbortController()55 const timer = setTimeout(() => {56 suggestContacts(q, ctrl.signal)57 .then((data) => {58 if (!ctrl.signal.aborted) setRemote({ q, data })59 })60 .catch(() => {61 /* serveur injoignable : l'historique local reste affiché */62 })63 }, 140)64 return () => {65 clearTimeout(timer)66 ctrl.abort()67 }68 }, [q, online])6970 const taken = (email: string) => value.some((v) => sameEmail(v.email, email))71 const local = filterLocalContacts(q, suggestions ?? [], 8)72 // la réponse du serveur remplace l'historique local dès qu'elle correspond à la saisie courante73 const contacts = (remote && remote.q === q && online ? remote.data : local).filter((a) => !taken(a.email)).slice(0, 7)74 const needle = q.toLowerCase()75 const matchedGroups = needle.length < 1 ? [] : groups.filter((g) => g.name.toLowerCase().includes(needle)).slice(0, 3)76 const options: Option[] = q.length < 1 ? [] : [...contacts.map((addr): Option => ({ kind: "contact", addr })), ...matchedGroups.map((group): Option => ({ kind: "group", group }))]77 const showList = open && options.length > 07879 const add = (list: Addr[]) => {80 const fresh = list.filter((a, i) => !taken(a.email) && list.findIndex((b) => sameEmail(b.email, a.email)) === i)81 if (fresh.length) {82 onChange([...value, ...fresh])83 setAnnounce(t("cmp.rcpt.added", { n: fresh.length, names: fresh.map(displayName).join(", ") }))84 }85 }86 const commit = (raw: string): boolean => {87 if (!raw.trim()) return true88 const { valid, invalid: bad } = parseRecipients(raw)89 add(valid)90 setText(bad.join(", "))91 setInvalid(bad.length > 0)92 return bad.length === 093 }94 const pick = (o: Option) => {95 setText("")96 setInvalid(false)97 setActive(-1)98 setRemote(null)99 input.current?.focus()100 if (o.kind === "contact") return add([{ name: o.addr.name ?? undefined, email: o.addr.email }])101 // un groupe se déploie en ses membres102 void groupMembers(o.group.id)103 .then((members) => {104 if (members.length) add(members)105 else setAnnounce(t("cmp.rcpt.groupEmpty", { name: o.group.name }))106 })107 .catch(() => setAnnounce(t("cmp.rcpt.groupFailed", { name: o.group.name })))108 }109 const remove = (i: number) => {110 setAnnounce(t("cmp.rcpt.removed", { name: displayName(value[i]) }))111 onChange(value.filter((_, j) => j !== i))112 }113 const focusChip = (i: number) => {114 const list = chips.current?.querySelectorAll<HTMLElement>(".cmp-token-main")115 if (!list?.length) return input.current?.focus()116 if (i >= list.length) return input.current?.focus()117 list[Math.max(0, i)]?.focus()118 }119 const refocus = useRef<number | null>(null)120 useLayoutEffect(() => {121 if (refocus.current === null) return122 const i = refocus.current123 refocus.current = null124 focusChip(i)125 }, [value])126127 return (128 <div129 className={`rcpt cmp-rcpt${over ? " cmp-rcpt-over" : ""}`}130 data-field={field}131 onDragOver={(e) => {132 if (!scope || !dragging || dragging.scope !== scope || dragging.field === field || !e.dataTransfer.types.includes(DRAG_TYPE)) return133 e.preventDefault()134 e.dataTransfer.dropEffect = "move"135 setOver(true)136 }}137 onDragLeave={(e) => {138 if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setOver(false)139 }}140 onDrop={(e) => {141 setOver(false)142 const raw = e.dataTransfer.getData(DRAG_TYPE)143 if (!raw) return144 e.preventDefault()145 e.stopPropagation()146 try {147 const a = JSON.parse(raw) as Addr148 if (a && typeof a.email === "string") add([a])149 } catch {150 /* contenu inattendu : ignoré */151 }152 }}153 >154 <label className="rcpt-label" htmlFor={inputId}>155 {label}156 </label>157 <div className="rcpt-box" onClick={(e) => (e.target === e.currentTarget ? input.current?.focus() : undefined)}>158 <ul ref={chips} className="rcpt-chips" aria-label={t("compose.recipientsOf", { field: label })}>159 {value.map((a, i) => {160 const bad = !isValidEmail(a.email)161 const dup = !bad && !!duplicates?.includes(a.email.trim().toLowerCase())162 const state = bad ? t("cmp.rcpt.stateInvalid") : dup ? t("cmp.rcpt.stateDuplicate") : ""163 return (164 <li165 key={`${a.email}-${i}`}166 className={`rcpt-chip cmp-token${bad ? " bad" : ""}${dup ? " dup" : ""}`}167 title={state ? `${formatAddress(a)} — ${state}` : formatAddress(a)}168 draggable={!!scope}169 onDragStart={(e) => {170 if (!scope) return171 dragging = { scope, field }172 e.dataTransfer.setData(DRAG_TYPE, JSON.stringify({ name: a.name ?? undefined, email: a.email }))173 e.dataTransfer.setData("text/plain", formatAddress(a))174 e.dataTransfer.effectAllowed = "move"175 }}176 onDragEnd={(e) => {177 dragging = null178 // déposée dans un autre champ de la même rédaction : elle quitte celui-ci179 if (e.dataTransfer.dropEffect === "move") onChange(value.filter((_, j) => j !== i))180 }}181 >182 <button183 type="button"184 className="cmp-token-main"185 tabIndex={-1}186 aria-label={state ? `${formatAddress(a)}, ${state}` : formatAddress(a)}187 aria-describedby={`${inputId}-keys`}188 onKeyDown={(e) => {189 if (e.key === "Backspace" || e.key === "Delete") {190 e.preventDefault()191 // le focus est replacé une fois la liste redessinée (voisin de gauche, ou de droite pour Suppr)192 refocus.current = e.key === "Backspace" ? i - 1 : i193 remove(i)194 } else if (e.key === "ArrowLeft") {195 e.preventDefault()196 focusChip(i - 1)197 } else if (e.key === "ArrowRight") {198 e.preventDefault()199 focusChip(i + 1)200 } else if (e.key === "Enter" || e.key === "F2") {201 // modifier : l'adresse revient dans la zone de saisie202 e.preventDefault()203 onChange(value.filter((_, j) => j !== i))204 setText(formatAddress(a))205 input.current?.focus()206 } else if (e.altKey && (e.key === "ArrowDown" || e.key === "ArrowUp") && onMove) {207 e.preventDefault()208 onMove(a, i, e.key === "ArrowDown" ? 1 : -1)209 }210 }}211 >212 <span className="truncate">{displayName(a)}</span>213 {state ? <span className="sr-only">{`, ${state}`}</span> : null}214 </button>215 <button type="button" className="cmp-token-remove" tabIndex={-1} aria-label={t("compose.removeRecipient", { name: displayName(a) })} onClick={() => remove(i)}>216 <Icon name="close" small />217 </button>218 </li>219 )220 })}221 </ul>222 <input223 ref={input}224 id={inputId}225 className="rcpt-input"226 type="text"227 inputMode="email"228 value={text}229 autoFocus={autoFocus}230 autoComplete="off"231 autoCapitalize="none"232 spellCheck={false}233 role="combobox"234 aria-expanded={showList}235 aria-controls={listId}236 aria-autocomplete="list"237 aria-activedescendant={showList && active >= 0 ? `${listId}-${active}` : undefined}238 aria-invalid={invalid}239 aria-describedby={invalid ? `${inputId}-error` : undefined}240 onChange={(e) => {241 const v = e.target.value242 setInvalid(false)243 setOpen(true)244 setActive(-1)245 if (/[,;\n]/.test(v)) commit(v)246 else setText(v)247 }}248 onBlur={() => {249 setOpen(false)250 commit(text)251 }}252 onPaste={(e) => {253 const pasted = e.clipboardData.getData("text")254 if (pasted.includes("@") && (/[,;\n\t]/.test(pasted) || /\s/.test(pasted.trim()) || isValidEmail(pasted.trim()))) {255 e.preventDefault()256 commit(`${text} ${pasted}`.trim().replace(/\t/g, "\n"))257 }258 }}259 onKeyDown={(e) => {260 if (e.nativeEvent.isComposing) return261 if (e.key === "ArrowDown" && options.length) {262 e.preventDefault()263 setOpen(true)264 setActive((a) => (a + 1) % options.length)265 } else if (e.key === "ArrowUp" && options.length) {266 e.preventDefault()267 setActive((a) => (a <= 0 ? options.length - 1 : a - 1))268 } else if ((e.key === "Enter" || e.key === "Tab") && showList && active >= 0) {269 e.preventDefault()270 pick(options[active])271 } else if (e.key === "Enter" && !(e.metaKey || e.ctrlKey)) {272 e.preventDefault()273 commit(text)274 } else if (e.key === " " && isValidEmail(text.trim())) {275 e.preventDefault()276 commit(text)277 } else if (e.key === "Backspace" && !text && value.length) {278 remove(value.length - 1)279 } else if (e.key === "ArrowLeft" && value.length && input.current?.selectionStart === 0 && input.current.selectionEnd === 0) {280 e.preventDefault()281 focusChip(value.length - 1)282 } else if (e.key === "Escape" && showList) {283 e.stopPropagation()284 setOpen(false)285 }286 }}287 />288 </div>289 <ul id={listId} role="listbox" aria-label={t("compose.suggestions")} className="rcpt-list cmp-suggest" hidden={!showList}>290 {showList291 ? options.map((o, i) => (292 <li293 key={o.kind === "contact" ? `c:${o.addr.email}` : `g:${o.group.id}`}294 id={`${listId}-${i}`}295 role="option"296 aria-selected={i === active}297 className={`cmp-suggest-item${i === active ? " active" : ""}`}298 onMouseDown={(e) => {299 e.preventDefault()300 pick(o)301 }}302 >303 {o.kind === "contact" ? (304 <>305 <span className="truncate">306 {o.addr.name || o.addr.email}307 {o.addr.favorite ? (308 <>309 <span className="cmp-suggest-star" aria-hidden="true">{" ★"}</span>310 <span className="sr-only">{`, ${t("cmp.rcpt.favorite")}`}</span>311 </>312 ) : null}313 </span>314 {o.addr.name ? <span className="muted small truncate">{o.addr.email}</span> : null}315 </>316 ) : (317 <>318 <span className="truncate cmp-suggest-group">319 <CmpIcon name="group" small />320 {o.group.name}321 </span>322 <span className="muted small truncate">{t("cmp.rcpt.group", { n: o.group.members ?? 0 })}</span>323 </>324 )}325 </li>326 ))327 : null}328 </ul>329 {invalid ? (330 <p id={`${inputId}-error`} className="small rcpt-error" role="alert">331 {t("compose.invalidAddress")}332 </p>333 ) : null}334 <span id={`${inputId}-keys`} hidden>335 {onMove ? t("cmp.rcpt.keysMove") : t("cmp.rcpt.keys")}336 </span>337 <span className="sr-only" role="status">338 {announce}339 </span>340 </div>341 )342}343