SPB Git

Repository Public

unified.ts 22.0 KB 478 lines typescript

1// « Toutes les boîtes » : liste unifiée (GET /api/v1/messages, session), sélection, actions par message (PATCH / move —2// idempotentes, donc appliquées à l'écran sans attendre), messages programmés, rafraîchissement sur les événements d'état3// des boîtes (EventSource existants). Module chargé avec la vue.4import { t } from "../i18n"5import { HttpError, errorDetail, errorKind, type ErrorKind } from "../jmap/errors"6import { apiPatch } from "../jmap/http"7import { MAILBOX_VIEW, UNIFIED_PAGE, appendPage, decodeV1Id, effectiveSubset, emptyUnified, unifiedKey, unifiedQuery, type UnifiedList, type UnifiedView } from "../mail/unified"8import { v1, type Outbound, type V1Message, type V1Page } from "../mail/v1"9import { S, routeHref, toast, type AppState } from "./app"10import { composeFromDraft } from "./composer"11import { mapLimit } from "../next/pool"12import { clientFor, enterMailbox, hasClient, setKeywordIn } from "./mail"13import { navigate } from "./session"14import { createStore } from "./store"1516export interface ScheduledItem extends Outbound {17  subject?: string18}19export interface UnifiedState {20  view: UnifiedView21  list: UnifiedList22  loading: boolean23  loadingMore: boolean24  error: ErrorKind | null25  selected: ReadonlySet<string>26  cursor: string | null27  /** messages programmés (vue « Programmés ») ; null = pas encore lus */28  scheduled: ScheduledItem[] | null29  /** mots-clés JMAP des lignes (épingle, veille, suivi, libellés), lus à part : /api/v1 ne rend que les mots-clés sans « $ » */30  kw: Readonly<Record<string, Record<string, boolean>>>31}32export const U = createStore<UnifiedState>({ view: "inbox", list: emptyUnified(""), loading: false, loadingMore: false, error: null, selected: new Set(), cursor: null, scheduled: null, kw: {} })3334// ---------------------------------------------------------------- sous-ensemble de boîtes35/** Boîtes retenues (identifiants) : vide = toutes. */36export const subsetIds = (s: AppState = S.get()): string[] => effectiveSubset(s.prefs.unifiedMailboxes, s.me?.mailboxes ?? [])37function subsetAddresses(s: AppState = S.get()): string[] {38  const ids = subsetIds(s)39  return (s.me?.mailboxes ?? []).filter((m) => ids.includes(m.id)).map((m) => m.address)40}41/** Enregistre le choix dans les préférences : PATCH (fusion côté serveur — les autres préférences ne sont pas touchées). */42export async function setSubset(ids: string[]) {43  const s = S.get()44  const next = effectiveSubset(ids, s.me?.mailboxes ?? [])45  S.set({ prefs: { ...s.prefs, unifiedMailboxes: next } })46  try {47    await apiPatch("/api/prefs", { unifiedMailboxes: next })48  } catch {49    toast({ kind: "error", text: t("prefs.saveFailed") })50  }51}5253// ---------------------------------------------------------------- chargement54let gen = 055const fetchPage = (view: Exclude<UnifiedView, "scheduled">, addresses: string[], cursor: string | null, limit = UNIFIED_PAGE) => v1<V1Page<V1Message>>(`/messages?${unifiedQuery(view, addresses, cursor, limit)}`)5657export function openUnified(view: UnifiedView) {58  const key = unifiedKey(view, subsetAddresses())59  const cur = U.get()60  if (view === "scheduled") {61    U.set({ view, list: emptyUnified(key), selected: new Set(), cursor: null, error: null, loading: false })62    void loadScheduled()63    return64  }65  if (cur.list.key === key && cur.list.rows.length) {66    U.set({ view })67    void refreshUnified()68    return69  }70  const my = ++gen71  U.set({ view, list: emptyUnified(key), loading: true, loadingMore: false, error: null, selected: new Set(), cursor: null })72  fetchPage(view, subsetAddresses(), null).then(73    (page) => {74      if (my !== gen) return75      U.set((u) => ({ list: appendPage(u.list, key, page, view, true), loading: false, error: null }))76      void enrichKeywords()77    },78    (e: unknown) => {79      if (my !== gen) return80      U.set({ loading: false, error: errorKind(e) })81    },82  )83}8485export async function loadMore() {86  const u = U.get()87  if (u.view === "scheduled" || u.loading || u.loadingMore || !u.list.cursor) return88  const my = gen89  const { key, cursor } = u.list90  U.set({ loadingMore: true })91  try {92    const page = await fetchPage(u.view, subsetAddresses(), cursor)93    if (my !== gen) return94    U.set((x) => ({ list: appendPage(x.list, key, page, x.view), loadingMore: false }))95    void enrichKeywords()96  } catch (e) {97    if (my !== gen) return98    // curseur périmé ou lié à un autre filtre : on repart du début99    if (errorKind(e) === "invalid") {100      U.set({ loadingMore: false })101      return void refreshUnified()102    }103    U.set({ loadingMore: false })104  }105}106107let refreshing = false108let refreshAgain = false109// Actions en vol (PATCH / move par message) : une relecture commencée avant leur fin rendrait l'état d'avant et écraserait110// l'affichage optimiste (un second geste lirait alors une ligne périmée). Elle est écartée et refaite quand elles ont abouti.111let acting = 0112let actionSeq = 0113let refreshDeferred = false114/** Relit la liste depuis le début, sur la longueur déjà affichée, sans la vider (nouveau courrier, action, retour d'onglet). */115export async function refreshUnified(): Promise<void> {116  const u = U.get()117  if (u.view === "scheduled") return loadScheduled()118  if (!u.list.key || u.loading) return119  if (acting) {120    refreshDeferred = true121    return122  }123  if (refreshing) {124    refreshAgain = true125    return126  }127  refreshing = true128  const my = gen129  const seq = actionSeq130  const view = u.view131  const key = u.list.key132  const want = Math.min(300, Math.max(UNIFIED_PAGE, u.list.rows.length))133  try {134    let list = emptyUnified(key)135    let cursor: string | null = null136    for (let guard = 0; guard < 8; guard++) {137      const page: V1Page<V1Message> = await fetchPage(view, subsetAddresses(), cursor, Math.min(100, Math.max(UNIFIED_PAGE, want - list.rows.length)))138      if (my !== gen) return139      list = appendPage(list, key, page, view, guard === 0)140      cursor = list.cursor141      if (!cursor || list.rows.length >= want) break142    }143    if (my !== gen) return144    if (seq !== actionSeq || acting) {145      // une action a eu lieu pendant la lecture : résultat périmé, relecture dès qu'elle a abouti146      if (acting) refreshDeferred = true147      else refreshAgain = true148      return149    }150    U.set((x) => {151      const ids = new Set(list.rows.map((m) => m.id))152      return { list, error: null, selected: new Set([...x.selected].filter((id) => ids.has(id))), cursor: x.cursor && ids.has(x.cursor) ? x.cursor : null }153    })154    void enrichKeywords()155  } catch (e) {156    if (my === gen && U.get().list.rows.length === 0) U.set({ error: errorKind(e) })157  } finally {158    refreshing = false159    if (refreshAgain) {160      refreshAgain = false161      void refreshUnified()162    }163  }164}165166// ---------------------------------------------------------------- mots-clés des lignes (épingle, libellés, veille, suivi)167/** Lignes groupées par boîte, avec leur identifiant JMAP (une ligne dont l'identifiant est illisible est écartée). */168export function unifiedGroups(ids: readonly string[]): { mailboxId: string; emailIds: string[]; rowIds: string[] }[] {169  const out = new Map<string, { mailboxId: string; emailIds: string[]; rowIds: string[] }>()170  for (const id of ids) {171    const d = decodeV1Id(id, "msg")172    if (!d) continue173    let g = out.get(d.mailboxId)174    if (!g) out.set(d.mailboxId, (g = { mailboxId: d.mailboxId, emailIds: [], rowIds: [] }))175    g.emailIds.push(d.jmapId)176    g.rowIds.push(id)177  }178  return [...out.values()]179}180/** Mots-clés d'une ligne : ceux lus par JMAP, à défaut ceux de /api/v1 (libellés seulement). */181export const rowKeywords = (m: Pick<V1Message, "labels" | "pinned" | "snoozed" | "followup">, kw: Record<string, boolean> | undefined): Record<string, boolean> =>182  kw ?? { ...Object.fromEntries(m.labels.map((k) => [k, true])), ...(m.pinned ? { $pinned: true } : {}), ...(m.snoozed ? { $snoozed: true } : {}), ...(m.followup ? { $followup: true } : {}) }183/** L'API rend-elle elle-même épingle, veille et suivi ? Alors aucune lecture JMAP par boîte n'est nécessaire. */184const flagsFromApi = (rows: readonly V1Message[]): boolean => rows.every((m) => typeof m.pinned === "boolean" && typeof m.snoozed === "boolean" && typeof m.followup === "boolean")185let kwGen = 0186/** Une requête Email/get par boîte (quatre de front au plus) ; une réponse dépassée par une lecture plus récente est ignorée. */187async function enrichKeywords(): Promise<void> {188  const my = ++kwGen189  if (flagsFromApi(U.get().list.rows)) {190    // les lignes portent déjà leurs mots-clés : les valeurs lues à part auparavant ne doivent pas masquer celles de l'API191    if (Object.keys(U.get().kw).length) U.set({ kw: {} })192    return193  }194  const groups = unifiedGroups(U.get().list.rows.map((m) => m.id)).filter((g) => hasClient(g.mailboxId))195  const found: Record<string, Record<string, boolean>> = {}196  await mapLimit(groups, 4, async (g) => {197    const r = await clientFor(g.mailboxId).call("Email/get", { ids: g.emailIds.slice(0, 500), properties: ["id", "keywords"] })198    const byId = new Map((r.list as { id: string; keywords?: Record<string, boolean> }[]).map((e) => [e.id, e.keywords ?? {}]))199    g.emailIds.forEach((jmapId, i) => {200      const k = byId.get(jmapId)201      if (k) found[g.rowIds[i]] = k202    })203  })204  if (my !== kwGen) return205  U.set((u) => {206    const kw: Record<string, Record<string, boolean>> = {}207    for (const m of u.list.rows) {208      const k = found[m.id] ?? u.kw[m.id]209      if (k) kw[m.id] = k210    }211    return { kw }212  })213}214/** Lignes (identifiants /api/v1) de messages d'une boîte désignés par leur identifiant JMAP. */215function rowsOf(mailboxId: string, emailIds: readonly string[]): string[] {216  const set = new Set(emailIds)217  return unifiedGroups(U.get().list.rows.map((m) => m.id)).filter((g) => g.mailboxId === mailboxId).flatMap((g) => g.rowIds.filter((_, i) => set.has(g.emailIds[i])))218}219/** Modules « Next » : un mot-clé vient d'être posé ou retiré par JMAP (libellé) — les lignes concernées le reflètent tout de suite. */220export function patchUnifiedKeyword(mailboxId: string, emailIds: readonly string[], keyword: string, on: boolean) {221  const ids = new Set(rowsOf(mailboxId, emailIds))222  if (!ids.size) return223  kwGen++ // une lecture en vol rendrait l'état d'avant224  U.set((u) => {225    const kw = { ...u.kw }226    const rows = u.list.rows.map((m) => {227      if (!ids.has(m.id)) return m228      const next = { ...rowKeywords(m, u.kw[m.id]) }229      if (on) next[keyword] = true230      else delete next[keyword]231      const flag = keyword === "$pinned" ? "pinned" : keyword === "$snoozed" ? "snoozed" : keyword === "$followup" ? "followup" : null232      // la ligne porte elle-même le libellé (ou l'épingle, quand l'API la rend) ; la lecture JMAP à part, si elle existe, suit233      const own = (flag && typeof m[flag] === "boolean") || !keyword.startsWith("$")234      if (!own || u.kw[m.id]) kw[m.id] = next235      if (flag && typeof m[flag] === "boolean") return { ...m, [flag]: on }236      return keyword.startsWith("$") ? m : { ...m, labels: on ? [...new Set([...m.labels, keyword])].sort() : m.labels.filter((k) => k !== keyword) }237    })238    return { kw, list: { ...u.list, rows } }239  })240  // une écriture en file (hors ligne) n'est pas encore sur le serveur : relire maintenant rendrait l'état d'avant241  if (S.get().online && !S.get().sync.queued) void enrichKeywords()242}243/** Lignes de « Toutes les boîtes » pour des groupes (boîte, identifiants JMAP). */244export const unifiedRowIds = (groups: readonly { mailboxId: string; emailIds: readonly string[] }[]): string[] => groups.flatMap((g) => rowsOf(g.mailboxId, g.emailIds))245/**246 * Épingle ou désépingle des lignes : écran tout de suite, écriture par la file durable de chaque boîte (hors ligne, elle attend247 * et compte dans « N en attente ») ; un refus du serveur remet les lignes.248 */249export async function setPinnedRows(ids: string[], on: boolean): Promise<void> {250  const groups = unifiedGroups(ids)251  if (!groups.length) return252  for (const g of groups) patchUnifiedKeyword(g.mailboxId, g.emailIds, "$pinned", on)253  const results = await mapLimit(groups, BULK_CONCURRENCY, (g) => setKeywordIn(g.mailboxId, g.emailIds, "$pinned", on))254  const failed = results.find((r) => r.status === "rejected") as PromiseRejectedResult | undefined255  if (failed) {256    toast({ kind: "error", text: t("error.actionFailed"), detail: errorDetail(failed.reason) || undefined })257    return void refreshUnified()258  }259  toast({ kind: "success", text: on ? t("toast.pinned") : t("toast.unpinned") })260}261/** Vrai si toutes ces lignes sont épinglées. */262export const rowsPinned = (ids: readonly string[]): boolean => {263  const u = U.get()264  const rows = u.list.rows.filter((m) => ids.includes(m.id))265  return rows.length > 0 && rows.every((m) => !!rowKeywords(m, u.kw[m.id]).$pinned)266}267/** Modules « Next » : des messages quittent la vue (mise en veille) — leurs lignes disparaissent tout de suite. */268export function dropUnifiedMessages(mailboxId: string, emailIds: readonly string[]) {269  const ids = rowsOf(mailboxId, emailIds)270  if (ids.length) dropRows(ids)271}272273// ---------------------------------------------------------------- synchronisation (événements d'état des boîtes)274let stop: (() => void) | null = null275let timer: ReturnType<typeof setTimeout> | undefined276const stateSig = (s: AppState) => {277  const ids = subsetIds(s)278  return (s.me?.mailboxes ?? []).filter((m) => !ids.length || ids.includes(m.id)).map((m) => `${m.id}:${s.accounts[m.id]?.emailState ?? ""}`).join("|")279}280/** La vue est affichée : toute boîte retenue dont l'état change (nouveau message, lecture, déplacement) relance une lecture. */281export function startUnifiedSync() {282  stop?.()283  let prevSig = stateSig(S.get())284  let prevSubset = subsetAddresses().join(",")285  let prevOpen = !!S.get().open286  const schedule = (ms: number) => {287    clearTimeout(timer)288    timer = setTimeout(() => void refreshUnified(), ms)289  }290  const unsub = S.subscribe(() => {291    const s = S.get()292    if (!s.all) return293    const subset = subsetAddresses(s).join(",")294    if (subset !== prevSubset) {295      prevSubset = subset296      prevSig = stateSig(s)297      openUnified(U.get().view)298      return299    }300    const sig = stateSig(s)301    const open = !!s.open302    if (sig !== prevSig) schedule(300)303    else if (prevOpen && !open) schedule(450) // retour du lecteur : une action a pu y sortir le message de la vue304    prevSig = sig305    prevOpen = open306  })307  const onVisible = () => document.visibilityState === "visible" && schedule(200)308  document.addEventListener("visibilitychange", onVisible)309  stop = () => {310    unsub()311    clearTimeout(timer)312    document.removeEventListener("visibilitychange", onVisible)313    stop = null314  }315  return () => stop?.()316}317318// ---------------------------------------------------------------- sélection et curseur319export const rowById = (id: string): V1Message | undefined => U.get().list.rows.find((m) => m.id === id)320export function toggleSelected(id: string, range = false) {321  U.set((u) => {322    const next = new Set(u.selected)323    const ids = u.list.rows.map((m) => m.id)324    if (range && u.cursor && u.cursor !== id) {325      const a = ids.indexOf(u.cursor)326      const b = ids.indexOf(id)327      if (a >= 0 && b >= 0) for (let i = Math.min(a, b); i <= Math.max(a, b); i++) next.add(ids[i])328    } else if (next.has(id)) next.delete(id)329    else next.add(id)330    return { selected: next, cursor: id }331  })332}333export const selectAllRows = (on: boolean) => U.set((u) => ({ selected: on ? new Set(u.list.rows.map((m) => m.id)) : new Set() }))334export function moveUnifiedCursor(delta: number): string | null {335  const u = U.get()336  const ids = u.list.rows.map((m) => m.id)337  if (!ids.length) return null338  let i = u.cursor ? ids.indexOf(u.cursor) : -1339  i = Math.max(0, Math.min(ids.length - 1, i < 0 ? (delta > 0 ? 0 : ids.length - 1) : i + delta))340  U.set({ cursor: ids[i] })341  if (i >= ids.length - 5) void loadMore()342  return ids[i]343}344/** Cibles d'une action : la sélection, sinon la ligne sous le curseur. */345export function unifiedTargets(): string[] {346  const u = U.get()347  return u.selected.size ? [...u.selected] : u.cursor ? [u.cursor] : []348}349350// ---------------------------------------------------------------- ouverture351export function openUnifiedRow(id: string) {352  const m = rowById(id)353  const me = S.get().me354  if (!m || !me) return355  U.set({ cursor: id })356  const thread = decodeV1Id(m.thread_id, "thr")357  const message = decodeV1Id(m.id, "msg")358  const mbIndex = thread ? me.mailboxes.findIndex((b) => b.id === thread.mailboxId) : -1359  if (!thread || !message || mbIndex < 0) return void toast({ kind: "error", text: t("unified.cannotOpen") })360  const view = U.get().view361  if (m.draft || view === "drafts") {362    // un brouillon se rouvre dans la rédaction, depuis sa boîte363    enterMailbox(thread.mailboxId, "drafts")364    void composeFromDraft(message.jmapId)365    return366  }367  if (m.unread) patchRows([id], { unread: false }) // le lecteur marque le fil comme lu à l'ouverture368  navigate(routeHref({ name: "mail", all: true, mbIndex, view, threadId: thread.jmapId, q: "" }))369}370371// ---------------------------------------------------------------- actions372function patchRows(ids: string[], patch: Partial<V1Message>) {373  const set = new Set(ids)374  U.set((u) => ({ list: { ...u.list, rows: u.list.rows.map((m) => (set.has(m.id) ? { ...m, ...patch } : m)) } }))375}376function dropRows(ids: string[]) {377  const set = new Set(ids)378  U.set((u) => {379    const rows = u.list.rows.filter((m) => !set.has(m.id))380    let cursor = u.cursor381    if (cursor && set.has(cursor)) {382      const at = u.list.rows.findIndex((m) => m.id === cursor)383      cursor = rows[Math.min(at, rows.length - 1)]?.id ?? null384    }385    return { list: { ...u.list, rows }, selected: new Set([...u.selected].filter((id) => !set.has(id))), cursor }386  })387}388/** Appels par message en vol en même temps, au plus (une sélection de 300 lignes ne lance pas 300 requêtes de front). */389export const BULK_CONCURRENCY = 4390/** Applique un appel par message ; en cas d'échec, la liste est relue (l'écran revient à la vérité du serveur). */391async function each(ids: string[], call: (id: string) => Promise<unknown>): Promise<boolean> {392  acting++393  actionSeq++394  const results = await mapLimit(ids, BULK_CONCURRENCY, (id) => call(id)).finally(() => {395    acting--396    if (!acting && refreshDeferred) {397      refreshDeferred = false398      void refreshUnified()399    }400  })401  const failed = results.find((r) => r.status === "rejected") as PromiseRejectedResult | undefined402  if (!failed) return true403  if (errorKind(failed.reason) !== "unauthorized") toast({ kind: "error", text: t("error.actionFailed"), detail: errorDetail(failed.reason) || undefined })404  void refreshUnified()405  return false406}407const enc = encodeURIComponent408409export async function setRead(ids: string[], read: boolean) {410  if (!ids.length) return411  if (U.get().view === "unread" && read) dropRows(ids)412  else patchRows(ids, { unread: !read })413  await each(ids, (id) => v1(`/messages/${enc(id)}`, { method: "PATCH", json: { unread: !read } }))414}415export async function setStarred(ids: string[], on: boolean) {416  if (!ids.length) return417  if (U.get().view === "starred" && !on) dropRows(ids)418  else patchRows(ids, { starred: on })419  await each(ids, (id) => v1(`/messages/${enc(id)}`, { method: "PATCH", json: { starred: on } }))420}421/** Archive ou met à la corbeille ; « Annuler » remet les messages dans leur dossier d'origine. */422export async function moveRows(ids: string[], folder: "archive" | "trash") {423  if (!ids.length) return424  const u = U.get()425  const rows = u.list.rows.filter((m) => ids.includes(m.id))426  // des favoris archivés restent des favoris : ils ne quittent pas la vue427  if (!(u.view === "starred" && folder === "archive")) dropRows(ids)428  if (!(await each(ids, (id) => v1(`/messages/${enc(id)}/move`, { method: "POST", json: { folder } })))) return429  const back = (m: V1Message) => m.folders.find((f) => f.role && f.role !== folder)?.role ?? m.folders[0]?.id ?? "inbox"430  toast({431    kind: "success", text: folder === "archive" ? t("toast.archived", { n: ids.length }) : t("toast.trashed", { n: ids.length }), actionLabel: t("action.undo"),432    action: () => {433      void each(rows.map((m) => m.id), (id) => v1(`/messages/${enc(id)}/move`, { method: "POST", json: { folder: back(rows.find((m) => m.id === id)!) } })).then((ok) => {434        if (ok) toast({ kind: "info", text: t("toast.undone") })435        void refreshUnified()436      })437    },438  })439}440441// ---------------------------------------------------------------- messages programmés442export async function loadScheduled() {443  const my = ++gen444  U.set((u) => ({ loading: u.scheduled === null, error: null }))445  try {446    const r = await v1<{ data: Outbound[] }>("/messages/scheduled")447    if (my !== gen) return448    const items: ScheduledItem[] = [...r.data].sort((a, b) => Date.parse(a.send_at ?? a.created_at) - Date.parse(b.send_at ?? b.created_at))449    const known = new Map((U.get().scheduled ?? []).map((x) => [x.id, x.subject]))450    U.set({ scheduled: items.map((x) => ({ ...x, subject: known.get(x.id) })), loading: false })451    // l'objet n'est pas copié dans le suivi : il est lu sur le brouillon conservé jusqu'à l'envoi452    for (const item of items.slice(0, 50)) {453      if (!item.message_id || known.get(item.id) !== undefined) continue454      void v1<{ subject: string }>(`/messages/${enc(item.message_id)}`).then(455        (m) => U.set((u) => ({ scheduled: u.scheduled?.map((x) => (x.id === item.id ? { ...x, subject: m.subject ?? "" } : x)) ?? null })),456        () => {},457      )458    }459  } catch (e) {460    if (my === gen) U.set({ loading: false, error: errorKind(e) })461  }462}463export async function cancelScheduled(id: string): Promise<boolean> {464  try {465    await v1(`/messages/scheduled/${enc(id)}`, { method: "DELETE" })466    U.set((u) => ({ scheduled: u.scheduled?.filter((x) => x.id !== id) ?? null }))467    toast({ kind: "success", text: t("unified.scheduled.cancelled") })468    return true469  } catch (e) {470    // déjà parti ou déjà annulé : la liste est relue471    toast({ kind: "error", text: (e instanceof HttpError && e.code === "not_cancellable") || errorKind(e) === "conflict" ? t("unified.scheduled.tooLate") : t("error.actionFailed"), detail: errorDetail(e) || undefined })472    void loadScheduled()473    return false474  }475}476477export { MAILBOX_VIEW }478
Files main
Menu

Theme