SPB Git

spb/ka-ui

Public
16.8 KB · 353 lines javascript
1// Auteur : Simon-Pierre Boucher — contact@spboucher.ai2// ka-ui/mobile-audit.mjs — audit mobile approfondi des 13 sites Groupe KA.3// Usage : cd ~/Desktop/ka-ui && node mobile-audit.mjs [site…]4// Pour chaque site (chromium mobile 390×844 + webkit iPhone) :5//  - meta viewport, débordement horizontal (+ éléments fautifs)6//  - inventaire des éléments fixed/sticky : ancrage bas, ancêtre transform/filter7//    (casse le fixed), safe-area, compensation padding, stabilité au scroll8//  - scan CSS : 100vh sans dvh, env(safe-area-inset-bottom), z-index extrêmes9//  - menus déroulants : règles :hover-reveal, cibles tactiles <44px, test tap10//  - champs avec font-size <16px (zoom iOS)11// Sortie : audit/report.json + captures audit/*.png + résumé console.12import { chromium, webkit, devices } from "playwright";13import { mkdirSync, readFileSync, writeFileSync } from "fs";14import { dirname, join } from "path";15import { fileURLToPath } from "url";1617const here = dirname(fileURLToPath(import.meta.url));18const eco = JSON.parse(readFileSync(join(here, "ecosystem.json"), "utf8"));19const outDir = join(here, "audit");20mkdirSync(outDir, { recursive: true });2122const only = process.argv.slice(2);23const sites = eco.sites.filter((s) => !only.length || only.includes(s.id));2425// ---------- code injecté dans la page ----------26const PAGE_AUDIT = `(() => {27  const res = {};28  const sel = (el) => {29    if (!el || el === document.documentElement) return "html";30    let s = el.tagName.toLowerCase();31    if (el.id) return s + "#" + el.id;32    const c = (el.className && typeof el.className === "string")33      ? el.className.trim().split(/\\s+/).slice(0, 3).join(".") : "";34    return c ? s + "." + c : s;35  };3637  // meta viewport38  const mv = document.querySelector('meta[name="viewport"]');39  res.viewport = mv ? mv.getAttribute("content") : null;4041  // débordement horizontal RÉEL (scrollWidth peut mentir quand overflow-x:clip42  // est posé — on vérifie que le viewport défile vraiment)43  const iw = window.innerWidth;44  const rawOverflow = Math.max(45    document.documentElement.scrollWidth - iw,46    document.body ? document.body.scrollWidth - iw : 0);47  res.overflowPx = 0;48  if (rawOverflow > 1) {49    const x0 = window.scrollX;50    window.scrollBy(rawOverflow, 0);51    if (window.scrollX - x0 > 1) res.overflowPx = rawOverflow;52    window.scrollTo(x0, 0);53  }54  res.overflowEls = [];55  if (res.overflowPx > 1) {56    for (const el of document.querySelectorAll("body *")) {57      const r = el.getBoundingClientRect();58      if (r.width > 1 && (r.right > iw + 1 || r.left < -1) && r.height > 4) {59        const cs = getComputedStyle(el);60        if (cs.position === "fixed" && r.left >= -1 && r.right <= iw + 1) continue;61        res.overflowEls.push({ sel: sel(el), left: Math.round(r.left), right: Math.round(r.right), w: Math.round(r.width) });62        if (res.overflowEls.length >= 12) break;63      }64    }65  }6667  // fixed / sticky68  const breaksFixed = (el) => {69    let p = el.parentElement;70    while (p && p !== document.documentElement) {71      const cs = getComputedStyle(p);72      if (cs.transform !== "none" || cs.filter !== "none" ||73          cs.backdropFilter && cs.backdropFilter !== "none" ||74          cs.perspective !== "none" ||75          (cs.willChange && /transform|filter|perspective/.test(cs.willChange)) ||76          (cs.contain && /layout|paint|strict|content/.test(cs.contain)))77        return sel(p) + " (" + [78          cs.transform !== "none" ? "transform" : "",79          cs.filter !== "none" ? "filter" : "",80          cs.backdropFilter && cs.backdropFilter !== "none" ? "backdrop-filter" : "",81          cs.perspective !== "none" ? "perspective" : "",82          cs.willChange && /transform|filter/.test(cs.willChange) ? "will-change" : "",83        ].filter(Boolean).join(",") + ")";84      p = p.parentElement;85    }86    return null;87  };88  res.fixed = [];89  for (const el of document.querySelectorAll("body *")) {90    const cs = getComputedStyle(el);91    if (cs.position !== "fixed" && cs.position !== "sticky") continue;92    const r = el.getBoundingClientRect();93    if (r.width < 8 || r.height < 8 || cs.display === "none") continue;94    const vh = window.innerHeight;95    /* une « barre » basse = pleine largeur (≥60 % du viewport) ; un bouton96       flottant (FAB, bulle KA Agent) n'exige pas de compensation de contenu */97    const bottomAnchored = cs.position === "fixed" && r.bottom > vh - 120 && r.top > vh * 0.498      && r.width >= window.innerWidth * 0.6;99    res.fixed.push({100      sel: sel(el), pos: cs.position,101      rect: { t: Math.round(r.top), b: Math.round(r.bottom), h: Math.round(r.height) },102      bottomAnchored,103      z: cs.zIndex,104      brokenBy: cs.position === "fixed" ? breaksFixed(el) : null,105      padBottom: cs.paddingBottom, cssBottom: cs.bottom,106    });107    if (res.fixed.length >= 25) break;108  }109110  // compensation : padding-bottom du body/main vs barre basse111  const bar = res.fixed.find((f) => f.bottomAnchored);112  if (bar) {113    const bodyPad = parseFloat(getComputedStyle(document.body).paddingBottom) || 0;114    const main = document.querySelector("main");115    const mainPad = main ? parseFloat(getComputedStyle(main).paddingBottom) || 0 : 0;116    let wrapPad = 0;117    for (const w of document.querySelectorAll("#root, #__next, .app, #app")) {118      wrapPad = Math.max(wrapPad, parseFloat(getComputedStyle(w).paddingBottom) || 0);119    }120    res.bottomBar = { sel: bar.sel, h: bar.rect.h, bodyPadBottom: bodyPad, mainPadBottom: mainPad, wrapPadBottom: wrapPad };121  }122123  // champs zoom iOS124  res.smallInputs = [];125  for (const el of document.querySelectorAll("input, select, textarea")) {126    const cs = getComputedStyle(el);127    if (el.type === "hidden" || el.type === "checkbox" || el.type === "radio" || cs.display === "none") continue;128    const rr = el.getBoundingClientRect();129    if (rr.width < 4 || rr.height < 4) continue; /* sr-only / clip */130    const fs = parseFloat(cs.fontSize);131    if (fs && fs < 16) res.smallInputs.push({ sel: sel(el), fs });132    if (res.smallInputs.length >= 10) break;133  }134135  // cibles tactiles dans header/nav — en tenant compte des extensions de zone136  // par pseudo-élément (::after/::before absolu avec inset négatif)137  const hitExt = (el) => {138    let ext = 0;139    for (const ps of ["::after", "::before"]) {140      const cs = getComputedStyle(el, ps);141      if (cs.content !== "none" && cs.position === "absolute") {142        const t = parseFloat(cs.top), b = parseFloat(cs.bottom);143        if (!isNaN(t) && t < 0) ext = Math.max(ext, -t - (isNaN(b) ? 0 : Math.min(b, 0)));144        else if (!isNaN(t) && !isNaN(b)) ext = Math.max(ext, Math.max(0, -t) + Math.max(0, -b));145      }146    }147    return ext;148  };149  res.smallTargets = [];150  for (const el of document.querySelectorAll("header a, header button, nav a, nav button, [class*=menu] a, [class*=menu] button")) {151    const r = el.getBoundingClientRect();152    if (r.width === 0 || r.height === 0) continue;153    const ext = hitExt(el);154    const effH = r.height + 2 * ext, effW = r.width + 2 * ext;155    if ((effH < 34 || effW < 34) && r.top >= 0 && r.top < window.innerHeight) {156      res.smallTargets.push({ sel: sel(el), w: Math.round(effW), h: Math.round(effH), text: (el.textContent || "").trim().slice(0, 20) });157      if (res.smallTargets.length >= 10) break;158    }159  }160161  // candidats menus déroulants162  res.dropdownCandidates = [];163  for (const el of document.querySelectorAll('[aria-haspopup], [class*="dropdown"], [class*="Dropdown"], details, [data-menu], [class*="select"]:not(select)')) {164    const r = el.getBoundingClientRect();165    if (r.width === 0) continue;166    res.dropdownCandidates.push({ sel: sel(el), tag: el.tagName.toLowerCase() });167    if (res.dropdownCandidates.length >= 15) break;168  }169170  // feuilles de style (mêmes origines) pour scan texte171  res.styleSheets = [...document.styleSheets].map((ss) => ss.href).filter(Boolean);172  res.inlineCss = [...document.querySelectorAll("style")].map((s) => s.textContent || "").join("\\n");173  return res;174})()`;175176// détection des règles :hover qui révèlent un sous-menu177function scanCss(text) {178  const out = { vh100: 0, dvh: 0, svh: 0, safeArea: 0, hoverReveal: [], zMax: 0 };179  if (!text) return out;180  out.vh100 = (text.match(/100vh/g) || []).length;181  out.dvh = (text.match(/dvh/g) || []).length;182  out.svh = (text.match(/svh/g) || []).length;183  out.safeArea = (text.match(/safe-area-inset-bottom/g) || []).length;184  const rules = text.match(/[^{}]+\{[^{}]*\}/g) || [];185  for (const rule of rules) {186    const [selPart, body] = rule.split("{");187    if (!selPart || !body) continue;188    if (/:hover/.test(selPart) &&189        /(display\s*:\s*(block|flex|grid)|visibility\s*:\s*visible|opacity\s*:\s*1|pointer-events\s*:\s*auto)/.test(body) &&190        /(menu|dropdown|nav|sub)/i.test(selPart)) {191      out.hoverReveal.push(selPart.trim().replace(/\s+/g, " ").slice(0, 90));192      if (out.hoverReveal.length >= 8) break;193    }194    const zm = body.match(/z-index\s*:\s*(\d+)/g) || [];195    for (const z of zm) out.zMax = Math.max(out.zMax, parseInt(z.replace(/\D+/g, ""), 10) || 0);196  }197  return out;198}199200async function auditPage(page, url, tag, shot) {201  const r = { url, tag, issues: [], data: null };202  const resp = await page.goto(url, { waitUntil: "domcontentloaded", timeout: 45000 });203  if (!resp || resp.status() >= 400) { r.issues.push(`HTTP ${resp ? resp.status() : "??"}`); return r; }204  await page.waitForLoadState("networkidle", { timeout: 20000 }).catch(() => {});205  await page.waitForTimeout(1500);206  const d = await page.evaluate(PAGE_AUDIT);207  r.data = d;208209  // scan CSS (inline + feuilles même origine)210  let cssText = d.inlineCss || "";211  const origin = new URL(url).origin;212  for (const href of d.styleSheets.slice(0, 8)) {213    try {214      if (!href.startsWith(origin) && !href.startsWith("/")) continue;215      const t = await page.evaluate(async (h) => { try { const x = await fetch(h); return await x.text(); } catch { return ""; } }, href);216      cssText += "\n" + t;217    } catch {}218  }219  r.css = scanCss(cssText);220  delete d.inlineCss;221222  // stabilité au scroll de la barre basse223  const bar = (d.fixed || []).find((f) => f.bottomAnchored);224  if (bar) {225    const track = await page.evaluate(async (barSel) => {226      const find = () => {227        for (const el of document.querySelectorAll("body *")) {228          const cs = getComputedStyle(el);229          if (cs.position !== "fixed") continue;230          const r = el.getBoundingClientRect();231          if (r.bottom > innerHeight - 120 && r.top > innerHeight * 0.4 && r.height >= 8) return el;232        }233        return null;234      };235      const el = find();236      if (!el) return null;237      const pos = [];238      for (let i = 0; i < 4; i++) {239        window.scrollBy(0, 600);240        await new Promise((r2) => setTimeout(r2, 350));241        const r = el.getBoundingClientRect();242        pos.push({ b: Math.round(innerHeight - r.bottom), visible: r.height > 0 && getComputedStyle(el).display !== "none" });243      }244      window.scrollTo(0, 0);245      return pos;246    }, bar.sel).catch(() => null);247    if (track) {248      const bottoms = track.map((p) => p.b);249      const drift = Math.max(...bottoms) - Math.min(...bottoms);250      if (drift > 2) r.issues.push(`barre basse instable au scroll (dérive ${drift}px) [${bar.sel}]`);251      if (track.some((p) => !p.visible)) r.issues.push(`barre basse disparaît au scroll [${bar.sel}]`);252    }253  }254255  // signalements256  if (!d.viewport || !/width=device-width/.test(d.viewport)) r.issues.push(`meta viewport: ${d.viewport || "ABSENTE"}`);257  if (d.overflowPx > 1) r.issues.push(`débordement horizontal +${d.overflowPx}px : ${(d.overflowEls || []).map((e) => e.sel).slice(0, 4).join(", ")}`);258  for (const f of d.fixed || []) if (f.brokenBy) r.issues.push(`fixed cassé par ancêtre ${f.brokenBy} → [${f.sel}]`);259  const bb = d.bottomBar;260  if (bb && !/cookie|consent|banner/i.test(bb.sel) && bb.bodyPadBottom < bb.h - 8 && bb.mainPadBottom < bb.h - 8 && (bb.wrapPadBottom ?? 0) < bb.h - 8)261    r.issues.push(`pas de compensation padding sous la barre basse [${bb.sel}] h=${bb.h}px (body ${bb.bodyPadBottom}px / main ${bb.mainPadBottom}px / wrapper ${bb.wrapPadBottom ?? 0}px)`);262  if (bar && !/env\(|calc\(/.test(bar.cssBottom || "") && r.css.safeArea === 0)263    r.issues.push(`aucune trace de safe-area-inset-bottom (barre basse [${bar.sel}])`);264  if (r.css.vh100 > 0 && r.css.dvh === 0 && r.css.svh === 0) r.issues.push(`${r.css.vh100}× 100vh sans dvh/svh`);265  if (r.css.hoverReveal.length) r.issues.push(`menus :hover-reveal CSS : ${r.css.hoverReveal.slice(0, 3).join(" | ")}`);266  if (d.smallInputs.length) r.issues.push(`${d.smallInputs.length} champ(s) <16px (zoom iOS) : ${d.smallInputs.slice(0, 3).map((i) => i.sel).join(", ")}`);267  if (d.smallTargets.length) r.issues.push(`${d.smallTargets.length} cible(s) tactile(s) <34px : ${d.smallTargets.slice(0, 3).map((t) => t.sel + "(" + t.w + "×" + t.h + ")").join(", ")}`);268269  // test tap : ouvrir le VRAI bouton de menu (aria-label/menu-btn/burger en270  // priorité — pas n'importe quel bouton du header), vérifier qu'un panneau271  // s'ouvre réellement (aria-expanded / classe open / dialog) puis le verrou.272  try {273    const btn = page.locator('button[aria-label*="menu" i], .menu-btn, [class*="burger"], [class*="hamburger"], label[for*="menu"]').first();274    if (await btn.count()) {275      await btn.tap({ timeout: 3000 }).catch(() => btn.click({ timeout: 3000 }));276      await page.waitForTimeout(600);277      const after = await page.evaluate(() => ({278        opened: !!document.querySelector('.mobile-menu.open, [role="dialog"], .gk-mobile-overlay, [aria-expanded="true"], .mm-backdrop, input[id*="menu"]:checked'),279        bodyOverflow: (document.body.style.overflow || getComputedStyle(document.body).overflow),280        htmlOverflow: getComputedStyle(document.documentElement).overflow,281        htmlLock: document.documentElement.classList.contains("ka-scroll-lock") || document.documentElement.classList.contains("kaa-lock"),282      }));283      if (after.opened && !after.htmlLock &&284          !/hidden/.test(after.bodyOverflow) && !/hidden/.test(after.htmlOverflow))285        r.issues.push("menu ouvert SANS blocage du scroll d'arrière-plan");286      if (shot && after.opened) await page.screenshot({ path: shot.replace(".png", "-menu.png") });287      await page.keyboard.press("Escape").catch(() => {});288      await page.mouse.click(5, Math.round((page.viewportSize()?.height || 800) * 0.75)).catch(() => {});289    }290  } catch {}291292  if (shot) {293    await page.evaluate(() => window.scrollTo(0, 0));294    await page.waitForTimeout(300);295    await page.screenshot({ path: shot });296    await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));297    await page.waitForTimeout(500);298    await page.screenshot({ path: shot.replace(".png", "-bas.png") });299  }300  return r;301}302303const engines = [304  { name: "android", launcher: chromium, ctx: { ...devices["Pixel 7"] } },305  { name: "ios", launcher: webkit, ctx: { ...devices["iPhone 13"] } },306];307308const report = [];309for (const engine of engines) {310  const browser = await engine.launcher.launch();311  for (const site of sites) {312    const ctx = await browser.newContext(engine.ctx);313    const page = await ctx.newPage();314    const siteRep = { site: site.id, engine: engine.name, pages: [] };315    try {316      const home = `https://${site.domain}/`;317      const shot = join(outDir, `${site.id}-${engine.name}.png`);318      siteRep.pages.push(await auditPage(page, home, "accueil", shot));319      // pages internes : 2 liens de nav distincts (chromium seulement pour limiter le temps)320      if (engine.name === "android") {321        const links = await page.evaluate(() => {322          const seen = new Set();323          const out = [];324          for (const a of document.querySelectorAll("a[href]")) {325            const h = a.getAttribute("href");326            if (!h || !h.startsWith("/") || h === "/" || h.startsWith("//") || h.startsWith("/#")) continue;327            const p = h.split("?")[0].split("#")[0];328            if (seen.has(p) || /\.(png|jpg|pdf|xml|js)$/.test(p)) continue;329            seen.add(p);330            out.push(p);331            if (out.length >= 6) break;332          }333          return out;334        }).catch(() => []);335        for (const l of links.slice(0, 2)) {336          siteRep.pages.push(await auditPage(page, `https://${site.domain}${l}`, l, null)337            .catch((e) => ({ url: l, issues: ["ERREUR " + String(e).slice(0, 80)] })));338        }339      }340    } catch (e) {341      siteRep.pages.push({ url: site.domain, issues: ["ERREUR " + String(e).split("\n")[0].slice(0, 120)] });342    }343    report.push(siteRep);344    const n = siteRep.pages.reduce((a, p) => a + (p.issues || []).length, 0);345    console.log(`${n ? "⚠️ " : "✅"} ${engine.name.padEnd(7)} ${site.id.padEnd(10)} ${n} problème(s)`);346    for (const p of siteRep.pages) for (const i of p.issues || []) console.log(`     [${p.tag || p.url}] ${i}`);347    await ctx.close();348  }349  await browser.close();350}351writeFileSync(join(outDir, "report.json"), JSON.stringify(report, null, 2));352console.log(`\nRapport : ${join(outDir, "report.json")}`);353
Files · e6df8e51af6369d8168f3913e3138836a837140e
Menu

Theme