300 lines
11 KiB
JavaScript
300 lines
11 KiB
JavaScript
// 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;
|
|
}
|