SPB Git forge

spb/ka-ui

Public
30commits 1branches 0releases
145.7 MBsize
maindefault branch
27 days agolast push
Python 33.5% JavaScript 30.1% TypeScript 25% CSS 10% Shell 1.4%
17.0 KB · 355 lines javascript
Raw Blame History
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    /* la compensation peut aussi être portée par le footer (pattern tab bar :118       le dernier bloc dégage la barre, le contenu défile dessous) */119    for (const w of document.querySelectorAll("#root, #__next, .app, #app, footer, .ka-footer")) {120      wrapPad = Math.max(wrapPad, parseFloat(getComputedStyle(w).paddingBottom) || 0);121    }122    res.bottomBar = { sel: bar.sel, h: bar.rect.h, bodyPadBottom: bodyPad, mainPadBottom: mainPad, wrapPadBottom: wrapPad };123  }124125  // champs zoom iOS126  res.smallInputs = [];127  for (const el of document.querySelectorAll("input, select, textarea")) {128    const cs = getComputedStyle(el);129    if (el.type === "hidden" || el.type === "checkbox" || el.type === "radio" || cs.display === "none") continue;130    const rr = el.getBoundingClientRect();131    if (rr.width < 4 || rr.height < 4) continue; /* sr-only / clip */132    const fs = parseFloat(cs.fontSize);133    if (fs && fs < 16) res.smallInputs.push({ sel: sel(el), fs });134    if (res.smallInputs.length >= 10) break;135  }136137  // cibles tactiles dans header/nav — en tenant compte des extensions de zone138  // par pseudo-élément (::after/::before absolu avec inset négatif)139  const hitExt = (el) => {140    let ext = 0;141    for (const ps of ["::after", "::before"]) {142      const cs = getComputedStyle(el, ps);143      if (cs.content !== "none" && cs.position === "absolute") {144        const t = parseFloat(cs.top), b = parseFloat(cs.bottom);145        if (!isNaN(t) && t < 0) ext = Math.max(ext, -t - (isNaN(b) ? 0 : Math.min(b, 0)));146        else if (!isNaN(t) && !isNaN(b)) ext = Math.max(ext, Math.max(0, -t) + Math.max(0, -b));147      }148    }149    return ext;150  };151  res.smallTargets = [];152  for (const el of document.querySelectorAll("header a, header button, nav a, nav button, [class*=menu] a, [class*=menu] button")) {153    const r = el.getBoundingClientRect();154    if (r.width === 0 || r.height === 0) continue;155    const ext = hitExt(el);156    const effH = r.height + 2 * ext, effW = r.width + 2 * ext;157    if ((effH < 34 || effW < 34) && r.top >= 0 && r.top < window.innerHeight) {158      res.smallTargets.push({ sel: sel(el), w: Math.round(effW), h: Math.round(effH), text: (el.textContent || "").trim().slice(0, 20) });159      if (res.smallTargets.length >= 10) break;160    }161  }162163  // candidats menus déroulants164  res.dropdownCandidates = [];165  for (const el of document.querySelectorAll('[aria-haspopup], [class*="dropdown"], [class*="Dropdown"], details, [data-menu], [class*="select"]:not(select)')) {166    const r = el.getBoundingClientRect();167    if (r.width === 0) continue;168    res.dropdownCandidates.push({ sel: sel(el), tag: el.tagName.toLowerCase() });169    if (res.dropdownCandidates.length >= 15) break;170  }171172  // feuilles de style (mêmes origines) pour scan texte173  res.styleSheets = [...document.styleSheets].map((ss) => ss.href).filter(Boolean);174  res.inlineCss = [...document.querySelectorAll("style")].map((s) => s.textContent || "").join("\\n");175  return res;176})()`;177178// détection des règles :hover qui révèlent un sous-menu179function scanCss(text) {180  const out = { vh100: 0, dvh: 0, svh: 0, safeArea: 0, hoverReveal: [], zMax: 0 };181  if (!text) return out;182  out.vh100 = (text.match(/100vh/g) || []).length;183  out.dvh = (text.match(/dvh/g) || []).length;184  out.svh = (text.match(/svh/g) || []).length;185  out.safeArea = (text.match(/safe-area-inset-bottom/g) || []).length;186  const rules = text.match(/[^{}]+\{[^{}]*\}/g) || [];187  for (const rule of rules) {188    const [selPart, body] = rule.split("{");189    if (!selPart || !body) continue;190    if (/:hover/.test(selPart) &&191        /(display\s*:\s*(block|flex|grid)|visibility\s*:\s*visible|opacity\s*:\s*1|pointer-events\s*:\s*auto)/.test(body) &&192        /(menu|dropdown|nav|sub)/i.test(selPart)) {193      out.hoverReveal.push(selPart.trim().replace(/\s+/g, " ").slice(0, 90));194      if (out.hoverReveal.length >= 8) break;195    }196    const zm = body.match(/z-index\s*:\s*(\d+)/g) || [];197    for (const z of zm) out.zMax = Math.max(out.zMax, parseInt(z.replace(/\D+/g, ""), 10) || 0);198  }199  return out;200}201202async function auditPage(page, url, tag, shot) {203  const r = { url, tag, issues: [], data: null };204  const resp = await page.goto(url, { waitUntil: "domcontentloaded", timeout: 45000 });205  if (!resp || resp.status() >= 400) { r.issues.push(`HTTP ${resp ? resp.status() : "??"}`); return r; }206  await page.waitForLoadState("networkidle", { timeout: 20000 }).catch(() => {});207  await page.waitForTimeout(1500);208  const d = await page.evaluate(PAGE_AUDIT);209  r.data = d;210211  // scan CSS (inline + feuilles même origine)212  let cssText = d.inlineCss || "";213  const origin = new URL(url).origin;214  for (const href of d.styleSheets.slice(0, 8)) {215    try {216      if (!href.startsWith(origin) && !href.startsWith("/")) continue;217      const t = await page.evaluate(async (h) => { try { const x = await fetch(h); return await x.text(); } catch { return ""; } }, href);218      cssText += "\n" + t;219    } catch {}220  }221  r.css = scanCss(cssText);222  delete d.inlineCss;223224  // stabilité au scroll de la barre basse225  const bar = (d.fixed || []).find((f) => f.bottomAnchored);226  if (bar) {227    const track = await page.evaluate(async (barSel) => {228      const find = () => {229        for (const el of document.querySelectorAll("body *")) {230          const cs = getComputedStyle(el);231          if (cs.position !== "fixed") continue;232          const r = el.getBoundingClientRect();233          if (r.bottom > innerHeight - 120 && r.top > innerHeight * 0.4 && r.height >= 8) return el;234        }235        return null;236      };237      const el = find();238      if (!el) return null;239      const pos = [];240      for (let i = 0; i < 4; i++) {241        window.scrollBy(0, 600);242        await new Promise((r2) => setTimeout(r2, 350));243        const r = el.getBoundingClientRect();244        pos.push({ b: Math.round(innerHeight - r.bottom), visible: r.height > 0 && getComputedStyle(el).display !== "none" });245      }246      window.scrollTo(0, 0);247      return pos;248    }, bar.sel).catch(() => null);249    if (track) {250      const bottoms = track.map((p) => p.b);251      const drift = Math.max(...bottoms) - Math.min(...bottoms);252      if (drift > 2) r.issues.push(`barre basse instable au scroll (dérive ${drift}px) [${bar.sel}]`);253      if (track.some((p) => !p.visible)) r.issues.push(`barre basse disparaît au scroll [${bar.sel}]`);254    }255  }256257  // signalements258  if (!d.viewport || !/width=device-width/.test(d.viewport)) r.issues.push(`meta viewport: ${d.viewport || "ABSENTE"}`);259  if (d.overflowPx > 1) r.issues.push(`débordement horizontal +${d.overflowPx}px : ${(d.overflowEls || []).map((e) => e.sel).slice(0, 4).join(", ")}`);260  for (const f of d.fixed || []) if (f.brokenBy) r.issues.push(`fixed cassé par ancêtre ${f.brokenBy} → [${f.sel}]`);261  const bb = d.bottomBar;262  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)263    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)`);264  if (bar && !/env\(|calc\(/.test(bar.cssBottom || "") && r.css.safeArea === 0)265    r.issues.push(`aucune trace de safe-area-inset-bottom (barre basse [${bar.sel}])`);266  if (r.css.vh100 > 0 && r.css.dvh === 0 && r.css.svh === 0) r.issues.push(`${r.css.vh100}× 100vh sans dvh/svh`);267  if (r.css.hoverReveal.length) r.issues.push(`menus :hover-reveal CSS : ${r.css.hoverReveal.slice(0, 3).join(" | ")}`);268  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(", ")}`);269  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(", ")}`);270271  // test tap : ouvrir le VRAI bouton de menu (aria-label/menu-btn/burger en272  // priorité — pas n'importe quel bouton du header), vérifier qu'un panneau273  // s'ouvre réellement (aria-expanded / classe open / dialog) puis le verrou.274  try {275    const btn = page.locator('button[aria-label*="menu" i], .menu-btn, [class*="burger"], [class*="hamburger"], label[for*="menu"]').first();276    if (await btn.count()) {277      await btn.tap({ timeout: 3000 }).catch(() => btn.click({ timeout: 3000 }));278      await page.waitForTimeout(600);279      const after = await page.evaluate(() => ({280        opened: !!document.querySelector('.mobile-menu.open, [role="dialog"], .gk-mobile-overlay, [aria-expanded="true"], .mm-backdrop, input[id*="menu"]:checked'),281        bodyOverflow: (document.body.style.overflow || getComputedStyle(document.body).overflow),282        htmlOverflow: getComputedStyle(document.documentElement).overflow,283        htmlLock: document.documentElement.classList.contains("ka-scroll-lock") || document.documentElement.classList.contains("kaa-lock"),284      }));285      if (after.opened && !after.htmlLock &&286          !/hidden/.test(after.bodyOverflow) && !/hidden/.test(after.htmlOverflow))287        r.issues.push("menu ouvert SANS blocage du scroll d'arrière-plan");288      if (shot && after.opened) await page.screenshot({ path: shot.replace(".png", "-menu.png") });289      await page.keyboard.press("Escape").catch(() => {});290      await page.mouse.click(5, Math.round((page.viewportSize()?.height || 800) * 0.75)).catch(() => {});291    }292  } catch {}293294  if (shot) {295    await page.evaluate(() => window.scrollTo(0, 0));296    await page.waitForTimeout(300);297    await page.screenshot({ path: shot });298    await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));299    await page.waitForTimeout(500);300    await page.screenshot({ path: shot.replace(".png", "-bas.png") });301  }302  return r;303}304305const engines = [306  { name: "android", launcher: chromium, ctx: { ...devices["Pixel 7"] } },307  { name: "ios", launcher: webkit, ctx: { ...devices["iPhone 13"] } },308];309310const report = [];311for (const engine of engines) {312  const browser = await engine.launcher.launch();313  for (const site of sites) {314    const ctx = await browser.newContext(engine.ctx);315    const page = await ctx.newPage();316    const siteRep = { site: site.id, engine: engine.name, pages: [] };317    try {318      const home = `https://${site.domain}/`;319      const shot = join(outDir, `${site.id}-${engine.name}.png`);320      siteRep.pages.push(await auditPage(page, home, "accueil", shot));321      // pages internes : 2 liens de nav distincts (chromium seulement pour limiter le temps)322      if (engine.name === "android") {323        const links = await page.evaluate(() => {324          const seen = new Set();325          const out = [];326          for (const a of document.querySelectorAll("a[href]")) {327            const h = a.getAttribute("href");328            if (!h || !h.startsWith("/") || h === "/" || h.startsWith("//") || h.startsWith("/#")) continue;329            const p = h.split("?")[0].split("#")[0];330            if (seen.has(p) || /\.(png|jpg|pdf|xml|js)$/.test(p)) continue;331            seen.add(p);332            out.push(p);333            if (out.length >= 6) break;334          }335          return out;336        }).catch(() => []);337        for (const l of links.slice(0, 2)) {338          siteRep.pages.push(await auditPage(page, `https://${site.domain}${l}`, l, null)339            .catch((e) => ({ url: l, issues: ["ERREUR " + String(e).slice(0, 80)] })));340        }341      }342    } catch (e) {343      siteRep.pages.push({ url: site.domain, issues: ["ERREUR " + String(e).split("\n")[0].slice(0, 120)] });344    }345    report.push(siteRep);346    const n = siteRep.pages.reduce((a, p) => a + (p.issues || []).length, 0);347    console.log(`${n ? "⚠️ " : "✅"} ${engine.name.padEnd(7)} ${site.id.padEnd(10)} ${n} problème(s)`);348    for (const p of siteRep.pages) for (const i of p.issues || []) console.log(`     [${p.tag || p.url}] ${i}`);349    await ctx.close();350  }351  await browser.close();352}353writeFileSync(join(outDir, "report.json"), JSON.stringify(report, null, 2));354console.log(`\nRapport : ${join(outDir, "report.json")}`);355