Proposer l'installation de l'app au bon moment (lot 3d)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
888aec1003
commit
84b4027796
@@ -28,12 +28,15 @@ import { readPairFragment } from "./ui/sync-model.js";
|
||||
import { toast } from "./ui/feedback.js";
|
||||
import { updateBanner } from "./ui/update-banner.js";
|
||||
import { loadDraft } from "./ui/draft-storage.js";
|
||||
import { startInstaller } from "./ui/install.js";
|
||||
|
||||
import { openEventStore } from "./infra/event-store.js";
|
||||
import { decodeProposalFragment } from "./domain/link.js";
|
||||
import { registerServiceWorker } from "./sw-register.js";
|
||||
|
||||
applyTheme(getTheme());
|
||||
// Tôt, pour ne pas manquer l'invite d'installation du navigateur.
|
||||
startInstaller();
|
||||
|
||||
// Le journal est gardé dans IndexedDB : chargé au démarrage, chaque événement
|
||||
// créé y est ajouté (ADR 0006).
|
||||
|
||||
+4
-2
@@ -7,6 +7,7 @@
|
||||
import { gameStats, sessionCombo, sessionRewards } from "../domain/gamification.js";
|
||||
import { h } from "./dom.js";
|
||||
import { href } from "./router.js";
|
||||
import { installOffer, strengthSessions } from "./install.js";
|
||||
|
||||
/** @typedef {import("../domain/state.js").State} State */
|
||||
/** @typedef {import("../domain/gamification.js").SessionRewards} SessionRewards */
|
||||
@@ -60,7 +61,7 @@ export function comboLabel(sets) {
|
||||
return sessionCombo(sets).label;
|
||||
}
|
||||
|
||||
/** @type {{rewards: SessionRewards, summary: SessionSummary}|null} */
|
||||
/** @type {{rewards: SessionRewards, summary: SessionSummary, sessions: number}|null} */
|
||||
let lastFinish = null;
|
||||
|
||||
/**
|
||||
@@ -81,7 +82,7 @@ let lastFinish = null;
|
||||
* @param {SessionSummary} summary
|
||||
*/
|
||||
export function recordFinish(before, after, today, summary) {
|
||||
lastFinish = { rewards: sessionRewards(before, after, { today }), summary };
|
||||
lastFinish = { rewards: sessionRewards(before, after, { today }), summary, sessions: strengthSessions(after) };
|
||||
}
|
||||
|
||||
export function takeFinish() {
|
||||
@@ -166,6 +167,7 @@ export function finishScreen({ nav }) {
|
||||
rewards.streak.after > 0 && h("p", { class: "muted reward__streak" },
|
||||
`Série : ${rewards.streak.after} semaine${rewards.streak.after > 1 ? "s" : ""}.`,
|
||||
rewards.streak.after > rewards.streak.before ? " Elle monte." : ""),
|
||||
installOffer("finish", { hasProgram: true, sessions: done.sessions }),
|
||||
h("div", { class: "action-bar" }, h("div", { class: "action-bar__in" },
|
||||
h("a", { class: "btn btn--primary btn--block btn--lg", href: href.home() }, "Continuer"))));
|
||||
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
// Installation de l'app sur l'écran d'accueil du téléphone.
|
||||
//
|
||||
// - Chrome et ses cousins envoient beforeinstallprompt : on garde l'invite
|
||||
// (sans la laisser s'afficher d'elle-même) et un bouton « Installer » l'ouvre.
|
||||
// - Sans invite (Safari sur iPhone, Firefox), on donne la marche à suivre.
|
||||
// - Une fois l'app installée (appinstalled, display-mode: standalone, ou
|
||||
// navigator.standalone sur iOS), on n'en parle plus.
|
||||
//
|
||||
// Quand le proposer (shouldOfferInstall) : après l'adoption du premier
|
||||
// programme (accueil), puis à la fin de la 1re et de la 3e séance. « Plus tard »
|
||||
// la cache pour 3 séances ; après deux refus, plus d'invite d'elle-même. Les
|
||||
// refus sont une préférence de l'appareil, gardée dans le stockage local, jamais
|
||||
// un événement (ADR 0006, point 3). Le Profil garde une entrée permanente.
|
||||
|
||||
import { h, replace } from "./dom.js";
|
||||
|
||||
/** @typedef {"ios"|"other"} InstallPlatform */
|
||||
/** @typedef {"home"|"finish"} InstallPlace */
|
||||
|
||||
/**
|
||||
* Refus de la carte sur cet appareil.
|
||||
* @typedef {object} InstallPref
|
||||
* @property {number} dismissals nombre de « Plus tard »
|
||||
* @property {number} dismissedAt séances faites au dernier « Plus tard »
|
||||
*/
|
||||
|
||||
/** Séances de plus avant que la carte revienne après un « Plus tard ». */
|
||||
export const SESSIONS_AFTER_DISMISS = 3;
|
||||
/** Au-delà de ce nombre de refus, la carte ne revient plus d'elle-même. */
|
||||
export const MAX_DISMISSALS = 2;
|
||||
|
||||
/**
|
||||
* La marche à suivre selon l'appareil : l'iPhone et l'iPad ont la leur (Safari,
|
||||
* Partager) ; les autres passent par le menu du navigateur. L'iPad récent se
|
||||
* présente comme un Mac : on le reconnaît à son écran tactile.
|
||||
* @param {string} userAgent
|
||||
* @param {number} [maxTouchPoints]
|
||||
* @returns {InstallPlatform}
|
||||
*/
|
||||
export function installPlatform(userAgent, maxTouchPoints = 0) {
|
||||
if (/iPhone|iPad|iPod/.test(userAgent)) return "ios";
|
||||
if (/Macintosh/.test(userAgent) && maxTouchPoints > 1) return "ios";
|
||||
return "other";
|
||||
}
|
||||
|
||||
/**
|
||||
* Faut-il montrer la carte d'installation à cet endroit ?
|
||||
* @param {object} o
|
||||
* @param {InstallPlace} o.place accueil, ou écran de fin de séance
|
||||
* @param {boolean} o.installed l'app tourne déjà installée
|
||||
* @param {boolean} o.hasProgram un programme est adopté (sinon : onboarding)
|
||||
* @param {number} o.sessions séances de force faites, celle qui vient de finir comprise
|
||||
* @param {InstallPref} o.pref
|
||||
*/
|
||||
export function shouldOfferInstall({ place, installed, hasProgram, sessions, pref }) {
|
||||
if (installed || !hasProgram) return false;
|
||||
if (pref.dismissals >= MAX_DISMISSALS) return false;
|
||||
if (pref.dismissals > 0) {
|
||||
// Après un refus : rien avant 3 séances de plus, puis à la fin d'une séance.
|
||||
return place === "finish" && sessions >= pref.dismissedAt + SESSIONS_AFTER_DISMISS;
|
||||
}
|
||||
if (place === "home") return sessions === 0;
|
||||
return sessions === 1 || sessions === 3;
|
||||
}
|
||||
|
||||
/**
|
||||
* Un « Plus tard » de plus.
|
||||
* @param {InstallPref} pref
|
||||
* @param {number} sessions
|
||||
* @returns {InstallPref}
|
||||
*/
|
||||
export function dismissInstall(pref, sessions) {
|
||||
return { dismissals: pref.dismissals + 1, dismissedAt: sessions };
|
||||
}
|
||||
|
||||
/**
|
||||
* Séances de force faites : ce qui compte pour le moment de la carte.
|
||||
* @param {import("../domain/state.js").State} state
|
||||
*/
|
||||
export function strengthSessions(state) {
|
||||
return state.sessions.filter((s) => s.kind === "strength").length;
|
||||
}
|
||||
|
||||
// ---- préférence de l'appareil -------------------------------------------------
|
||||
|
||||
const KEY = "ia-fit.install";
|
||||
/** @type {InstallPref} */
|
||||
const NONE = { dismissals: 0, dismissedAt: 0 };
|
||||
/** Repli si le stockage est interdit : le refus vaut pour cette visite. */
|
||||
let memory = NONE;
|
||||
|
||||
/** @returns {InstallPref} */
|
||||
export function readInstallPref() {
|
||||
try {
|
||||
const raw = localStorage.getItem(KEY);
|
||||
if (!raw) return memory;
|
||||
const v = JSON.parse(raw);
|
||||
const n = (/** @type {unknown} */ x) => (Number.isInteger(x) && /** @type {number} */ (x) >= 0 ? /** @type {number} */ (x) : 0);
|
||||
return { dismissals: n(v?.dismissals), dismissedAt: n(v?.dismissedAt) };
|
||||
} catch {
|
||||
return memory;
|
||||
}
|
||||
}
|
||||
|
||||
/** @param {InstallPref} pref */
|
||||
export function writeInstallPref(pref) {
|
||||
memory = pref;
|
||||
try {
|
||||
localStorage.setItem(KEY, JSON.stringify(pref));
|
||||
} catch {
|
||||
// stockage plein ou interdit : gardé en mémoire
|
||||
}
|
||||
}
|
||||
|
||||
// ---- l'écoute du navigateur ---------------------------------------------------
|
||||
|
||||
/**
|
||||
* L'événement beforeinstallprompt (Chrome), absent des types du DOM.
|
||||
* @typedef {Event & {prompt: () => Promise<unknown>, userChoice: Promise<{outcome: "accepted"|"dismissed"}>}} InstallPromptEvent
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {object} Installer
|
||||
* @property {boolean} installed l'app tourne installée, ou vient de l'être
|
||||
* @property {boolean} canPrompt le navigateur a donné son invite
|
||||
* @property {() => Promise<"accepted"|"dismissed"|"unavailable">} offer ouvre l'invite du système
|
||||
* @property {(fn: () => void) => () => void} subscribe prévenu à chaque changement ; renvoie de quoi se désabonner
|
||||
*/
|
||||
|
||||
/**
|
||||
* Ce dont l'installateur a besoin de la fenêtre (une fausse fenêtre en test).
|
||||
* @typedef {object} InstallWindow
|
||||
* @property {(type: string, fn: (e: Event) => void) => void} addEventListener
|
||||
* @property {(query: string) => {matches: boolean}} matchMedia
|
||||
* @property {{standalone?: boolean}} navigator
|
||||
*/
|
||||
|
||||
/**
|
||||
* Écoute la fenêtre : garde l'invite, note l'installation.
|
||||
* @param {InstallWindow} win
|
||||
* @returns {Installer}
|
||||
*/
|
||||
export function createInstaller(win) {
|
||||
let installedNow = false;
|
||||
/** @type {InstallPromptEvent|null} */
|
||||
let deferred = null;
|
||||
/** @type {Set<() => void>} */
|
||||
const listeners = new Set();
|
||||
const changed = () => { for (const fn of [...listeners]) fn(); };
|
||||
|
||||
win.addEventListener("beforeinstallprompt", (e) => {
|
||||
e.preventDefault();
|
||||
deferred = /** @type {InstallPromptEvent} */ (e);
|
||||
changed();
|
||||
});
|
||||
win.addEventListener("appinstalled", () => {
|
||||
installedNow = true;
|
||||
deferred = null;
|
||||
changed();
|
||||
});
|
||||
|
||||
return {
|
||||
get installed() {
|
||||
return installedNow || win.matchMedia("(display-mode: standalone)").matches || win.navigator.standalone === true;
|
||||
},
|
||||
get canPrompt() {
|
||||
return deferred !== null;
|
||||
},
|
||||
async offer() {
|
||||
const e = deferred;
|
||||
if (!e) return "unavailable";
|
||||
// Une invite ne sert qu'une fois.
|
||||
deferred = null;
|
||||
try {
|
||||
await e.prompt();
|
||||
return (await e.userChoice).outcome;
|
||||
} catch {
|
||||
return "unavailable";
|
||||
} finally {
|
||||
changed();
|
||||
}
|
||||
},
|
||||
subscribe(fn) {
|
||||
listeners.add(fn);
|
||||
return () => listeners.delete(fn);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** @type {Installer|null} */
|
||||
let current = null;
|
||||
|
||||
/**
|
||||
* L'installateur de la page, créé au premier appel : main.js l'appelle au
|
||||
* démarrage pour ne pas manquer beforeinstallprompt.
|
||||
* @returns {Installer}
|
||||
*/
|
||||
export function startInstaller() {
|
||||
current ??= createInstaller(/** @type {InstallWindow} */ (/** @type {unknown} */ (window)));
|
||||
return current;
|
||||
}
|
||||
|
||||
// ---- la carte -----------------------------------------------------------------
|
||||
|
||||
/** @type {Record<InstallPlatform, string[][]>} */
|
||||
const STEPS = {
|
||||
ios: [
|
||||
["Touche Partager", " (le carré avec une flèche vers le haut)."],
|
||||
["Choisis « Sur l'écran d'accueil »", ", plus bas dans la liste."],
|
||||
["Touche « Ajouter »", ". IA-Fit s'ouvre ensuite comme une app."],
|
||||
],
|
||||
other: [
|
||||
["Ouvre le menu", " du navigateur (⋮ ou ☰)."],
|
||||
["Choisis « Installer »", " ou « Ajouter à l'écran d'accueil »."],
|
||||
["Confirme", ". IA-Fit s'ouvre ensuite comme une app."],
|
||||
],
|
||||
};
|
||||
|
||||
/**
|
||||
* Le contenu de la carte : le bouton de l'invite système, sinon la marche à
|
||||
* suivre.
|
||||
* @param {Installer} installer
|
||||
*/
|
||||
function installBody(installer) {
|
||||
if (installer.canPrompt) {
|
||||
return h("button", { type: "button", class: "btn btn--primary btn--block", on: { click: () => void installer.offer() } }, "Installer");
|
||||
}
|
||||
const platform = installPlatform(navigator.userAgent, navigator.maxTouchPoints);
|
||||
return h("ol", { class: "how" }, STEPS[platform].map(([strong, rest]) =>
|
||||
h("li", { class: "how__step" }, h("span", null, h("strong", null, strong), rest))));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tient un nœud à jour au fil de l'installateur ; le retire une fois l'app
|
||||
* installée. L'abonnement tombe quand le nœud a quitté la page (les
|
||||
* événements du navigateur arrivent toujours après l'affichage).
|
||||
* @param {HTMLElement} node
|
||||
* @param {Installer} installer
|
||||
* @param {() => void} paint
|
||||
*/
|
||||
function follow(node, installer, paint) {
|
||||
const stop = installer.subscribe(() => {
|
||||
if (!node.isConnected || installer.installed) {
|
||||
stop();
|
||||
node.remove();
|
||||
} else paint();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Carte « Sur ton écran d'accueil ». Avec onLater, un bouton « Plus tard » la
|
||||
* retire.
|
||||
* @param {{installer: Installer, onLater?: () => void}} o
|
||||
* @returns {HTMLElement}
|
||||
*/
|
||||
export function installCard({ installer, onLater }) {
|
||||
const body = h("div");
|
||||
const paint = () => replace(body, installBody(installer));
|
||||
paint();
|
||||
const node = h("section", { class: "block install", "aria-label": "Installer l'app" },
|
||||
h("h2", { class: "h2" }, "Sur ton écran d'accueil"),
|
||||
h("p", { class: "block__meta" }, "IA-Fit s'ouvre comme une app : plein écran, d'un geste, même hors ligne."),
|
||||
body,
|
||||
onLater && h("button", { type: "button", class: "btn btn--ghost btn--block", on: { click: () => { onLater(); node.remove(); } } }, "Plus tard"));
|
||||
follow(node, installer, paint);
|
||||
return node;
|
||||
}
|
||||
|
||||
/**
|
||||
* La carte, si c'est le moment de la proposer ici ; sinon null.
|
||||
* @param {InstallPlace} place
|
||||
* @param {{hasProgram: boolean, sessions: number}} o
|
||||
* @returns {HTMLElement|null}
|
||||
*/
|
||||
export function installOffer(place, { hasProgram, sessions }) {
|
||||
const installer = startInstaller();
|
||||
if (!shouldOfferInstall({ place, installed: installer.installed, hasProgram, sessions, pref: readInstallPref() })) return null;
|
||||
return installCard({ installer, onLater: () => writeInstallPref(dismissInstall(readInstallPref(), sessions)) });
|
||||
}
|
||||
|
||||
/**
|
||||
* Entrée permanente (Profil) : « Installer l'app sur l'écran d'accueil » ouvre
|
||||
* la carte, tant que l'app n'est pas installée.
|
||||
* @returns {HTMLElement|null}
|
||||
*/
|
||||
export function installEntry() {
|
||||
const installer = startInstaller();
|
||||
if (installer.installed) return null;
|
||||
const panel = installCard({ installer });
|
||||
panel.hidden = true;
|
||||
const toggle = h("button", { type: "button", class: "btn btn--block", "aria-expanded": "false" }, "Installer l'app sur l'écran d'accueil");
|
||||
toggle.addEventListener("click", () => {
|
||||
panel.hidden = !panel.hidden;
|
||||
toggle.setAttribute("aria-expanded", String(!panel.hidden));
|
||||
});
|
||||
const node = h("div", { class: "install-entry" }, toggle, panel);
|
||||
follow(node, installer, () => {});
|
||||
return node;
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import { proposalCard } from "../proposal-card.js";
|
||||
import { estimatedMinutes } from "../../domain/progression.js";
|
||||
import { hud } from "../game.js";
|
||||
import { toast } from "../feedback.js";
|
||||
import { installOffer, strengthSessions } from "../install.js";
|
||||
|
||||
/** @typedef {import("../../domain/state.js").State} State */
|
||||
/** @typedef {import("../../domain/planning.js").Slot} Slot */
|
||||
@@ -163,6 +164,7 @@ function homeContent(store, nav, today, synced) {
|
||||
hud(state, today),
|
||||
h("header", { class: "visually-hidden" }, h("h1", null, program.name)),
|
||||
todayBlock,
|
||||
installOffer("home", { hasProgram: true, sessions: strengthSessions(state) }),
|
||||
|
||||
oneOffs.length > 0 && [
|
||||
h("h2", { class: "tape" }, "WOD proposé", h("span", { class: "tape__hint" }, "hors rotation")),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Profil (ProfileUpdated) et mode (ModeChanged) : ce que l'IA doit savoir pour
|
||||
// construire et faire évoluer le programme. Plus le thème, simple préférence
|
||||
// d'affichage de l'appareil (pas un événement, ADR 0006 point 3).
|
||||
// d'affichage de l'appareil (pas un événement, ADR 0006 point 3), et l'entrée
|
||||
// permanente pour installer l'app sur l'écran d'accueil (install.js).
|
||||
|
||||
import { h } from "../dom.js";
|
||||
import { MODES } from "../../domain/vocabulary.js";
|
||||
@@ -9,6 +10,7 @@ import { screenHeader } from "../layout.js";
|
||||
import { href } from "../router.js";
|
||||
import { toast } from "../feedback.js";
|
||||
import { getTheme, setTheme } from "../theme-pref.js";
|
||||
import { installEntry } from "../install.js";
|
||||
|
||||
/** @type {Record<string, {label: string, text: string}>} */
|
||||
export const MODE_LABELS = {
|
||||
@@ -117,6 +119,7 @@ export function profileScreen({ store, nav }) {
|
||||
h("h2", { class: "tape" }, "Affichage"),
|
||||
h("div", { class: "segmented", role: "group", "aria-label": "Thème" }, themeBtns),
|
||||
h("p", { class: "muted" }, "Sombre par défaut : un écran OLED noir consomme moins."),
|
||||
installEntry(),
|
||||
h("h2", { class: "tape" }, "Appareils et IA"),
|
||||
h("p", { class: "muted" }, "Relier ton téléphone et ton PC, brancher ton IA : sans compte, par une clé de synchro."),
|
||||
h("a", { class: "btn btn--block sync-gap", href: href.sync() }, "Synchro et IA"));
|
||||
|
||||
@@ -22,7 +22,7 @@ const START = new Date("2026-11-18T09:00:00");
|
||||
|
||||
const TYPES = {
|
||||
".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".mjs": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8",
|
||||
".json": "application/json", ".webmanifest": "application/manifest+json", ".svg": "image/svg+xml",
|
||||
".json": "application/json", ".webmanifest": "application/manifest+json", ".svg": "image/svg+xml", ".png": "image/png",
|
||||
".woff2": "font/woff2", ".md": "text/markdown; charset=utf-8", ".txt": "text/plain; charset=utf-8",
|
||||
};
|
||||
|
||||
@@ -107,6 +107,28 @@ function check(scheme, cond, msg) {
|
||||
ok(await page.getByText("Pas de planning").isVisible(), "accueil sans planning : rotation annoncée");
|
||||
ok(await page.locator(".hud").isVisible(), "HUD de niveau affiché");
|
||||
|
||||
// ---- installation : carte après l'adoption, « Plus tard », icônes ----------------
|
||||
const install = page.locator(".install");
|
||||
ok(await install.isVisible() && await install.getByText("Ouvre le menu").isVisible(), "carte d'installation après l'adoption (marche à suivre)");
|
||||
await shot("02b-installation", true);
|
||||
await install.getByRole("button", { name: "Plus tard" }).click();
|
||||
ok(await install.count() === 0, "« Plus tard » cache la carte");
|
||||
await go("#/");
|
||||
ok(await page.locator(".install").count() === 0, "carte toujours cachée après rechargement");
|
||||
ok(await page.evaluate(() => localStorage.getItem("ia-fit.install")) === '{"dismissals":1,"dismissedAt":0}', "refus gardé sur l'appareil");
|
||||
const manifest = await (await page.request.get(base + "manifest.webmanifest")).json();
|
||||
const pngs = manifest.icons.filter((i) => i.type === "image/png");
|
||||
ok(pngs.some((i) => i.sizes === "192x192") && pngs.some((i) => i.sizes === "512x512" && i.purpose === "any")
|
||||
&& pngs.some((i) => i.sizes === "512x512" && i.purpose === "maskable"), "manifeste : PNG 192, 512 et maskable 512");
|
||||
const apple = await page.locator('link[rel="apple-touch-icon"]').getAttribute("href");
|
||||
for (const { src, sizes } of [...pngs, { src: apple, sizes: "180x180" }]) {
|
||||
const res = await page.request.get(base + src);
|
||||
const body = await res.body();
|
||||
// Largeur et hauteur d'un PNG : octets 16 à 23 (en-tête IHDR).
|
||||
const size = `${body.readUInt32BE(16)}x${body.readUInt32BE(20)}`;
|
||||
ok(res.status() === 200 && res.headers()["content-type"] === "image/png" && size === sizes, `icône ${src} servie, ${size}`);
|
||||
}
|
||||
|
||||
// ---- semaine : jours, jour imposé, semaine suivante, .ics ------------------------
|
||||
await go("#/semaine");
|
||||
for (const d of ["lundi", "mercredi", "vendredi", "samedi"]) await page.getByRole("button", { name: d, exact: true }).click();
|
||||
@@ -200,6 +222,7 @@ function check(scheme, cond, msg) {
|
||||
ok(await page.getByText("Bien joué.").isVisible(), "écran de fin de séance");
|
||||
ok(await page.locator(".reward__gain").innerText().then((t) => /\+\d+ XP/.test(t.replace(/\s/g, " "))), "XP gagnée affichée");
|
||||
ok(await page.locator(".reward__big .big-number").innerText().then((t) => t.replace(/\s/g, "") === "1860"), "1 860 kg soulevés (31 répétitions × 60 kg)");
|
||||
ok(await page.locator(".install").count() === 0, "fin de la 1re séance : pas de carte, refusée il y a moins de 3 séances");
|
||||
await shot("07-fin-de-seance", true);
|
||||
await page.getByRole("link", { name: "Continuer" }).click();
|
||||
await settle();
|
||||
@@ -275,6 +298,18 @@ function check(scheme, cond, msg) {
|
||||
await button("Maintien").click();
|
||||
ok(await button("Maintien").getAttribute("aria-pressed") === "true", "mode maintien");
|
||||
await shot("11-profil", true);
|
||||
// Entrée permanente : invite du navigateur simulée, puis installation.
|
||||
await button("Installer l'app sur l'écran d'accueil").click();
|
||||
ok(await page.locator(".install-entry .install").getByText("Choisis « Installer »").isVisible(), "profil : marche à suivre sans invite du navigateur");
|
||||
await page.evaluate(() => {
|
||||
const e = new Event("beforeinstallprompt", { cancelable: true });
|
||||
Object.assign(e, { prompt: async () => { window.__prompted = true; }, userChoice: Promise.resolve({ outcome: "accepted" }) });
|
||||
window.dispatchEvent(e);
|
||||
});
|
||||
await page.locator(".install-entry").getByRole("button", { name: "Installer", exact: true }).click();
|
||||
ok(await page.evaluate(() => window.__prompted === true), "profil : « Installer » ouvre l'invite du navigateur");
|
||||
await page.evaluate(() => window.dispatchEvent(new Event("appinstalled")));
|
||||
ok(await page.locator(".install-entry").count() === 0, "plus d'entrée une fois l'app installée");
|
||||
await button("Progression", { exact: true }).click();
|
||||
|
||||
// ---- analyses, progression -------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
// Installation de l'app : plateforme, moment de la carte, invite du navigateur.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { createInstaller, dismissInstall, installPlatform, shouldOfferInstall } from "../../app/ui/install.js";
|
||||
|
||||
const IPHONE = "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1";
|
||||
const IPAD = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Safari/605.1.15";
|
||||
const ANDROID_FIREFOX = "Mozilla/5.0 (Android 14; Mobile; rv:132.0) Gecko/132.0 Firefox/132.0";
|
||||
const ANDROID_CHROME = "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Mobile Safari/537.36";
|
||||
|
||||
test("plateforme : iPhone et iPad à part, les autres par le menu", () => {
|
||||
assert.equal(installPlatform(IPHONE), "ios");
|
||||
assert.equal(installPlatform(IPAD, 5), "ios", "l'iPad se présente comme un Mac tactile");
|
||||
assert.equal(installPlatform(IPAD, 0), "other", "un vrai Mac n'est pas tactile");
|
||||
assert.equal(installPlatform(ANDROID_FIREFOX), "other");
|
||||
assert.equal(installPlatform(ANDROID_CHROME), "other");
|
||||
assert.equal(installPlatform(""), "other");
|
||||
});
|
||||
|
||||
const fresh = { dismissals: 0, dismissedAt: 0 };
|
||||
/** @param {Partial<Parameters<typeof shouldOfferInstall>[0]>} o */
|
||||
const offer = (o) => shouldOfferInstall({ place: "home", installed: false, hasProgram: true, sessions: 0, pref: fresh, ...o });
|
||||
|
||||
test("jamais une fois installée, ni pendant l'onboarding", () => {
|
||||
assert.equal(offer({ installed: true }), false);
|
||||
assert.equal(offer({ place: "finish", sessions: 1, installed: true }), false);
|
||||
assert.equal(offer({ hasProgram: false }), false);
|
||||
});
|
||||
|
||||
test("accueil : après l'adoption, jusqu'à la première séance", () => {
|
||||
assert.equal(offer({ sessions: 0 }), true);
|
||||
assert.equal(offer({ sessions: 1 }), false);
|
||||
assert.equal(offer({ sessions: 5 }), false);
|
||||
});
|
||||
|
||||
test("fin de séance : après la 1re, puis la 3e, et plus ensuite", () => {
|
||||
const at = (/** @type {number} */ sessions) => offer({ place: "finish", sessions });
|
||||
assert.deepEqual([1, 2, 3, 4, 5, 6].map(at), [true, false, true, false, false, false]);
|
||||
});
|
||||
|
||||
test("« Plus tard » cache la carte pour 3 séances, deux refus l'arrêtent", () => {
|
||||
const once = dismissInstall(fresh, 0);
|
||||
assert.deepEqual(once, { dismissals: 1, dismissedAt: 0 });
|
||||
assert.equal(offer({ pref: once }), false, "plus sur l'accueil");
|
||||
assert.equal(offer({ place: "finish", sessions: 1, pref: once }), false, "pas à la 1re séance");
|
||||
assert.equal(offer({ place: "finish", sessions: 2, pref: once }), false);
|
||||
assert.equal(offer({ place: "finish", sessions: 3, pref: once }), true, "de retour 3 séances plus tard");
|
||||
assert.equal(offer({ place: "home", sessions: 3, pref: once }), false, "à la fin d'une séance seulement");
|
||||
|
||||
const later = dismissInstall(fresh, 1);
|
||||
assert.equal(offer({ place: "finish", sessions: 3, pref: later }), false, "refusée à la 1re : pas à la 3e");
|
||||
assert.equal(offer({ place: "finish", sessions: 4, pref: later }), true);
|
||||
|
||||
const twice = dismissInstall(once, 3);
|
||||
assert.deepEqual(twice, { dismissals: 2, dismissedAt: 3 });
|
||||
for (const sessions of [3, 6, 10, 50]) assert.equal(offer({ place: "finish", sessions, pref: twice }), false);
|
||||
});
|
||||
|
||||
/** Fausse fenêtre : événements à la main, display-mode réglable. */
|
||||
function fakeWindow({ standalone = false, iosStandalone = false } = {}) {
|
||||
/** @type {Record<string, ((e: any) => void)[]>} */
|
||||
const handlers = {};
|
||||
return {
|
||||
addEventListener: (/** @type {string} */ type, /** @type {(e: any) => void} */ fn) => { (handlers[type] ??= []).push(fn); },
|
||||
matchMedia: (/** @type {string} */ q) => ({ matches: standalone && q === "(display-mode: standalone)" }),
|
||||
navigator: { standalone: iosStandalone },
|
||||
/** @param {string} type @param {any} [e] */
|
||||
fire: (type, e = {}) => { for (const fn of handlers[type] ?? []) fn(e); },
|
||||
};
|
||||
}
|
||||
|
||||
/** @param {"accepted"|"dismissed"} outcome */
|
||||
function promptEvent(outcome) {
|
||||
const e = { prevented: false, prompted: 0, preventDefault() { e.prevented = true; }, async prompt() { e.prompted++; }, userChoice: Promise.resolve({ outcome }) };
|
||||
return e;
|
||||
}
|
||||
|
||||
test("installateur : garde l'invite, l'ouvre une fois, note l'installation", async () => {
|
||||
const win = fakeWindow();
|
||||
const installer = createInstaller(win);
|
||||
let changes = 0;
|
||||
installer.subscribe(() => changes++);
|
||||
assert.equal(installer.installed, false);
|
||||
assert.equal(installer.canPrompt, false);
|
||||
assert.equal(await installer.offer(), "unavailable");
|
||||
|
||||
const e = promptEvent("accepted");
|
||||
win.fire("beforeinstallprompt", e);
|
||||
assert.equal(e.prevented, true, "le navigateur ne l'affiche pas de lui-même");
|
||||
assert.equal(installer.canPrompt, true);
|
||||
assert.equal(await installer.offer(), "accepted");
|
||||
assert.equal(e.prompted, 1);
|
||||
assert.equal(installer.canPrompt, false, "une invite ne sert qu'une fois");
|
||||
|
||||
win.fire("appinstalled");
|
||||
assert.equal(installer.installed, true);
|
||||
assert.ok(changes >= 3);
|
||||
});
|
||||
|
||||
test("installateur : déjà installée (display-mode ou iOS)", () => {
|
||||
assert.equal(createInstaller(fakeWindow({ standalone: true })).installed, true);
|
||||
assert.equal(createInstaller(fakeWindow({ iosStandalone: true })).installed, true);
|
||||
});
|
||||
|
||||
test("installateur : se désabonner", () => {
|
||||
const win = fakeWindow();
|
||||
const installer = createInstaller(win);
|
||||
let changes = 0;
|
||||
const stop = installer.subscribe(() => changes++);
|
||||
stop();
|
||||
win.fire("appinstalled");
|
||||
assert.equal(changes, 0);
|
||||
});
|
||||
Reference in New Issue
Block a user