Repository Public
1// SP Mail Next — recherche : logique PURE (pastilles ⇄ requête du langage du serveur, erreurs d'analyse, panneau de filtres, fusion des pages, formes d'API).2// Le découpage en jetons reprend exactement celui de server/src/next/query.ts (docs/next/SEARCH.md) : guillemets, négation « - », OR, clé inconnue = texte libre.3import type { EmailSummary } from "../jmap/types"4import type { Params } from "./api"5import type { MessageSummary } from "./types"67// ---------------------------------------------------------------- vocabulaire (copie du serveur, qui fait foi)8export type Op = "text" | "from" | "to" | "cc" | "bcc" | "subject" | "body" | "filename" | "label" | "in" | "has" | "is" | "before" | "after" | "larger" | "smaller"9/** Minuscules, sans accents : « Après » → « apres ». */10export const fold = (s: string) => s.normalize("NFD").replace(/\p{M}+/gu, "").toLowerCase()11const squash = (s: string) => fold(s).replace(/[\s_'’-]+/g, "")1213export const KEYS: Record<string, Op> = {14 from: "from", de: "from", expediteur: "from", sender: "from",15 to: "to", a: "to", pour: "to", destinataire: "to",16 cc: "cc", bcc: "bcc", cci: "bcc",17 subject: "subject", sujet: "subject", objet: "subject",18 body: "body", corps: "body", texte: "body", contenu: "body",19 has: "has", avec: "has", contient: "has",20 is: "is", est: "is",21 label: "label", etiquette: "label", libelle: "label", tag: "label",22 in: "in", dans: "in", dossier: "in", folder: "in",23 before: "before", avant: "before", older: "before", older_than: "before",24 after: "after", apres: "after", since: "after", depuis: "after", newer: "after", newer_than: "after",25 larger: "larger", bigger: "larger", plusgrand: "larger", plusde: "larger",26 smaller: "smaller", pluspetit: "smaller", moinsde: "smaller",27 filename: "filename", file: "filename", fichier: "filename", nom: "filename",28}29const HAS_ATTACHMENT = new Set(["attachment", "attachments", "piece", "pieces", "piecejointe", "piecesjointes", "pj", "fichier", "fichiers", "file", "files"])30const IS: Record<string, string> = {31 unread: "unread", unseen: "unread", new: "unread", nonlu: "unread", nonlus: "unread", nouveau: "unread",32 read: "read", seen: "read", lu: "read", lus: "read",33 starred: "starred", flagged: "starred", star: "starred", important: "starred", suivi: "starred", etoile: "starred", marque: "starred",34 pinned: "pinned", epingle: "pinned",35 snoozed: "snoozed", reporte: "snoozed", enattente: "snoozed",36 followup: "followup", relance: "followup", arelancer: "followup", asuivre: "followup",37 answered: "answered", replied: "answered", repondu: "answered",38 forwarded: "forwarded", transfere: "forwarded",39 draft: "draft", brouillon: "draft",40}41const IN: Record<string, string> = {42 inbox: "inbox", reception: "inbox", boite: "inbox", boitedereception: "inbox",43 sent: "sent", envoyes: "sent", envoye: "sent", sentitems: "sent",44 drafts: "drafts", draft: "drafts", brouillons: "drafts", brouillon: "drafts",45 trash: "trash", bin: "trash", corbeille: "trash", deleted: "trash", deleteditems: "trash",46 junk: "junk", spam: "junk", indesirables: "junk", indesirable: "junk", pourriel: "junk", junkmail: "junk",47 archive: "archive", archives: "archive",48 all: "all", any: "all", anywhere: "all", tout: "all", tous: "all", partout: "all",49 snoozed: "snoozed", reportes: "snoozed",50}51export const IS_STATES = ["unread", "read", "starred", "pinned", "snoozed", "followup", "answered", "forwarded", "draft"] as const52export const IN_ROLES = ["inbox", "sent", "drafts", "archive", "trash", "junk", "all"] as const53/** État canonique de `is:<valeur>` (null : inconnu du serveur). */54export const isState = (value: string): string | null => IS[squash(value)] ?? null55/** Rôle canonique de `in:<valeur>` (null : c'est un nom de dossier). */56export const inRole = (value: string): string | null => IN[squash(value)] ?? null57export const isAttachmentValue = (value: string): boolean => HAS_ATTACHMENT.has(squash(value))5859// ---------------------------------------------------------------- pastilles ⇄ requête60/** Un terme de la requête (ou le mot OR entre deux termes). `value` est le texte tel que saisi, sans guillemets. */61export interface Chip {62 op: Op | "or"63 value: string64 negated: boolean65 /** texte libre entre guillemets (expression exacte) */66 phrase: boolean67}68const TOKEN = /(-)?(?:([\p{L}_]+):(?:"([^"]*)"|(\S*))|"([^"]*)"?|(\S+))/gu69export const OR_CHIP: Chip = { op: "or", value: "", negated: false, phrase: false }7071/** Texte libre saisi dans l'interface : une expression exacte dès qu'il contient une espace. */72export function textChip(value: string, negated = false): Chip {73 const v = value.replace(/"/g, "").trim()74 return { op: "text", value: v, negated, phrase: /\s/.test(v) }75}76export function termChip(op: Op, value: string, negated = false): Chip {77 return op === "text" ? textChip(value, negated) : { op, value: value.replace(/"/g, "").trim(), negated, phrase: false }78}7980/** Découpe une requête comme le serveur. Ne lève jamais ; ce que le serveur ignore (« - » seul, guillemets vides) disparaît. */81export function queryToChips(q: string): Chip[] {82 const out: Chip[] = []83 for (const m of (typeof q === "string" ? q : "").matchAll(TOKEN)) {84 const negated = !!m[1]85 if (m[2] === undefined && m[5] === undefined && !negated && (m[6] === "OR" || m[6] === "OU")) {86 out.push({ ...OR_CHIP })87 continue88 }89 if (m[2] !== undefined) {90 const op = KEYS[fold(m[2])]91 // clé inconnue (« http://… », « note:x ») : le jeton entier est du texte libre92 if (!op) out.push({ op: "text", value: negated ? m[0].slice(1) : m[0], negated, phrase: false })93 else out.push({ op, value: (m[3] ?? m[4] ?? "").replace(/^"|"$/g, "").trim(), negated, phrase: false })94 } else if (m[5] !== undefined) {95 if (m[5].trim()) out.push({ op: "text", value: m[5].trim(), negated, phrase: true })96 } else if (m[6] !== undefined && m[6] !== "-") out.push({ op: "text", value: m[6], negated, phrase: false })97 }98 return out99}100101/** Écrit un terme : clé canonique (anglaise), valeur entre guillemets si elle contient une espace. */102export function chipToken(c: Chip): string {103 if (c.op === "or") return "OR"104 const neg = c.negated ? "-" : ""105 if (c.op === "text") return c.phrase ? `${neg}"${c.value.replace(/"/g, "")}"` : `${neg}${c.value}`106 return `${neg}${c.op}:${/\s/.test(c.value) ? `"${c.value.replace(/"/g, "")}"` : c.value}`107}108export interface Span {109 start: number110 end: number111}112/** Requête normalisée et position de chaque pastille dans cette requête (pour y rattacher les erreurs du serveur). */113export function layoutChips(chips: readonly Chip[]): { q: string; spans: Span[] } {114 const spans: Span[] = []115 let q = ""116 for (const c of chips) {117 const tok = chipToken(c)118 if (q) q += " "119 spans.push({ start: q.length, end: q.length + tok.length })120 q += tok121 }122 return { q, spans }123}124export const chipsToQuery = (chips: readonly Chip[]): string => layoutChips(chips).q125/** Forme normalisée d'une requête : clés canoniques, une espace entre les termes. `chipsToQuery(queryToChips(q)) === normalizeQuery(q)`. */126export const normalizeQuery = (q: string): string => chipsToQuery(queryToChips(q))127/** Requête complète du champ : pastilles validées + texte en cours de frappe. */128export function fullQuery(chips: readonly Chip[], draft: string): string {129 const base = chipsToQuery(chips)130 const d = draft.trim()131 return base && d ? `${base} ${d}` : base || d132}133/**134 * Ce que le champ montre d'une requête : les mots libres de la FIN restent du texte à modifier (comme dans un champ ordinaire),135 * tout le reste est en pastilles. `fullQuery(chips, draft)` redonne la requête normalisée.136 */137export function splitTrailingText(all: readonly Chip[]): { chips: Chip[]; draft: string } {138 let cut = all.length139 while (cut > 0 && all[cut - 1].op === "text" && !all[cut - 1].phrase && !all[cut - 1].negated) cut--140 return { chips: all.slice(0, cut), draft: all.slice(cut).map(chipToken).join(" ") }141}142export const sameChip = (a: Chip, b: Chip) => a.op === b.op && a.value === b.value && a.negated === b.negated && a.phrase === b.phrase143144/** Les guillemets du texte en cours sont-ils fermés ? (sinon l'espace fait partie de la valeur) */145export const quotesBalanced = (s: string): boolean => (s.match(/"/g)?.length ?? 0) % 2 === 0146/**147 * Une espace vient d'être tapée : si le dernier jeton terminé est un opérateur (`from:alice`, `has:attachment`), tout le texte148 * devient pastilles ; les mots libres restent du texte tant que la recherche n'est pas lancée. Rend null s'il n'y a rien à convertir.149 */150export function commitOnSpace(draft: string): Chip[] | null {151 if (!/\s$/.test(draft) || !quotesBalanced(draft)) return null152 const chips = queryToChips(draft)153 const last = chips[chips.length - 1]154 if (!last || last.op === "text" || last.op === "or" || !last.value) return null155 return chips156}157158// ---------------------------------------------------------------- erreurs d'analyse159/** Erreur rendue par `POST /api/next/search/parse` et `GET /api/next/search` (`parsed.errors`). */160export interface QueryError {161 token: string162 start: number163 end: number164 code: string165 message: string166}167export const ERROR_CODES = ["empty_value", "invalid_value", "invalid_date", "invalid_size", "dangling_or", "filename_in_or", "unknown_label", "unknown_folder", "query_too_long", "too_many_terms"] as const168export type ErrorCode = (typeof ERROR_CODES)[number] | "generic"169export const errorCode = (code: string): ErrorCode => ((ERROR_CODES as readonly string[]).includes(code) ? (code as ErrorCode) : "generic")170/** Ne garde d'une réponse que les erreurs bien formées (un mandataire peut répondre autre chose). */171export function readErrors(raw: unknown): QueryError[] {172 if (!Array.isArray(raw)) return []173 return raw.filter((e): e is QueryError => !!e && typeof e === "object" && typeof (e as QueryError).code === "string" && typeof (e as QueryError).start === "number" && typeof (e as QueryError).end === "number")174 .map((e) => ({ token: typeof e.token === "string" ? e.token : "", start: e.start, end: e.end, code: e.code, message: typeof e.message === "string" ? e.message : "" }))175}176/**177 * Rattache chaque erreur à la pastille dont elle recouvre la position dans la requête normalisée (celle envoyée au serveur) ;178 * `draft` : erreurs du texte en cours de frappe (après la dernière pastille) ; `rest` : erreurs globales (requête trop longue).179 */180export function mapErrors(chips: readonly Chip[], errors: readonly QueryError[]): { byChip: Map<number, QueryError>; draft: QueryError[]; rest: QueryError[] } {181 const { q, spans } = layoutChips(chips)182 const byChip = new Map<number, QueryError>()183 const draft: QueryError[] = []184 const rest: QueryError[] = []185 for (const e of errors) {186 const i = spans.findIndex((s) => e.start < s.end && e.end > s.start)187 if (i >= 0) {188 if (!byChip.has(i)) byChip.set(i, e)189 } else if (e.token && e.start >= q.length) draft.push(e)190 else rest.push(e)191 }192 return { byChip, draft, rest }193}194/** Erreurs à montrer pendant la frappe : un opérateur encore sans valeur à la toute fin (« from: ») n'en est pas une. */195export function visibleErrors(q: string, errors: readonly QueryError[]): QueryError[] {196 const seen = new Set<string>()197 return errors.filter((e) => {198 if (e.code === "empty_value" && e.end >= q.trimEnd().length) return false199 const k = `${e.code}:${e.start}`200 if (seen.has(k)) return false201 seen.add(k)202 return true203 })204}205206// ---------------------------------------------------------------- suggestions : où en est la frappe207export interface DraftContext {208 /** texte avant le jeton en cours (espace finale comprise) */209 head: string210 /** jeton en cours, tel que tapé */211 token: string212 negated: boolean213 /** opérateur reconnu dont on tape la valeur ; null : mot libre (ou début de clé) */214 op: Op | null215 /** ce qui est tapé de la valeur (ou du mot), sans guillemet ouvrant */216 needle: string217}218/** Jeton sous le curseur (toujours le dernier : le champ n'édite qu'en fin de texte). */219export function draftContext(draft: string): DraftContext {220 let cut = 0221 let quoted = false222 for (let i = 0; i < draft.length; i++) {223 if (draft[i] === '"') quoted = !quoted224 else if (!quoted && /\s/.test(draft[i])) cut = i + 1225 }226 const token = draft.slice(cut)227 const negated = token.startsWith("-")228 const body = negated ? token.slice(1) : token229 const m = /^([\p{L}_]+):(.*)$/su.exec(body)230 const op = m ? (KEYS[fold(m[1])] ?? null) : null231 return { head: draft.slice(0, cut), token, negated, op, needle: (op && m ? m[2] : body).replace(/^"/, "").replace(/"$/, "") }232}233/** Remplace le jeton en cours par un terme complet ; rend les pastilles à ajouter (tout le texte en cours est converti). */234export function completeDraft(draft: string, chip: Chip): Chip[] {235 const ctx = draftContext(draft)236 return [...queryToChips(ctx.head), { ...chip, negated: chip.negated || ctx.negated }]237}238/** Remplace le jeton en cours par une clé d'opérateur (« from: »), la valeur restant à taper. */239export function draftWithKey(draft: string, op: Op): string {240 const ctx = draftContext(draft)241 return `${ctx.head}${ctx.negated ? "-" : ""}${op}:`242}243244// ---------------------------------------------------------------- panneau de filtres (il ÉDITE les pastilles)245export interface PanelState {246 from: string247 to: string248 subject: string249 /** AAAA-MM-JJ */250 after: string251 before: string252 hasAttachment: boolean253 /** tailles en Mo (texte du champ numérique) */254 minSize: string255 maxSize: string256 /** nom du libellé */257 label: string258 /** rôle canonique (`inbox`…) ou nom de dossier */259 folder: string260}261export const emptyPanel = (): PanelState => ({ from: "", to: "", subject: "", after: "", before: "", hasAttachment: false, minSize: "", maxSize: "", label: "", folder: "" })262const PANEL_OPS: Record<Exclude<keyof PanelState, "hasAttachment">, Op> = { from: "from", to: "to", subject: "subject", after: "after", before: "before", minSize: "larger", maxSize: "smaller", label: "label", folder: "in" }263const DAY = /^\d{4}-\d{2}-\d{2}$/264265/** « 10k », « 5m », « 1,5mo », « 2g », « 300 » → octets (comme le serveur) ; null si ce n'est pas une taille. */266export function sizeBytes(value: string): number | null {267 const m = /^(\d+(?:[.,]\d+)?)(b|o|k|kb|ko|m|mb|mo|g|gb|go)?$/.exec(fold(value).replace(/\s+/g, ""))268 if (!m) return null269 const mult = !m[2] || m[2] === "b" || m[2] === "o" ? 1 : m[2][0] === "k" ? 1024 : m[2][0] === "m" ? 1024 ** 2 : 1024 ** 3270 const n = Math.round(Number(m[1].replace(",", ".")) * mult)271 return Number.isFinite(n) && n <= 1e13 ? n : null272}273const mbText = (value: string): string => {274 const b = sizeBytes(value)275 return b === null ? "" : String(Math.round((b / 1024 ** 2) * 100) / 100)276}277const mbValue = (text: string): string => {278 const n = Number(text.replace(",", "."))279 return Number.isFinite(n) && n > 0 ? `${Math.round(n * 100) / 100}m` : ""280}281/** Pastilles que le panneau peut modifier : positives et hors de tout groupe OR. */282function editable(chips: readonly Chip[]): boolean[] {283 return chips.map((c, i) => c.op !== "or" && !c.negated && chips[i - 1]?.op !== "or" && chips[i + 1]?.op !== "or")284}285function firstOf(chips: readonly Chip[], op: Op, ok: boolean[], accept: (c: Chip) => boolean = () => true): number {286 return chips.findIndex((c, i) => ok[i] && c.op === op && accept(c))287}288/** État du panneau d'après les pastilles (un terme que le panneau ne sait pas représenter — `after:7d` — laisse son champ vide). */289export function panelFromChips(chips: readonly Chip[]): PanelState {290 const ok = editable(chips)291 const val = (op: Op) => chips[firstOf(chips, op, ok)]?.value ?? ""292 const day = (op: Op) => (DAY.test(val(op)) ? val(op) : "")293 const folder = val("in")294 return {295 from: val("from"), to: val("to"), subject: val("subject"), after: day("after"), before: day("before"),296 hasAttachment: firstOf(chips, "has", ok, (c) => isAttachmentValue(c.value)) >= 0,297 minSize: mbText(val("larger")), maxSize: mbText(val("smaller")), label: val("label"), folder: folder ? (inRole(folder) ?? folder) : "",298 }299}300/** Applique au jeu de pastilles les champs du panneau qui ont changé ; les autres termes (texte libre, OR, négations) ne bougent pas. */301export function applyPanel(chips: readonly Chip[], next: PanelState): Chip[] {302 const prev = panelFromChips(chips)303 let out = [...chips]304 const set = (op: Op, value: string) => {305 const ok = editable(out)306 const at = firstOf(out, op, ok, op === "has" ? (c) => isAttachmentValue(c.value) : undefined)307 const v = value.trim()308 if (!v) {309 if (at >= 0) out = out.filter((_, i) => i !== at)310 } else if (at >= 0) out = out.map((c, i) => (i === at ? termChip(op, v) : c))311 else out.push(termChip(op, v))312 }313 for (const k of Object.keys(PANEL_OPS) as (keyof typeof PANEL_OPS)[]) {314 if (next[k] === prev[k]) continue315 set(PANEL_OPS[k], k === "minSize" || k === "maxSize" ? mbValue(next[k]) : next[k])316 }317 if (next.hasAttachment !== prev.hasAttachment) set("has", next.hasAttachment ? "attachment" : "")318 return out319}320321// ---------------------------------------------------------------- résultats : pages, clés, formes d'API322export type Scope = "all" | string323export const rowKey = (m: { mailbox_id: string; email_id: string }): string => `${m.mailbox_id}:${m.email_id}`324/** Ajoute une page aux résultats, sans doublon (clé boîte + message) ; `replace` : la page remplace la liste (première page, relecture). */325export function mergePage<T extends { mailbox_id: string; email_id: string }>(rows: readonly T[], page: readonly T[], replace = false): T[] {326 const out: T[] = replace ? [] : [...rows]327 const seen = new Set(out.map(rowKey))328 for (const m of page) {329 const k = rowKey(m)330 if (seen.has(k)) continue331 seen.add(k)332 out.push(m)333 }334 return out335}336/** Identité d'une liste de résultats : toute différence impose un nouveau chargement (et périme les pages en vol). */337export const resultsKey = (o: { q: string; scope: Scope; threads: boolean; semantic?: boolean }): string => `${o.scope}|${o.threads ? 1 : 0}|${o.semantic ? 1 : 0}|${o.q}`338/** Paramètres de `GET /api/next/search`. */339export function searchParams(o: { q: string; scope: Scope; threads: boolean; tz: string; cursor?: string | null; limit?: number }): Params {340 return { q: o.q, mailboxes: o.scope, limit: o.limit ?? 50, threads: o.threads, tz: o.tz, cursor: o.cursor ?? undefined }341}342export const keywordMap = (keywords: readonly string[]): Record<string, boolean> => Object.fromEntries(keywords.map((k) => [k, true]))343/** Ne garde d'une page que les résultats bien formés. */344export function readSummaries(raw: unknown): MessageSummary[] {345 if (!Array.isArray(raw)) return []346 return raw.filter((m): m is MessageSummary => !!m && typeof m === "object" && typeof (m as MessageSummary).mailbox_id === "string" && typeof (m as MessageSummary).email_id === "string" && typeof (m as MessageSummary).thread_id === "string")347 .map((m) => ({ ...m, from: Array.isArray(m.from) ? m.from : [], to: Array.isArray(m.to) ? m.to : [], subject: m.subject ?? "", preview: m.preview ?? "", keywords: Array.isArray(m.keywords) ? m.keywords : [], mailbox_ids: Array.isArray(m.mailbox_ids) ? m.mailbox_ids : [], folder_roles: Array.isArray(m.folder_roles) ? m.folder_roles : [] }))348}349/** Résultat → résumé JMAP (copie hors ligne de la première page, relue par la liste d'origine). */350export function toEmailSummary(m: MessageSummary): EmailSummary {351 return {352 id: m.email_id, blobId: "", threadId: m.thread_id, mailboxIds: keywordMap(m.mailbox_ids), keywords: keywordMap(m.keywords), size: m.size, receivedAt: m.received_at,353 from: m.from.map((p) => ({ email: p.email, name: p.name })), to: m.to.map((p) => ({ email: p.email, name: p.name })), subject: m.subject, preview: m.preview, hasAttachment: m.has_attachment,354 }355}356357// ---------------------------------------------------------------- recherches enregistrées358/** `GET /api/next/searches` (server/src/next/organize.ts, `presentSearch`). */359export interface SavedSearch {360 id: string361 name: string362 query: string363 /** null = toutes les boîtes */364 mailbox_ids: string[] | null365 icon: string | null366 color: string | null367 pinned: boolean368 position: number369 notify: boolean370 updated_at: string371}372/** Épinglées d'abord, puis l'ordre du serveur. */373export function sortSaved(list: readonly SavedSearch[]): SavedSearch[] {374 return [...list].sort((a, b) => Number(b.pinned) - Number(a.pinned) || a.position - b.position || a.name.localeCompare(b.name))375}376/** Portée d'une recherche enregistrée : toutes les boîtes, ou la première de ses boîtes encore rattachée (à défaut toutes). */377export function savedScope(s: Pick<SavedSearch, "mailbox_ids">, mailboxIds: readonly string[]): Scope {378 if (!s.mailbox_ids || s.mailbox_ids.length !== 1) return "all"379 return mailboxIds.includes(s.mailbox_ids[0]) ? s.mailbox_ids[0] : "all"380}381