Repository Public
1// Courrier : comptes JMAP, dossiers, liste fenêtrée, fil ouvert, actions optimistes avec annulation, synchronisation delta.2import { t } from "../i18n"3import { JmapClient, assertSet } from "../jmap/client"4import { JmapMethodError, NetworkError, errorDetail, errorKind } from "../jmap/errors"5import { api } from "../jmap/http"6import { PushConnection } from "../jmap/push"7import { BODY_PROPS, CAP, FULL_PROPS, KW, SUMMARY_PROPS, type EmailFilter, type EmailFull, type EmailSort, type EmailSummary, type Id, type Mailbox, type StateChange } from "../jmap/types"8import { dedupeAddrs, type Addr } from "../mail/address"9import { applyQueryChange, densePrefix, hasId, indexOfId, isDensePrefix, listAffected, loadedPages, mergePage, pagesAround, shownThreadSize, visibleInThread as visibleIn, type RoleFolders, type ViewScope } from "../mail/listmodel"10import { isEmptySearch, parseSearch, searchToConditions } from "../mail/search"11import { S, currentAccount, emptyList, folderByRole, folderOfView, routeHref, setAccount, toast, viewOfFolder, type Account, type OpenThread, type Route, type SyncInfo } from "./app"12import { cacheDeleteMailbox, cacheGet, cachePut, cachePutThread } from "./cache"13import { bindOffline, queueOrSend } from "./offline"14import { hasSnoozeHandler } from "./registry"1516export const PAGE = 5017const clients = new Map<string, JmapClient>()18const pushes = new Map<string, PushConnection>()1920export function clientFor(mb: string): JmapClient {21 const c = clients.get(mb)22 if (!c) throw new NetworkError("mailbox not connected")23 return c24}25export const hasClient = (mb: string) => clients.has(mb)26/** @internal Tests unitaires : branche un client (factice) sur une boîte sans passer par le réseau. */27export function attachClient(mb: string, client: JmapClient) {28 clients.set(mb, client)29}3031// ---------------------------------------------------------------- état de synchronisation (indicateur discret)32function patchSync(patch: Partial<SyncInfo> | ((s: SyncInfo) => Partial<SyncInfo>)) {33 S.set((s) => ({ sync: { ...s.sync, ...(typeof patch === "function" ? patch(s.sync) : patch) } }))34}35/** Encadre une modification envoyée au serveur : comptée « en attente » jusqu'à sa réponse. */36async function tracked<T>(op: () => Promise<T>): Promise<T> {37 patchSync((y) => ({ pendingOps: y.pendingOps + 1 }))38 try {39 return await op()40 } finally {41 patchSync((y) => ({ pendingOps: Math.max(0, y.pendingOps - 1) }))42 }43}44/** Bouton « Réessayer » de l'indicateur : relance les comptes en erreur, les connexions de notification et la liste. */45export function retrySync() {46 patchSync({ error: null })47 const s = S.get()48 for (const [mb, a] of Object.entries(s.accounts)) {49 if (a.status === "error") void initAccount(mb)50 else if (a.status === "ready") void syncAll(mb)51 }52 for (const p of pushes.values()) p.kick()53}5455function reportError(e: unknown, fallback: string) {56 const kind = errorKind(e)57 if (kind === "unauthorized") return // l'écran de connexion prend le relais58 toast({ kind: "error", text: kind === "unknown" ? fallback : t(`error.${kind}`), detail: errorDetail(e) || undefined })59}6061// ================================================================ comptes62export function startAccounts() {63 const me = S.get().me64 if (!me) return65 for (const m of me.mailboxes) void initAccount(m.id)66 document.addEventListener("visibilitychange", onVisible)67 window.addEventListener("online", onVisible)68}69export function stopAccounts() {70 for (const p of pushes.values()) p.stop()71 pushes.clear()72 clients.clear()73 for (const timer of syncTimers.values()) clearTimeout(timer)74 syncTimers.clear()75 pending.clear()76 listGen++77 pageStates.clear()78 document.removeEventListener("visibilitychange", onVisible)79 window.removeEventListener("online", onVisible)80}81function onVisible() {82 if (document.visibilityState !== "visible") return83 const st = S.get()84 if (navigator.onLine && !st.all && st.mb && st.list.stale && st.accounts[st.mb]?.status === "ready") openListFresh()85 for (const p of pushes.values()) p.kick()86 for (const [mb] of Object.entries(S.get().accounts)) if (S.get().accounts[mb].status === "error") void initAccount(mb)87}8889/** La boîte fait-elle encore partie du compte ? (elle peut être retirée pendant qu'une requête est en vol) */90const stillMine = (mb: string) => !!S.get().me?.mailboxes.some((m) => m.id === mb)9192/**93 * Une boîte a été retirée du compte côté serveur : ferme sa connexion de notification, oublie son client, son état et son94 * cache. Si elle était affichée, l'appelant (session) ramène ensuite à une boîte qui existe.95 */96export function teardownAccount(mb: string) {97 pushes.get(mb)?.stop()98 pushes.delete(mb)99 clients.delete(mb)100 clearTimeout(syncTimers.get(mb))101 syncTimers.delete(mb)102 pending.delete(mb)103 S.set((s) => {104 const accounts = { ...s.accounts }105 delete accounts[mb]106 const contacts = { ...s.contacts }107 delete contacts[mb]108 const out: Partial<ReturnType<typeof S.get>> = { accounts, contacts, deliveries: s.deliveries.filter((d) => d.mb !== mb) }109 if (s.mb === mb) {110 listGen++111 pagesInFlight.clear()112 pagesLoaded.clear()113 pageStates.clear()114 Object.assign(out, { mb: null, list: emptyList(), emails: {}, threads: {}, threadShown: {}, selected: new Set(), cursor: null, open: null })115 }116 return out117 })118 void cacheDeleteMailbox(mb)119}120121export async function initAccount(mb: string) {122 if (!stillMine(mb)) return123 setAccount(mb, { status: "loading", error: undefined })124 try {125 const c = new JmapClient(mb)126 await c.connect()127 if (!stillMine(mb)) return128 clients.set(mb, c)129 const b = c.batch()130 const boxes = b.add("Mailbox/get", { ids: null })131 const idents = b.add("Identity/get", { ids: null })132 const quota = b.add("Quota/get", { ids: null }, CAP.quota)133 const state = b.add("Email/get", { ids: [], properties: ["id"] })134 await b.send()135 if (!stillMine(mb) || clients.get(mb) !== c) return136 setAccount(mb, {137 status: "ready", stale: false, folders: boxes.result.list, mailboxState: boxes.result.state, identities: idents.error ? [] : idents.result.list,138 quota: quota.error ? [] : quota.result.list, emailState: state.result.state,139 })140 S.set({ offlineShell: false })141 void cachePut(`folders:${mb}`, boxes.result.list)142 void cachePut(`identities:${mb}`, idents.error ? [] : idents.result.list)143 startPush(mb)144 const s = S.get()145 if (s.route.name === "mail" && s.route.all) applyMailRoute(s.route)146 else if (s.route.name === "mail" && s.mb === mb) openList(mb, s.view, s.query, true)147 else if (s.route.name === "mail" && !s.mb) applyMailRoute(s.route)148 // un fil ouvert avant la connexion (copie locale, ou échec) est relu maintenant que le compte répond149 const open = S.get().open150 if (open && S.get().mb === mb && (open.stale || open.status === "error")) void openThread(open.threadId)151 } catch (e) {152 const kind = errorKind(e)153 if (kind === "unauthorized" || !stillMine(mb)) return154 const folders = (await cacheGet<Mailbox[]>(`folders:${mb}`)) ?? []155 if (!stillMine(mb)) return156 setAccount(mb, { status: "error", error: kind, folders, stale: folders.length > 0 })157 const s = S.get()158 if (s.route.name === "mail" && (s.mb === mb || !s.mb)) applyMailRoute(s.route)159 // démarrage sans réseau (coque servie par le service worker) : la liste affichée n'a jamais été chargée — elle était en160 // attente du compte — et vient donc de la copie locale161 const now = S.get()162 if (now.route.name === "mail" && !now.all && now.mb === mb && now.list.total === null && !now.list.error) openList(mb, now.view, now.query, true)163 }164}165166function startPush(mb: string) {167 pushes.get(mb)?.stop()168 const p = new PushConnection({169 url: clientFor(mb).eventSourceUrl(),170 onChange: (c) => onStateChange(mb, c),171 onStatus: (status) => setAccount(mb, { push: status }),172 onReconnect: () => void syncAll(mb),173 onTrouble: () => void api("/api/me").catch(() => {}), // un 401 ici ramène à l'écran de connexion174 })175 pushes.set(mb, p)176 p.start()177}178179// ================================================================ dossiers180/** Dossiers sans rôle que le serveur crée et gère lui-même, à la racine (`Snoozed` : messages en veille — server/src/next/snooze.ts). */181export const MANAGED_FOLDERS: readonly string[] = ["Snoozed"]182export const isManagedFolder = (f: Pick<Mailbox, "name" | "role" | "parentId">): boolean => !f.role && !f.parentId && MANAGED_FOLDERS.includes(f.name)183/**184 * Dossiers d'une boîte, dans l'ordre d'affichage. Un dossier géré par le serveur n'est pas un dossier de la personne : quand son185 * écran existe (« En veille »), il ne figure ni dans l'arbre ni dans les menus de déplacement — `managed: true` le garde186 * (export complet du courrier).187 */188export function sortedFolders(a: Account | undefined, opts: { managed?: boolean } = {}): { system: Mailbox[]; custom: Mailbox[] } {189 const order = ["inbox", "drafts", "sent", "archive", "junk", "trash"]190 const hide = !opts.managed && hasSnoozeHandler()191 const folders = (a?.folders ?? []).filter((f) => !hide || !isManagedFolder(f))192 const system = order.map((r) => folders.find((f) => f.role === r)).filter((f): f is Mailbox => !!f)193 const custom = folders.filter((f) => !system.includes(f)).sort((x, y) => folderPath(a, x).localeCompare(folderPath(a, y), undefined, { sensitivity: "base" }))194 return { system, custom }195}196/** Chemin « Parent/Enfant » d'un dossier (c'est ce nom qu'emploient les règles Sieve). */197export function folderPath(a: Account | undefined, f: Mailbox): string {198 const parts = [f.name]199 let cur = f200 for (let i = 0; i < 12 && cur.parentId; i++) {201 const p = a?.folders.find((x) => x.id === cur.parentId)202 if (!p) break203 parts.unshift(p.name)204 cur = p205 }206 return parts.join("/")207}208export function folderDepth(a: Account | undefined, f: Mailbox): number {209 return folderPath(a, f).split("/").length - 1210}211const ROLE_LABEL: Record<string, "folder.inbox" | "folder.drafts" | "folder.sent" | "folder.archive" | "folder.junk" | "folder.trash"> = { inbox: "folder.inbox", drafts: "folder.drafts", sent: "folder.sent", archive: "folder.archive", junk: "folder.junk", trash: "folder.trash" }212export function folderLabel(f: Mailbox): string {213 return f.role && ROLE_LABEL[f.role] ? t(ROLE_LABEL[f.role]) : f.name214}215export function viewLabel(a: Account | undefined, view: string): string {216 if (view === "unread") return t("view.unread")217 if (view === "flagged") return t("view.flagged")218 if (view === "pinned") return t("view.pinned")219 if (view === "search") return t("view.search")220 const f = folderOfView(a, view)221 if (f) return folderLabel(f)222 return ROLE_LABEL[view] ? t(ROLE_LABEL[view]) : view223}224225export async function createFolder(mb: string, name: string, parentId: Id | null = null, role: string | null = null): Promise<Id> {226 const r = await clientFor(mb).call("Mailbox/set", { create: { n: { name: name.trim(), parentId, role, isSubscribed: true } } })227 assertSet("Mailbox/set", r, "n")228 await syncMailboxes(mb, true)229 return r.created!.n.id230}231export async function renameFolder(mb: string, id: Id, name: string) {232 const r = await clientFor(mb).call("Mailbox/set", { update: { [id]: { name: name.trim() } } })233 assertSet("Mailbox/set", r, id)234 await syncMailboxes(mb, true)235}236export async function deleteFolder(mb: string, id: Id) {237 const r = await clientFor(mb).call("Mailbox/set", { destroy: [id], onDestroyRemoveEmails: true })238 assertSet("Mailbox/set", r, id)239 await syncMailboxes(mb, true)240 const s = S.get()241 if (s.mb === mb && s.view === `f:${id}` && s.route.name === "mail") gotoView("inbox")242}243async function ensureFolder(mb: string, role: "archive" | "trash" | "junk" | "inbox" | "drafts" | "sent"): Promise<Id> {244 const existing = folderByRole(S.get().accounts[mb], role)245 if (existing) return existing.id246 const names = { archive: "Archive", trash: "Deleted Items", junk: "Junk Mail", inbox: "Inbox", drafts: "Drafts", sent: "Sent Items" }247 return createFolder(mb, names[role], null, role)248}249export const ensureRoleFolder = ensureFolder250251// ================================================================ route → liste252function gotoView(view: string) {253 const s = S.get()254 if (s.route.name !== "mail") return255 const href = routeHref({ ...s.route, view, threadId: null, q: "" })256 history.replaceState(null, "", href)257 applyMailRoute({ ...s.route, view, threadId: null, q: "" })258 S.set({ route: { ...s.route, view, threadId: null, q: "" } })259}260261/** Vue par boîte dans laquelle s'ouvre un message d'une vue « Toutes les boîtes » (dossiers et actions du lecteur). */262const MAILBOX_VIEW: Record<string, string> = { inbox: "inbox", unread: "inbox", starred: "flagged", drafts: "drafts", sent: "sent", scheduled: "sent" }263264/**265 * « Toutes les boîtes » : la liste affichée vient de state/unified.ts ; pour le lecteur et ses actions, la boîte du message266 * ouvert devient la boîte courante (avec une liste par boîte vide, non affichée) — tout fonctionne alors comme en vue par boîte.267 */268export function enterMailbox(mb: string, unifiedView: string) {269 const view = MAILBOX_VIEW[unifiedView] ?? "inbox"270 const key = listKey(mb, view, "")271 const s = S.get()272 if (s.mb === mb && s.view === view && s.list.key === key) return273 listGen++274 pagesInFlight.clear()275 pagesLoaded.clear()276 pageStates.clear()277 S.set({ mb, view, query: "", list: { ...emptyList(key), loadingFirst: false }, emails: {}, threads: {}, threadShown: {}, selected: new Set(), cursor: null })278}279280/** Aligne l'état sur l'URL : boîte, vue, recherche, fil ouvert. */281export function applyMailRoute(route: Extract<Route, { name: "mail" }>) {282 const s = S.get()283 const me = s.me284 if (!me) return285 if (!me.mailboxes.length) {286 // plus aucune boîte rattachée : rien à lister287 if (s.mb || s.open) S.set({ mb: null, all: false, list: { ...emptyList(), loadingFirst: false }, emails: {}, threads: {}, threadShown: {}, selected: new Set(), cursor: null, open: null })288 return289 }290 if (route.all) {291 if (!s.all) S.set({ all: true })292 const box = route.threadId ? me.mailboxes[route.mbIndex] : undefined293 if (box) {294 enterMailbox(box.id, route.view)295 const open = S.get().open296 if (!isOpenThread(box.id, route.threadId!, open) || open?.status === "error") void openThread(route.threadId!)297 } else {298 if (!S.get().mb) S.set({ mb: me.mailboxes[0].id })299 if (S.get().open) S.set({ open: null })300 }301 return302 }303 const mb = (me.mailboxes[route.mbIndex] ?? me.mailboxes[0]).id304 const key = listKey(mb, route.view, route.q)305 if (s.list.key !== key || s.mb !== mb || s.all) {306 S.set({ mb, view: route.view, query: route.q, all: false })307 if (S.get().accounts[mb]?.status !== "loading") openList(mb, route.view, route.q)308 else {309 listGen++310 pagesInFlight.clear()311 pagesLoaded.clear()312 pageStates.clear()313 S.set({ list: emptyList(key), emails: {}, threads: {}, threadShown: {}, selected: new Set(), cursor: null, open: null })314 }315 } else if (s.list.total === null && !s.list.stale && !s.list.error && !pagesInFlight.size && S.get().accounts[mb]?.status === "ready") {316 // même liste, jamais chargée : le compte s'est connecté pendant qu'une autre page (réglages…) était affichée317 openList(mb, route.view, route.q, true)318 }319 const open = S.get().open320 // même identifiant de fil dans une autre boîte = un autre fil : la clé est (boîte, fil)321 if (route.threadId && !isOpenThread(mb, route.threadId, open)) void openThread(route.threadId)322 else if (!route.threadId && open) S.set({ open: null })323}324325const listKey = (mb: string, view: string, q: string) => `${mb}|${view}|${q}`326327/** Un module (recherche du serveur) tient lui-même la vue « search » : la requête JMAP d'origine n'est alors pas lancée. */328let searchTakeover: (() => boolean) | null = null329export function setSearchTakeover(fn: (() => boolean) | null) {330 searchTakeover = fn331}332333function filterFor(a: Account, view: string, q: string): EmailFilter | null {334 const trash = folderByRole(a, "trash")?.id335 const junk = folderByRole(a, "junk")?.id336 const hidden = [trash, junk].filter((x): x is Id => !!x)337 const notHidden: EmailFilter[] = hidden.length ? [{ inMailboxOtherThan: hidden }] : []338 switch (view) {339 case "unread": {340 const inbox = folderByRole(a, "inbox")?.id341 return { operator: "AND", conditions: [...(inbox ? [{ inMailbox: inbox }] : []), { notKeyword: KW.seen }] }342 }343 case "flagged":344 return { operator: "AND", conditions: [{ hasKeyword: KW.flagged }, ...notHidden] }345 case "pinned":346 return { operator: "AND", conditions: [{ hasKeyword: KW.pinned }, ...notHidden] }347 case "search": {348 const conds = searchToConditions(parseSearch(q))349 return { operator: "AND", conditions: [...conds, ...notHidden] }350 }351 default: {352 const f = folderOfView(a, view)353 return f ? { inMailbox: f.id } : null354 }355 }356}357function sortFor(view: string): EmailSort[] {358 const byDate: EmailSort = { property: "receivedAt", isAscending: false }359 // les messages épinglés restent en tête de leur dossier360 return view === "search" || view === "pinned" || view === "flagged" || view === "unread" ? [byDate] : [{ property: "hasKeyword", keyword: KW.pinned, isAscending: false }, byDate]361}362363// ================================================================ liste fenêtrée364let listGen = 0365const pagesInFlight = new Set<number>()366const pagesLoaded = new Set<number>()367/** Fenêtre affichée (positions), tenue à jour par la liste virtualisée : c'est autour d'elle que l'on relit après un changement. */368let viewport = { first: 0, last: PAGE - 1 }369/** État de requête (queryState) rendu par le serveur avec chaque page chargée. */370const pageStates = new Map<number, string>()371/**372 * État de requête commun à toutes les pages chargées (Email/queryChanges part de lui). `null` : inconnu, ou pages lues à des373 * états différents — le delta n'est alors pas applicable et l'on relit les pages visibles.374 */375function commonQueryState(): string | null {376 let common: string | null = null377 for (const p of pagesLoaded) {378 const st = pageStates.get(p)379 if (!st || (common !== null && common !== st)) return null380 common = st381 }382 return common383}384385function rolesOf(a: Account | undefined): RoleFolders {386 return { trash: folderByRole(a, "trash")?.id, junk: folderByRole(a, "junk")?.id, drafts: folderByRole(a, "drafts")?.id }387}388function scopeOf(a: Account | undefined, view: string): ViewScope {389 const r = rolesOf(a)390 const folderId = view === "unread" ? (folderByRole(a, "inbox")?.id ?? null) : (folderOfView(a, view)?.id ?? null)391 return { view, folderId, hidden: [r.trash, r.junk].filter((x): x is Id => !!x) }392}393/** Taille affichée de chaque fil : seuls comptent les messages que le lecteur montrera dans cette vue. */394function shownSizes(a: Account | undefined, view: string, threads: { id: Id; emailIds: Id[] }[], members: Pick<EmailSummary, "id" | "mailboxIds">[]): Record<Id, number> {395 const byId = new Map(members.map((e) => [e.id, e]))396 const roles = rolesOf(a)397 const out: Record<Id, number> = {}398 for (const th of threads) {399 const known = th.emailIds.map((id) => byId.get(id)).filter((e): e is Pick<EmailSummary, "id" | "mailboxIds"> => !!e)400 out[th.id] = known.length === th.emailIds.length ? shownThreadSize(roles, view, known) : th.emailIds.length401 }402 return out403}404405interface CachedList {406 ids: Id[]407 total: number408 emails: Record<Id, EmailSummary>409 threads: Record<Id, Id[]>410}411412export function openList(mb: string, view: string, q: string, keepSelection = false) {413 listGen++414 pagesInFlight.clear()415 pagesLoaded.clear()416 pageStates.clear()417 const key = listKey(mb, view, q)418 const same = S.get().list.key === key419 if (!same) viewport = { first: 0, last: PAGE - 1 }420 S.set((s) => ({421 mb, view, query: q,422 list: same ? { ...s.list, error: null } : emptyList(key),423 emails: same ? s.emails : {}, threads: same ? s.threads : {}, threadShown: same ? s.threadShown : {},424 selected: same && keepSelection ? s.selected : new Set(), cursor: same ? s.cursor : null,425 }))426 const a = S.get().accounts[mb]427 if (view === "search" && (searchTakeover?.() || isEmptySearch(parseSearch(q)))) {428 S.set((s) => ({ list: { ...s.list, total: 0, ids: [], loadingFirst: false } }))429 return430 }431 if (!a || a.status !== "ready") {432 // hors ligne : dernière première page connue de cette vue433 const gen = listGen434 void cacheGet<CachedList>(`list:${key}`).then((c) => {435 if (gen !== listGen) return436 if (c) S.set((s) => ({ list: { ...s.list, ids: c.ids, total: c.ids.length, loadingFirst: false, stale: true, error: null }, emails: c.emails, threads: c.threads }))437 else if (a?.status === "error") S.set((s) => ({ list: { ...s.list, loadingFirst: false, error: a.error ?? "offline" } }))438 })439 return440 }441 if (view !== "search" && !["unread", "flagged", "pinned"].includes(view) && !folderOfView(a, view)) {442 // dossier système absent (ex. Archive jamais créé) : liste vide, pas une erreur443 S.set((s) => ({ list: { ...s.list, total: 0, ids: [], loadingFirst: false } }))444 return445 }446 void loadPage(0)447}448449function openListFresh() {450 const s = S.get()451 if (!s.mb) return452 S.set({ list: emptyList() })453 openList(s.mb, s.view, s.query)454}455456async function loadPage(page: number, silent = false): Promise<void> {457 const s0 = S.get()458 const mb = s0.mb459 if (!mb || pagesInFlight.has(page)) return460 const a = s0.accounts[mb]461 if (!a || a.status !== "ready") return462 if (s0.view === "search" && searchTakeover?.()) return463 const filter = filterFor(a, s0.view, s0.query)464 if (!filter) return465 const gen = listGen466 const view = s0.view467 pagesInFlight.add(page)468 try {469 const c = clientFor(mb)470 const b = c.batch()471 const q = b.add("Email/query", { filter, sort: sortFor(view), collapseThreads: true, position: page * PAGE, limit: PAGE, calculateTotal: true })472 const g = b.add("Email/get", { "#ids": q.ref("/ids"), properties: SUMMARY_PROPS })473 const th = b.add("Thread/get", { "#ids": g.ref("/list/*/threadId") })474 // dossiers de tous les messages de ces fils : la pastille de la liste ne compte que ceux que le lecteur montrera475 const members = b.add("Email/get", { "#ids": th.ref("/list/*/emailIds"), properties: ["id", "mailboxIds"] })476 await b.send()477 if (gen !== listGen) return478 const ids = q.result.ids479 const total = q.result.total ?? page * PAGE + ids.length480 const list = g.result.list481 const prevTotal = S.get().list.total482 const merged = mergePage(S.get().list.ids, prevTotal, page, ids, total, PAGE)483 pagesLoaded.add(page)484 for (const p of merged.stale) pagesLoaded.delete(p)485 for (const p of merged.stale) pageStates.delete(p)486 if (q.result.canCalculateChanges === false || !q.result.queryState) pageStates.delete(page)487 else pageStates.set(page, q.result.queryState)488 S.set((s) => {489 const emails = { ...s.emails }490 for (const e of list) emails[e.id] = e491 const threads = { ...s.threads }492 let threadShown = s.threadShown493 if (!th.error) {494 for (const tItem of th.result.list) threads[tItem.id] = tItem.emailIds495 threadShown = { ...s.threadShown, ...shownSizes(a, view, th.result.list, members.error ? [] : members.result.list) }496 }497 const cursor = s.cursor && !hasId(merged.ids, s.cursor) && !s.emails[s.cursor] ? null : s.cursor498 return { list: { ...s.list, ids: merged.ids, total, loadingFirst: false, error: null, stale: false }, emails, threads, threadShown, cursor }499 })500 patchSync({ error: null })501 // des positions ont glissé (ajout ou retrait ailleurs) : les pages visibles devenues douteuses sont relues tout de suite502 if (merged.stale.length) ensureRange(viewport.first, viewport.last)503 if (page === 0) {504 const s = S.get()505 const firstIds = s.list.ids.slice(0, PAGE).filter((x): x is Id => !!x)506 const emails: Record<Id, EmailSummary> = {}507 const threads: Record<Id, Id[]> = {}508 for (const id of firstIds) {509 const e = s.emails[id]510 if (!e) continue511 emails[id] = e512 if (s.threads[e.threadId]) threads[e.threadId] = s.threads[e.threadId]513 }514 void cachePut(`list:${s.list.key}`, { ids: firstIds, total, emails, threads } satisfies CachedList)515 }516 } catch (e) {517 if (gen !== listGen) return518 const kind = errorKind(e)519 if (kind === "offline" && S.get().list.ids.length === 0) {520 // réseau coupé : dernière première page connue de cette vue521 const c = await cacheGet<CachedList>(`list:${S.get().list.key}`)522 if (gen !== listGen) return523 if (c) {524 S.set((s) => ({ list: { ...s.list, ids: c.ids, total: c.ids.length, loadingFirst: false, stale: true, error: null }, emails: { ...c.emails, ...s.emails }, threads: { ...c.threads, ...s.threads } }))525 return526 }527 }528 if (!silent || S.get().list.ids.length === 0) S.set((s) => ({ list: { ...s.list, loadingFirst: false, error: kind } }))529 else if (kind !== "unauthorized") patchSync({ error: kind })530 } finally {531 if (gen === listGen) pagesInFlight.delete(page)532 }533}534535/** Charge les pages qui couvrent les positions visibles. */536export function ensureRange(first: number, last: number) {537 viewport = { first, last }538 const s = S.get()539 if (s.all || s.list.total === null || s.list.stale) return540 const from = Math.max(0, Math.floor(first / PAGE))541 const to = Math.min(Math.floor(Math.max(0, s.list.total - 1) / PAGE), Math.floor(last / PAGE))542 for (let p = from; p <= to; p++) if (!pagesLoaded.has(p) && !pagesInFlight.has(p)) void loadPage(p)543}544545export function retryList() {546 const s = S.get()547 if (!s.mb) return548 S.set((x) => ({ list: { ...x.list, error: null, loadingFirst: x.list.ids.length === 0 } }))549 if (s.accounts[s.mb]?.status === "error") void initAccount(s.mb)550 else void loadPage(0)551}552553/**554 * Relit la liste après un changement, sans vider l'affichage : seules les pages qui couvrent la fenêtre visible (marge de555 * défilement comprise) sont redemandées ; les autres sont oubliées et seront relues quand on y défilera.556 */557export async function refreshList() {558 if (S.get().all) return // vue « Toutes les boîtes » : sa liste se rafraîchit elle-même (state/unified.ts)559 const keep = pagesAround(viewport.first, viewport.last, S.get().list.total, PAGE)560 for (const p of [...pagesLoaded])561 if (!keep.includes(p)) {562 pagesLoaded.delete(p)563 pageStates.delete(p)564 }565 await Promise.all(keep.map((p) => loadPage(p, true)))566}567568// ================================================================ sélection et curseur569export function rowIds(): Id[] {570 return S.get().list.ids.filter((x): x is Id => !!x)571}572export function toggleSelect(id: Id, range = false) {573 S.set((s) => {574 const next = new Set(s.selected)575 if (range && s.cursor && s.cursor !== id) {576 const ids = s.list.ids577 const a = indexOfId(ids, s.cursor)578 const b = indexOfId(ids, id)579 if (a >= 0 && b >= 0) for (let i = Math.min(a, b); i <= Math.max(a, b); i++) if (ids[i]) next.add(ids[i]!)580 } else if (next.has(id)) next.delete(id)581 else next.add(id)582 return { selected: next, cursor: id }583 })584}585export function selectAll(on: boolean) {586 S.set({ selected: on ? new Set(rowIds()) : new Set() })587}588export function moveCursor(delta: number): Id | null {589 const s = S.get()590 const ids = s.list.ids591 if (!ids.length) return null592 let i = indexOfId(ids, s.cursor)593 i = Math.max(0, Math.min(ids.length - 1, i < 0 ? (delta > 0 ? 0 : ids.length - 1) : i + delta))594 const id = ids[i]595 if (!id) {596 ensureRange(i, i)597 return null598 }599 S.set({ cursor: id })600 return id601}602603// ================================================================ fil ouvert604export function threadHref(threadId: Id | null): string {605 const s = S.get()606 const r = s.route.name === "mail" ? s.route : { name: "mail" as const, mbIndex: 0, view: s.view, threadId: null, q: s.query }607 return routeHref({ ...r, threadId })608}609610const visibleInThread = (a: Account | undefined, view: string, e: EmailSummary): boolean => visibleIn(rolesOf(a), view, e)611612/** Vrai si le fil affiché est ce fil de CETTE boîte. */613export const isOpenThread = (mb: string, threadId: Id, open: OpenThread | null = S.get().open): boolean => !!open && open.threadId === threadId && open.mb === mb614615export async function openThread(threadId: Id) {616 const s0 = S.get()617 const mb = s0.mb618 if (!mb) return619 const known = s0.threads[threadId] ?? []620 S.set({ open: { mb, threadId, status: "loading", emailIds: known, emails: {}, expanded: new Set(), stale: false } })621 const a = s0.accounts[mb]622 if (!a || a.status !== "ready") {623 const cached = await cacheGet<{ emailIds: Id[]; emails: Record<Id, EmailFull> }>(`thread:${mb}:${threadId}`)624 if (!isOpenThread(mb, threadId)) return625 if (cached) S.set({ open: { mb, threadId, status: "ready", emailIds: cached.emailIds, emails: cached.emails, expanded: new Set(cached.emailIds.slice(-1)), stale: true } })626 else S.set({ open: { mb, threadId, status: "error", error: "offline", emailIds: [], emails: {}, expanded: new Set(), stale: false } })627 return628 }629 try {630 const { emailIds, emails } = await fetchThread(mb, threadId)631 if (!isOpenThread(mb, threadId)) return632 const view = S.get().view633 const shown = emailIds.filter((id) => emails[id] && visibleInThread(a, view, emails[id]))634 const ids = shown.length ? shown : emailIds.filter((id) => emails[id])635 const unread = ids.filter((id) => !emails[id].keywords[KW.seen])636 const expanded = new Set<Id>([...unread, ...ids.slice(-1)])637 S.set((s) => ({ open: { mb, threadId, status: "ready", emailIds: ids, emails, expanded, stale: false }, threads: { ...s.threads, [threadId]: emailIds }, threadShown: { ...s.threadShown, [threadId]: ids.length } }))638 void cachePutThread(mb, threadId, { emailIds: ids, emails })639 if (unread.length && view !== "drafts") void setKeyword(unread, KW.seen, true, { quiet: true })640 } catch (e) {641 if (!isOpenThread(mb, threadId)) return642 if (errorKind(e) === "offline") {643 const cached = await cacheGet<{ emailIds: Id[]; emails: Record<Id, EmailFull> }>(`thread:${mb}:${threadId}`)644 if (!isOpenThread(mb, threadId)) return645 if (cached) return S.set({ open: { mb, threadId, status: "ready", emailIds: cached.emailIds, emails: cached.emails, expanded: new Set(cached.emailIds.slice(-1)), stale: true } })646 }647 S.set({ open: { mb, threadId, status: "error", error: errorKind(e), emailIds: [], emails: {}, expanded: new Set(), stale: false } })648 }649}650651async function fetchThread(mb: string, threadId: Id): Promise<{ emailIds: Id[]; emails: Record<Id, EmailFull> }> {652 const b = clientFor(mb).batch()653 const th = b.add("Thread/get", { ids: [threadId] })654 const g = b.add("Email/get", { "#ids": th.ref("/list/*/emailIds"), properties: FULL_PROPS, bodyProperties: BODY_PROPS, fetchHTMLBodyValues: true, fetchTextBodyValues: true, maxBodyValueBytes: 2_000_000 })655 await b.send()656 const emailIds = th.result.list[0]?.emailIds ?? []657 if (!emailIds.length) throw new JmapMethodError("Thread/get", "notFound")658 const emails: Record<Id, EmailFull> = {}659 for (const e of g.result.list) emails[e.id] = e660 return { emailIds, emails }661}662663export function toggleExpanded(id: Id) {664 S.set((s) => {665 if (!s.open) return {}666 const expanded = new Set(s.open.expanded)667 if (expanded.has(id)) expanded.delete(id)668 else expanded.add(id)669 return { open: { ...s.open, expanded } }670 })671}672673async function refreshOpenThread(mb: string) {674 const open = S.get().open675 if (!open || open.status !== "ready" || S.get().mb !== mb) return676 try {677 const { emailIds, emails } = await fetchThread(mb, open.threadId)678 const cur = S.get().open679 if (!cur || cur.threadId !== open.threadId || S.get().mb !== mb) return680 const a = S.get().accounts[mb]681 const view = S.get().view682 const shown = emailIds.filter((id) => emails[id] && visibleInThread(a, view, emails[id]))683 if (!shown.length) {684 // tout le fil a quitté cette vue (supprimé, déplacé ailleurs)685 closeThread()686 return687 }688 const added = shown.filter((id) => !cur.emailIds.includes(id))689 const expanded = new Set([...cur.expanded].filter((id) => shown.includes(id)))690 for (const id of added) expanded.add(id)691 S.set((s) => ({ open: { ...cur, emailIds: shown, emails, expanded }, threads: { ...s.threads, [open.threadId]: emailIds }, threadShown: { ...s.threadShown, [open.threadId]: shown.length } }))692 } catch (e) {693 if (e instanceof JmapMethodError && e.type === "notFound" && S.get().mb === mb && S.get().open?.threadId === open.threadId) closeThread()694 }695}696697export function closeThread() {698 const s = S.get()699 if (s.route.name === "mail" && s.route.threadId) {700 const href = threadHref(null)701 history.pushState(null, "", href)702 S.set({ route: { ...s.route, threadId: null }, open: null })703 } else S.set({ open: null })704}705706// ================================================================ actions sur les messages707interface Snapshot {708 mailboxIds: Record<Id, boolean>709 keywords: Record<string, boolean>710}711interface Patch {712 mailboxIds?: Record<Id, boolean>713 keywords?: Record<string, boolean>714}715716function lookup(id: Id): EmailSummary | undefined {717 const s = S.get()718 return s.emails[id] ?? s.open?.emails[id]719}720721/** Messages du même fil que la ligne, situés dans un même dossier qu'elle (l'action d'une ligne vise la conversation). */722async function threadTargets(mb: string, ids: Id[]): Promise<Id[]> {723 const s = S.get()724 const out = new Set<Id>(ids)725 const missing: Id[] = []726 for (const id of ids) {727 const e = lookup(id)728 if (!e) continue729 for (const sib of s.threads[e.threadId] ?? []) if (sib !== id && !lookup(sib)) missing.push(sib)730 }731 if (missing.length) {732 const r = await clientFor(mb).call("Email/get", { ids: missing.slice(0, 500), properties: SUMMARY_PROPS })733 // les identifiants JMAP sont propres à un compte : après un changement de boîte, ils ne désignent plus rien ici734 if (S.get().mb !== mb) throw new StaleMailboxError()735 S.set((st) => {736 const emails = { ...st.emails }737 for (const e of r.list) emails[e.id] = e738 return { emails }739 })740 }741 for (const id of ids) {742 const e = lookup(id)743 if (!e) continue744 for (const sib of S.get().threads[e.threadId] ?? []) {745 const se = lookup(sib)746 if (se && Object.keys(se.mailboxIds).some((m) => e.mailboxIds[m])) out.add(sib)747 }748 }749 return [...out]750}751752/** La boîte affichée a changé pendant une attente : l'action en cours ne doit plus rien écrire dans l'état. */753class StaleMailboxError extends Error {754 constructor() {755 super("mailbox changed")756 }757}758759function applyLocal(id: Id, snap: Snapshot) {760 S.set((s) => {761 const out: Partial<ReturnType<typeof S.get>> = {}762 if (s.emails[id]) out.emails = { ...s.emails, [id]: { ...s.emails[id], ...snap } }763 if (s.open?.emails[id]) out.open = { ...s.open, emails: { ...s.open.emails, [id]: { ...s.open.emails[id], ...snap } } }764 return out765 })766}767768async function sendUpdates(mb: string, updates: Record<Id, Record<string, unknown>>) {769 const ids = Object.keys(updates)770 for (let i = 0; i < ids.length; i += 400) {771 const chunk: Record<Id, Record<string, unknown>> = {}772 for (const id of ids.slice(i, i + 400)) chunk[id] = updates[id]773 const r = await tracked(() => clientFor(mb).call("Email/set", { update: chunk }))774 assertSet("Email/set", r)775 }776}777778// File hors ligne (state/offline.ts) : elle envoie par `sendUpdates`, rejoue avec les clients de ce module, puis fait relire ce qui779// est affiché. Tout appelant de `act()` en bénéficie sans rien faire ; un autre module peut aussi appeler `queueOrSend` lui-même.780bindOffline({781 send: sendUpdates,782 client: (mb) => clients.get(mb),783 refresh: async (mb) => {784 await syncEmails(mb)785 if (S.get().mb === mb) await refreshList()786 },787 // des actions attendent et le serveur ne répondait pas au démarrage : toutes les boîtes en erreur retentent leur connexion788 // (sans événement « online » du navigateur, rien d'autre ne le ferait avant le retour sur l'onglet)789 reconnect: () => {790 for (const [id, a] of Object.entries(S.get().accounts)) if (a.status === "error") void initAccount(id)791 },792})793export { queueOrSend }794795interface ActOptions {796 /** texte de la notification ; avec `undo`, propose « Annuler » */797 label?: string798 undo?: boolean799 /** retirer les lignes de la liste affichée (le message quitte cette vue) */800 leavesView?: boolean801 quiet?: boolean802}803804/** Applique une modification à des messages : immédiate à l'écran, envoyée au serveur, annulable. */805async function act(mb: string, ids: Id[], patchOf: (e: EmailSummary) => Patch | null, opts: ActOptions = {}): Promise<boolean> {806 // la boîte affichée a changé pendant la préparation (recherche des messages du fil) : l'état montré est celui d'un autre807 // compte, où les mêmes identifiants désignent d'autres messages — on n'y touche pas808 if (S.get().mb !== mb) {809 reportError(new StaleMailboxError(), t("error.actionFailed"))810 return false811 }812 /** vrai tant que l'état affiché est encore celui de la boîte visée */813 const local = () => S.get().mb === mb814 const before = new Map<Id, Snapshot>()815 const updates: Record<Id, Record<string, unknown>> = {}816 const inverse: Record<Id, Record<string, unknown>> = {}817 for (const id of ids) {818 const e = lookup(id)819 if (!e) continue820 const p = patchOf(e)821 if (!p) continue822 before.set(id, { mailboxIds: e.mailboxIds, keywords: e.keywords })823 const up: Record<string, unknown> = {}824 const inv: Record<string, unknown> = {}825 const keywords = { ...e.keywords }826 if (p.keywords)827 for (const [k, v] of Object.entries(p.keywords)) {828 if (!!e.keywords[k] === v) continue829 up[`keywords/${k}`] = v ? true : null830 inv[`keywords/${k}`] = e.keywords[k] ? true : null831 if (v) keywords[k] = true832 else delete keywords[k]833 }834 if (p.mailboxIds) {835 up.mailboxIds = p.mailboxIds836 inv.mailboxIds = e.mailboxIds837 }838 if (!Object.keys(up).length) continue839 updates[id] = up840 inverse[id] = inv841 applyLocal(id, { mailboxIds: p.mailboxIds ?? e.mailboxIds, keywords })842 }843 const changed = Object.keys(updates)844 if (!changed.length) return true845 if (opts.leavesView) removeRows(changed)846 try {847 // hors ligne ou panne de transport : l'action reste appliquée à l'écran et attend dans la file durable (« queued ») ;848 // seul un refus du serveur arrive dans le `catch` et annule l'affichage optimiste849 await queueOrSend(mb, updates, inverse)850 } catch (e) {851 if (local()) {852 for (const [id, snap] of before) applyLocal(id, snap)853 if (opts.leavesView) void refreshList()854 }855 reportError(e, t("error.actionFailed"))856 return false857 }858 if (opts.label && !opts.quiet)859 toast({860 kind: "success", text: opts.label,861 ...(opts.undo862 ? {863 actionLabel: t("action.undo"),864 action: () => {865 // l'annulation passe par la même file : hors ligne, elle s'annule avec l'action encore en attente866 void queueOrSend(mb, inverse, updates)867 .then(() => {868 if (local()) {869 for (const [id, snap] of before) applyLocal(id, snap)870 void refreshList()871 }872 toast({ kind: "info", text: t("toast.undone") })873 })874 .catch((e) => reportError(e, t("error.actionFailed")))875 },876 }877 : {}),878 })879 return true880}881882/** Retire de la liste les lignes des messages (ou de leurs fils) qui viennent de quitter la vue. */883function removeRows(emailIds: Id[]) {884 S.set((s) => {885 const gone = new Set(emailIds)886 const goneThreads = new Set<Id>()887 for (const id of emailIds) {888 const e = s.emails[id] ?? s.open?.emails[id]889 if (e) goneThreads.add(e.threadId)890 }891 const ids = s.list.ids.filter((id) => !id || !(gone.has(id) || (s.emails[id] && goneThreads.has(s.emails[id].threadId))))892 const removed = s.list.ids.length - ids.length893 if (!removed) return {}894 const selected = new Set([...s.selected].filter((id) => hasId(ids, id)))895 let cursor = s.cursor896 if (cursor && !hasId(ids, cursor)) {897 const at = indexOfId(s.list.ids, cursor)898 cursor = ids[Math.min(at, ids.length - 1)] ?? null899 }900 return { list: { ...s.list, ids, total: s.list.total === null ? null : Math.max(0, s.list.total - removed) }, selected, cursor }901 })902 const s = S.get()903 if (s.open && emailIds.some((id) => s.open!.emailIds.includes(id)) && s.open.emailIds.every((id) => emailIds.includes(id))) closeThread()904}905906/** Repli de `threadTargets` : les lignes seules si la recherche du fil échoue ; rien du tout si la boîte a changé entre-temps. */907const staleOr = (ids: Id[]) => (e: unknown): Id[] | null => {908 if (!(e instanceof StaleMailboxError)) return ids909 reportError(e, t("error.actionFailed"))910 return null911}912913function requireMb(): string | null {914 return S.get().mb915}916const isFolderView = (view: string) => !["unread", "flagged", "pinned", "search"].includes(view)917918export async function setKeyword(ids: Id[], keyword: string, on: boolean, opts: ActOptions & { wholeThread?: boolean } = {}) {919 const mb = requireMb()920 if (!mb || !ids.length) return921 const targets = opts.wholeThread ? await threadTargets(mb, ids).catch(staleOr(ids)) : ids922 if (!targets) return923 const view = S.get().view924 const leaves = (view === "unread" && keyword === KW.seen && on && !opts.quiet) || (view === "flagged" && keyword === KW.flagged && !on) || (view === "pinned" && keyword === KW.pinned && !on)925 await act(mb, targets, () => ({ keywords: { [keyword]: on } }), { ...opts, leavesView: leaves })926 if (keyword === KW.pinned && isFolderView(view)) void refreshList() // l'ordre de la liste dépend de l'épinglage927}928export const markRead = (ids: Id[], read: boolean) => setKeyword(ids, KW.seen, read, { wholeThread: true })929export const setFlag = (ids: Id[], on: boolean) => setKeyword(ids, KW.flagged, on)930export const setPinned = (ids: Id[], on: boolean) => setKeyword(ids, KW.pinned, on, { label: on ? t("toast.pinned") : t("toast.unpinned") })931932/**933 * Modules « Next » (libellés, épingle) : pose ou retire un mot-clé sur des messages d'une boîte qui n'est pas forcément celle934 * affichée (« Toutes les boîtes », résultats de recherche). Passe par la file durable comme `act()` : hors ligne ou serveur935 * injoignable, la modification attend et part à la reconnexion (elle compte dans « N en attente »). Sans mise à jour locale :936 * l'appelant ajuste sa propre liste ; la boîte affichée, elle, passe par `setKeyword`. Rend « queued » si l'écriture attend.937 */938export async function setKeywordIn(mb: string, ids: Id[], keyword: string, on: boolean): Promise<"sent" | "queued"> {939 if (!ids.length) return "sent"940 const patch = (v: boolean) => Object.fromEntries(ids.map((id) => [id, { [`keywords/${keyword}`]: v ? true : null }]))941 return queueOrSend(mb, patch(on), patch(!on))942}943/**944 * Modules « Next » (mise en veille) : le serveur va sortir ces messages de la vue — leurs lignes (celles de leurs fils si945 * `exact` est faux, ou gardées si `keepRows`) quittent tout de suite la liste. Rend les messages visés, ou null si la boîte946 * affichée a changé. L'appelant relit la liste (`refreshList`) à la réponse du serveur comme à l'échec.947 */948export async function takeFromView(mb: string, ids: Id[], exact = false, keepRows = false): Promise<Id[] | null> {949 if (S.get().mb !== mb || !ids.length) return null950 const targets = exact ? ids : await threadTargets(mb, ids).catch(staleOr(ids))951 if (!targets || S.get().mb !== mb) return null952 if (!keepRows) removeRows(targets)953 return targets954}955956/** Déplace des conversations vers un dossier. */957export async function moveTo(ids: Id[], targetFolderId: Id, label?: string, extraKeywords?: Record<string, boolean>, exact = false) {958 const mb = requireMb()959 if (!mb || !ids.length) return960 const s = S.get()961 const a = s.accounts[mb]962 const target = a?.folders.find((f) => f.id === targetFolderId)963 const targets = exact ? ids : await threadTargets(mb, ids).catch(staleOr(ids))964 if (!targets) return965 const current = folderOfView(a, s.view)966 const hidden = target?.role === "trash" || target?.role === "junk"967 const leaves = isFolderView(s.view) ? current?.id !== targetFolderId : hidden968 await act(mb, targets, (e) => (e.mailboxIds[targetFolderId] && Object.keys(e.mailboxIds).length === 1 && !extraKeywords ? null : { mailboxIds: { [targetFolderId]: true }, keywords: extraKeywords }), {969 label: label ?? t("toast.movedTo", { folder: target ? folderLabel(target) : "" }), undo: true, leavesView: leaves,970 })971}972973export async function archive(ids: Id[], exact = false) {974 const mb = requireMb()975 if (!mb || !ids.length) return976 try {977 const target = await ensureFolder(mb, "archive")978 await moveTo(ids, target, t("toast.archived", { n: ids.length }), undefined, exact)979 } catch (e) {980 reportError(e, t("error.actionFailed"))981 }982}983984/** Corbeille ; depuis la corbeille ou les brouillons, suppression définitive (à confirmer par l'appelant). */985export async function trash(ids: Id[], exact = false) {986 const mb = requireMb()987 if (!mb || !ids.length) return988 try {989 const target = await ensureFolder(mb, "trash")990 await moveTo(ids, target, t("toast.trashed", { n: ids.length }), undefined, exact)991 } catch (e) {992 reportError(e, t("error.actionFailed"))993 }994}995export function isPermanentDeleteView(): boolean {996 const v = S.get().view997 return v === "trash" || v === "drafts"998}999export async function destroyForever(ids: Id[], exact = false) {1000 const mb = requireMb()1001 if (!mb || !ids.length) return1002 // jamais mise en file : une suppression définitive ne se rejoue pas à l'aveugle — elle exige une connexion1003 if (typeof navigator !== "undefined" && navigator.onLine === false) {1004 toast({ kind: "info", text: t("offline.deleteNeedsConnection") })1005 return1006 }1007 const targets = exact ? ids : await threadTargets(mb, ids).catch(staleOr(ids))1008 if (!targets || S.get().mb !== mb) return1009 removeRows(targets)1010 try {1011 for (let i = 0; i < targets.length; i += 400) {1012 const r = await tracked(() => clientFor(mb).call("Email/set", { destroy: targets.slice(i, i + 400) }))1013 assertSet("Email/set", r)1014 }1015 toast({ kind: "success", text: t("toast.deletedForever", { n: ids.length }) })1016 } catch (e) {1017 if (S.get().mb === mb) void refreshList()1018 reportError(e, t("error.actionFailed"))1019 }1020}10211022/** Signaler comme indésirable (→ Indésirables + $junk) ou légitime (→ Boîte de réception + $notjunk). */1023export async function reportJunk(ids: Id[], isJunk: boolean, exact = false) {1024 const mb = requireMb()1025 if (!mb || !ids.length) return1026 try {1027 const target = await ensureFolder(mb, isJunk ? "junk" : "inbox")1028 await moveTo(ids, target, isJunk ? t("toast.markedJunk") : t("toast.markedNotJunk"), { [KW.junk]: isJunk, [KW.notJunk]: !isJunk }, exact)1029 } catch (e) {1030 reportError(e, t("error.actionFailed"))1031 }1032}10331034export async function emptyFolder(mb: string, folderId: Id) {1035 const c = clientFor(mb)1036 for (let guard = 0; guard < 200; guard++) {1037 const q = await c.call("Email/query", { filter: { inMailbox: folderId }, limit: 400 })1038 if (!q.ids.length) break1039 const r = await tracked(() => c.call("Email/set", { destroy: q.ids }))1040 assertSet("Email/set", r)1041 }1042 if (S.get().mb === mb) void refreshList()1043}10441045// ================================================================ synchronisation1046const syncTimers = new Map<string, ReturnType<typeof setTimeout>>()1047const pending = new Map<string, { email: boolean; mailbox: boolean }>()10481049function onStateChange(mb: string, change: StateChange) {1050 const a = S.get().accounts[mb]1051 if (!a || a.status !== "ready") return1052 const c = clients.get(mb)1053 const states = c ? change.changed[c.accountId] : undefined1054 if (!states) return1055 const p = pending.get(mb) ?? { email: false, mailbox: false }1056 if (states.Email && states.Email !== a.emailState) p.email = true1057 if (states.Thread) p.email = true1058 if (states.Mailbox && states.Mailbox !== a.mailboxState) p.mailbox = true1059 if (states.EmailDelivery) p.email = true1060 pending.set(mb, p)1061 clearTimeout(syncTimers.get(mb))1062 syncTimers.set(mb, setTimeout(() => void flushSync(mb), 250))1063}10641065const syncing = new Set<string>()1066async function flushSync(mb: string) {1067 if (syncing.has(mb)) {1068 syncTimers.set(mb, setTimeout(() => void flushSync(mb), 300))1069 return1070 }1071 const p = pending.get(mb)1072 pending.delete(mb)1073 if (!p) return1074 syncing.add(mb)1075 patchSync({ busy: true })1076 try {1077 if (p.mailbox) await syncMailboxes(mb)1078 if (p.email) await syncEmails(mb)1079 } finally {1080 syncing.delete(mb)1081 if (!syncing.size) patchSync({ busy: false })1082 }1083}10841085/** Après une reconnexion : tout a pu changer pendant la coupure. */1086async function syncAll(mb: string) {1087 await syncMailboxes(mb)1088 await syncEmails(mb)1089}10901091export async function syncMailboxes(mb: string, force = false) {1092 const a = S.get().accounts[mb]1093 const c = clients.get(mb)1094 if (!a || !c) return1095 try {1096 if (force || !a.mailboxState) throw new JmapMethodError("Mailbox/changes", "cannotCalculateChanges")1097 const b = c.batch()1098 const ch = b.add("Mailbox/changes", { sinceState: a.mailboxState })1099 const created = b.add("Mailbox/get", { "#ids": ch.ref("/created") })1100 const updated = b.add("Mailbox/get", { "#ids": ch.ref("/updated") })1101 await b.send()1102 const r = ch.result1103 if (r.hasMoreChanges) throw new JmapMethodError("Mailbox/changes", "cannotCalculateChanges")1104 const byId = new Map(a.folders.map((f) => [f.id, f]))1105 for (const id of r.destroyed) byId.delete(id)1106 for (const f of [...created.result.list, ...updated.result.list]) byId.set(f.id, f)1107 setAccount(mb, { folders: [...byId.values()], mailboxState: r.newState })1108 } catch (e) {1109 if (errorKind(e) === "unauthorized" || e instanceof NetworkError) return1110 // cannotCalculateChanges (ou état inconnu du serveur) : relecture complète1111 try {1112 const r = await c.call("Mailbox/get", { ids: null })1113 setAccount(mb, { folders: r.list, mailboxState: r.state })1114 } catch {1115 return1116 }1117 }1118 void cachePut(`folders:${mb}`, S.get().accounts[mb]?.folders ?? [])1119}11201121/** Listes pour lesquelles le serveur a refusé Email/queryChanges : inutile de le redemander à chaque notification. */1122const noQueryChanges = new Set<string>()11231124/**1125 * Met la liste affichée à jour par delta (Email/queryChanges) à partir de l'état de requête mémorisé.1126 * « unavailable » : pas possible ici (état inconnu, liste à trous, refus du serveur) — l'appelant choisit le repli ;1127 * « refresh » : le delta ne suffit pas, les pages visibles doivent être relues.1128 */1129async function syncListByDelta(mb: string, c: JmapClient, gen: number): Promise<"done" | "refresh" | "unavailable"> {1130 const s = S.get()1131 const a = s.accounts[mb]1132 const since = commonQueryState()1133 if (s.all || !a || !since || gen !== listGen || s.list.total === null || s.list.stale || noQueryChanges.has(s.list.key)) return "unavailable"1134 if (pagesInFlight.size || !isDensePrefix(s.list.ids)) return "unavailable"1135 const filter = filterFor(a, s.view, s.query)1136 if (!filter) return "unavailable"1137 const view = s.view1138 const prefix = densePrefix(s.list.ids)1139 try {1140 const b = c.batch()1141 const ch = b.add("Email/queryChanges", { filter, sort: sortFor(view), collapseThreads: true, sinceQueryState: since, maxChanges: 500, calculateTotal: true, ...(prefix > 0 && prefix < s.list.total ? { upToId: s.list.ids[prefix - 1]! } : {}) })1142 const g = b.add("Email/get", { "#ids": ch.ref("/added/*/id"), properties: SUMMARY_PROPS })1143 const th = b.add("Thread/get", { "#ids": g.ref("/list/*/threadId") })1144 const members = b.add("Email/get", { "#ids": th.ref("/list/*/emailIds"), properties: ["id", "mailboxIds"] })1145 await b.send()1146 if (gen !== listGen || S.get().mb !== mb) return "done" // la liste a changé entre-temps : plus rien à réconcilier1147 const r = ch.result1148 if (!r.removed.length && !r.added.length) {1149 if (typeof r.total === "number" && r.total !== S.get().list.total) return "refresh"1150 for (const p of pagesLoaded) pageStates.set(p, r.newQueryState)1151 return "done"1152 }1153 if (g.error) return "refresh"1154 const next = applyQueryChange(S.get().list.ids, S.get().list.total, r)1155 if (!next) return "refresh"1156 pagesLoaded.clear()1157 pageStates.clear()1158 for (const p of loadedPages(next.ids, next.total, PAGE)) {1159 pagesLoaded.add(p)1160 pageStates.set(p, r.newQueryState)1161 }1162 S.set((st) => {1163 const emails = { ...st.emails }1164 for (const e of g.result.list) emails[e.id] = e1165 const threads = { ...st.threads }1166 let threadShown = st.threadShown1167 if (!th.error) {1168 for (const tItem of th.result.list) threads[tItem.id] = tItem.emailIds1169 threadShown = { ...st.threadShown, ...shownSizes(a, view, th.result.list, members.error ? [] : members.result.list) }1170 }1171 const selected = st.selected.size ? new Set([...st.selected].filter((id) => hasId(next.ids, id))) : st.selected1172 let cursor = st.cursor1173 if (cursor && !hasId(next.ids, cursor)) {1174 const at = indexOfId(st.list.ids, cursor)1175 cursor = next.ids[Math.min(Math.max(0, at), densePrefix(next.ids) - 1)] ?? null1176 }1177 return { list: { ...st.list, ids: next.ids, total: next.total, error: null }, emails, threads, threadShown, selected, cursor }1178 })1179 // le préfixe connu a pu raccourcir (lignes retirées) : la fenêtre visible redemande ce qui lui manque1180 ensureRange(viewport.first, viewport.last)1181 return "done"1182 } catch (e) {1183 if (e instanceof JmapMethodError) {1184 // cannotCalculateChanges : l'état mémorisé est trop ancien pour le serveur — on l'oublie (il reviendra avec la prochaine1185 // page lue) ; toute autre erreur : le serveur ne sait pas le faire pour cette requête, inutile de le redemander.1186 // Dans les deux cas l'appelant décide, d'après les messages modifiés, si la liste doit être relue.1187 if (gen === listGen) {1188 if (e.type === "cannotCalculateChanges") pageStates.clear()1189 else noQueryChanges.add(S.get().list.key)1190 }1191 return "unavailable"1192 }1193 throw e1194 }1195}11961197/** @internal Exportée pour les tests unitaires. Synchronisation delta des messages d'une boîte (Email/changes). */1198export async function syncEmails(mb: string) {1199 const a = S.get().accounts[mb]1200 const c = clients.get(mb)1201 if (!a || !c) return1202 // la boîte affichée est relue après chaque attente : une réponse tardive ne doit jamais écrire dans l'état d'une autre boîte1203 const active = () => S.get().mb === mb && clients.get(mb) === c1204 try {1205 let since = a.emailState1206 if (!since) throw new JmapMethodError("Email/changes", "cannotCalculateChanges")1207 const updated = new Set<Id>()1208 const destroyed = new Set<Id>()1209 let created = 01210 for (let guard = 0; guard < 20; guard++) {1211 const r = await c.call("Email/changes", { sinceState: since, maxChanges: 500 })1212 for (const id of r.updated) updated.add(id)1213 for (const id of r.destroyed) destroyed.add(id)1214 created += r.created.length1215 since = r.newState1216 if (!r.hasMoreChanges) break1217 if (guard === 19) throw new JmapMethodError("Email/changes", "cannotCalculateChanges")1218 }1219 if (!stillMine(mb) || clients.get(mb) !== c) return1220 setAccount(mb, { emailState: since })1221 patchSync({ error: null })1222 if (!active() || !(created || updated.size || destroyed.size)) return1223 const gen = listGen1224 // ---- messages modifiés : relus et corrigés sur place (lu, favori, épinglé changés sur un autre appareil)1225 const before = new Map<Id, EmailSummary | undefined>()1226 for (const id of updated) before.set(id, S.get().emails[id])1227 const scope = scopeOf(a, S.get().view)1228 let affected = created > 0 || updated.size > 5001229 for (const id of destroyed) if (S.get().emails[id]) affected = true1230 if (updated.size && updated.size <= 500) {1231 const r = await c.call("Email/get", { ids: [...updated], properties: SUMMARY_PROPS })1232 if (!active() || gen !== listGen) return1233 for (const e of r.list) if (listAffected(scope, before.get(e.id), e)) affected = true1234 for (const id of r.notFound ?? []) if (before.get(id)) affected = true1235 S.set((st) => {1236 const emails = { ...st.emails }1237 // seuls les messages que la liste connaît déjà : pas d'entrée fantôme pour les autres dossiers1238 for (const e of r.list) if (emails[e.id]) emails[e.id] = e1239 for (const id of r.notFound ?? []) delete emails[id]1240 return { emails }1241 })1242 }1243 if (destroyed.size)1244 S.set((st) => {1245 const emails = { ...st.emails }1246 for (const id of destroyed) delete emails[id]1247 return { emails }1248 })1249 // ---- composition de la liste : par delta si possible ; sinon rien si elle n'est pas concernée ; sinon relecture des pages visibles1250 if (!S.get().all) {1251 const delta = await syncListByDelta(mb, c, gen)1252 if (!active() || gen !== listGen) return1253 if (delta === "refresh" || (delta === "unavailable" && affected)) await refreshList()1254 }1255 if (!active()) return1256 const open = S.get().open1257 if (open && (created || open.emailIds.some((id) => updated.has(id) || destroyed.has(id)))) await refreshOpenThread(mb)1258 } catch (e) {1259 if (errorKind(e) === "unauthorized") return1260 if (e instanceof NetworkError) {1261 if (typeof navigator !== "undefined" && navigator.onLine) patchSync({ error: "offline" })1262 return1263 }1264 // Repli : l'état est trop ancien ou inconnu → on repart de l'état courant et on relit ce qui est affiché.1265 try {1266 const r = await c.call("Email/get", { ids: [], properties: ["id"] })1267 if (!stillMine(mb) || clients.get(mb) !== c) return1268 setAccount(mb, { emailState: r.state })1269 if (active()) {1270 await refreshList()1271 if (active()) await refreshOpenThread(mb)1272 }1273 } catch {1274 /* prochaine notification */1275 }1276 }1277}12781279// ================================================================ correspondants récents (saisie semi-automatique)1280export async function loadContacts(mb: string): Promise<void> {1281 if (S.get().contacts[mb]) return1282 const cached = await cacheGet<Addr[]>(`contacts:${mb}`)1283 if (cached) S.set((s) => ({ contacts: { ...s.contacts, [mb]: cached } }))1284 const a = S.get().accounts[mb]1285 const sent = folderByRole(a, "sent")1286 if (!a || a.status !== "ready" || !sent) return1287 try {1288 const b = clientFor(mb).batch()1289 const q = b.add("Email/query", { filter: { inMailbox: sent.id }, sort: [{ property: "receivedAt", isAscending: false }], limit: 150 })1290 const g = b.add("Email/get", { "#ids": q.ref("/ids"), properties: ["to", "cc", "bcc"] })1291 await b.send()1292 const count = new Map<string, { addr: Addr; n: number }>()1293 for (const e of g.result.list)1294 for (const ad of [...(e.to ?? []), ...(e.cc ?? []), ...(e.bcc ?? [])]) {1295 const k = ad.email.toLowerCase()1296 const cur = count.get(k)1297 if (cur) {1298 cur.n++1299 if (!cur.addr.name && ad.name) cur.addr = { name: ad.name, email: ad.email }1300 } else count.set(k, { addr: { name: ad.name, email: ad.email }, n: 1 })1301 }1302 const list = dedupeAddrs([...count.values()].sort((x, y) => y.n - x.n).map((x) => x.addr)).slice(0, 300)1303 S.set((s) => ({ contacts: { ...s.contacts, [mb]: list } }))1304 void cachePut(`contacts:${mb}`, list)1305 } catch {1306 /* la saisie fonctionne sans suggestions */1307 }1308}13091310export function myAddresses(): string[] {1311 const s = S.get()1312 const out = new Set<string>()1313 for (const m of s.me?.mailboxes ?? []) out.add(m.address.toLowerCase())1314 for (const a of Object.values(s.accounts)) for (const i of a.identities) out.add(i.email.toLowerCase())1315 return [...out]1316}13171318export function unreadTotal(): number {1319 let n = 01320 for (const a of Object.values(S.get().accounts)) n += folderByRole(a, "inbox")?.unreadThreads ?? 01321 return n1322}13231324export { currentAccount, viewOfFolder }1325export type { OpenThread }1326