Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : SP Mail8 * File : web/src/ui/next/SearchResults.tsx9 * Module : ui10 * Repository : https://git.spboucher.ai/sp-mail11 * Project Website : https://mail.spboucher.ai12 * Created : 2026-11-2013 * Last Modified : 2026-11-2014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: support@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243// SP Mail Next — résultats de la recherche du serveur (une boîte ou toutes) : même liste virtualisée et même lecteur que le courrier, pages à curseur, sélection et actions groupées.44import { memo, useEffect, useId, useRef } from "react"45import { fmtListDate, fmtNumber, t } from "../../i18n"46import { KW } from "../../jmap/types"47import { displayName } from "../../mail/address"48import { addressHue } from "../../mail/unified"49import { searchHref } from "../../next/nav"50import { keywordMap, rowKey, type Scope } from "../../next/search"51import { SR, askSaveSearch, loadMore, moveResultCursor, moveRows, openResult, openSearch, resultTargets, routeSearch, selectAllRows, setRead, setStarred, setThreads, startResultsSync, toggleSelected } from "../../next/search-state"52import type { MessageSummary } from "../../next/types"53import { S } from "../../state/app"54import { closeThread } from "../../state/mail"55import { requestSnooze, useRowGlyphs, useRowLabels } from "../../state/registry"56import { navigate } from "../../state/session"57import { shallowEqual, useStore } from "../../state/store"58import { RowLead, SkeletonList, SkeletonRow, SwipeLayer, VirtualRows, useRowSwipe, type SwipeActions } from "../MessageList"59import { Icon, IconButton, MenuButton } from "../kit"60import SearchBar, { roleLabel } from "./SearchBar"6162const canHover = () => typeof matchMedia === "function" && matchMedia("(hover: hover)").matches63const has = (m: MessageSummary, keyword: string) => m.keywords.includes(keyword)64/** Dossier d'un résultat hors de la boîte de réception (une recherche traverse les dossiers). */65const folderTag = (m: MessageSummary): string | null => {66 const role = m.folder_roles.find((r) => r !== "inbox")67 return m.folder_roles.includes("inbox") || !role ? null : roleLabel(role)68}6970// ---------------------------------------------------------------- barre d'actions71function Toolbar() {72 const { count, loaded, more, loading, threads, q, by } = useStore(SR, (s) => ({ count: s.selected.size, loaded: s.rows.length, more: !!s.next, loading: s.loading, threads: s.threads, q: s.q, by: s.by }), shallowEqual)73 const anyUnread = useStore(SR, (s) => s.rows.some((m) => s.selected.has(rowKey(m)) && !has(m, KW.seen)))74 const online = useStore(S, (s) => s.online)75 const allSelected = count > 0 && count >= loaded76 const box = useRef<HTMLInputElement>(null)77 useEffect(() => {78 if (box.current) box.current.indeterminate = count > 0 && !allSelected79 }, [count, allSelected])80 const selected = () => [...SR.get().selected]81 return (82 <div className={`list-toolbar${count ? " selecting" : ""}`} role="toolbar" aria-label={t("list.toolbar")}>83 <label className="check list-selectall" title={t("list.selectAll")}>84 <input ref={box} type="checkbox" checked={allSelected} onChange={(e) => selectAllRows(e.target.checked)} disabled={!loaded} />85 <span className="sr-only">{t("list.selectAll")}</span>86 </label>87 {count === 0 ? (88 <>89 <h1 className="list-title truncate">{t("nx.search.title")}</h1>90 <span className="muted small list-count" aria-live="polite" data-testid="search-count">91 {loading || !q.trim() ? "" : more ? t("nx.search.countMore", { n: loaded, count: fmtNumber(loaded) }) : t("nx.search.count", { n: loaded, count: fmtNumber(loaded) })}92 </span>93 <span className="spacer" />94 {by === null ? <IconButton icon="list" label={t("nx.search.threads")} pressed={threads} onClick={() => setThreads(!threads)} /> : null}95 <IconButton icon="save" label={t("nx.search.save")} disabled={!q.trim()} onClick={() => askSaveSearch()} />96 </>97 ) : (98 <>99 <span className="list-selcount truncate" aria-live="polite">100 {t("list.selected", { n: count })}101 </span>102 <span className="spacer" />103 {anyUnread ? <IconButton icon="mail" label={t("action.markRead")} shortcut="Shift+I" disabled={!online} onClick={() => void setRead(selected(), true)} /> : <IconButton icon="unread" label={t("action.markUnread")} shortcut="Shift+U" disabled={!online} onClick={() => void setRead(selected(), false)} />}104 <IconButton icon="star" label={t("action.flag")} shortcut="s" disabled={!online} onClick={() => void setStarred(selected(), true)} />105 <IconButton icon="archive" label={t("action.archive")} shortcut="e" disabled={!online} onClick={() => void moveRows(selected(), "archive")} />106 <IconButton icon="trash" label={t("action.delete")} shortcut="#" disabled={!online} onClick={() => void moveRows(selected(), "trash")} />107 <MenuButton108 label={t("list.moreActions")}109 items={[110 { label: t("action.markRead"), icon: "mail", disabled: !online, onSelect: () => void setRead(selected(), true) },111 { label: t("action.markUnread"), icon: "unread", disabled: !online, onSelect: () => void setRead(selected(), false) },112 { label: t("action.flag"), icon: "star", disabled: !online, onSelect: () => void setStarred(selected(), true) },113 { label: t("action.unflag"), icon: "star", disabled: !online, onSelect: () => void setStarred(selected(), false) },114 ]}115 />116 <IconButton icon="close" label={t("list.clearSelection")} className="list-clear" onClick={() => SR.set({ selected: new Set() })} />117 </>118 )}119 </div>120 )121}122123/** Portée (cette boîte / toutes), origine des résultats « par le sens », repli discret. */124function ScopeStrip({ scope }: { scope: Scope }) {125 const boxes = useStore(S, (s) => s.me?.mailboxes ?? [])126 const current = useStore(S, (s) => (s.route.name === "mail" && !s.route.all ? s.me?.mailboxes[s.route.mbIndex]?.id : s.mb) ?? null)127 const { q, by, note } = useStore(SR, (s) => ({ q: s.q, by: s.by, note: s.note }), shallowEqual)128 const box = boxes.find((b) => b.id === (scope === "all" ? current : scope)) ?? boxes[0]129 if (boxes.length < 2 && by === null && note === null) return null130 return (131 <div className="nx-sr-strip">132 {boxes.length > 1 && box ? (133 <div className="segmented nx-sr-scope" role="group" aria-label={t("nx.search.scope")}>134 <button type="button" aria-pressed={scope !== "all"} title={box.address} onClick={() => scope === "all" && navigate(searchHref(q, { mailboxId: box.id }))}>135 <span className="truncate">{t("nx.search.scope.one", { name: box.address.split("@")[0] })}</span>136 </button>137 <button type="button" aria-pressed={scope === "all"} onClick={() => scope !== "all" && navigate(searchHref(q, { all: true }))}>138 {t("nx.allMailboxes")}139 </button>140 </div>141 ) : null}142 {by !== null ? (143 <span className="nx-ai-by" data-testid="semantic-by">144 <Icon name="sparkle" small />145 <span className="truncate">{t("nx.search.semantic.by", { provider: by })}</span>146 </span>147 ) : null}148 {note !== null ? (149 <span className="nx-note nx-sr-note" role="status" data-testid="semantic-note">150 {t(note === "ai_disabled" ? "nx.search.semantic.disabled" : note === "consent_required" ? "nx.search.semantic.consent" : note === "rate_limited" ? "nx.search.semantic.rate" : note === "offline" ? "nx.search.semantic.offline" : "nx.search.semantic.unavailable")}151 </span>152 ) : null}153 </div>154 )155}156157// ---------------------------------------------------------------- lignes158const Row = memo(function Row({ id, index, top, total, showBox }: { id: string; index: number; top: number; total: number; showBox: boolean }) {159 const m = useStore(SR, (s) => (s.rows[index] && rowKey(s.rows[index]) === id ? s.rows[index] : s.rows.find((x) => rowKey(x) === id)))160 const selected = useStore(SR, (s) => s.selected.has(id))161 const isCursor = useStore(SR, (s) => s.cursor === id)162 const isOpen = useStore(S, (s) => !!m && !!s.open && s.open.threadId === m.thread_id && s.open.mb === m.mailbox_id)163 const address = useStore(S, (s) => (m ? (s.me?.mailboxes.find((b) => b.id === m.mailbox_id)?.address ?? "") : ""))164 const labelsOf = useRowLabels()165 const glyphsOf = useRowGlyphs()166 const unread = m ? !has(m, KW.seen) : false167 const actions: SwipeActions | null =168 m && !canHover()169 ? {170 lead: { icon: unread ? "mail" : "unread", label: unread ? t("action.markRead") : t("action.markUnread"), run: () => void setRead([id], unread) },171 trail: { icon: "archive", label: t("action.archive"), run: () => void moveRows([id], "archive") },172 trailLong: { icon: "snooze", label: t("action.snooze"), run: () => requestSnooze([m.email_id], m.mailbox_id) },173 }174 : null175 const swipe = useRowSwipe(actions)176 if (!m) return <SkeletonRow top={top} />177 const keywords = keywordMap(m.keywords)178 const starred = has(m, KW.flagged)179 const outgoing = m.folder_roles.includes("sent") || m.folder_roles.includes("drafts")180 const person = outgoing ? m.to[0] : m.from[0]181 const who = outgoing ? m.to.map((a) => displayName(a)).join(", ") || t("list.noRecipient") : displayName(m.from[0]) || t("list.unknownSender")182 const subject = m.subject.trim() || t("list.noSubject")183 const labels = labelsOf ? labelsOf({ keywords }) : []184 const glyphs = glyphsOf ? glyphsOf({ id: m.email_id, mailboxId: m.mailbox_id, keywords }) : []185 const folder = folderTag(m)186 const label = [unread ? t("list.unread") : "", who, subject, fmtListDate(m.received_at), showBox && address ? (outgoing ? t("unified.sentFrom", { address }) : t("unified.receivedBy", { address })) : "", folder ?? "", m.has_attachment ? t("list.hasAttachment") : "", starred ? t("list.flagged") : "", ...labels.map((l) => l.name), ...glyphs.map((g) => g.label)].filter(Boolean).join(", ")187 return (188 <div189 id={`row-${id}`}190 role="option"191 aria-selected={selected}192 aria-setsize={total}193 aria-posinset={index + 1}194 data-id={id}195 data-mailbox={m.mailbox_id}196 className={`mrow${unread ? " unread" : ""}${selected ? " selected" : ""}${isCursor ? " cursor" : ""}${isOpen ? " open" : ""}`}197 style={{ transform: `translateY(${top}px)` }}198 onClick={(e) => {199 if (swipe.swallowClick.current) return200 if (e.metaKey || e.ctrlKey) toggleSelected(id)201 else if (e.shiftKey) toggleSelected(id, true)202 else openResult(id)203 }}204 {...swipe.handlers}205 >206 <span className="sr-only">{label}</span>207 {actions ? <SwipeLayer actions={actions} /> : null}208 <span className="mrow-card" aria-hidden="true" ref={swipe.card}>209 <RowLead address={person?.email ?? ""} name={person?.name ?? ""} selected={selected} unread={unread} onToggle={(shift) => toggleSelected(id, shift)} />210 <span className="mrow-main">211 <span className="mrow-top">212 <span className="mrow-from truncate">{who}</span>213 {showBox && address ? (214 <span className="addr-chip" style={{ "--h": addressHue(address) } as React.CSSProperties} title={address} data-address={address}>215 <span className="addr-dot" aria-hidden="true" />216 <span className="truncate">{address.split("@")[0]}</span>217 </span>218 ) : null}219 <span className="mrow-icons">220 {folder ? <span className="nx-sr-folder">{folder}</span> : null}221 {labels.slice(0, 3).map((l) => (222 <span key={l.id} className="label-dot" style={{ background: l.color }} title={l.name} />223 ))}224 {glyphs.map((g) => (225 <span key={g.id} className={`mrow-glyph mrow-glyph-${g.id}`} title={g.label}>226 <Icon name={g.icon} small />227 </span>228 ))}229 {m.has_attachment ? <Icon name="attach" small /> : null}230 {has(m, KW.answered) ? <Icon name="reply" small /> : null}231 </span>232 <span className="mrow-date">{fmtListDate(m.received_at)}</span>233 </span>234 <span className="mrow-bottom">235 <span className="mrow-subject truncate">{subject}</span>236 <span className="mrow-preview">{m.preview}</span>237 </span>238 </span>239 <span240 className={`mrow-star${starred ? " on" : ""}`}241 title={starred ? t("action.unflag") : t("action.flag")}242 onClick={(e) => {243 e.stopPropagation()244 void setStarred([id], !starred)245 }}246 >247 <Icon name="star" />248 </span>249 </span>250 </div>251 )252})253254/** Sélection et favori d'une ligne pour les technologies d'assistance (voir RowControls de MessageList). */255const RowControls = memo(function RowControls({ id }: { id: string }) {256 const m = useStore(SR, (s) => s.rows.find((x) => rowKey(x) === id))257 const selected = useStore(SR, (s) => s.selected.has(id))258 if (!m) return null259 const subject = m.subject.trim() || t("list.noSubject")260 return (261 <li>262 <label>263 <input type="checkbox" tabIndex={-1} checked={selected} onChange={() => toggleSelected(id)} />264 {t("list.selectRow", { subject })}265 </label>266 <button type="button" tabIndex={-1} aria-pressed={has(m, KW.flagged)} onClick={() => void setStarred([id], !has(m, KW.flagged))}>267 {t("list.starRow", { subject })}268 </button>269 </li>270 )271})272273// ---------------------------------------------------------------- liste274function Body({ scope }: { scope: Scope }) {275 const { loading, error, n, more, key, cursor, q } = useStore(SR, (s) => ({ loading: s.loading, error: s.error, n: s.rows.length, more: !!s.next, key: s.key, cursor: s.cursor, q: s.q }), shallowEqual)276 const ids = useStore(SR, (s) => s.rows, (a, b) => a === b || (a.length === b.length && a.every((m, i) => rowKey(m) === rowKey(b[i])))).map(rowKey)277 const online = useStore(S, (s) => s.online)278 const many = useStore(S, (s) => (s.me?.mailboxes.length ?? 0) > 1)279 const labelId = useId()280 if (!q.trim())281 return (282 <div className="empty" id={labelId}>283 <Icon name="search" />284 <h2>{t("list.searchPromptTitle")}</h2>285 <p>{t("nx.search.prompt")}</p>286 </div>287 )288 if (n === 0 && (!online || error === "offline") && scope === "all")289 return (290 <div className="empty" role="alert" data-testid="search-needs-network">291 <Icon name="offline" />292 <h2>{t("nx.search.offlineAll.title")}</h2>293 <p>{t("nx.search.offlineAll.body")}</p>294 <button type="button" className="btn" onClick={() => navigate(searchHref(q))}>295 <Icon name="search" />296 <span>{t("nx.search.offlineAll.action")}</span>297 </button>298 </div>299 )300 if (error && n === 0)301 return (302 <div className="empty" role="alert">303 <Icon name={error === "offline" ? "offline" : "warn"} />304 <h2>{t("list.errorTitle")}</h2>305 <p>{error === "offline" ? t("error.offline") : error === "rate_limited" ? t("nx.error.rateLimited") : error === "unavailable" ? t("nx.error.unavailable") : t("nx.error.generic")}</p>306 <button type="button" className="btn" onClick={() => openSearch(q, scope, true)}>307 <Icon name="refresh" />308 <span>{t("common.retry")}</span>309 </button>310 </div>311 )312 if (loading && n === 0) return <SkeletonList />313 if (n === 0 && !more)314 return (315 <div className="empty" id={labelId}>316 <Icon name="search" />317 <h2>{t("list.emptySearchTitle")}</h2>318 <p>{t("list.emptySearchBody")}</p>319 {scope !== "all" && many ? (320 <button type="button" className="btn" onClick={() => navigate(searchHref(q, { all: true }))}>321 <Icon name="search" />322 <span>{t("nx.search.everywhere")}</span>323 </button>324 ) : null}325 </div>326 )327 return (328 <>329 {error ? (330 <div className="banner warn list-banner" role="status">331 <Icon name="warn" small />332 <span className="spacer">{error === "offline" ? t("error.offline") : t("nx.error.generic")}</span>333 <button type="button" className="btn small" onClick={() => void loadMore()}>334 {t("common.retry")}335 </button>336 </div>337 ) : null}338 <VirtualRows339 ids={ids}340 // une ligne d'attente annonce la page suivante341 total={n + (more ? 1 : 0)}342 cursor={cursor}343 label={t("list.aria", { name: t("nx.search.title") })}344 listKey={key}345 ensureRange={(_first, last) => {346 if (last >= n - 8) void loadMore()347 }}348 renderRow={(id, i, top, count) => <Row key={id} id={id} index={i} top={top} total={count} showBox={scope === "all"} />}349 renderControls={(id) => <RowControls key={id} id={id} />}350 onFocusEmpty={() => {351 if (!SR.get().cursor) moveResultCursor(1)352 }}353 />354 </>355 )356}357358// ---------------------------------------------------------------- clavier359/** Mêmes touches que la liste du courrier, appliquées aux résultats. Rend vrai si la touche est traitée. */360function handleKey(k: string, target: HTMLElement | null): boolean {361 const s = S.get()362 const r = SR.get()363 const hasSelection = r.selected.size > 0364 // un fil est ouvert et rien n'est coché : archiver, supprimer, favori… visent ce fil (actions du lecteur, par boîte)365 const reader = !!s.open && !hasSelection366 switch (k) {367 case "j":368 case "ArrowDown":369 case "k":370 case "ArrowUp": {371 if ((k === "ArrowDown" || k === "ArrowUp") && !target?.closest("#message-list")) return false372 const id = moveResultCursor(k === "j" || k === "ArrowDown" ? 1 : -1)373 if (id && s.open) openResult(id)374 return true375 }376 case "o":377 case "Enter": {378 if (k === "Enter" && target && /^(BUTTON|A|SUMMARY)$/.test(target.tagName)) return false379 const id = r.cursor ?? moveResultCursor(1)380 if (id) openResult(id)381 return !!id382 }383 case " ":384 case "x": {385 if (k === " " && !target?.closest("#message-list")) return false386 const id = r.cursor ?? moveResultCursor(1)387 if (id) toggleSelected(id)388 return !!id389 }390 case "Escape":391 if (s.navOpen) return false392 if (hasSelection) {393 SR.set({ selected: new Set() })394 return true395 }396 if (s.open) {397 closeThread()398 document.getElementById("message-list")?.focus()399 return true400 }401 return false402 case "u":403 if (!s.open) return false404 closeThread()405 document.getElementById("message-list")?.focus()406 return true407 case "e":408 if (reader) return false409 void moveRows(resultTargets(), "archive")410 return true411 case "#":412 case "Delete":413 if (reader) return false414 void moveRows(resultTargets(), "trash")415 return true416 case "s": {417 if (reader) return false418 const ids = resultTargets()419 void setStarred(ids, ids.some((id) => !r.rows.find((m) => rowKey(m) === id)?.keywords.includes(KW.flagged)))420 return true421 }422 case "I":423 case "U":424 if (reader) return false425 void setRead(resultTargets(), k === "I")426 return true427 case "!":428 case "p":429 case "b":430 return !reader // indésirable, épingle, veille : dans le lecteur seulement431 }432 return false433}434/** Écoute en phase de capture : la touche traitée ici n'atteint pas le gestionnaire de la coquille (qui vise la liste d'une boîte). */435function onKey(e: KeyboardEvent) {436 if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return437 const s = S.get()438 if (s.phase !== "ready" || !routeSearch(s)) return439 const target = e.target as HTMLElement | null440 if (target && (target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName))) return441 if (document.querySelector('[aria-modal="true"]')) return442 if (target?.closest(".composer, .menu")) return443 // `preventDefault` suffit : le gestionnaire de la coquille ignore une touche déjà traitée444 if (handleKey(e.key, target)) e.preventDefault()445}446447export default function SearchResults() {448 const q = useStore(S, (s) => routeSearch(s)?.q ?? "")449 const scope = useStore(S, (s) => routeSearch(s)?.scope ?? "all")450 const ready = useStore(S, (s) => s.phase === "ready")451 const online = useStore(S, (s) => s.online)452 useEffect(() => {453 if (ready) openSearch(q, scope)454 }, [q, scope, ready, online])455 useEffect(() => {456 document.addEventListener("keydown", onKey, true)457 const stop = startResultsSync()458 return () => {459 document.removeEventListener("keydown", onKey, true)460 stop()461 }462 }, [])463 return (464 <section className="list-pane" id="list-pane" aria-label={t("list.region")} data-search={scope === "all" ? "all" : "mailbox"}>465 <SearchBar />466 <Toolbar />467 <ScopeStrip scope={scope} />468 <Body scope={scope} />469 </section>470 )471}472