SPB Git

Repository Public

labelsUi.ts 5.8 KB 103 lines typescript

1// SP Mail Next — libellés, côté interface : état des dialogues (sélecteur, édition, gestion), application d'un libellé à des2// conversations par la mécanique optimiste de state/mail.ts, ouverture de la recherche `label:`.3import { t } from "../i18n"4import { errorDetail } from "../jmap/errors"5import { S, toast } from "../state/app"6import { setKeyword, setKeywordIn } from "../state/mail"7import { navigate } from "../state/session"8import { createStore } from "../state/store"9import { confirmAsync } from "../ui/kit"10import { deleteLabel, labelsCollection, moveLabel, type Label } from "./labels"11import { operator, searchHref } from "./nav"12import { currentMsgTargets, type Targets } from "./rowmenu"1314export interface LabelUiState {15  /** sélecteur de libellés ouvert sur ces cibles ; `keywords` : mots-clés de chaque conversation à l'ouverture */16  picker: { targets: Targets; keywords: Record<string, boolean>[] } | null17  /** création (`label` nul) ou modification ; `applyTo` : appliquer le libellé créé à ces cibles */18  edit: { label: Label | null; name: string; applyTo: Targets | null } | null19  manage: boolean20}21export const LabelUi = createStore<LabelUiState>({ picker: null, edit: null, manage: false })2223export const labelHref = (label: Pick<Label, "name">): string => searchHref(operator("label", label.name))24export const openLabelSearch = (label: Pick<Label, "name">) => navigate(labelHref(label))2526/** Mots-clés actuels des conversations visées (une entrée par conversation connue). */27async function keywordsOf(targets: Targets): Promise<Record<string, boolean>[]> {28  if (targets.unified) {29    const u = await import("../state/unified")30    const rows = u.U.get()31    const out: Record<string, boolean>[] = []32    for (const m of rows.list.rows) {33      const g = u.unifiedGroups([m.id])[0]34      if (g && targets.groups.some((x) => x.mailboxId === g.mailboxId && x.emailIds.includes(g.emailIds[0]))) out.push(u.rowKeywords(m, rows.kw[m.id]))35    }36    return out37  }38  const s = S.get()39  const all = targets.groups.flatMap((g) => g.emailIds).map((id) => (s.emails[id] ?? s.open?.emails[id])?.keywords).filter((k): k is Record<string, boolean> => !!k)40  // fil ouvert : un libellé porté par un seul message du fil est un libellé de la conversation41  return targets.exact && all.length ? [Object.assign({}, ...all) as Record<string, boolean>] : all42}4344export async function openLabelPicker(targets: Targets | null) {45  if (!targets || !targets.groups.length) return46  void labelsCollection.refresh()47  const keywords = await keywordsOf(targets)48  LabelUi.set({ picker: { targets, keywords }, edit: null, manage: false })49}50export const openLabelPickerForCurrent = async () => openLabelPicker(await currentMsgTargets())51export const openLabelCreate = (name = "", applyTo: Targets | null = null) => LabelUi.set({ edit: { label: null, name, applyTo } })52export const openLabelEdit = (label: Label) => LabelUi.set({ edit: { label, name: label.name, applyTo: null } })53export const openLabelManage = () => {54  void labelsCollection.refresh()55  LabelUi.set({ manage: true, picker: null })56}57export const closeLabelUi = (key: keyof LabelUiState) => LabelUi.set({ [key]: key === "manage" ? false : null } as Partial<LabelUiState>)5859/**60 * Pose ou retire un libellé sur des conversations. Dans la boîte affichée, c'est la mécanique optimiste commune (écran61 * immédiat, retour en arrière si le serveur refuse) ; ailleurs (« Toutes les boîtes »), un Email/set puis la ligne est ajustée.62 */63export function applyLabel(label: Label, on: boolean, targets: Targets, announce = false): Promise<boolean> {64  // une écriture à la fois : cocher puis décocher très vite ne doit pas arriver au serveur dans le désordre65  const run = queue.then(() => applyNow(label, on, targets, announce))66  queue = run.then(() => undefined, () => undefined)67  return run68}69let queue: Promise<void> = Promise.resolve()70async function applyNow(label: Label, on: boolean, targets: Targets, announce: boolean): Promise<boolean> {71  let ok = true72  for (const g of targets.groups) {73    if (!g.emailIds.length) continue74    const s = S.get()75    try {76      if (!targets.unified && g.mailboxId === s.mb) await setKeyword(g.emailIds, label.keyword, on, { wholeThread: !targets.exact })77      else await setKeywordIn(g.mailboxId, g.emailIds, label.keyword, on)78      if (S.get().all) (await import("../state/unified")).patchUnifiedKeyword(g.mailboxId, g.emailIds, label.keyword, on)79    } catch (e) {80      ok = false81      toast({ kind: "error", text: S.get().online ? t("nx.labels.err.apply") : t("nx.offline"), detail: errorDetail(e) || undefined })82    }83  }84  if (ok && announce) toast({ kind: "success", text: t(on ? "nx.labels.applied" : "nx.labels.removed", { name: label.name }) })85  return ok86}8788// ---------------------------------------------------------------- gestion (menu de la barre latérale et dialogue)89const writeFailed = () => toast({ kind: "error", text: S.get().online ? t("nx.labels.err.failed") : t("nx.offline") })90export async function confirmDeleteLabel(label: Label) {91  if (!(await confirmAsync({ title: t("nx.labels.deleteTitle", { name: label.name }), body: t("nx.labels.deleteBody"), confirmLabel: t("nx.labels.delete"), danger: true }))) return92  if (await deleteLabel(label.id)) toast({ kind: "success", text: t("nx.labels.deleted", { name: label.name }) })93  else writeFailed()94}95/** Monte ou descend un libellé ; rend la phrase à annoncer (« … déplacé en position n »), ou null si l'écriture a échoué. */96export async function moveLabelBy(label: Label, delta: number): Promise<string | null> {97  if (!(await moveLabel(label.id, delta))) {98    writeFailed()99    return null100  }101  return t("nx.labels.moved", { name: label.name, n: labelsCollection.store.get().items.findIndex((l) => l.id === label.id) + 1 })102}103
Files main
Menu

Theme