SPB Git

Repository Public

next-shell.spec.ts 57.2 KB 923 lines typescript

1// Coquille « SP Mail Next » : thèmes (clair, sombre, minuit), volets redimensionnables, barre réduite, palette de commandes,2// dispositions, mouvement réduit, téléphone (barre du bas, glissements), synchronisation sans relecture, brouillon gardé hors3// ligne, boîte retirée côté serveur, cache effacé à la perte de session. Captures dans /tmp/spmail-next-shots/web.4// Le fichier se suffit : lancé seul (--project=next --no-deps), il fait lui-même l'enrôlement ; après le parcours « desktop »,5// il reprend la clé d'accès exportée. Ses boîtes (web-n*-<run>) et leurs messages lui sont propres.6import AxeBuilder from "@axe-core/playwright"7import { expect, test, type Browser, type BrowserContext, type Page } from "@playwright/test"8import fs from "node:fs"9import { OUT, readState, writeState } from "./env"10import { addAuthenticator, exportCredential, importCredential, list, purgeLeftoverMailboxes, row, signIn, toastText, track } from "./helpers"1112test.describe.configure({ mode: "serial" })1314const SHOTS = "/tmp/spmail-next-shots/web"15const st = readState()16const N1 = `web-n1-${st.run}@stg.spboucher.ai`17const N2 = `web-n2-${st.run}@stg.spboucher.ai`18const N3 = `web-n3-${st.run}@stg.spboucher.ai`19const THEMES = [["light", "Clair"], ["dark", "Sombre"], ["midnight", "Minuit"]] as const2021let context: BrowserContext22let page: Page23let storage: Awaited<ReturnType<BrowserContext["storageState"]>>24const consoleErrors: string[] = []2526async function axe(p: Page, name: string) {27  const r = await new AxeBuilder({ page: p }).withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"]).exclude(".html-frame iframe").exclude(".html-measure").analyze()28  const bad = r.violations.filter((v) => v.impact === "serious" || v.impact === "critical")29  fs.appendFileSync(`${OUT}/axe.log`, `next-${name}: ${r.violations.length} violation(s), ${bad.length} serious/critical, ${r.passes.length} passes\n${bad.map((v) => `  ${v.id}: ${v.nodes.map((n) => n.target.join(" ")).join(" | ")}`).join("\n")}\n`)30  expect(bad.map((v) => `${v.id}: ${v.nodes.map((n) => n.target.join(" ")).slice(0, 4).join(" | ")}`), `axe ${name}`).toEqual([])31}32const shot = (p: Page, name: string) => p.screenshot({ path: `${SHOTS}/${name}.png` })3334/** Appel d'API authentifié depuis la page (cookie de session, en-tête anti-CSRF). */35async function api<T>(p: Page, method: string, url: string, body?: unknown): Promise<T> {36  return p.evaluate(37    async ({ method, url, body }) => {38      const r = await fetch(url, { method, headers: { "x-spmail": "1", ...(body === undefined ? {} : { "content-type": "application/json" }) }, body: body === undefined ? undefined : JSON.stringify(body) })39      if (!r.ok) throw new Error(`${method} ${url} → ${r.status} ${await r.text()}`)40      return r.json()41    },42    { method, url, body },43  ) as Promise<T>44}45interface Seed {46  subject: string47  from: [string, string]48  preview: string49  keywords?: string[]50  html?: string51  folder?: "inbox" | "trash"52  messageId?: string53  references?: string54  minutesAgo: number55}56/** Dépose des messages directement dans une boîte (aucun envoi) ; rend leurs identifiants JMAP, dans l'ordre. */57async function seed(p: Page, address: string, seeds: Seed[]): Promise<string[]> {58  return p.evaluate(59    async ({ address, seeds }) => {60      const me = await (await fetch("/api/me")).json()61      const mb = me.mailboxes.find((m: { address: string }) => m.address === address).id62      const session = await (await fetch(`/api/jmap/${mb}/session`)).json()63      const accountId = session.primaryAccounts["urn:ietf:params:jmap:mail"]64      const call = async (methodCalls: unknown[]) => (await (await fetch(`/api/jmap/${mb}/api`, { method: "POST", headers: { "content-type": "application/json", "x-spmail": "1" }, body: JSON.stringify({ using: ["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail"], methodCalls }) })).json()).methodResponses65      const boxes = (await call([["Mailbox/get", { accountId, properties: ["role"] }, "m"]]))[0][1].list as { id: string; role: string }[]66      const create: Record<string, unknown> = {}67      seeds.forEach((s, i) => {68        const folder = boxes.find((b) => b.role === (s.folder ?? "inbox"))!.id69        create[`e${i}`] = {70          mailboxIds: { [folder]: true }, keywords: Object.fromEntries((s.keywords ?? []).map((k) => [k, true])), from: [{ name: s.from[0], email: s.from[1] }], to: [{ email: address }], subject: s.subject,71          receivedAt: new Date(Date.now() - s.minutesAgo * 60_000).toISOString().replace(/\.\d+Z$/, "Z"),72          ...(s.messageId ? { messageId: [s.messageId] } : {}), ...(s.references ? { references: [s.references], inReplyTo: [s.references] } : {}),73          ...(s.html ? { bodyValues: { h: { value: s.html } }, htmlBody: [{ partId: "h", type: "text/html" }] } : { bodyValues: { t: { value: s.preview } }, textBody: [{ partId: "t", type: "text/plain" }] }),74        }75      })76      const r = (await call([["Email/set", { accountId, create }, "c"]]))[0][1]77      if (r.notCreated && Object.keys(r.notCreated).length) throw new Error(JSON.stringify(r.notCreated))78      return seeds.map((_, i) => r.created[`e${i}`].id as string)79    },80    { address, seeds },81  )82}83/** Modifie des mots-clés par JMAP, comme le ferait un autre appareil. */84async function setKeyword(p: Page, address: string, emailId: string, keyword: string, on: boolean) {85  await p.evaluate(86    async ({ address, emailId, keyword, on }) => {87      const me = await (await fetch("/api/me")).json()88      const mb = me.mailboxes.find((m: { address: string }) => m.address === address).id89      const session = await (await fetch(`/api/jmap/${mb}/session`)).json()90      const accountId = session.primaryAccounts["urn:ietf:params:jmap:mail"]91      const r = await fetch(`/api/jmap/${mb}/api`, { method: "POST", headers: { "content-type": "application/json", "x-spmail": "1" }, body: JSON.stringify({ using: ["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail"], methodCalls: [["Email/set", { accountId, update: { [emailId]: { [`keywords/${keyword}`]: on ? true : null } } }, "u"]] }) })92      if (!r.ok) throw new Error(`Email/set → ${r.status}`)93    },94    { address, emailId, keyword, on },95  )96}97const mailboxId = (p: Page, address: string) => p.evaluate(async (address) => ((await (await fetch("/api/me")).json()).mailboxes as { id: string; address: string }[]).find((m) => m.address === address)?.id ?? null, address)98/** Rend la boîte courante (lien de la barre latérale si elle ne l'est pas déjà). */99async function openBox(p: Page, address: string) {100  await p.getByRole("link", { name: address }).or(p.getByRole("heading", { level: 2, name: address })).first().waitFor()101  if (await p.getByRole("link", { name: address }).count()) await p.getByRole("link", { name: address }).click()102  await expect(p.getByRole("heading", { level: 2, name: address })).toBeVisible()103  await expect(p.getByRole("heading", { level: 1, name: "Boîte de réception" })).toBeVisible()104}105/** Change de thème par la palette de commandes : aucun rechargement, la page affichée reste en place. */106async function setTheme(p: Page, label: string, theme: string) {107  await palette(p, `>theme ${label}`, `Thème : ${label}`)108  await expect(p.locator("html")).toHaveAttribute("data-theme", theme)109}110/** Réglages › Apparence, par les liens de l'application (« Courrier » ramène ensuite à la boîte affichée). */111async function openAppearance(p: Page) {112  await p.getByRole("link", { name: "Réglages" }).click()113  await p.getByRole("link", { name: "Apparence" }).click()114  await expect(p.getByRole("heading", { level: 2, name: "Apparence" })).toBeVisible()115}116/** Lance une commande par la palette (Ctrl+K, saisie, Entrée). */117async function palette(p: Page, query: string, expected: string | RegExp) {118  await p.keyboard.press("Control+k")119  const dlg = p.getByRole("dialog", { name: "Palette de commandes" })120  await expect(dlg).toBeVisible()121  await dlg.getByRole("combobox").fill(query)122  await expect(dlg.getByRole("option").first()).toHaveText(expected)123  await p.keyboard.press("Enter")124  await expect(dlg).toHaveCount(0)125}126async function fromStorage(browser: Browser, viewport: { width: number; height: number }, touch = false) {127  const ctx = await browser.newContext({ viewport, locale: "fr-CA", timezoneId: "America/Toronto", storageState: storage, ...(touch ? { isMobile: true, hasTouch: true, deviceScaleFactor: 2 } : {}) })128  return { ctx, p: await ctx.newPage() }129}130/** Glissement au doigt (vrais événements tactiles, par le protocole du navigateur). */131async function swipe(p: Page, ctx: BrowserContext, from: { x: number; y: number }, dx: number) {132  const cdp = await ctx.newCDPSession(p)133  await cdp.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [{ x: from.x, y: from.y }] })134  const steps = 8135  for (let i = 1; i <= steps; i++) {136    await cdp.send("Input.dispatchTouchEvent", { type: "touchMove", touchPoints: [{ x: from.x + (dx * i) / steps, y: from.y }] })137    await p.waitForTimeout(16)138  }139  const stage = await p.locator(".mrow.swiping").getAttribute("data-swipe")140  await cdp.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] })141  await cdp.detach()142  return stage143}144145test.beforeAll(async ({ browser }) => {146  fs.mkdirSync(SHOTS, { recursive: true })147  context = await browser.newContext({ viewport: { width: 1440, height: 900 }, locale: "fr-CA", timezoneId: "America/Toronto" })148  page = await context.newPage()149  page.on("console", (m) => {150    if (m.type() === "error") consoleErrors.push(m.text())151  })152  page.on("pageerror", (e) => consoleErrors.push(`pageerror: ${e.message}`))153  const authn = await addAuthenticator(context, page)154  if (readState().credential) {155    await importCredential(authn, 2000)156    await signIn(page)157  } else {158    // lancé seul : premier enrôlement de l'installation159    await page.goto(st.enrollUrl)160    await page.getByLabel("Nom affiché").fill("Propriétaire Essai")161    await page.getByLabel("Identifiant").fill("owner")162    await page.getByRole("button", { name: "Créer la clé d'accès" }).click()163    await expect(page.locator("#sidebar")).toBeAttached()164    await exportCredential(authn)165  }166  await purgeLeftoverMailboxes(page)167  track(N1, N2, N3)168  for (const [address, name] of [[N1, "Next Un"], [N2, "Next Deux"]]) await api(page, "POST", "/api/admin/mailboxes", { address, display_name: name })169  await seed(page, N1, [170    { subject: `Compte rendu du comité ${st.run}`, from: ["Camille Roy", "camille.roy@example.org"], preview: "Bonjour, voici le compte rendu de la rencontre de mardi, avec les décisions prises et les suites à donner d'ici la fin du mois.", minutesAgo: 2 },171    { subject: `Infolettre ${st.run}`, from: ["Atelier Nord", "bonjour@atelier-nord.example"], preview: "", html: `<div style="font-family:Georgia,serif;max-width:560px"><h1 style="color:#2c5b4d">Atelier Nord</h1><p>Les nouveautés de l'automne sont arrivées : papiers, encres et carnets cousus main.</p><p><a href="https://atelier-nord.example/automne">Voir la collection</a></p><table style="width:100%;background:#f3efe6"><tr><td style="padding:12px">Livraison offerte dès 60 $ d'achat.</td></tr></table></div>`, minutesAgo: 9 },172    { subject: `Facture de novembre ${st.run}`, from: ["Hydro Estrie", "factures@hydro-estrie.example"], preview: "Votre facture du mois de novembre est disponible. Montant : 84,12 $. Échéance : le 5 décembre.", keywords: ["$seen"], minutesAgo: 40 },173    { subject: `Souper de vendredi ${st.run}`, from: ["Léa Tremblay", "lea@example.org"], preview: "On se retrouve à 18 h 30 chez Marco ? Dis-moi si tu apportes le dessert.", keywords: ["$flagged"], minutesAgo: 75 },174    { subject: `Épinglé : accès au stationnement ${st.run}`, from: ["Gestion Immeuble", "gestion@immeuble.example"], preview: "Le code de la barrière change le 1er décembre. Conservez ce message.", keywords: ["$seen", "$pinned"], minutesAgo: 600 },175    { subject: `Fil ${st.run}`, from: ["Noah Gagnon", "noah@example.org"], preview: "Premier message du fil.", keywords: ["$seen"], messageId: `fil-1-${st.run}@example.org`, minutesAgo: 190 },176    { subject: `Re: Fil ${st.run}`, from: ["Zoé Martin", "zoe@example.org"], preview: "Deuxième message du fil.", keywords: ["$seen"], messageId: `fil-2-${st.run}@example.org`, references: `fil-1-${st.run}@example.org`, minutesAgo: 180 },177    { subject: `Re: Fil ${st.run}`, from: ["Noah Gagnon", "noah@example.org"], preview: "Troisième message, mis à la corbeille.", keywords: ["$seen"], folder: "trash", messageId: `fil-3-${st.run}@example.org`, references: `fil-1-${st.run}@example.org`, minutesAgo: 170 },178  ])179  await seed(page, N2, [{ subject: `Bienvenue ${st.run}`, from: ["Équipe SP Mail", "equipe@example.org"], preview: "Votre seconde boîte est prête.", minutesAgo: 5 }])180  await page.goto("/")181  await openBox(page, N1)182  storage = await context.storageState()183  writeState({ storage: JSON.stringify(storage) })184})185test.afterAll(async () => {186  fs.writeFileSync(`${OUT}/next-console-errors.log`, consoleErrors.join("\n"))187  // les boîtes créées ici sont détachées et leur courrier détruit (le démontage global purge aussi les comptes web-*)188  for (const address of [N1, N2, N3]) {189    const id = await mailboxId(page, address).catch(() => null)190    if (id) await api(page, "DELETE", `/api/admin/mailboxes/${id}?purge=delete-all-mail`).catch(() => {})191  }192  await context?.close()193})194195test("ligne en carte : pastille, aperçu, sélection et favori au pointeur ET pour les technologies d'assistance", async () => {196  const r = row(page, new RegExp(`Compte rendu du comité ${st.run}`))197  await expect(r).toBeVisible()198  await expect(r.locator(".mrow-avatar")).toHaveText("CR")199  await expect(r.locator(".dot")).toBeVisible()200  await expect(r.locator(".mrow-preview")).toContainText("voici le compte rendu")201  // pointeur : la pastille devient une case au survol ; le favori apparaît202  await r.hover()203  await expect(r.locator(".box")).toBeVisible()204  await expect(r.locator(".mrow-quick")).toBeVisible()205  await r.locator(".mrow-check").click()206  await expect(r).toHaveAttribute("aria-selected", "true")207  await expect(page.locator(".list-toolbar.selecting")).toContainText("1 sélectionnée")208  await page.getByRole("button", { name: "Désélectionner" }).click()209  await expect(r).toHaveAttribute("aria-selected", "false")210  await r.locator(".mrow-star").click()211  await expect(r.locator(".mrow-star.on")).toHaveCount(1)212  // technologies d'assistance : de vrais contrôles nommés, avec leur état, hors de la liste (rôle option = enfants de présentation)213  const check = page.getByRole("checkbox", { name: new RegExp(`Sélectionner la conversation : Compte rendu du comité ${st.run}`) })214  const star = page.getByRole("button", { name: new RegExp(`Favori : Compte rendu du comité ${st.run}`) })215  await expect(star).toHaveAttribute("aria-pressed", "true")216  await check.dispatchEvent("click")217  await expect(check).toBeChecked()218  await expect(r).toHaveAttribute("aria-selected", "true")219  await check.dispatchEvent("click")220  await expect(r).toHaveAttribute("aria-selected", "false")221  await star.dispatchEvent("click")222  await expect(star).toHaveAttribute("aria-pressed", "false")223  await expect(r.locator(".mrow-star.on")).toHaveCount(0)224  // épinglé en tête ; pastille de fil : seuls les messages que le lecteur montrera sont comptés (pas celui de la corbeille)225  await expect(list(page).getByRole("option").first()).toContainText("Épinglé : accès au stationnement")226  const thread = row(page, new RegExp(`Re: Fil ${st.run}`))227  await expect(thread.locator(".mrow-n")).toHaveText("2")228  await thread.click()229  await expect(page.locator("article.msg")).toHaveCount(2)230  await expect(page.locator(".reader-count")).toContainText("2 messages")231  // message antérieur replié : une ligne232  const collapsed = page.locator("article.msg:not(.expanded)")233  await expect(collapsed).toHaveCount(1)234  expect((await collapsed.boundingBox())!.height).toBeLessThanOrEqual(52)235  await page.getByRole("button", { name: "Retour à la liste" }).click()236})237238test("lecture : cadre isolé mesuré sans injecter le HTML dans la page ; lecture sombre", async () => {239  await row(page, new RegExp(`Infolettre ${st.run}`)).click()240  const frame = page.locator(".html-frame iframe")241  await expect(page.frameLocator(".html-frame iframe").locator("h1")).toHaveText("Atelier Nord")242  // le cadre visible garde son origine opaque et n'exécute rien ; le cadre de mesure est invisible, inerte et sans scripts243  expect(await frame.getAttribute("sandbox")).toBe("allow-popups allow-popups-to-escape-sandbox")244  const measure = page.locator("iframe.html-measure")245  expect(await measure.getAttribute("sandbox")).toBe("allow-same-origin")246  await expect(measure).toHaveAttribute("aria-hidden", "true")247  await expect(measure).toBeHidden()248  // plus aucune copie du message dans le document de l'application (ni racine fantôme, ni nœud .spm-root)249  const leaks = await page.evaluate(() => ({ spm: document.querySelectorAll(".spm-root, .spm-body").length, shadows: [...document.querySelectorAll("*")].filter((e) => e.shadowRoot).length, markup: [...document.querySelectorAll("h1, table, a")].filter((e) => /Atelier Nord|Livraison offerte|Voir la collection/.test(e.textContent ?? "") && !e.closest(".mrow")).length }))250  expect(leaks).toEqual({ spm: 0, shadows: 0, markup: 0 })251  // la hauteur du cadre visible suit celle du contenu mesuré252  const sizes = await page.evaluate(() => {253    const m = document.querySelector<HTMLIFrameElement>("iframe.html-measure")!254    const v = document.querySelector<HTMLIFrameElement>(".html-frame iframe")!255    return { content: Math.ceil(m.contentDocument!.querySelector(".spm-root")!.getBoundingClientRect().height), frame: v.getBoundingClientRect().height, scripts: m.contentDocument!.scripts.length, widths: [m.getBoundingClientRect().width, v.getBoundingClientRect().width] }256  })257  expect(sizes.content).toBeGreaterThan(100)258  expect(sizes.frame).toBe(sizes.content + 12)259  expect(sizes.scripts).toBe(0)260  expect(Math.abs(sizes.widths[0] - sizes.widths[1])).toBeLessThanOrEqual(1)261  // thème clair : pas de bouton « Lecture sombre »262  await expect(page.getByRole("button", { name: "Lecture sombre" })).toHaveCount(0)263  await page.getByRole("button", { name: "Retour à la liste" }).click()264})265266test("thèmes : minuit persiste ; clair, sombre et minuit passent axe (liste, lecture, palette, réglages)", async () => {267  await openAppearance(page)268  await page.getByRole("button", { name: "Minuit", exact: true }).click()269  await expect(page.locator("html")).toHaveAttribute("data-theme", "midnight")270  expect(await page.evaluate(() => getComputedStyle(document.body).backgroundColor)).toBe("rgb(0, 0, 0)")271  await page.reload()272  await expect(page.locator("html")).toHaveAttribute("data-theme", "midnight")273  await expect(page.getByRole("button", { name: "Minuit", exact: true })).toHaveAttribute("aria-pressed", "true")274  // choix propre à l'appareil (stockage local) ; proposé aussi comme thème de départ du compte275  expect(await page.evaluate(() => JSON.parse(localStorage.getItem("spmail.device") ?? "{}").theme)).toBe("midnight")276  await expect.poll(async () => (await api<{ user: { prefs: Record<string, unknown> } }>(page, "GET", "/api/me")).user.prefs.theme).toBe("midnight")277  await page.getByRole("link", { name: "Courrier" }).click()278  await openBox(page, N1)279  for (const [theme, label] of THEMES) {280    await setTheme(page, label, theme)281    await openAppearance(page)282    await axe(page, `settings-${theme}`)283    await shot(page, `desktop-${theme}-settings`)284    await page.getByRole("link", { name: "Courrier" }).click()285    await expect(row(page, new RegExp(`Infolettre ${st.run}`))).toBeVisible()286    await axe(page, `list-${theme}`)287    await shot(page, `desktop-${theme}-list`)288    await row(page, new RegExp(`Infolettre ${st.run}`)).click()289    await expect(page.frameLocator(".html-frame iframe").locator("h1")).toHaveText("Atelier Nord")290    await axe(page, `reader-${theme}`)291    await shot(page, `desktop-${theme}-reader`)292    if (theme !== "light") {293      // lecture sombre : filtre sur le cadre isolé, images ré-inversées dans le document du message294      await page.getByRole("button", { name: "Lecture sombre" }).click()295      await expect(page.locator(".html-frame.dark")).toHaveCount(1)296      expect(await page.locator(".html-frame iframe").evaluate((el) => getComputedStyle(el).filter)).toContain("invert")297      expect(await page.locator(".html-frame iframe").getAttribute("srcdoc")).toContain("filter:invert(1)")298      await shot(page, `desktop-${theme}-reader-dark-reading`)299      await page.getByRole("button", { name: "Lecture sombre" }).click()300      await expect(page.locator(".html-frame.dark")).toHaveCount(0)301    }302    await page.keyboard.press("Control+k")303    await expect(page.getByRole("dialog", { name: "Palette de commandes" })).toBeVisible()304    await axe(page, `palette-${theme}`)305    await shot(page, `desktop-${theme}-palette`)306    await page.keyboard.press("Escape")307    await page.getByRole("button", { name: "Retour à la liste" }).click()308    await row(page, new RegExp(`Compte rendu du comité ${st.run}`)).click({ modifiers: ["ControlOrMeta"] })309    await axe(page, `selection-${theme}`)310    await shot(page, `desktop-${theme}-selection`)311    await page.keyboard.press("Escape")312  }313  await setTheme(page, "Clair", "light")314})315316test("administration et studio de modèles : les jetons d'origine tiennent dans les trois thèmes (axe, captures)", async () => {317  for (const [theme, label] of THEMES) {318    await setTheme(page, label, theme)319    await page.getByRole("link", { name: "Administration" }).click()320    await expect(page.getByRole("heading", { name: "Administration", level: 1 })).toBeVisible()321    await expect(page.locator(".page-body .spinner")).toHaveCount(0, { timeout: 20_000 })322    await axe(page, `admin-overview-${theme}`)323    await shot(page, `desktop-${theme}-admin-overview`)324    await page.getByRole("link", { name: /Boîtes/ }).click()325    await expect(page.locator(`tr[data-address="${N1}"]`)).toBeVisible({ timeout: 20_000 })326    await axe(page, `admin-mailboxes-${theme}`)327    await shot(page, `desktop-${theme}-admin-mailboxes`)328    await page.getByRole("link", { name: "Courrier" }).click()329    await page.getByRole("link", { name: "Modèles" }).click()330    await expect(page.getByRole("heading", { level: 1 }).first()).toBeVisible()331    await page.waitForTimeout(600)332    await axe(page, `templates-${theme}`)333    await shot(page, `desktop-${theme}-templates`)334    await page.getByRole("link", { name: "Courrier" }).click()335    await expect(list(page)).toBeVisible()336  }337  await setTheme(page, "Clair", "light")338})339340test("séparateurs : glissement et clavier, taille conservée après rechargement, double-clic pour rétablir", async () => {341  const pane = page.locator("#list-pane")342  const sep = page.getByRole("separator", { name: "Largeur de la liste des messages" })343  const width = async () => Math.round((await pane.boundingBox())!.width)344  expect(await width()).toBe(400)345  await expect(sep).toHaveAttribute("aria-valuenow", "400")346  const box = (await sep.boundingBox())!347  await page.mouse.move(box.x + box.width / 2, box.y + 300)348  await page.mouse.down()349  await page.mouse.move(box.x + 50, box.y + 300, { steps: 4 })350  await page.mouse.move(box.x + 80.5, box.y + 300, { steps: 4 })351  await page.mouse.up()352  expect(await width()).toBe(480)353  await expect(sep).toHaveAttribute("aria-valuenow", "480")354  await sep.focus()355  await page.keyboard.press("ArrowLeft")356  await page.keyboard.press("ArrowLeft")357  expect(await width()).toBe(448)358  await page.keyboard.press("End")359  expect(await width()).toBe(560)360  await page.keyboard.press("Shift+ArrowLeft")361  expect(await width()).toBe(512)362  const side = page.getByRole("separator", { name: "Largeur de la barre latérale" })363  await side.focus()364  await page.keyboard.press("Home")365  expect(Math.round((await page.locator("#sidebar").boundingBox())!.width)).toBe(200)366  await page.reload()367  await expect(list(page)).toBeVisible()368  expect(await width()).toBe(512)369  expect(Math.round((await page.locator("#sidebar").boundingBox())!.width)).toBe(200)370  await expect(sep).toHaveAttribute("aria-valuenow", "512")371  await sep.dblclick()372  expect(await width()).toBe(400)373  await side.focus()374  await page.keyboard.press("Enter")375  expect(Math.round((await page.locator("#sidebar").boundingBox())!.width)).toBe(264)376})377378test("barre latérale réduite à une colonne d'icônes, état conservé", async () => {379  const sidebar = page.locator("#sidebar")380  await page.getByRole("button", { name: "Réduire la barre latérale" }).click()381  await expect(page.locator("html")).toHaveAttribute("data-sidebar", "rail")382  expect(Math.round((await sidebar.boundingBox())!.width)).toBe(64)383  // les liens gardent leur nom accessible (libellés masqués visuellement, pas retirés)384  await expect(page.getByRole("link", { name: /Boîte de réception/ })).toBeVisible()385  await expect(page.getByRole("button", { name: "Nouveau message" })).toBeVisible()386  await axe(page, "rail")387  await shot(page, "desktop-light-rail")388  await page.reload()389  await expect(list(page)).toBeVisible()390  expect(Math.round((await sidebar.boundingBox())!.width)).toBe(64)391  await page.getByRole("link", { name: "Envoyés" }).click()392  await expect(page.getByRole("heading", { level: 1, name: "Envoyés" })).toBeVisible()393  await page.getByRole("link", { name: /Boîte de réception/ }).click()394  // raccourci « [ »395  await page.keyboard.press("[")396  await expect(page.locator("html")).toHaveAttribute("data-sidebar", "full")397  expect(Math.round((await sidebar.boundingBox())!.width)).toBe(264)398  await expect(page.getByRole("button", { name: "Réduire la barre latérale" })).toHaveAttribute("aria-expanded", "true")399})400401test("palette de commandes : ouverture au clavier, filtre, exécution, focus rendu, recherche et préfixes", async () => {402  await expect(row(page, new RegExp(`Compte rendu du comité ${st.run}`))).toBeVisible()403  await list(page).focus()404  await page.keyboard.press("j") // une conversation sous le curseur : les actions qui la visent sont proposées405  await expect(page.locator(".mrow.cursor")).toHaveCount(1)406  await page.keyboard.press("Control+k")407  const dlg = page.getByRole("dialog", { name: "Palette de commandes" })408  const input = dlg.getByRole("combobox")409  await expect(input).toBeFocused()410  await expect(dlg.getByRole("option").first()).toHaveAttribute("aria-selected", "true")411  expect(await input.getAttribute("aria-activedescendant")).toBe(await dlg.getByRole("option").first().getAttribute("id"))412  // navigation au clavier dans la liste413  await page.keyboard.press("ArrowDown")414  await expect(dlg.getByRole("option").nth(1)).toHaveAttribute("aria-selected", "true")415  expect(await input.getAttribute("aria-activedescendant")).toBe(await dlg.getByRole("option").nth(1).getAttribute("id"))416  // filtre approximatif, insensible aux accents ; les raccourcis sont affichés417  await input.fill("archiv")418  await expect(dlg.getByRole("option").first()).toContainText("Archiver")419  await expect(dlg.getByRole("option").first().locator("kbd")).toHaveText("e")420  await input.fill("minuit")421  await expect(dlg.getByRole("option").first()).toHaveText("Thème : Minuit")422  await expect(dlg.getByRole("option").last()).toHaveText("Rechercher « minuit » dans le courrier")423  await input.fill(">minuit")424  await expect(dlg.getByRole("option")).toHaveCount(1)425  // « > » : commandes seulement426  await input.fill(">densite compacte")427  await expect(dlg.getByRole("option").first()).toHaveText("Densité : Compacte")428  await page.keyboard.press("Enter")429  await expect(dlg).toHaveCount(0)430  await expect(page.locator("html")).toHaveAttribute("data-density", "compact")431  // le focus revient là où il était432  await expect(list(page)).toBeFocused()433  expect(Math.round((await list(page).getByRole("option").first().boundingBox())!.height)).toBe(44)434  await page.waitForTimeout(300) // les lignes ont fini de glisser à leur nouvelle place435  await shot(page, "desktop-light-compact")436  await palette(page, ">densite interm", "Densité : Intermédiaire")437  await expect(page.locator("html")).toHaveAttribute("data-density", "cozy")438  expect(Math.round((await list(page).getByRole("option").first().boundingBox())!.height)).toBe(60)439  await page.waitForTimeout(300)440  await shot(page, "desktop-light-cozy")441  await palette(page, ">densite aer", "Densité : Aérée")442  await expect(page.locator("html")).toHaveAttribute("data-density", "comfortable")443  expect(Math.round((await list(page).getByRole("option").first().boundingBox())!.height)).toBe(72)444  // dossiers et boîtes445  await page.keyboard.press("Control+k")446  await input.fill("corbeil")447  await expect(dlg.getByRole("option").filter({ hasText: "Corbeille" }).first()).toBeVisible()448  await input.fill(N2.split("@")[0])449  await expect(dlg.getByRole("option").first()).toContainText(N2)450  // « @ » et « # » : servis par les modules contacts et libellés (inscrits quand le serveur les annonce) — plus d'annonce « bientôt »451  await input.fill("@zzz-aucun-contact")452  await expect(dlg.getByRole("status")).toContainText("Aucun résultat")453  await input.fill("#zzz-aucun-libelle")454  await expect(dlg.getByRole("status")).toContainText("Aucun résultat")455  await expect(dlg).not.toContainText("bientôt")456  // « / » : recherche dans le courrier, mémorisée457  await input.fill("/Hydro")458  await expect(dlg.getByRole("option").first()).toContainText("Rechercher « Hydro »")459  await page.keyboard.press("Enter")460  await expect(page).toHaveURL(/\/search\?q=Hydro/)461  await expect(row(page, new RegExp(`Facture de novembre ${st.run}`))).toBeVisible()462  await page.keyboard.press("Control+k")463  await input.fill("/")464  await expect(dlg.getByRole("option", { name: "Hydro", exact: true })).toBeVisible()465  // Échap ferme ; clic hors de la palette aussi466  await page.keyboard.press("Escape")467  await expect(dlg).toHaveCount(0)468  await page.getByRole("button", { name: "Palette de commandes" }).click()469  await expect(dlg).toBeVisible()470  await page.mouse.click(20, 880)471  await expect(dlg).toHaveCount(0)472  await page.getByRole("button", { name: "Effacer la recherche" }).click()473  await expect(page.getByRole("heading", { level: 1, name: "Boîte de réception" })).toBeVisible()474})475476test("disposition : lecture en bas, liste seule, lecture à droite ; choix conservé", async () => {477  await palette(page, ">disposition bas", "Disposition : Lecture en bas")478  await expect(page.locator("html")).toHaveAttribute("data-layout", "below")479  await row(page, new RegExp(`Souper de vendredi ${st.run}`)).click()480  await expect(page.locator(".reader-subject")).toBeVisible()481  const listBox = (await page.locator("#list-pane").boundingBox())!482  const readerBox = (await page.locator(".reader-pane").boundingBox())!483  expect(readerBox.y).toBeGreaterThanOrEqual(listBox.y + listBox.height)484  expect(Math.round(readerBox.width)).toBe(Math.round(listBox.width))485  const sep = page.getByRole("separator", { name: "Hauteur de la liste des messages" })486  await expect(sep).toHaveAttribute("aria-orientation", "horizontal")487  await sep.focus()488  await page.keyboard.press("ArrowDown")489  expect(Math.round((await page.locator("#list-pane").boundingBox())!.height)).toBe(Math.round(listBox.height) + 16)490  await page.keyboard.press("Enter")491  await shot(page, "desktop-light-layout-below")492  await page.reload()493  await expect(page.locator("html")).toHaveAttribute("data-layout", "below")494  // liste seule : la lecture remplace la liste, « Retour » la rend495  await list(page).focus()496  await palette(page, ">disposition liste", "Disposition : Liste seule")497  await page.getByRole("button", { name: "Retour à la liste" }).click()498  await expect(page.locator(".reader-pane")).toBeHidden()499  expect(Math.round((await page.locator("#list-pane").boundingBox())!.width)).toBeGreaterThan(1000)500  await shot(page, "desktop-light-layout-none")501  await row(page, new RegExp(`Souper de vendredi ${st.run}`)).click()502  await expect(page.locator(".reader-subject")).toBeVisible()503  await expect(page.locator("#list-pane")).toBeHidden()504  await page.getByRole("button", { name: "Retour à la liste" }).click()505  await expect(list(page)).toBeVisible()506  // retour par les réglages (les trois choix y sont)507  await openAppearance(page)508  await page.getByRole("button", { name: "Lecture à droite" }).click()509  await expect(page.locator("html")).toHaveAttribute("data-layout", "right")510  await page.getByRole("link", { name: "Courrier" }).click()511  await expect(page.locator(".reader-pane")).toBeVisible()512})513514test("réglages d'apparence : aperçu, pastilles, taille du texte, police de lecture, transparence", async () => {515  await openAppearance(page)516  await page.getByRole("button", { name: "Deux lignes" }).click()517  await expect(page.locator("html")).toHaveAttribute("data-preview", "2")518  await page.getByRole("button", { name: "Très grande" }).click()519  expect(await page.evaluate(() => Number.parseFloat(getComputedStyle(document.documentElement).fontSize))).toBeCloseTo(16 * 1.18, 1)520  await page.getByRole("button", { name: "Normale" }).click()521  await page.getByRole("button", { name: "Avec empattements" }).click()522  await expect(page.locator("html")).toHaveAttribute("data-reading-font", "serif")523  await page.getByLabel("Afficher les pastilles d'initiales dans la liste").uncheck()524  await expect(page.locator("html")).toHaveAttribute("data-avatars", "off")525  await page.getByLabel("Réduire la transparence").check()526  await expect(page.locator("html")).toHaveAttribute("data-transparency", "reduce")527  expect(await page.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue("--glass-filter").trim())).toBe("none")528  await page.getByRole("link", { name: "Courrier" }).click()529  const r = row(page, new RegExp(`Compte rendu du comité ${st.run}`))530  expect(Math.round((await r.boundingBox())!.height)).toBe(92)531  await expect(r.locator(".mrow-avatar")).toBeHidden()532  await expect(r.locator(".box")).toBeVisible()533  // texte brut : police de lecture534  await r.click()535  expect(await page.locator(".text-body").evaluate((el) => getComputedStyle(el).fontFamily)).toContain("ui-serif")536  await page.getByRole("button", { name: "Retour à la liste" }).click()537  // préférences synchronisées relues du serveur après rechargement ; celles de l'appareil, du stockage local538  await page.reload()539  await expect(page.locator("html")).toHaveAttribute("data-preview", "2")540  await expect(page.locator("html")).toHaveAttribute("data-avatars", "off")541  await expect(page.locator("html")).toHaveAttribute("data-transparency", "reduce")542  const prefs = await api<{ user: { prefs: Record<string, unknown> } }>(page, "GET", "/api/me")543  expect(prefs.user.prefs).toMatchObject({ previewLines: 2, avatars: false, readingFont: "serif" })544  // un autre réglage enregistré depuis un appareil au thème différent ne change pas le thème du compte545  await api(page, "PUT", "/api/prefs", { ...prefs.user.prefs, theme: "dark" })546  await page.reload()547  await expect(page.locator("html")).toHaveAttribute("data-theme", "light") // le choix de l'appareil l'emporte548  await openAppearance(page)549  await page.getByRole("button", { name: "Une ligne" }).click()550  await expect.poll(async () => (await api<{ user: { prefs: Record<string, unknown> } }>(page, "GET", "/api/me")).user.prefs.previewLines).toBe(1)551  expect((await api<{ user: { prefs: Record<string, unknown> } }>(page, "GET", "/api/me")).user.prefs.theme).toBe("dark")552  await page.getByRole("button", { name: "Deux lignes" }).click()553  await page.getByRole("link", { name: "Courrier" }).click()554  await openAppearance(page)555  await page.getByRole("button", { name: "Une ligne" }).click()556  await page.getByRole("button", { name: "Standard" }).click()557  await page.getByLabel("Afficher les pastilles d'initiales dans la liste").check()558  await page.getByLabel("Réduire la transparence").uncheck()559  await page.getByRole("link", { name: "Courrier" }).click()560  await expect(list(page)).toBeVisible()561})562563test("mouvement réduit : aucune transition de liste ni de lecture ; sinon ≤ 240 ms, transform seulement", async () => {564  const animations = () =>565    page.evaluate(() => ({566      list: getComputedStyle(document.querySelector(".mlist-inner")!).animationName,567      reader: document.querySelector(".reader-body") ? getComputedStyle(document.querySelector(".reader-body")!).animationName : null,568      row: getComputedStyle(document.querySelector(".mrow")!).transitionDuration,569      // durée du jeton en millisecondes (la feuille minifiée écrit « .24s »)570      dur: ((v) => (v.endsWith("ms") ? Number.parseFloat(v) : Number.parseFloat(v) * 1000))(getComputedStyle(document.documentElement).getPropertyValue("--dur-3").trim()),571      running: document.getAnimations().filter((a) => a.playState === "running" && (a.effect?.getComputedTiming().duration as number) > 1).length,572    }))573  await row(page, new RegExp(`Souper de vendredi ${st.run}`)).click()574  await expect(page.locator(".reader-subject")).toBeVisible()575  const normal = await animations()576  expect(normal.list).toBe("list-in")577  expect(normal.reader).toBe("reader-in")578  expect(normal.dur).toBe(240)579  // les transitions n'animent que transform (et l'opacité des éléments sans texte) : jamais de fondu sur le contenu580  const frames = await page.evaluate(() => {581    const names = new Set(["list-in", "reader-in", "pane-in", "pop"])582    const props = new Set<string>()583    let longest = 0584    for (const sheet of document.styleSheets)585      for (const rule of sheet.cssRules) {586        if (rule instanceof CSSKeyframesRule && names.has(rule.name)) for (const k of rule.cssRules) for (const p of (k as CSSKeyframeRule).style) props.add(p)587      }588    for (const name of ["--dur-1", "--dur-2", "--dur-3"]) {589      const v = getComputedStyle(document.documentElement).getPropertyValue(name).trim()590      longest = Math.max(longest, v.endsWith("ms") ? Number.parseFloat(v) : Number.parseFloat(v) * 1000)591    }592    return { props: [...props], longest }593  })594  expect(frames.props).toEqual(["transform"])595  expect(frames.longest).toBe(240)596  await page.getByRole("button", { name: "Retour à la liste" }).click()597  await page.emulateMedia({ reducedMotion: "reduce" })598  await page.getByRole("link", { name: "Envoyés" }).click()599  await page.getByRole("link", { name: /Boîte de réception/ }).click()600  await row(page, new RegExp(`Souper de vendredi ${st.run}`)).click()601  await expect(page.locator(".reader-subject")).toBeVisible()602  const reduced = await animations()603  expect(reduced.list).toBe("none")604  expect(reduced.reader).toBe("none")605  expect(reduced.dur).toBe(0)606  expect(reduced.running).toBe(0)607  expect(Number.parseFloat(reduced.row)).toBeLessThan(0.01)608  // tout reste utilisable : palette, retour609  await page.keyboard.press("Control+k")610  await expect(page.getByRole("dialog", { name: "Palette de commandes" })).toBeVisible()611  await page.keyboard.press("Escape")612  await page.getByRole("button", { name: "Retour à la liste" }).click()613  await expect(list(page)).toBeVisible()614  await page.emulateMedia({ reducedMotion: "no-preference" })615})616617test("synchronisation : un message lu sur un autre appareil est corrigé sur place, sans relecture ni clignotement de la liste", async ({ browser }) => {618  const ids = await seed(page, N1, [{ subject: `Lu ailleurs ${st.run}`, from: ["Olivier Caron", "olivier@example.org"], preview: "Ce message sera marqué comme lu depuis un autre appareil.", minutesAgo: 0 }])619  const r = row(page, new RegExp(`Lu ailleurs ${st.run}`))620  await expect(r).toBeVisible({ timeout: 30_000 })621  await expect(r).toHaveClass(/unread/)622  await page.waitForTimeout(1500) // la synchronisation de l'arrivée est terminée623  // témoins : requêtes JMAP de la page, et toute ligne retirée, ajoutée ou remplacée par une ligne fantôme624  const calls: string[] = []625  const onRequest = (req: { url(): string; method(): string; postData(): string | null }) => {626    if (req.url().endsWith("/api") && req.method() === "POST") for (const m of req.postData()?.matchAll(/\["((?:Email|Thread|Mailbox)\/[A-Za-z]+)"/g) ?? []) calls.push(m[1])627  }628  page.on("request", onRequest)629  await page.evaluate(() => {630    const w = window as unknown as { __rows: { added: number; removed: number; skeleton: number } }631    w.__rows = { added: 0, removed: 0, skeleton: 0 }632    new MutationObserver((records) => {633      for (const rec of records) {634        w.__rows.added += rec.addedNodes.length635        w.__rows.removed += rec.removedNodes.length636        for (const n of rec.addedNodes) if (n instanceof HTMLElement && n.classList.contains("skeleton-row")) w.__rows.skeleton++637      }638    }).observe(document.getElementById("message-list")!, { childList: true })639  })640  const before = await r.elementHandle()641  // second contexte de navigateur : même session, un autre « appareil »642  const other = await fromStorage(browser, { width: 1280, height: 800 })643  await other.p.goto("/")644  await expect(other.p.locator("#sidebar")).toBeAttached()645  await setKeyword(other.p, N1, ids[0], "$seen", true)646  await expect(r).not.toHaveClass(/unread/, { timeout: 20_000 })647  await expect(r.locator(".dot")).toHaveCount(0)648  await page.waitForTimeout(1200)649  page.off("request", onRequest)650  fs.appendFileSync(`${OUT}/axe.log`, `next-sync: appels JMAP du premier contexte après la modification distante : ${calls.join(", ")}\n`)651  expect(calls).toContain("Email/changes")652  expect(calls.filter((c) => c === "Email/query"), `appels : ${calls.join(", ")}`).toEqual([])653  expect(await page.evaluate(() => (window as unknown as { __rows: unknown }).__rows)).toEqual({ added: 0, removed: 0, skeleton: 0 })654  expect(await page.evaluate((el) => el?.isConnected === true && el === document.querySelector(`[data-id="${el.getAttribute("data-id")}"]`), before)).toBe(true)655  // et dans l'autre sens : favori posé ailleurs656  await setKeyword(other.p, N1, ids[0], "$flagged", true)657  await expect(r.locator(".mrow-star.on")).toHaveCount(1, { timeout: 20_000 })658  await other.ctx.close()659})660661test("brouillon conservé quand on ferme la rédaction hors ligne, repris après rechargement", async () => {662  await page.getByRole("button", { name: "Nouveau message" }).click()663  const dlg = page.locator("section.composer")664  await expect(dlg).toBeVisible()665  await context.setOffline(true)666  const sync = page.locator("#sidebar .sync-indicator")667  await expect(sync).toHaveAttribute("data-sync", "offline")668  await dlg.getByRole("combobox", { name: "À :" }).fill("personne@example.org")669  await dlg.getByRole("combobox", { name: "À :" }).press("Enter")670  await dlg.getByLabel("Objet :").fill(`Hors ligne ${st.run}`)671  await dlg.getByRole("textbox", { name: "Corps du message" }).click()672  await page.keyboard.type("Texte écrit sans réseau, à ne pas perdre.")673  await dlg.getByRole("button", { name: "Enregistrer et fermer" }).click()674  // rien n'est effacé : la rédaction est réduite, la copie locale existe, l'indicateur compte une modification en attente675  await expect(dlg).toHaveCount(0)676  await expect(page.locator(".composer-min")).toContainText(`Hors ligne ${st.run}`)677  await expect(toastText(page, /reste sur cet appareil/)).toBeVisible()678  await expect(sync).toContainText("Hors ligne · 1 en attente")679  await shot(page, "desktop-light-offline-draft")680  const local = await page.evaluate(() => JSON.parse(localStorage.getItem("spmail.draft") ?? "null") as { subject: string; html: string } | null)681  expect(local?.subject).toBe(`Hors ligne ${st.run}`)682  expect(local?.html).toContain("Texte écrit sans réseau")683  // Échap dans la rédaction rouverte : même garantie684  await page.locator(".composer-min-main").click()685  await expect(dlg).toBeVisible()686  await dlg.getByLabel("Objet :").press("Escape")687  await expect(dlg).toHaveCount(0)688  expect(await page.evaluate(() => localStorage.getItem("spmail.draft") !== null)).toBe(true)689  await context.setOffline(false)690  await expect(sync).toHaveAttribute("data-sync", "idle", { timeout: 30_000 })691  await page.reload()692  await page.locator(".composer-min-main").click()693  await expect(dlg.getByLabel("Objet :")).toHaveValue(`Hors ligne ${st.run}`)694  await expect(dlg.getByRole("textbox", { name: "Corps du message" })).toContainText("Texte écrit sans réseau, à ne pas perdre.")695  await expect(dlg.locator(".rcpt-chip")).toHaveCount(1)696  await dlg.getByRole("button", { name: "Supprimer le brouillon" }).click()697  await page.getByRole("alertdialog").getByRole("button", { name: "Supprimer le brouillon" }).click()698  await expect(dlg).toHaveCount(0)699})700701test("boîte retirée côté serveur : elle disparaît proprement, l'adresse suit la boîte affichée", async () => {702  // Une seule boîte de plus : chaque boîte tient une connexion de notification ouverte, et le serveur d'essai parle HTTP/1.1703  // (six connexions par hôte au plus dans le navigateur ; en production, HTTP/2 lève cette limite).704  await api(page, "POST", "/api/admin/mailboxes", { address: N3, display_name: "Next Trois" })705  await seed(page, N3, [{ subject: `Dernière boîte ${st.run}`, from: ["Équipe SP Mail", "equipe@example.org"], preview: "Message de la dernière boîte.", minutesAgo: 1 }])706  const refresh = () => page.evaluate(() => void document.dispatchEvent(new Event("visibilitychange")))707  await refresh()708  await openBox(page, N3)709  await expect(row(page, new RegExp(`Dernière boîte ${st.run}`))).toBeVisible()710  const index3 = Number(new URL(page.url()).pathname.split("/")[2])711  const [id2, id3] = [await mailboxId(page, N2), await mailboxId(page, N3)]712  expect(id2 && id3).toBeTruthy()713  await page.waitForTimeout(800)714  const requests: string[] = []715  page.on("request", (r) => requests.push(`${r.method()} ${new URL(r.url()).pathname}${r.method() === "POST" ? ` ${(r.postData() ?? "").match(/"Email\/query"/)?.[0] ?? ""}` : ""}`))716  // une boîte placée AVANT la boîte affichée est retirée : le rang change, la boîte affichée ne bouge pas717  await api(page, "DELETE", `/api/admin/mailboxes/${id2}?purge=delete-all-mail`)718  const shown = await row(page, new RegExp(`Dernière boîte ${st.run}`)).elementHandle()719  await refresh()720  await expect(page.getByRole("link", { name: N2 })).toHaveCount(0)721  await expect(page).toHaveURL(new RegExp(`/m/${index3 - 1}/inbox`))722  await expect(page.getByRole("heading", { level: 2, name: N3 })).toBeVisible()723  expect(await page.evaluate((el) => el?.isConnected, shown), "la liste affichée n'a pas été rechargée").toBe(true)724  expect(requests.filter((r) => r.includes(`/api/jmap/${id3}/api`) && r.includes("Email/query"))).toEqual([])725  // l'entrée d'historique garde l'identifiant stable de sa boîte : « Précédent » ramène à la même boîte, au bon rang726  await page.getByRole("link", { name: "Envoyés" }).click()727  await expect(page.getByRole("heading", { level: 1, name: "Envoyés" })).toBeVisible()728  await page.goBack()729  await expect(page).toHaveURL(new RegExp(`/m/${index3 - 1}/inbox`))730  await expect(page.getByRole("heading", { level: 2, name: N3 })).toBeVisible()731  await expect(row(page, new RegExp(`Dernière boîte ${st.run}`))).toBeVisible()732  // la boîte affichée elle-même est retirée733  await api(page, "DELETE", `/api/admin/mailboxes/${id3}?purge=delete-all-mail`)734  await refresh()735  await expect(toastText(page, new RegExp(`${N3.split("@")[0]}.*n'est plus rattachée`))).toBeVisible()736  // la boîte vient d'être démontée : à partir d'ici, plus rien ne doit partir vers elle737  requests.length = 0738  await expect(page.getByRole("link", { name: N3 })).toHaveCount(0)739  await expect(page.getByRole("heading", { level: 2, name: N3 })).toHaveCount(0)740  await expect(page).toHaveURL(/\/m\/0\/inbox$/)741  await expect(page.getByRole("heading", { level: 1, name: "Boîte de réception" })).toBeVisible()742  await expect(list(page).or(page.getByRole("heading", { name: "Rien ici" })).first()).toBeVisible()743  // la session n'est pas tombée pour autant (le serveur de courrier répond 401 pour une boîte détruite)744  await expect(page.getByRole("heading", { name: "Connexion à SP Mail" })).toHaveCount(0)745  // plus aucune requête vers les boîtes retirées : ni JMAP, ni reconnexion de leur connexion de notification746  await page.waitForTimeout(4000)747  expect(requests.filter((r) => r.includes(`/api/jmap/${id3}/`) || r.includes(`/api/jmap/${id2}/`))).toEqual([])748  expect(await page.evaluate(async (id) => {749    const db = await new Promise<IDBDatabase>((resolve, reject) => {750      const q = indexedDB.open("spmail-cache")751      q.onsuccess = () => resolve(q.result)752      q.onerror = () => reject(q.error)753    })754    const keys = await new Promise<IDBValidKey[]>((resolve) => {755      const q = db.transaction("kv").objectStore("kv").getAllKeys()756      q.onsuccess = () => resolve(q.result)757    })758    db.close()759    return keys.filter((k) => String(k).includes(id as string))760  }, id3), "le cache de la boîte retirée est vidé").toEqual([])761  await openBox(page, N1)762})763764test("tablette (900 × 1100) : tiroir, deux volets ; captures dans les trois thèmes", async ({ browser }) => {765  const { ctx, p } = await fromStorage(browser, { width: 900, height: 1100 })766  await p.goto("/")767  await openBoxNarrow(p, N1)768  await expect(p.locator(".sidebar")).toBeHidden()769  await expect(p.locator(".reader-pane")).toBeVisible()770  await expect(p.getByRole("separator", { name: "Largeur de la barre latérale" })).toBeHidden()771  for (const [theme, label] of THEMES) {772    await setTheme(p, label, theme)773    await row(p, new RegExp(`Infolettre ${st.run}`)).click()774    await expect(p.frameLocator(".html-frame iframe").locator("h1")).toHaveText("Atelier Nord")775    await axe(p, `tablet-${theme}`)776    await shot(p, `tablet-${theme}-reader`)777    await p.getByRole("button", { name: "Ouvrir le menu" }).click()778    await expect(p.getByRole("link", { name: "Envoyés" })).toBeVisible()779    await axe(p, `tablet-drawer-${theme}`)780    await shot(p, `tablet-${theme}-drawer`)781    await p.getByRole("button", { name: "Fermer le menu" }).click()782    await expect(p.locator(".sidebar")).toBeHidden()783    await p.getByRole("button", { name: "Retour à la liste" }).click()784  }785  await ctx.close()786})787788/** Écrans étroits : la barre latérale est un tiroir. */789async function openBoxNarrow(p: Page, address: string) {790  await expect(p.locator("#sidebar")).toBeAttached()791  await p.getByRole("button", { name: "Ouvrir le menu" }).first().click()792  const link = p.getByRole("link", { name: address })793  await link.or(p.getByRole("heading", { level: 2, name: address })).first().waitFor()794  if (await link.count()) await link.click()795  else await p.getByRole("button", { name: "Fermer le menu" }).click()796  await expect(p.locator(".sidebar")).toBeHidden()797  await expect(p.getByRole("heading", { level: 1, name: "Boîte de réception" })).toBeVisible()798}799800test("téléphone (390 × 844) : barre de navigation du bas, glissements de ligne, mouvement réduit ; captures", async ({ browser }) => {801  const { ctx, p } = await fromStorage(browser, { width: 390, height: 844 }, true)802  await p.goto("/")803  await seed(p, N1, [804    { subject: `Glisser pour archiver ${st.run}`, from: ["Maude Lavoie", "maude@example.org"], preview: "Un glissement vers la gauche archive cette conversation.", minutesAgo: 0 },805    { subject: `Glisser pour lire ${st.run}`, from: ["Félix Bouchard", "felix@example.org"], preview: "Un glissement vers la droite marque cette conversation comme lue.", minutesAgo: 1 },806  ])807  await openBoxNarrow(p, N1)808  const nav = p.getByRole("navigation", { name: "Navigation principale" })809  await expect(nav).toBeVisible()810  await expect(p.locator(".reader-pane")).toBeHidden()811  expect(await p.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true)812  // cibles tactiles d'au moins 44 px813  for (const box of await nav.locator(".bottom-item").evaluateAll((els) => els.map((e) => e.getBoundingClientRect().height))) expect(box).toBeGreaterThanOrEqual(44)814  await expect(nav.getByRole("link", { name: "Réception" })).toHaveAttribute("aria-current", "page")815  for (const [theme, label] of THEMES) {816    await setTheme(p, label, theme)817    await expect(row(p, new RegExp(`Glisser pour archiver ${st.run}`))).toBeVisible({ timeout: 30_000 })818    await axe(p, `phone-list-${theme}`)819    await shot(p, `phone-${theme}-list`)820    await row(p, new RegExp(`Infolettre ${st.run}`)).tap()821    await expect(p.frameLocator(".html-frame iframe").locator("h1")).toHaveText("Atelier Nord")822    await expect(nav).toBeHidden()823    await axe(p, `phone-reader-${theme}`)824    await shot(p, `phone-${theme}-reader`)825    await p.getByRole("button", { name: "Retour à la liste" }).tap()826    await expect(nav).toBeVisible()827  }828  await setTheme(p, "Clair", "light")829  // ---- barre du bas : recherche, écrire, commandes, plus830  await nav.getByRole("button", { name: "Rechercher" }).tap()831  await expect(p.getByRole("searchbox")).toBeFocused()832  // le Command Center (module inscrit quand le serveur l'annonce) prend la place de « Commandes » ; la palette reste au clavier et dans le tiroir833  await nav.getByRole("link", { name: "Centre" }).tap()834  await expect(p).toHaveURL(/\/dashboard$/)835  await nav.getByRole("link", { name: "Réception" }).tap()836  await expect(list(p)).toBeVisible()837  await p.keyboard.press("Control+k")838  await expect(p.getByRole("dialog", { name: "Palette de commandes" })).toBeVisible()839  await shot(p, "phone-light-palette")840  await p.keyboard.press("Escape")841  await nav.getByRole("button", { name: "Écrire" }).tap()842  await expect(p.locator("section.composer")).toBeVisible()843  await p.locator("section.composer").getByRole("button", { name: "Enregistrer et fermer" }).tap()844  await expect(p.locator("section.composer")).toHaveCount(0)845  await nav.getByRole("button", { name: "Plus" }).tap()846  await expect(p.getByRole("link", { name: "Envoyés" })).toBeVisible()847  await shot(p, "phone-light-drawer")848  await p.getByRole("button", { name: "Fermer le menu" }).tap()849  await expect(p.locator(".sidebar")).toBeHidden()850  // ---- glissement vers la droite : lu851  const read = row(p, new RegExp(`Glisser pour lire ${st.run}`))852  await expect(read).toHaveClass(/unread/)853  let box = (await read.boundingBox())!854  expect(await swipe(p, ctx, { x: box.x + 60, y: box.y + box.height / 2 }, 130)).toBe("lead-armed")855  await expect(read).not.toHaveClass(/unread/)856  // un glissement trop court n'arme rien857  expect(await swipe(p, ctx, { x: box.x + 60, y: box.y + box.height / 2 }, 40)).toBe("lead")858  await expect(read).not.toHaveClass(/unread/)859  // ---- glissement vers la gauche : archiver (annulable)860  const arch = row(p, new RegExp(`Glisser pour archiver ${st.run}`))861  const n = await list(p).getByRole("option").count()862  box = (await arch.boundingBox())!863  expect(await swipe(p, ctx, { x: box.x + box.width * 0.7, y: box.y + box.height / 2 }, -130)).toBe("trail-armed")864  await expect(list(p).getByRole("option")).toHaveCount(n - 1)865  await toastText(p, /archivée/).getByRole("button", { name: "Annuler" }).tap()866  await expect(arch).toBeVisible()867  // ---- glissement long vers la gauche : reporter — le module de mise en veille (inscrit quand le serveur l'annonce) ouvre son sélecteur868  box = (await arch.boundingBox())!869  expect(await swipe(p, ctx, { x: box.x + box.width - 20, y: box.y + box.height / 2 }, -260)).toBe("trail-long")870  await expect(p.getByTestId("snooze-picker")).toBeVisible()871  await p.keyboard.press("Escape")872  await expect(p.getByTestId("snooze-picker")).toHaveCount(0)873  await expect(arch).toBeVisible()874  // ---- mouvement réduit : la carte ne suit pas le doigt, l'action part quand même875  await p.emulateMedia({ reducedMotion: "reduce" })876  box = (await read.boundingBox())!877  const cdp = await ctx.newCDPSession(p)878  await cdp.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [{ x: box.x + 60, y: box.y + box.height / 2 }] })879  for (const dx of [30, 70, 110, 140]) await cdp.send("Input.dispatchTouchEvent", { type: "touchMove", touchPoints: [{ x: box.x + 60 + dx, y: box.y + box.height / 2 }] })880  expect(await read.locator(".mrow-card").evaluate((el) => (el as HTMLElement).style.transform)).toBe("")881  await expect(read).toHaveAttribute("data-swipe", "lead-armed")882  await cdp.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] })883  await expect(read).toHaveClass(/unread/)884  await p.emulateMedia({ reducedMotion: "no-preference" })885  await ctx.close()886})887888test("perte de session : le courrier mis en cache est effacé (pas seulement à la déconnexion volontaire)", async ({ browser }) => {889  const { ctx, p } = await fromStorage(browser, { width: 1280, height: 800 })890  await p.goto("/")891  await openBox(p, N1)892  const keys = () =>893    p.evaluate(async () => {894      const names = (await indexedDB.databases()).map((d) => d.name)895      if (!names.includes("spmail-cache")) return []896      const db = await new Promise<IDBDatabase>((resolve, reject) => {897        const q = indexedDB.open("spmail-cache")898        q.onsuccess = () => resolve(q.result)899        q.onerror = () => reject(q.error)900      })901      const out = db.objectStoreNames.contains("kv") ? await new Promise<string[]>((resolve) => {902        const q = db.transaction("kv").objectStore("kv").getAllKeys()903        q.onsuccess = () => resolve(q.result.map(String))904      }) : []905      db.close()906      return out907    })908  await expect.poll(async () => (await keys()).some((k) => k.startsWith("list:"))).toBe(true)909  expect(await keys()).toContain("me")910  // la session disparaît (expiration ou révocation) : la prochaine requête reçoit 401911  await ctx.clearCookies()912  await p.getByRole("link", { name: "Envoyés" }).click()913  await expect(p.getByRole("heading", { name: "Connexion à SP Mail" })).toBeVisible()914  await expect(p.getByText(/session a expiré/)).toBeVisible()915  await expect.poll(keys).toEqual([])916  await ctx.close()917})918919test("aucune erreur de console dans le parcours « Next »", async () => {920  const relevant = consoleErrors.filter((e) => !/Failed to load resource: the server responded with a status of (401|404|409|502)/.test(e) && !/Blocked script execution in 'about:srcdoc'/.test(e) && !/ERR_INTERNET_DISCONNECTED/.test(e))921  expect(relevant).toEqual([])922})923
Files main
Menu

Theme