211 lines
9.2 KiB
JavaScript
211 lines
9.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, point 4) sont réservés : le routeur ne les interprète pas et ne
|
|
// les réécrit pas : main.js les lit (link.js, sync-model.js), puis remplace
|
|
// l'adresse.
|
|
//
|
|
// Une adresse peut porter des paramètres après « ? » : l'état de navigation
|
|
// (filtres, recherche) y vit, ADR 0009. L'écran qui les lit ignore ceux qu'il ne
|
|
// connaît pas ; changer un filtre remplace l'adresse sans reconstruire l'écran
|
|
// (nav.set) ; ouvrir un élément sur place l'empile (nav.set avec push). La page
|
|
// d'autorisation d'une IA (#/connecter-ia?…) reçoit sa requête brute, à renvoyer
|
|
// telle quelle.
|
|
|
|
/**
|
|
* @typedef {{name: "home"}
|
|
* | {name: "session", key: string, date: string|null}
|
|
* | {name: "finish"}
|
|
* | {name: "progress"}
|
|
* | {name: "history"}
|
|
* | {name: "history-edit", id: string}
|
|
* | {name: "week", query: string}
|
|
* | {name: "activities", query: string}
|
|
* | {name: "weight", query: string}
|
|
* | {name: "data"}
|
|
* | {name: "profile"}
|
|
* | {name: "analysis", exercise: string|null}
|
|
* | {name: "proposal", id: string}
|
|
* | {name: "sync"}
|
|
* | {name: "pair"}
|
|
* | {name: "connect-ai", query: string}
|
|
* | {name: "library", query: string}
|
|
* | {name: "library-item", id: string, query: string}
|
|
* | {name: "wods", query: string}
|
|
* | {name: "wod", id: string}
|
|
* | {name: "reserved"}
|
|
* | {name: "not-found"}} Route
|
|
*/
|
|
|
|
/** Fragments réservés à d'autres modules. */
|
|
export const RESERVED = ["#import=", "#import-json=", "#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 q = hash.indexOf("?");
|
|
const query = q < 0 ? "" : hash.slice(q + 1);
|
|
const path = (q < 0 ? hash : hash.slice(0, q)).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 (head === "connecter-ia" && parts.length === 1) return { name: "connect-ai", query };
|
|
if (head === "bibliotheque" && parts.length === 1) return { name: "library", query };
|
|
if (head === "bibliotheque" && parts.length === 2 && arg) return { name: "library-item", id: arg, query };
|
|
if (head === "wod" && parts.length === 1) return { name: "wods", query };
|
|
if (head === "wod" && parts.length === 2 && arg) return { name: "wod", id: arg };
|
|
if (parts.length === 1 && WITH_QUERY[head]) return /** @type {Route} */ ({ name: WITH_QUERY[head], query });
|
|
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",
|
|
donnees: "data", profil: "profile", synchro: "sync", relier: "pair",
|
|
};
|
|
|
|
/** Écrans à chemin simple qui lisent leur requête : adresse → nom. @type {Record<string, string>} */
|
|
const WITH_QUERY = { semaine: "week", activites: "activities", poids: "weight" };
|
|
|
|
/**
|
|
* Une adresse et sa requête, dans l'ordre des clés. Une valeur absente (null,
|
|
* undefined, chaîne vide) ou égale à sa valeur par défaut est omise : l'adresse
|
|
* reste la plus courte possible, et la même pour un même état.
|
|
* @param {string} path chemin, par exemple « #/poids »
|
|
* @param {Record<string, string|number|null|undefined>} params
|
|
* @param {Record<string, string|number>} [defaults]
|
|
*/
|
|
export function withParams(path, params, defaults = {}) {
|
|
const p = new URLSearchParams();
|
|
for (const [key, value] of Object.entries(params))
|
|
if (value != null && value !== "" && !(key in defaults && String(value) === String(defaults[key]))) p.set(key, String(value));
|
|
const query = p.toString();
|
|
return query ? path + "?" + query : path;
|
|
}
|
|
|
|
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),
|
|
/** semaine : AAAA-Www, absente pour la semaine en cours ; jour : 1 (lundi) à 7, le jour déplié */
|
|
week: (/** @type {{week?: string|null, day?: number|null}} */ { week = null, day = null } = {}) => withParams("#/semaine", { semaine: week, jour: day }),
|
|
/** modifier : l'activité en cours de modification */
|
|
activities: (/** @type {string|null} */ edit = null) => withParams("#/activites", { modifier: edit }),
|
|
/** periode : 3mois (par défaut, omise), 1an ou tout */
|
|
weight: (/** @type {string|null} */ period = null) => withParams("#/poids", { periode: period }, { periode: "3mois" }),
|
|
data: () => "#/donnees",
|
|
profile: () => "#/profil",
|
|
analysis: (/** @type {string|null} */ exercise = null) => "#/analyses" + (exercise ? "/" + enc(exercise) : ""),
|
|
proposal: (/** @type {string} */ id) => "#/proposition/" + enc(id),
|
|
sync: () => "#/synchro",
|
|
pair: () => "#/relier",
|
|
library: (/** @type {string} */ query = "") => "#/bibliotheque" + (query ? "?" + query : ""),
|
|
/** Le catalogue, et le tirage du WOD du jour (1 omis). */
|
|
wods: (/** @type {number} */ draw = 1) => withParams("#/wod", { tirage: draw > 1 ? draw : null }),
|
|
wod: (/** @type {string} */ id) => "#/wod/" + enc(id),
|
|
libraryItem: (/** @type {string} */ id, /** @type {string} */ query = "") => "#/bibliotheque/" + enc(id) + (query ? "?" + query : ""),
|
|
};
|
|
|
|
/**
|
|
* @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
|
|
* @property {(hash: string, options?: {push?: boolean}) => void} set change l'adresse
|
|
* sans reconstruire l'écran (un filtre qui change : l'écran se repeint lui-même,
|
|
* garde focus et défilement). L'adresse est remplacée, ou empilée avec push : un
|
|
* élément ouvert sur place, que le retour referme en reconstruisant l'écran.
|
|
*/
|
|
|
|
/**
|
|
* 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;
|
|
},
|
|
set(hash, { push = false } = {}) {
|
|
if (hash === location.hash) return;
|
|
if (push) {
|
|
// pushState ne déclenche pas hashchange ; revenir en arrière, si.
|
|
history.pushState(null, "", hash);
|
|
visited.push(hash);
|
|
} else {
|
|
history.replaceState(null, "", hash);
|
|
visited[visited.length - 1] = 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;
|
|
}
|