Repository Public
1// SP Mail Next — recherche : état (résultats paginés par curseur, sélection, actions par boîte, validation, suggestions, recherches enregistrées, repli hors ligne).2import { t } from "../i18n"3import { assertSet } from "../jmap/client"4import { errorDetail } from "../jmap/errors"5import { KW, type EmailSummary } from "../jmap/types"6import { S, routeHref, toast, type AppState } from "../state/app"7import { cachePut } from "../state/cache"8import { composeFromDraft } from "../state/composer"9import { clientFor, enterMailbox, ensureRoleFolder } from "../state/mail"10import { navigate } from "../state/session"11import { createStore } from "../state/store"12import { hasFeature, isAbort, nx, toNextError, type NextErrorKind } from "./api"13import { createCollection } from "./collection"14import { mergePage, readErrors, readSummaries, resultsKey, rowKey, searchParams, toEmailSummary, type QueryError, type SavedSearch, type Scope } from "./search"15import { semanticProvider } from "./semantic"16import type { MessageSummary } from "./types"1718export const timeZone = (): string => {19 try {20 return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"21 } catch {22 return "UTC"23 }24}2526// ---------------------------------------------------------------- préférences de l'appareil (regroupement par fil, recherche par le sens)27const PREFS_KEY = "spmail.search"28function readPrefs(): { threads: boolean; semantic: boolean } {29 try {30 const r = JSON.parse(localStorage.getItem(PREFS_KEY) ?? "{}") as Record<string, unknown>31 return { threads: r.threads !== false, semantic: r.semantic === true }32 } catch {33 return { threads: true, semantic: false }34 }35}36export const PREFS = createStore(readPrefs())37function setPrefs(patch: Partial<{ threads: boolean; semantic: boolean }>) {38 PREFS.set(patch)39 try {40 localStorage.setItem(PREFS_KEY, JSON.stringify(PREFS.get()))41 } catch {42 /* stockage indisponible : le choix dure le temps de la visite */43 }44}4546// ---------------------------------------------------------------- résultats47export interface ResultsState {48 /** requête + portée + regroupement + mode : change → nouvelle liste */49 key: string50 q: string51 scope: Scope52 threads: boolean53 semantic: boolean54 rows: MessageSummary[]55 /** curseur de la page suivante ; null = fin */56 next: string | null57 loading: boolean58 loadingMore: boolean59 error: NextErrorKind | null60 /** erreurs d'analyse rendues avec les résultats (étiquette ou dossier inconnu compris) */61 errors: QueryError[]62 selected: ReadonlySet<string>63 cursor: string | null64 /** résultats « par le sens » : fournisseur et modèle à afficher ; null = recherche normale */65 by: string | null66 /** la recherche par le sens a échoué (cause classée) : résultats de la recherche normale */67 note: NextErrorKind | null68}69const empty = (): ResultsState => ({ key: "", q: "", scope: "all", threads: true, semantic: false, rows: [], next: null, loading: false, loadingMore: false, error: null, errors: [], selected: new Set(), cursor: null, by: null, note: null })70export const SR = createStore<ResultsState>(empty())71/** Repli sur la liste d'origine (requête JMAP de la boîte) : serveur injoignable pendant une recherche dans une seule boîte. */72export const FALLBACK = createStore({ legacy: false })7374/** Recherche demandée par l'adresse : requête et portée ; null hors de la vue de recherche. */75export function routeSearch(s: AppState = S.get()): { q: string; scope: Scope; all: boolean } | null {76 if (s.route.name !== "mail" || s.route.view !== "search" || !s.me?.mailboxes.length) return null77 if (s.route.all) return { q: s.route.q, scope: "all", all: true }78 return { q: s.route.q, scope: (s.me.mailboxes[s.route.mbIndex] ?? s.me.mailboxes[0]).id, all: false }79}80/** La recherche du serveur tient-elle la vue affichée ? (sinon : liste d'origine, hors ligne ou serveur injoignable) */81export function serverSearchActive(s: AppState = S.get()): boolean {82 if (s.route.name !== "mail" || s.route.view !== "search") return false83 return s.route.all ? true : s.online && !FALLBACK.get().legacy84}8586interface Page {87 data: MessageSummary[]88 next_cursor: string | null89 errors: QueryError[]90}91let gen = 092let ctrl: AbortController | null = null93async function fetchPage(o: { q: string; scope: Scope; threads: boolean }, cursor: string | null, signal: AbortSignal | undefined, limit = 50): Promise<Page> {94 const r = await nx.get<{ data?: unknown; next_cursor?: unknown; parsed?: { errors?: unknown } }>("search", searchParams({ q: o.q, scope: o.scope, threads: o.threads, tz: timeZone(), cursor, limit }), signal)95 return { data: readSummaries(r.data), next_cursor: typeof r.next_cursor === "string" && r.next_cursor ? r.next_cursor : null, errors: readErrors(r.parsed?.errors) }96}9798/** Copie hors ligne de la première page d'une recherche dans une boîte, au format de la liste d'origine (qui la relit sans réseau). */99function cacheFirstPage(o: { q: string; scope: Scope }, rows: MessageSummary[]) {100 if (o.scope === "all" || !rows.length) return101 const emails: Record<string, EmailSummary> = {}102 const threads: Record<string, string[]> = {}103 for (const m of rows) {104 emails[m.email_id] = toEmailSummary(m)105 threads[m.thread_id] = [...(threads[m.thread_id] ?? []), m.email_id]106 }107 void cachePut(`list:${o.scope}|search|${o.q}`, { ids: rows.map((m) => m.email_id), total: rows.length, emails, threads })108}109110/** Lance (ou retrouve) la recherche. Même requête déjà affichée : simple relecture, sans vider la liste. */111export function openSearch(q: string, scope: Scope, force = false) {112 const { threads } = PREFS.get()113 const semantic = PREFS.get().semantic && !!semanticProvider()114 const key = resultsKey({ q, scope, threads, semantic })115 const cur = SR.get()116 if (!force && cur.key === key && (cur.rows.length > 0 || cur.loading)) {117 if (!cur.loading) void refreshResults()118 return119 }120 const my = ++gen121 ctrl?.abort()122 ctrl = new AbortController()123 SR.set({ ...empty(), key, q, scope, threads, semantic, loading: !!q.trim() })124 if (!q.trim()) return125 void load(my, ctrl.signal)126}127128async function load(my: number, signal: AbortSignal) {129 const s = SR.get()130 let note: NextErrorKind | null = null131 const provider = s.semantic ? semanticProvider() : null132 if (provider) {133 try {134 const rows = readSummaries(await provider.search(s.q, s.scope === "all" ? null : [s.scope], signal))135 if (my !== gen) return136 SR.set({ rows: mergePage([], rows, true), next: null, loading: false, error: null, by: provider.label(), note: null })137 return138 } catch (e) {139 if (isAbort(e) || my !== gen) return140 // désactivée, consentement manquant, fournisseur indisponible, débit, hors ligne : la recherche normale prend le relais141 note = toNextError(e).kind142 }143 }144 try {145 const page = await fetchPage(s, null, signal)146 if (my !== gen) return147 SR.set({ rows: mergePage([], page.data, true), next: page.next_cursor, errors: page.errors, loading: false, error: null, by: null, note })148 cacheFirstPage(s, page.data)149 } catch (e) {150 if (isAbort(e) || my !== gen) return151 const kind = toNextError(e).kind152 SR.set({ loading: false, error: kind, note })153 // serveur injoignable : pour une seule boîte, la liste d'origine (et sa copie locale) prend le relais154 if (kind === "offline" && s.scope !== "all") FALLBACK.set({ legacy: true })155 }156}157158/** Page suivante (défilement). Curseur refusé (`400 invalid_cursor`) : la recherche repart du début. */159export async function loadMore() {160 const s = SR.get()161 if (s.loading || s.loadingMore || !s.next) return162 const my = gen163 SR.set({ loadingMore: true, error: null })164 try {165 let cursor: string | null = s.next166 // une page peut ne rien apporter de neuf (frontière de lecture entre boîtes) : on avance, sans boucler sans fin167 for (let guard = 0; guard < 6 && cursor; guard++) {168 const page: Page = await fetchPage(s, cursor, ctrl?.signal)169 if (my !== gen) return170 const before = SR.get().rows.length171 SR.set((x) => ({ rows: mergePage(x.rows, page.data), next: page.next_cursor }))172 cursor = page.next_cursor173 if (SR.get().rows.length > before) break174 }175 SR.set({ loadingMore: false })176 } catch (e) {177 if (isAbort(e) || my !== gen) return178 SR.set({ loadingMore: false })179 const kind = toNextError(e).kind180 if (kind === "invalid") return openSearch(s.q, s.scope, true)181 SR.set({ error: kind })182 }183}184185let refreshing = false186let refreshAgain = false187/** Relit les résultats depuis le début, sur la longueur affichée, sans vider la liste (action, nouveau courrier, retour du lecteur). */188export async function refreshResults(): Promise<void> {189 const s = SR.get()190 if (!s.key || !s.q.trim() || s.loading || s.by !== null || !S.get().online) return191 if (refreshing) {192 refreshAgain = true193 return194 }195 refreshing = true196 const my = gen197 const want = Math.min(200, Math.max(50, s.rows.length))198 try {199 let rows: MessageSummary[] = []200 let cursor: string | null = null201 let errors: QueryError[] = []202 for (let guard = 0; guard < 6; guard++) {203 const page: Page = await fetchPage(s, cursor, ctrl?.signal, Math.min(100, Math.max(50, want - rows.length)))204 if (my !== gen) return205 rows = mergePage(rows, page.data, guard === 0)206 if (guard === 0) errors = page.errors207 cursor = page.next_cursor208 if (!cursor || rows.length >= want) break209 }210 if (my !== gen) return211 SR.set((x) => {212 const keys = new Set(rows.map(rowKey))213 return { rows, next: cursor, errors, error: null, selected: new Set([...x.selected].filter((k) => keys.has(k))), cursor: x.cursor && keys.has(x.cursor) ? x.cursor : null }214 })215 cacheFirstPage(s, rows.slice(0, 50))216 } catch {217 /* relecture silencieuse : l'affichage reste celui d'avant */218 } finally {219 refreshing = false220 if (refreshAgain) {221 refreshAgain = false222 void refreshResults()223 }224 }225}226let refreshTimer: ReturnType<typeof setTimeout> | undefined227function scheduleRefresh(ms: number) {228 clearTimeout(refreshTimer)229 refreshTimer = setTimeout(() => void refreshResults(), ms)230}231232/** Les résultats sont affichés : tout changement d'état d'une boîte de la portée (nouveau message, lecture, déplacement) les relit. */233export function startResultsSync(): () => void {234 const sig = (s: AppState) => {235 const scope = SR.get().scope236 return (s.me?.mailboxes ?? []).filter((m) => scope === "all" || m.id === scope).map((m) => `${m.id}:${s.accounts[m.id]?.emailState ?? ""}`).join("|")237 }238 let prev = sig(S.get())239 let prevOpen = !!S.get().open240 const unsub = S.subscribe(() => {241 const s = S.get()242 const now = sig(s)243 const open = !!s.open244 if (now !== prev) scheduleRefresh(500)245 else if (prevOpen && !open) scheduleRefresh(450) // retour du lecteur : une action a pu y changer le message246 prev = now247 prevOpen = open248 })249 const onVisible = () => document.visibilityState === "visible" && scheduleRefresh(300)250 document.addEventListener("visibilitychange", onVisible)251 return () => {252 unsub()253 clearTimeout(refreshTimer)254 document.removeEventListener("visibilitychange", onVisible)255 }256}257258/** Regroupement par fil (une ligne par conversation et par boîte) : choix de l'appareil, la recherche repart. */259export function setThreads(on: boolean) {260 setPrefs({ threads: on })261 const s = SR.get()262 if (s.key) openSearch(s.q, s.scope, true)263}264/** Recherche « par le sens » (n'a d'effet que si le module d'IA en a inscrit le fournisseur). */265export function setSemantic(on: boolean) {266 setPrefs({ semantic: on })267 const s = SR.get()268 if (s.key && routeSearch()) openSearch(s.q, s.scope, true)269}270271// ---------------------------------------------------------------- sélection et curseur272export const resultByKey = (key: string): MessageSummary | undefined => SR.get().rows.find((m) => rowKey(m) === key)273export function toggleSelected(key: string, range = false) {274 SR.set((s) => {275 const next = new Set(s.selected)276 const keys = s.rows.map(rowKey)277 if (range && s.cursor && s.cursor !== key) {278 const a = keys.indexOf(s.cursor)279 const b = keys.indexOf(key)280 if (a >= 0 && b >= 0) for (let i = Math.min(a, b); i <= Math.max(a, b); i++) next.add(keys[i])281 } else if (next.has(key)) next.delete(key)282 else next.add(key)283 return { selected: next, cursor: key }284 })285}286export const selectAllRows = (on: boolean) => SR.set((s) => ({ selected: on ? new Set(s.rows.map(rowKey)) : new Set() }))287export function moveResultCursor(delta: number): string | null {288 const s = SR.get()289 const keys = s.rows.map(rowKey)290 if (!keys.length) return null291 let i = s.cursor ? keys.indexOf(s.cursor) : -1292 i = Math.max(0, Math.min(keys.length - 1, i < 0 ? (delta > 0 ? 0 : keys.length - 1) : i + delta))293 SR.set({ cursor: keys[i] })294 if (i >= keys.length - 5) void loadMore()295 return keys[i]296}297/** Cibles d'une action : la sélection, sinon la ligne sous le curseur. */298export function resultTargets(): string[] {299 const s = SR.get()300 return s.selected.size ? [...s.selected] : s.cursor ? [s.cursor] : []301}302303// ---------------------------------------------------------------- ouverture304/** Ouvre la conversation d'un résultat dans le volet de lecture ; l'adresse garde la requête : « retour » retrouve les résultats. */305export function openResult(key: string) {306 const m = resultByKey(key)307 const me = S.get().me308 if (!m || !me) return309 SR.set({ cursor: key })310 const s = SR.get()311 const mbIndex = me.mailboxes.findIndex((b) => b.id === m.mailbox_id)312 if (mbIndex < 0) return void toast({ kind: "error", text: t("unified.cannotOpen") })313 if (m.keywords.includes(KW.draft)) {314 // un brouillon se rouvre dans la rédaction, depuis sa boîte315 if (s.scope === "all") enterMailbox(m.mailbox_id, "drafts")316 void composeFromDraft(m.email_id)317 return318 }319 if (!m.keywords.includes(KW.seen)) patchRows([key], (x) => ({ ...x, keywords: [...x.keywords, KW.seen] })) // le lecteur marque le fil comme lu320 // les identifiants de fil sont propres à chaque boîte : deux boîtes peuvent porter le même — le fil ouvert d'une autre boîte est fermé d'abord321 if (S.get().open && S.get().mb !== m.mailbox_id) S.set({ open: null })322 navigate(routeHref({ name: "mail", all: s.scope === "all", mbIndex, view: "search", threadId: m.thread_id, q: s.q }))323}324325// ---------------------------------------------------------------- actions (JMAP, par boîte)326function patchRows(keys: string[], fn: (m: MessageSummary) => MessageSummary) {327 const set = new Set(keys)328 SR.set((s) => ({ rows: s.rows.map((m) => (set.has(rowKey(m)) ? fn(m) : m)) }))329}330function dropRows(keys: string[]) {331 const set = new Set(keys)332 SR.set((s) => {333 const rows = s.rows.filter((m) => !set.has(rowKey(m)))334 let cursor = s.cursor335 if (cursor && set.has(cursor)) {336 const at = s.rows.findIndex((m) => rowKey(m) === cursor)337 cursor = rows[Math.min(at, rows.length - 1)] ? rowKey(rows[Math.min(at, rows.length - 1)]) : null338 }339 return { rows, selected: new Set([...s.selected].filter((k) => !set.has(k))), cursor }340 })341}342interface Snap {343 mailboxIds: Record<string, boolean>344 keywords: Record<string, boolean>345}346type Update = Record<string, unknown>347type Change = { up: Update; inv: Update } | null348/** Mise à jour JMAP par boîte : identifiant du message → modification. */349type Batch = Map<string, Record<string, Update>>350351/** Exécute au plus `n` tâches à la fois ; rend les échecs. */352async function pool<T>(items: T[], n: number, fn: (item: T) => Promise<void>): Promise<unknown[]> {353 const failures: unknown[] = []354 let i = 0355 const worker = async () => {356 while (i < items.length) {357 const item = items[i++]358 try {359 await fn(item)360 } catch (e) {361 failures.push(e)362 }363 }364 }365 await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker))366 return failures367}368/** État actuel des messages visés dans une boîte ; `wholeThread` : avec les messages du même fil rangés dans un même dossier. */369async function snapshots(mb: string, rows: MessageSummary[], wholeThread: boolean): Promise<Map<string, Snap>> {370 const b = clientFor(mb).batch()371 const props = ["id", "threadId", "mailboxIds", "keywords"]372 const out = new Map<string, Snap>()373 if (!wholeThread) {374 const g = b.add("Email/get", { ids: rows.map((m) => m.email_id), properties: props })375 await b.send()376 for (const e of g.result.list) out.set(e.id, { mailboxIds: e.mailboxIds, keywords: e.keywords })377 return out378 }379 const th = b.add("Thread/get", { ids: [...new Set(rows.map((m) => m.thread_id))] })380 const g = b.add("Email/get", { "#ids": th.ref("/list/*/emailIds"), properties: props })381 await b.send()382 const list = g.result.list383 const mine = new Set(rows.map((m) => m.email_id))384 for (const e of list) {385 const lead = list.find((x) => x.threadId === e.threadId && mine.has(x.id))386 if (mine.has(e.id) || (lead && Object.keys(e.mailboxIds).some((f) => lead.mailboxIds[f]))) out.set(e.id, { mailboxIds: e.mailboxIds, keywords: e.keywords })387 }388 return out389}390async function send(batch: Batch): Promise<unknown[]> {391 return pool([...batch], 3, async ([mb, update]) => {392 const ids = Object.keys(update)393 for (let i = 0; i < ids.length; i += 400) {394 const r = await clientFor(mb).call("Email/set", { update: Object.fromEntries(ids.slice(i, i + 400).map((id) => [id, update[id]])) })395 assertSet("Email/set", r)396 }397 })398}399/**400 * Applique une modification aux résultats visés, boîte par boîte (au plus trois à la fois). Rend l'inverse (pour « Annuler »),401 * ou null en cas d'échec — l'écran est alors remis dans l'état d'avant puis relu.402 */403async function apply(keys: string[], change: (snap: Snap, mb: string) => Change | Promise<Change>, opts: { wholeThread: boolean; optimistic: () => void }): Promise<Batch | null> {404 if (!S.get().online) {405 toast({ kind: "error", text: t("nx.offline") })406 return null407 }408 const before = SR.get()409 const set = new Set(keys)410 const groups = new Map<string, MessageSummary[]>()411 for (const m of before.rows) if (set.has(rowKey(m))) groups.set(m.mailbox_id, [...(groups.get(m.mailbox_id) ?? []), m])412 if (!groups.size) return new Map()413 opts.optimistic()414 const inverse: Batch = new Map()415 const failures = await pool([...groups], 3, async ([mb, rows]) => {416 const snaps = await snapshots(mb, rows, opts.wholeThread)417 const up: Record<string, Update> = {}418 const inv: Record<string, Update> = {}419 for (const [id, snap] of snaps) {420 const c = await change(snap, mb)421 if (!c) continue422 up[id] = c.up423 inv[id] = c.inv424 }425 if (!Object.keys(up).length) return426 const failed = await send(new Map([[mb, up]]))427 if (failed.length) throw failed[0]428 inverse.set(mb, inv)429 })430 scheduleRefresh(700)431 if (!failures.length) return inverse432 // retour à l'état d'avant (si la liste est toujours la même), puis la vérité du serveur433 if (SR.get().key === before.key) SR.set({ rows: before.rows, selected: before.selected, cursor: before.cursor })434 toast({ kind: "error", text: t("error.actionFailed"), detail: errorDetail(failures[0]) || undefined })435 return null436}437const keywordChange = (keyword: string, on: boolean) => (snap: Snap): Change => (!!snap.keywords[keyword] === on ? null : { up: { [`keywords/${keyword}`]: on ? true : null }, inv: { [`keywords/${keyword}`]: snap.keywords[keyword] ? true : null } })438const withKeyword = (m: MessageSummary, keyword: string, on: boolean): MessageSummary => ({ ...m, keywords: on ? [...new Set([...m.keywords, keyword])] : m.keywords.filter((k) => k !== keyword) })439440export async function setRead(keys: string[], read: boolean) {441 if (!keys.length) return442 await apply(keys, keywordChange(KW.seen, read), { wholeThread: SR.get().threads, optimistic: () => patchRows(keys, (m) => withKeyword(m, KW.seen, read)) })443}444export async function setStarred(keys: string[], on: boolean) {445 if (!keys.length) return446 await apply(keys, keywordChange(KW.flagged, on), { wholeThread: false, optimistic: () => patchRows(keys, (m) => withKeyword(m, KW.flagged, on)) })447}448/** Archive ou met à la corbeille ; « Annuler » remet chaque message dans ses dossiers d'origine. */449export async function moveRows(keys: string[], role: "archive" | "trash") {450 if (!keys.length) return451 const n = keys.length452 const targets = new Map<string, Promise<string>>()453 const target = (mb: string) => targets.get(mb) ?? targets.set(mb, ensureRoleFolder(mb, role)).get(mb)!454 const inverse = await apply(keys, async (snap, mb) => {455 const id = await target(mb)456 return snap.mailboxIds[id] && Object.keys(snap.mailboxIds).length === 1 ? null : { up: { mailboxIds: { [id]: true } }, inv: { mailboxIds: snap.mailboxIds } }457 }, {458 wholeThread: SR.get().threads,459 // la corbeille sort des résultats (portée par défaut) ; un message archivé y reste, rangé ailleurs — la relecture tranche460 optimistic: () => (role === "trash" ? dropRows(keys) : (patchRows(keys, (m) => ({ ...m, folder_roles: ["archive"] })), SR.set({ selected: new Set() }))),461 })462 if (!inverse) return463 toast({464 kind: "success", text: role === "archive" ? t("toast.archived", { n }) : t("toast.trashed", { n }), actionLabel: t("action.undo"),465 action: () => {466 void send(inverse).then((failed) => {467 if (failed.length) toast({ kind: "error", text: t("error.actionFailed"), detail: errorDetail(failed[0]) || undefined })468 else toast({ kind: "info", text: t("toast.undone") })469 void refreshResults()470 })471 },472 })473}474475// ---------------------------------------------------------------- validation en cours de frappe, suggestions476/** `POST /api/next/search/parse` : ne refuse jamais une entrée, les défauts sont dans `errors`. */477export async function parseRemote(q: string, signal: AbortSignal): Promise<QueryError[]> {478 const r = await nx.post<{ errors?: unknown }>("search/parse", { q, tz: timeZone() }, signal)479 return readErrors(r.errors)480}481export interface ContactHit {482 name: string483 email: string484}485/** Contacts proposés pour `from:` / `to:` (seulement si le serveur a le carnet de contacts). */486export async function suggestContacts(q: string, signal: AbortSignal): Promise<ContactHit[]> {487 if (!hasFeature("contacts")) return []488 const list = await nx.list<ContactHit>("contacts/suggest", { q, limit: 6 }, signal)489 return list.filter((c) => c && typeof c.email === "string" && c.email).map((c) => ({ name: typeof c.name === "string" ? c.name : "", email: c.email }))490}491export interface LabelHit {492 id: string493 name: string494 color: string495 keyword: string496}497/** Libellés proposés pour `label:` et le panneau de filtres (copie propre au module de recherche). */498export const LABELS = createCollection<LabelHit>("search-labels", async () => (hasFeature("labels") ? nx.list<LabelHit>("labels") : []))499500// ---------------------------------------------------------------- recherches enregistrées (dossiers intelligents)501export const SAVED = createCollection<SavedSearch>("searches", () => nx.list<SavedSearch>("searches"))502export interface SavedInput {503 name: string504 query: string505 /** null = toutes les boîtes */506 mailbox_ids: string[] | null507 pinned: boolean508}509/** Les trois écritures lèvent une NextError classée (`invalid` + message du serveur pour une requête refusée) : le dialogue l'affiche. */510export async function createSaved(input: SavedInput): Promise<SavedSearch> {511 const row = await nx.post<SavedSearch>("searches", input)512 SAVED.mutate((items) => [...items.filter((x) => x.id !== row.id), row])513 return row514}515export async function updateSaved(id: string, patch: Partial<SavedInput>): Promise<SavedSearch> {516 const row = await nx.patch<SavedSearch>(`searches/${encodeURIComponent(id)}`, patch)517 SAVED.mutate((items) => items.map((x) => (x.id === id ? row : x)))518 return row519}520export async function deleteSaved(id: string): Promise<void> {521 const before = SAVED.store.get().items522 SAVED.mutate((items) => items.filter((x) => x.id !== id))523 try {524 await nx.del(`searches/${encodeURIComponent(id)}`)525 } catch (e) {526 if (toNextError(e).kind !== "not_found") {527 SAVED.mutate(() => before)528 throw e529 }530 }531}532533/** Dialogue « enregistrer / modifier une recherche » : son état vit ici, le dialogue est monté à la racine (registerOverlay). */534export interface SaveDialogState {535 open: null | { id: string | null; name: string; query: string; scope: Scope; pinned: boolean; focus: "name" | "query" }536}537export const DIALOG = createStore<SaveDialogState>({ open: null })538/** Ouvre le dialogue sur la recherche affichée (ou vide, pour créer un dossier intelligent de toutes pièces). */539export function askSaveSearch(q?: string, scope?: Scope) {540 const cur = routeSearch()541 const s = S.get()542 const fallbackScope: Scope = s.route.name === "mail" && !s.route.all && s.mb ? s.mb : "all"543 DIALOG.set({ open: { id: null, name: "", query: q ?? cur?.q ?? "", scope: scope ?? cur?.scope ?? fallbackScope, pinned: false, focus: "name" } })544}545export function askEditSearch(saved: SavedSearch, focus: "name" | "query" = "name") {546 const ids = (S.get().me?.mailboxes ?? []).map((m) => m.id)547 const scope: Scope = saved.mailbox_ids && saved.mailbox_ids.length === 1 && ids.includes(saved.mailbox_ids[0]) ? saved.mailbox_ids[0] : "all"548 DIALOG.set({ open: { id: saved.id, name: saved.name, query: saved.query, scope, pinned: saved.pinned, focus } })549}550export const closeSaveDialog = () => DIALOG.set({ open: null })551552/** Déconnexion : rien ne survit en mémoire. */553export function resetSearchState() {554 gen++555 ctrl?.abort()556 ctrl = null557 clearTimeout(refreshTimer)558 SR.set(empty())559 FALLBACK.set({ legacy: false })560 DIALOG.set({ open: null })561}562