Files
ia-fit/app/ui/router.js
T

144 lines
5.2 KiB
JavaScript

// Un écran par adresse, dans le fragment (#/…) : l'app reste un site statique
// et le bouton retour du navigateur fonctionne.
//
// Les fragments #import= (lien d'une IA, ADR 0005 point 7) et #pair=
// (appariement, lot 2) sont réservés : le routeur ne les interprète pas et ne
// les réécrit pas : main.js lit #import= (link.js) ; #pair= attend le lot 2.
/**
* @typedef {{name: "home"}
* | {name: "session", key: string, date: string|null}
* | {name: "finish"}
* | {name: "progress"}
* | {name: "history"}
* | {name: "history-edit", id: string}
* | {name: "week"}
* | {name: "activities"}
* | {name: "weight"}
* | {name: "data"}
* | {name: "profile"}
* | {name: "analysis", exercise: string|null}
* | {name: "proposal", id: string}
* | {name: "reserved"}
* | {name: "not-found"}} Route
*/
/** Fragments réservés à d'autres modules. */
export const RESERVED = ["#import=", "#pair="];
/**
* Lit une adresse. Fonction pure, testée.
* @param {string} hash location.hash, avec son #
* @returns {Route}
*/
export function parseRoute(hash) {
if (RESERVED.some((p) => hash.startsWith(p))) return { name: "reserved" };
const path = hash.replace(/^#\/?/, "").replace(/\/+$/, "");
if (path === "") return { name: "home" };
const parts = path.split("/").map((p) => {
try { return decodeURIComponent(p); } catch { return p; }
});
const [head, arg, extra] = parts;
if (head === "seance" && arg && parts.length === 2) return { name: "session", key: arg, date: null };
if (head === "seance" && arg && parts.length === 3 && /^\d{4}-\d{2}-\d{2}$/.test(extra)) return { name: "session", key: arg, date: extra };
if (head === "historique" && parts.length === 2 && arg) return { name: "history-edit", id: arg };
if (head === "analyses" && parts.length === 1) return { name: "analysis", exercise: null };
if (head === "analyses" && parts.length === 2 && arg) return { name: "analysis", exercise: arg };
if (head === "proposition" && parts.length === 2 && arg) return { name: "proposal", id: arg };
if (parts.length === 1 && SIMPLE[head]) return /** @type {Route} */ ({ name: SIMPLE[head] });
return { name: "not-found" };
}
/** Écrans sans paramètre : adresse → nom. @type {Record<string, string>} */
const SIMPLE = {
bravo: "finish", progression: "progress", historique: "history", semaine: "week", activites: "activities",
poids: "weight", donnees: "data", profil: "profile",
};
const enc = encodeURIComponent;
/** Adresses, pour écrire les liens sans les recopier. */
export const href = {
home: () => "#/",
session: (/** @type {string} */ key, /** @type {string|null} */ date = null) => "#/seance/" + enc(key) + (date ? "/" + date : ""),
finish: () => "#/bravo",
progress: () => "#/progression",
history: () => "#/historique",
historyEdit: (/** @type {string} */ id) => "#/historique/" + enc(id),
week: () => "#/semaine",
activities: () => "#/activites",
weight: () => "#/poids",
data: () => "#/donnees",
profile: () => "#/profil",
analysis: (/** @type {string|null} */ exercise = null) => "#/analyses" + (exercise ? "/" + enc(exercise) : ""),
proposal: (/** @type {string} */ id) => "#/proposition/" + enc(id),
};
/**
* @typedef {object} Screen
* @property {HTMLElement} node
* @property {string} title titre de l'onglet
* @property {() => void} [destroy] appelé quand on quitte l'écran
*/
/**
* @typedef {object} Navigation
* @property {(hash: string, options?: {replace?: boolean}) => void} go
* @property {(fallback?: string) => void} back retour dans l'app, ou vers fallback
*/
/**
* Branche le routeur sur la fenêtre.
* @param {HTMLElement} root
* @param {(route: Route, nav: Navigation) => Screen} render
*/
export function startRouter(root, render) {
/** Adresses vues pendant la visite, pour savoir si « retour » reste dans l'app. */
const visited = [location.hash];
/** @type {Screen|null} */
let current = null;
/** @type {Navigation} */
const nav = {
go(hash, { replace = false } = {}) {
if (replace) {
history.replaceState(null, "", hash);
visited[visited.length - 1] = hash;
show();
} else location.hash = hash;
},
back(fallback = href.home()) {
if (visited.length > 1) history.back();
else nav.go(fallback, { replace: true });
},
};
const show = () => {
let route = parseRoute(location.hash);
// Un fragment réservé ne change pas l'écran ; au démarrage, on montre l'accueil.
if (route.name === "reserved") {
if (current) return;
route = { name: "home" };
}
current?.destroy?.();
current = render(route, nav);
root.replaceChildren(current.node);
document.title = current.title ? `${current.title} · IA-Fit` : "IA-Fit";
window.scrollTo(0, 0);
// Le focus suit l'écran (lecteurs d'écran, clavier).
const heading = current.node.querySelector("h1");
if (heading) {
heading.setAttribute("tabindex", "-1");
heading.focus({ preventScroll: true });
}
};
window.addEventListener("hashchange", () => {
if (visited.length > 1 && visited[visited.length - 2] === location.hash) visited.pop();
else visited.push(location.hash);
show();
});
show();
return nav;
}