Repository Public
1// SP Mail Next — champ de recherche à pastilles : langage du serveur, suggestions (opérateurs, contacts, libellés, dossiers, recherches récentes), validation en cours de frappe, filtres, « par le sens ».2import { Fragment, Suspense, lazy, useEffect, useId, useMemo, useRef, useState } from "react"3import { t, type MsgKey } from "../../i18n"4import { useFeature } from "../../next/api"5import { labelColor } from "../../next/labels"6import { searchHref } from "../../next/nav"7import {8 IN_ROLES, IS_STATES, KEYS, chipToken, chipsToQuery, commitOnSpace, completeDraft, draftContext, draftWithKey, errorCode, fold, fullQuery, inRole, isAttachmentValue, isState, mapErrors, queryToChips, splitTrailingText, termChip, visibleErrors,9 type Chip, type Op, type QueryError,10} from "../../next/search"11import { FALLBACK, LABELS, PREFS, SR, parseRemote, setSemantic, suggestContacts, type ContactHit } from "../../next/search-state"12import { useSemanticProvider } from "../../next/semantic"13import { S, routeHref } from "../../state/app"14import { folderLabel, sortedFolders } from "../../state/mail"15import { navigate, rememberSearch } from "../../state/session"16import { shallowEqual, useStore } from "../../state/store"17import { SyncIndicator } from "../SyncIndicator"18import { PaletteButton } from "../PaletteButton"19import { Icon, IconButton, PHONE, useMedia, type IconName } from "../kit"20import "./search.css"2122const FilterPanel = lazy(() => import("./FilterPanel"))2324// ---------------------------------------------------------------- libellés des pastilles25const OP_LABEL: Record<Op, MsgKey> = {26 text: "nx.search.op.text", from: "nx.search.op.from", to: "nx.search.op.to", cc: "nx.search.op.cc", bcc: "nx.search.op.bcc", subject: "nx.search.op.subject", body: "nx.search.op.body", filename: "nx.search.op.filename",27 label: "nx.search.op.label", in: "nx.search.op.in", has: "nx.search.op.has", is: "nx.search.op.is", before: "nx.search.op.before", after: "nx.search.op.after", larger: "nx.search.op.larger", smaller: "nx.search.op.smaller",28}29const OP_ICON: Record<Op, IconName> = { text: "search", from: "user", to: "user", cc: "user", bcc: "user", subject: "text", body: "text", filename: "file", label: "tag", in: "folder", has: "attach", is: "mail", before: "calendar", after: "calendar", larger: "file", smaller: "file" }30const STATE_LABEL: Record<string, MsgKey> = {31 unread: "nx.search.is.unread", read: "nx.search.is.read", starred: "nx.search.is.starred", pinned: "nx.search.is.pinned", snoozed: "nx.search.is.snoozed", followup: "nx.search.is.followup", answered: "nx.search.is.answered", forwarded: "nx.search.is.forwarded", draft: "nx.search.is.draft",32}33const ROLE_LABEL: Record<string, MsgKey> = { inbox: "folder.inbox", sent: "folder.sent", drafts: "folder.drafts", archive: "folder.archive", trash: "folder.trash", junk: "folder.junk", all: "nx.search.in.all", snoozed: "nx.search.is.snoozed" }34const ERROR_LABEL: Record<ReturnType<typeof errorCode>, MsgKey> = {35 empty_value: "nx.search.err.empty_value", invalid_value: "nx.search.err.invalid_value", invalid_date: "nx.search.err.invalid_date", invalid_size: "nx.search.err.invalid_size", dangling_or: "nx.search.err.dangling_or", filename_in_or: "nx.search.err.filename_in_or",36 unknown_label: "nx.search.err.unknown_label", unknown_folder: "nx.search.err.unknown_folder", query_too_long: "nx.search.err.query_too_long", too_many_terms: "nx.search.err.too_many_terms", generic: "nx.search.err.generic",37}38export const roleLabel = (role: string): string => (ROLE_LABEL[role] ? t(ROLE_LABEL[role]) : role)39/** Texte d'une pastille, dans la langue de l'interface : « De : alice », « Avec pièce jointe », « Sauf Non lu ». */40export function chipLabel(c: Chip): string {41 let label: string42 if (c.op === "or") return t("nx.search.or")43 if (c.op === "text") label = c.phrase ? `« ${c.value} »` : c.value44 else if (c.op === "has" && isAttachmentValue(c.value)) label = t("search.hasAttachment")45 else if (c.op === "is" && isState(c.value)) label = t(STATE_LABEL[isState(c.value)!])46 else if (c.op === "in") label = t("nx.search.chip", { key: t(OP_LABEL.in), value: inRole(c.value) ? roleLabel(inRole(c.value)!) : c.value })47 else label = t("nx.search.chip", { key: t(OP_LABEL[c.op]), value: c.value || "…" })48 return c.negated ? t("nx.search.chip.not", { label }) : label49}5051// ---------------------------------------------------------------- suggestions52interface Suggestion {53 id: string54 icon: IconName55 title: string56 hint?: string57 /** pastille de couleur (libellés) */58 color?: string59 group: "recent" | "operators" | "values" | "contacts"60 /** terme complet à ajouter ; sinon `key` (clé d'opérateur dont la valeur reste à taper) ou `query` (recherche récente à relancer) */61 chip?: Chip62 key?: Op63 query?: string64}65const STARTERS: { op: Op; value?: string }[] = [{ op: "from" }, { op: "to" }, { op: "subject" }, { op: "has", value: "attachment" }, { op: "is", value: "unread" }, { op: "is", value: "starred" }, { op: "label" }, { op: "in" }, { op: "after" }, { op: "before" }, { op: "filename" }, { op: "larger" }]66const DATES: [string, MsgKey][] = [["today", "nx.search.date.today"], ["yesterday", "nx.search.date.yesterday"], ["7d", "nx.search.date.7d"], ["1m", "nx.search.date.1m"], ["1y", "nx.search.date.1y"]]67const SIZES = ["1m", "5m", "10m", "25m"]68const starts = (hay: string, needle: string) => fold(hay).startsWith(needle)69const holds = (hay: string, needle: string) => fold(hay).includes(needle)7071function useSuggestions(draft: string, focused: boolean): Suggestion[] {72 const recent = useStore(S, (s) => s.device.recentSearches)73 const labels = LABELS.use()74 const folders = useStore(S, (s) => (s.mb && !(s.route.name === "mail" && s.route.all) ? (s.accounts[s.mb]?.folders ?? []) : []), shallowEqual)75 const account = useStore(S, (s) => (s.mb ? s.accounts[s.mb] : undefined))76 const hasContacts = useFeature("contacts")77 const ctx = useMemo(() => draftContext(draft), [draft])78 const [contacts, setContacts] = useState<{ needle: string; list: ContactHit[] }>({ needle: "", list: [] })79 const person = ctx.op === "from" || ctx.op === "to" || ctx.op === "cc" || ctx.op === "bcc"80 const contactNeedle = hasContacts && focused && (person || (!ctx.op && ctx.needle.length >= 2 && !ctx.needle.includes(":"))) ? ctx.needle : null81 useEffect(() => {82 if (contactNeedle === null) return83 const c = new AbortController()84 const timer = setTimeout(() => {85 suggestContacts(contactNeedle, c.signal).then(86 (list) => !c.signal.aborted && setContacts({ needle: contactNeedle, list }),87 () => {},88 )89 }, 140)90 return () => {91 clearTimeout(timer)92 c.abort()93 }94 }, [contactNeedle])9596 return useMemo(() => {97 const out: Suggestion[] = []98 const needle = fold(ctx.needle)99 const opSuggestion = (op: Op, value?: string): Suggestion =>100 value ? { id: `v.${op}.${value}`, icon: OP_ICON[op], title: chipLabel(termChip(op, value)), hint: `${op}:${value}`, group: "operators", chip: termChip(op, value) } : { id: `k.${op}`, icon: OP_ICON[op], title: t(OP_LABEL[op]), hint: `${op}:`, group: "operators", key: op }101 const contactItems = (op: Op): Suggestion[] =>102 contactNeedle !== null && contacts.needle === contactNeedle ? contacts.list.map((c) => ({ id: `c.${op}.${c.email}`, icon: "user" as const, title: c.name || c.email, hint: c.name ? c.email : undefined, group: "contacts" as const, chip: termChip(op, c.email) })) : []103 if (!draft.trim()) {104 for (const q of recent.slice(0, 5)) out.push({ id: `r.${q}`, icon: "clock", title: q, group: "recent", query: q })105 for (const s of STARTERS) if (s.op !== "label" || labels.length) out.push(opSuggestion(s.op, s.value))106 return out107 }108 switch (ctx.op) {109 case "from": case "to": case "cc": case "bcc":110 out.push(...contactItems(ctx.op))111 break112 case "label":113 for (const l of labels) if (holds(l.name, needle)) out.push({ id: `l.${l.id}`, icon: "tag", color: l.color, title: l.name, group: "values", chip: termChip("label", l.name) })114 break115 case "in": {116 for (const r of IN_ROLES) if (starts(roleLabel(r), needle) || starts(r, needle)) out.push({ id: `in.${r}`, icon: "folder", title: roleLabel(r), hint: `in:${r}`, group: "values", chip: termChip("in", r) })117 for (const f of sortedFolders(account).custom) if (folders.includes(f) && holds(f.name, needle)) out.push({ id: `in.f.${f.id}`, icon: "folder", title: folderLabel(f), group: "values", chip: termChip("in", f.name) })118 break119 }120 case "is":121 for (const st of IS_STATES) if (starts(t(STATE_LABEL[st]), needle) || starts(st, needle)) out.push({ id: `is.${st}`, icon: "mail", title: t(STATE_LABEL[st]), hint: `is:${st}`, group: "values", chip: termChip("is", st) })122 break123 case "has":124 out.push({ id: "has.attachment", icon: "attach", title: t("search.hasAttachment"), hint: "has:attachment", group: "values", chip: termChip("has", "attachment") })125 break126 case "before": case "after":127 for (const [v, label] of DATES) if (!needle || starts(v, needle) || starts(t(label), needle)) out.push({ id: `d.${ctx.op}.${v}`, icon: "calendar", title: t(label), hint: `${ctx.op}:${v}`, group: "values", chip: termChip(ctx.op, v) })128 break129 case "larger": case "smaller":130 for (const v of SIZES) if (!needle || starts(v, needle)) out.push({ id: `s.${ctx.op}.${v}`, icon: "file", title: t("nx.search.size.mb", { n: v.slice(0, -1) }), hint: `${ctx.op}:${v}`, group: "values", chip: termChip(ctx.op, v) })131 break132 case null: {133 if (!needle || ctx.needle.includes(":")) break134 // début d'une clé (anglaise, française ou son libellé) : l'opérateur est proposé135 const ops = new Set<Op>()136 for (const [k, op] of Object.entries(KEYS)) if (k.startsWith(needle)) ops.add(op)137 for (const op of Object.keys(OP_LABEL) as Op[]) if (op !== "text" && starts(t(OP_LABEL[op]), needle)) ops.add(op)138 for (const op of ops) {139 if (op === "has") out.push(opSuggestion("has", "attachment"))140 else if (op !== "label" || labels.length) out.push(opSuggestion(op))141 }142 out.push(...contactItems("from"))143 for (const q of recent) if (holds(q, needle) && out.length < 10) out.push({ id: `r.${q}`, icon: "clock", title: q, group: "recent", query: q })144 break145 }146 }147 return out.slice(0, 12)148 }, [draft, ctx, recent, labels, folders, account, contacts, contactNeedle])149}150151// ---------------------------------------------------------------- validation en cours de frappe152/** Erreurs d'analyse de la requête affichée (demande différée et annulable ; elles ne bloquent jamais ni la frappe ni l'envoi). */153export function useLiveErrors(q: string): QueryError[] {154 const online = useStore(S, (s) => s.online)155 const [remote, setRemote] = useState<{ q: string; errors: QueryError[] }>({ q: "", errors: [] })156 const fromResults = useStore(SR, (s) => (s.q === q ? s.errors : null))157 useEffect(() => {158 if (!q.trim() || !online) return159 const c = new AbortController()160 const timer = setTimeout(() => {161 parseRemote(q, c.signal).then(162 (errors) => !c.signal.aborted && setRemote({ q, errors }),163 () => {},164 )165 }, 260)166 return () => {167 clearTimeout(timer)168 c.abort()169 }170 }, [q, online])171 return useMemo(() => visibleErrors(q, [...(remote.q === q ? remote.errors : []), ...(fromResults ?? [])]), [q, remote, fromResults])172}173export function errorText(e: QueryError): string {174 const text = t(ERROR_LABEL[errorCode(e.code)])175 return e.token ? t("nx.search.err.line", { token: e.token, text }) : text176}177178// ---------------------------------------------------------------- le champ179export default function SearchBar() {180 const query = useStore(S, (s) => (s.route.name === "mail" && s.route.view === "search" ? s.route.q : ""))181 const searching = useStore(S, (s) => s.route.name === "mail" && s.route.view === "search")182 const inAll = useStore(S, (s) => s.route.name === "mail" && !!s.route.all)183 const mbIndex = useStore(S, (s) => (s.route.name === "mail" && !s.route.all ? s.route.mbIndex : Math.max(0, s.me?.mailboxes.findIndex((m) => m.id === s.mb) ?? 0)))184 const online = useStore(S, (s) => s.online)185 const legacy = useStore(FALLBACK, (f) => f.legacy)186 const semanticOn = useStore(PREFS, (p) => p.semantic)187 const provider = useSemanticProvider()188 const phone = useMedia(PHONE)189 // les mots libres de la fin restent du texte dans le champ ; les critères sont en pastilles190 const [chips, setChips] = useState<Chip[]>(() => splitTrailingText(queryToChips(query)).chips)191 const [draft, setDraft] = useState(() => splitTrailingText(queryToChips(query)).draft)192 const [focused, setFocused] = useState(false)193 const [open, setOpen] = useState(false)194 const [active, setActive] = useState(-1)195 const [panel, setPanel] = useState(false)196 const input = useRef<HTMLInputElement>(null)197 const wrap = useRef<HTMLDivElement>(null)198 const ids = { list: useId(), err: useId(), note: useId() }199 useEffect(() => {200 const shown = splitTrailingText(queryToChips(query))201 setChips(shown.chips)202 setDraft(shown.draft)203 }, [query])204 useEffect(() => void LABELS.refresh(), [])205206 const full = fullQuery(chips, draft)207 const errors = useLiveErrors(full)208 const mapped = useMemo(() => mapErrors(chips, errors), [chips, errors])209 const suggestions = useSuggestions(draft, focused)210 const showList = open && focused && suggestions.length > 0 && !panel211 const optionId = (i: number) => `${ids.list}-o${i}`212 const current = showList && active >= 0 ? suggestions[Math.min(active, suggestions.length - 1)] : undefined213214 /** Lance la recherche des pastilles données (tout le texte en cours devient pastilles) ; rien à chercher : retour à la boîte. */215 const run = (nextChips: Chip[], nextDraft = "") => {216 const all = [...nextChips, ...queryToChips(nextDraft)]217 const q = chipsToQuery(all)218 const shown = splitTrailingText(all)219 setOpen(false)220 setActive(-1)221 setChips(shown.chips)222 setDraft(shown.draft)223 if (!q) {224 if (searching) navigate(routeHref({ name: "mail", all: inAll, mbIndex: inAll ? 0 : mbIndex, view: "inbox", threadId: null, q: "" }))225 return226 }227 rememberSearch(q)228 navigate(searchHref(q, { all: inAll }))229 }230 const removeChip = (i: number) => {231 const next = chips.filter((_, j) => j !== i)232 // sur la page de résultats, retirer un critère relance aussitôt (comme les filtres d'origine)233 if (searching) run(next, draft)234 else setChips(next)235 input.current?.focus()236 }237 const apply = (s: Suggestion) => {238 if (s.query !== undefined) return run(queryToChips(s.query))239 if (s.key) {240 setDraft(draftWithKey(draft, s.key))241 setActive(-1)242 setOpen(true)243 } else if (s.chip) {244 setChips([...chips, ...completeDraft(draft, s.chip)])245 setDraft("")246 setActive(-1)247 }248 input.current?.focus()249 }250 const hasContent = chips.length > 0 || draft.trim().length > 0251 const lines = [...mapped.byChip.values(), ...mapped.draft, ...mapped.rest].slice(0, 3)252 const fallbackNote = searching && !inAll && (!online || legacy)253254 return (255 <div256 className={`search nx-sb${searching || !inAll ? "" : " nx-sb-embedded"}`}257 ref={wrap}258 onBlur={(e) => {259 if (!wrap.current?.contains(e.relatedTarget as Node | null)) {260 setFocused(false)261 setOpen(false)262 }263 }}264 >265 <form266 role="search"267 className="search-form"268 onSubmit={(e) => {269 e.preventDefault()270 setPanel(false)271 run(chips, draft)272 }}273 >274 {searching || !inAll ? <IconButton icon="menu" label={t("nav.open")} className="only-narrow" onClick={() => S.set({ navOpen: true })} /> : null}275 <div276 className="search-box nx-sb-box"277 onMouseDown={(e) => {278 // un clic dans le cadre (hors pastille et bouton) place le curseur dans le champ279 if (e.target === e.currentTarget || (e.target as HTMLElement).closest(".nx-sb-chips") === e.target) {280 e.preventDefault()281 input.current?.focus()282 }283 }}284 >285 <Icon name="search" />286 <div className="nx-sb-flow">287 {chips.length ? (288 <ul className="chips nx-sb-chips" aria-label={t("nx.search.chips")}>289 {chips.map((c, i) => {290 const err = mapped.byChip.get(i)291 const label = chipLabel(c)292 return (293 <li key={`${i}-${chipToken(c)}`} className={`${c.op === "text" || c.op === "or" ? "nx-sb-word" : "chip"} nx-sb-chip${c.negated ? " neg" : ""}${err ? " err" : ""}${c.op === "or" ? " or" : ""}`} data-token={chipToken(c)} title={err ? errorText(err) : chipToken(c)}>294 {err ? <Icon name="warn" small /> : null}295 <span className="truncate">{label}</span>296 {err ? <span className="sr-only">{t("nx.search.chip.invalid")}</span> : null}297 <button type="button" aria-label={t("search.removeFilter", { label })} onClick={() => removeChip(i)}>298 <Icon name="close" small />299 </button>300 </li>301 )302 })}303 </ul>304 ) : null}305 <input306 ref={input}307 id="search-input"308 type="search"309 className={`nx-sb-input${chips.length && !draft ? " idle" : ""}`}310 aria-label={t("search.label")}311 aria-autocomplete="list"312 aria-haspopup="listbox"313 aria-controls={showList ? ids.list : undefined}314 aria-activedescendant={current ? optionId(suggestions.indexOf(current)) : undefined}315 aria-describedby={lines.length ? ids.err : undefined}316 aria-invalid={mapped.draft.length > 0 || undefined}317 value={draft}318 placeholder={chips.length ? "" : inAll ? t("nx.search.placeholderAll") : t("search.placeholder")}319 autoComplete="off"320 autoCapitalize="off"321 spellCheck={false}322 enterKeyHint="search"323 onFocus={() => {324 setFocused(true)325 // champ déjà rempli (retour sur des résultats) : les suggestions attendent la frappe, un clic ou ↓326 setOpen(!chips.length && !draft)327 }}328 onClick={() => {329 // le focus a pu revenir sans événement (fermeture d'un dialogue) : le clic rouvre toujours les suggestions330 setFocused(true)331 setOpen(true)332 }}333 onChange={(e) => {334 setFocused(true)335 const v = e.target.value336 const done = commitOnSpace(v)337 if (done) {338 setChips([...chips, ...done])339 setDraft("")340 } else setDraft(v)341 setOpen(true)342 setActive(-1)343 }}344 onKeyDown={(e) => {345 if (e.key === "ArrowDown" || e.key === "ArrowUp") {346 if (!suggestions.length) return347 e.preventDefault()348 if (!showList) return setOpen(true)349 const n = suggestions.length350 setActive(e.key === "ArrowDown" ? (active + 1) % n : active <= 0 ? n - 1 : active - 1)351 } else if (e.key === "Enter") {352 if (current) {353 e.preventDefault()354 apply(current)355 }356 } else if (e.key === "Escape") {357 e.preventDefault() // un champ de type « search » se viderait de lui-même358 if (showList) {359 // premier Échap : ferme les suggestions ; le second quitte le champ360 e.stopPropagation()361 setOpen(false)362 setActive(-1)363 } else {364 if (draft && !query) setDraft("")365 e.currentTarget.blur()366 }367 } else if (e.key === "Backspace" && !draft && chips.length) {368 e.preventDefault()369 setChips(chips.slice(0, -1))370 }371 }}372 />373 </div>374 {provider ? (375 <button type="button" className={`nx-sb-sem${semanticOn ? " on" : ""}`} aria-pressed={semanticOn} title={t("nx.search.semantic.hint")} onClick={() => setSemantic(!semanticOn)} data-testid="semantic-toggle">376 <Icon name="sparkle" small />377 <span>{t("nx.search.semantic")}</span>378 </button>379 ) : null}380 {hasContent || query ? (381 <button type="button" className="nx-sb-clear" aria-label={t("search.clear")} onClick={() => (searching ? run([]) : (setChips([]), setDraft(""), input.current?.focus()))}>382 <Icon name="close" small />383 </button>384 ) : null}385 </div>386 <PaletteButton />387 <IconButton icon="filter" label={t("search.filters")} pressed={panel} onClick={() => setPanel((p) => !p)} />388 {searching || !inAll ? <SyncIndicator compact /> : null}389 </form>390 {lines.length ? (391 <div id={ids.err} role="status" data-testid="search-errors">392 <ul className="nx-sb-errors">393 {lines.map((e) => (394 <li key={`${e.code}:${e.start}`}>395 <Icon name="warn" small />396 <span>{errorText(e)}</span>397 </li>398 ))}399 </ul>400 </div>401 ) : null}402 {fallbackNote ? (403 <p className="nx-sb-note" id={ids.note} role="status" data-testid="search-fallback">404 <Icon name="offline" small />405 <span>{t("nx.search.fallback")}</span>406 </p>407 ) : null}408 {showList ? (409 <div className="nx-sb-pop" id={ids.list} role="listbox" aria-label={t("nx.search.suggestions")}>410 {suggestions.map((s, i) => (411 <Fragment key={s.id}>412 {i === 0 || suggestions[i - 1].group !== s.group ? (413 <div className="nx-sb-group" role="presentation">414 {t(s.group === "recent" ? "nx.search.group.recent" : s.group === "contacts" ? "nx.search.group.contacts" : s.group === "values" ? "nx.search.group.values" : "nx.search.group.operators")}415 </div>416 ) : null}417 <div418 id={optionId(i)}419 role="option"420 aria-selected={current === s}421 className={`nx-sb-opt${current === s ? " active" : ""}`}422 data-suggestion={s.id}423 // le champ garde le focus : la suggestion s'applique sans le quitter424 onMouseDown={(e) => e.preventDefault()}425 onMouseMove={() => active !== i && setActive(i)}426 onClick={() => apply(s)}427 >428 {s.color ? <span className="label-dot" style={{ background: labelColor(s.color) }} aria-hidden="true" /> : <Icon name={s.icon} small />}429 <span className="truncate nx-sb-opt-title">{s.title}</span>430 {s.hint ? <span className="nx-sb-opt-hint truncate">{s.hint}</span> : null}431 </div>432 </Fragment>433 ))}434 </div>435 ) : null}436 {panel ? (437 <Suspense fallback={null}>438 <FilterPanel439 chips={chips}440 sheet={phone}441 all={inAll}442 onChange={setChips}443 onClose={() => setPanel(false)}444 onRun={(next) => {445 setPanel(false)446 run(next, draft)447 }}448 />449 </Suspense>450 ) : null}451 </div>452 )453}454