diff --git a/Makefile b/Makefile
index db66f83..a9e4a8c 100644
--- a/Makefile
+++ b/Makefile
@@ -67,6 +67,25 @@ lint: $(TSC) $(TYPES_NODE) ## Vérifie les types (JSDoc), la syntaxe et les scri
else docker run --rm -v "$(CURDIR):/mnt:ro" -w /mnt $(SHELLCHECK_IMAGE) scripts/*.sh tests/*.sh; fi
@echo "Lint : OK"
+# Parcours dans un vrai navigateur (ADR 0007) : Chromium de l'image Playwright,
+# le paquet playwright (Apache-2.0) installé dans build/browser-tools, jamais
+# publié. Captures 412×915 et poids transféré dans build/shots/.
+PLAYWRIGHT_VERSION := 1.48.2
+PLAYWRIGHT_IMAGE := mcr.microsoft.com/playwright:v$(PLAYWRIGHT_VERSION)-noble
+BROWSER_TOOLS := build/browser-tools
+PLAYWRIGHT := $(BROWSER_TOOLS)/node_modules/playwright/package.json
+
+$(PLAYWRIGHT):
+ npm install --silent --no-audit --no-fund --prefix $(BROWSER_TOOLS) playwright@$(PLAYWRIGHT_VERSION)
+
+.PHONY: test-browser
+test-browser: $(PLAYWRIGHT) ## Parcours Playwright de l'app, captures dans build/shots/ (Docker)
+ @mkdir -p build/shots
+ @docker run --rm --init --ipc=host -u "$$(id -u):$$(id -g)" -e HOME=/tmp \
+ -v "$(CURDIR)/$(APP_DIR):/app:ro" -v "$(CURDIR)/tests/browser:/tests:ro" \
+ -v "$(CURDIR)/$(BROWSER_TOOLS):/tools:ro" -v "$(CURDIR)/build/shots:/shots" \
+ $(PLAYWRIGHT_IMAGE) node /tests/parcours.cjs /app /shots
+
test-site: ## Construit l'image de production en local et vérifie ce qu'elle sert (Docker)
@tests/test_site.sh
diff --git a/app/fonts/barlow-condensed-bold.woff2 b/app/fonts/barlow-condensed-bold.woff2
index bfa5f5d..790097d 100644
Binary files a/app/fonts/barlow-condensed-bold.woff2 and b/app/fonts/barlow-condensed-bold.woff2 differ
diff --git a/app/fonts/barlow-condensed-medium.woff2 b/app/fonts/barlow-condensed-medium.woff2
deleted file mode 100644
index ba4fb60..0000000
Binary files a/app/fonts/barlow-condensed-medium.woff2 and /dev/null differ
diff --git a/app/fonts/barlow-condensed-semibold.woff2 b/app/fonts/barlow-condensed-semibold.woff2
deleted file mode 100644
index 67c352f..0000000
Binary files a/app/fonts/barlow-condensed-semibold.woff2 and /dev/null differ
diff --git a/app/icons/icon-maskable.svg b/app/icons/icon-maskable.svg
index d0b1ad3..f637bd2 100644
--- a/app/icons/icon-maskable.svg
+++ b/app/icons/icon-maskable.svg
@@ -1,8 +1,8 @@
diff --git a/app/icons/icon.svg b/app/icons/icon.svg
index a9c7cbb..0bbe636 100644
--- a/app/icons/icon.svg
+++ b/app/icons/icon.svg
@@ -1,8 +1,8 @@
diff --git a/app/index.html b/app/index.html
index 6bd02f5..5c2d4a3 100644
--- a/app/index.html
+++ b/app/index.html
@@ -4,18 +4,20 @@
-
-
-
+
+
+
IA-Fit
+
+
diff --git a/app/infra/event-store.js b/app/infra/event-store.js
index 1dca54c..bffa582 100644
--- a/app/infra/event-store.js
+++ b/app/infra/event-store.js
@@ -78,7 +78,9 @@ export async function openEventStore(dbName = "ia-fit") {
r.onsuccess = () => added++;
// id déjà présent : on empêche l'erreur d'annuler toute la transaction
r.onerror = (e) => {
- if (r.error?.name === "ConstraintError") e.preventDefault();
+ // Déjà présent : ce n'est pas une erreur (fusion par union). Sans
+ // stopPropagation, l'erreur remonte quand même à la transaction.
+ if (r.error?.name === "ConstraintError") { e.preventDefault(); e.stopPropagation(); }
};
}
await committed(tx);
diff --git a/app/main.js b/app/main.js
index dc18c73..3121d98 100644
--- a/app/main.js
+++ b/app/main.js
@@ -1,18 +1,31 @@
-// Démarrage de l'app : le magasin, le minuteur, le routeur et ses écrans.
+// Démarrage de l'app : le journal (IndexedDB), le magasin, le minuteur, le
+// routeur et ses écrans.
import { createStore } from "./ui/store.js";
-import { startRouter } from "./ui/router.js";
+import { href, startRouter } from "./ui/router.js";
import { createTimer } from "./ui/timer.js";
import { h } from "./ui/dom.js";
import { screenHeader } from "./ui/layout.js";
+import { localDay } from "./ui/format.js";
import { homeScreen } from "./ui/screens/home.js";
import { sessionScreen } from "./ui/screens/session.js";
import { historyEditScreen, historyScreen } from "./ui/screens/history.js";
+import { weekScreen } from "./ui/screens/week.js";
+import { activitiesScreen } from "./ui/screens/activities.js";
+import { weightScreen } from "./ui/screens/weight.js";
+import { dataScreen } from "./ui/screens/data.js";
+import { profileScreen } from "./ui/screens/profile.js";
+import { analysisScreen } from "./ui/screens/analysis.js";
+import { proposalScreen } from "./ui/proposal-card.js";
+import { finishScreen, progressScreen } from "./ui/game.js";
+import { applyTheme, getTheme } from "./ui/theme-pref.js";
import { openEventStore } from "./infra/event-store.js";
import { decodeProposalFragment } from "./domain/link.js";
import { registerServiceWorker } from "./sw-register.js";
+applyTheme(getTheme());
+
// Le journal est gardé dans IndexedDB : chargé au démarrage, chaque événement
// créé y est ajouté (ADR 0006).
const db = await openEventStore();
@@ -20,20 +33,46 @@ const device = await db.deviceId();
export const store = createStore({ device, onAppend: (event) => { void db.add([event]); } });
store.load(await db.list());
-// Lien d'une IA (#import= ou #import-json=) : il devient une proposition à valider.
+/** Écritures en bloc (import, réinitialisation) : IndexedDB puis magasin. */
+const journal = {
+ /** @param {import("./domain/events.js").DomainEvent[]} events */
+ async merge(events) {
+ // On n'envoie que les nouveaux : un id déjà présent fait échouer la
+ // transaction d'event-store.add (l'erreur remonte à tx.onerror malgré
+ // preventDefault), signalé au domaine infra.
+ const known = new Set(store.getEvents().map((e) => e.id));
+ const fresh = events.filter((e) => !known.has(e.id) && (known.add(e.id), true));
+ const added = fresh.length ? await db.add(fresh) : 0;
+ store.load(await db.list());
+ return added;
+ },
+ /** @param {import("./domain/events.js").DomainEvent[]} events */
+ async replace(events) {
+ await db.replaceAll(events);
+ store.load(await db.list());
+ },
+};
+
+/** Le jour local, relu à chaque écran : l'app peut rester ouverte passé minuit. */
+const today = () => localDay();
+
+// Lien d'une IA (#import= ou #import-json=) : il devient une proposition à
+// valider. Son id est tiré de son contenu : un lien déjà ouvert retrouve la même
+// proposition, et l'écran dit si elle a déjà été adoptée ou refusée.
async function importFromLink() {
if (!/^#import(-json)?=/.test(location.hash)) return;
+ let target = href.home();
try {
const event = await decodeProposalFragment(location.hash, { device, now: new Date() });
- if (!store.getEvents().some((e) => e.id === event.id)) {
- await db.add([event]);
- store.load(await db.list());
- }
+ if (!store.getEvents().some((e) => e.id === event.id)) await journal.merge([event]);
+ target = href.proposal(event.id);
} catch (e) {
alert("Ce lien ne contient pas un programme valide :\n" + (e instanceof Error ? e.message : String(e)));
}
- history.replaceState(null, "", "#/");
+ history.replaceState(null, "", target);
+ if (started) window.dispatchEvent(new HashChangeEvent("hashchange"));
}
+let started = false;
await importFromLink();
window.addEventListener("hashchange", () => { void importFromLink(); });
registerServiceWorker();
@@ -43,17 +82,27 @@ document.body.append(timer.node);
const root = /** @type {HTMLElement} */ (document.getElementById("app"));
+started = true;
startRouter(root, (route, nav) => {
switch (route.name) {
- case "session": return sessionScreen({ store, key: route.key, nav, timer });
+ case "session": return sessionScreen({ store, key: route.key, date: route.date, nav, timer });
+ case "finish": return finishScreen({ nav });
+ case "progress": return progressScreen({ store, nav, today: today() });
case "history": return historyScreen({ store, nav });
case "history-edit": return historyEditScreen({ store, nav, id: route.id });
+ case "week": return weekScreen({ store, nav, today });
+ case "activities": return activitiesScreen({ store, nav, today });
+ case "weight": return weightScreen({ store, nav, today });
+ case "data": return dataScreen({ store, nav, journal, today });
+ case "profile": return profileScreen({ store, nav });
+ case "analysis": return analysisScreen({ store, nav, today, exercise: route.exercise });
+ case "proposal": return proposalScreen({ store, nav, id: route.id });
case "not-found":
return {
title: "Page introuvable",
node: h("div", { class: "screen" },
- screenHeader({ back: { label: "Accueil", onClick: () => nav.go("#/") }, title: "Page introuvable", sub: "Cette adresse ne correspond à aucun écran." })),
+ screenHeader({ back: { label: "Accueil", onClick: () => nav.go(href.home()) }, title: "Introuvable", sub: "Cette adresse ne mène à aucun écran." })),
};
- default: return homeScreen({ store });
+ default: return homeScreen({ store, nav, today });
}
});
diff --git a/app/manifest.webmanifest b/app/manifest.webmanifest
index b69ce69..d38f07b 100644
--- a/app/manifest.webmanifest
+++ b/app/manifest.webmanifest
@@ -7,8 +7,8 @@
"scope": "./",
"display": "standalone",
"orientation": "portrait",
- "background_color": "#14171A",
- "theme_color": "#14171A",
+ "background_color": "#000000",
+ "theme_color": "#000000",
"icons": [
{ "src": "icons/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any" },
{ "src": "icons/icon-maskable.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "maskable" }
diff --git a/app/styles/base.css b/app/styles/base.css
index ce999c2..31a7bdf 100644
--- a/app/styles/base.css
+++ b/app/styles/base.css
@@ -1,9 +1,8 @@
-/* Base : remise à zéro, typographie, mise en page de l'écran. */
-*, *::before, *::after { box-sizing: border-box; }
+/* Base : remise à zéro, typographie, mise en page de l'écran. Angles droits
+ partout, aucune ombre, aucun dégradé. */
+*, *::before, *::after { box-sizing: border-box; border-radius: 0; }
html {
-webkit-text-size-adjust: 100%; text-size-adjust: 100%;
- /* Le défilement vers un élément (focus, lien) tient compte de l'en-tête
- collant de l'exercice et des barres fixées en bas. */
scroll-padding-top: 72px;
scroll-padding-bottom: calc(var(--action-bar-h) + var(--space-4));
}
@@ -11,68 +10,76 @@ html:has(body.has-timer) { scroll-padding-bottom: calc(var(--action-bar-h) + var
html, body { margin: 0; padding: 0; }
body {
background: var(--bg);
- color: var(--text);
+ color: var(--ink);
font-family: var(--font-body);
font-size: var(--fs-md);
- line-height: 1.5;
+ line-height: 1.45;
overscroll-behavior-y: none;
-webkit-tap-highlight-color: transparent;
- /* place pour la barre d'action collée en bas */
padding-bottom: calc(var(--action-bar-h) + env(safe-area-inset-bottom));
}
body.has-timer { padding-bottom: calc(var(--action-bar-h) + var(--timer-h) + env(safe-area-inset-bottom)); }
.wrap { max-width: var(--max); margin: 0 auto; padding: 0 var(--gutter); }
-h1, h2, h3, p, ul, ol { margin: 0; }
+h1, h2, h3, p, ul, ol, figure { margin: 0; }
ul, ol { padding: 0; list-style: none; }
-a { color: inherit; }
+a { color: inherit; text-underline-offset: 3px; text-decoration-thickness: 2px; }
button, input, select, textarea { font: inherit; color: inherit; }
button { cursor: pointer; }
[hidden] { display: none !important; }
+svg { display: block; }
-:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; border-radius: var(--radius-sm); }
+:focus-visible { outline: var(--b) solid var(--focus); outline-offset: 3px; }
h1:focus { outline: none; }
.visually-hidden {
position: absolute !important; width: 1px; height: 1px; overflow: hidden;
clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap;
}
-.skip-link { position: absolute; left: var(--space-2); top: -100px; z-index: 50; }
-.skip-link:focus { top: var(--space-2); background: var(--surface); padding: var(--space-2) var(--space-3); }
+.skip-link { position: absolute; left: var(--space-2); top: -100px; z-index: 50; background: var(--signal); color: var(--on-signal); padding: var(--space-2) var(--space-3); }
+.skip-link:focus { top: var(--space-2); }
/* Chiffres alignés partout où l'on compare des nombres. */
-.tnum, .timer__time, .stepper__value, .set-btn, .field__input, .exercise__count, .objective__value, .action-bar__meta { font-variant-numeric: tabular-nums; }
+.num, .timer__time, .stepper__value, .set-btn, .field__input, .exercise__count, .action-bar__meta, .stat__value { font-variant-numeric: tabular-nums lining-nums; }
-/* Typographie d'affichage : capitales condensées. */
-.kicker, .section-label, .mini-label, .card__eyebrow, .plate__id, .plate__last, .tag, .back, .btn, .timer__label {
- font-family: var(--font-display);
- text-transform: uppercase;
- font-weight: 600;
- letter-spacing: 0.1em;
+/* Trois voix typographiques :
+ - affichage (fonte condensée, capitales) : titres et grands chiffres ;
+ - marquage (chasse fixe du système, capitales) : étiquettes, comme un ruban
+ ou un chiffre frappé sur un disque ;
+ - texte courant (police du système). */
+.title, .h2, .num, .btn, .stat__value, .timer__time, .stepper__value, .set-btn, .dialog__title {
+ font-family: var(--font-display); font-weight: 700; text-transform: uppercase; letter-spacing: 0.01em;
}
-.title, .card__title, .plate__name, .note__title, .dialog__title, .timer__time, .objective__value, .stepper__value {
- font-family: var(--font-display);
- font-weight: 700;
+.mark, .kicker, .tape, .back, .field__label, .mini-label, .tag, .badge, .stat__label, .chip, .timer__label, .action-bar__meta {
+ font-family: var(--font-mark); font-size: var(--fs-mark); text-transform: uppercase; letter-spacing: 0.06em; font-weight: 700;
}
-.screen-head { padding: var(--space-5) 0 var(--space-4); }
-.kicker { font-size: var(--fs-xs); color: var(--text-muted); letter-spacing: 0.16em; }
-.title { font-size: var(--fs-3xl); line-height: 0.95; text-transform: uppercase; margin-top: var(--space-1); letter-spacing: -0.005em; }
-.title--hero { font-size: 3.25rem; }
-.lede { color: var(--text-muted); font-size: var(--fs-sm); margin-top: var(--space-2); max-width: 46ch; }
-.muted { color: var(--text-muted); font-size: var(--fs-sm); }
-.foot { color: var(--text-muted); font-size: var(--fs-xs); margin: var(--space-6) 0 var(--space-4); }
-.empty { color: var(--text-muted); padding: var(--space-5) 0; }
+.screen-head { padding: var(--space-4) 0 var(--space-3); border-bottom: var(--b-heavy) solid var(--ink); margin-bottom: var(--space-4); }
+.kicker { color: var(--muted); display: block; }
+.title { font-size: var(--fs-3xl); line-height: 0.88; margin-top: var(--space-2); overflow-wrap: anywhere; }
+.title--hero { font-size: 4rem; }
+.lede { color: var(--muted); margin-top: var(--space-2); max-width: 46ch; }
+.h2 { font-size: var(--fs-xl); line-height: 0.95; }
+.muted { color: var(--muted); font-size: var(--fs-sm); }
+.foot { color: var(--muted); font-size: var(--fs-sm); margin: var(--space-6) 0 var(--space-4); border-top: var(--b) solid var(--ink); padding-top: var(--space-3); }
+.empty { color: var(--muted); padding: var(--space-4) 0; }
+.prose > * + * { margin-top: var(--space-3); }
-.section-label {
- font-size: var(--fs-sm); color: var(--text-muted); letter-spacing: 0.16em;
- margin: var(--space-6) 0 var(--space-3); display: flex; align-items: baseline; gap: var(--space-2);
+/* Ruban adhésif de salle : l'étiquette d'une section. */
+.tape {
+ display: inline-block; background: var(--signal); color: var(--on-signal);
+ padding: 4px var(--space-2); margin: var(--space-6) 0 var(--space-3);
}
-.section-label__hint { font-size: var(--fs-xs); letter-spacing: 0.08em; text-transform: none; font-family: var(--font-body); font-weight: 400; }
+.tape { box-shadow: 0 0 0 2px var(--signal-edge); }
+.tape__hint { color: var(--on-signal); font-family: var(--font-body); font-size: var(--fs-sm); text-transform: none; letter-spacing: 0; font-weight: 400; }
+.tape__hint::before { content: " · "; }
+.section-head { display: flex; align-items: baseline; flex-wrap: wrap; }
-.status { min-height: 1.5em; margin-top: var(--space-3); color: var(--danger); font-size: var(--fs-sm); }
-.status--ok { color: var(--primary); }
+.status { min-height: 1.45em; margin-top: var(--space-3); font-weight: 700; }
+.status:empty { min-height: 0; margin: 0; }
+.status--err:not(:empty)::before { content: "! "; }
+.status--ok:not(:empty)::before { content: "✓ "; }
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { transition: none !important; animation: none !important; }
diff --git a/app/styles/components.css b/app/styles/components.css
index cec7233..9962192 100644
--- a/app/styles/components.css
+++ b/app/styles/components.css
@@ -1,234 +1,226 @@
-/* Composants communs (docs/design.md). Un composant = un bloc nommé, avec ses
- éléments (bloc__element) et variantes (bloc--variante). */
+/* Composants (docs/design.md). Bordures franches de 3 px, angles droits, aucune
+ ombre : un bloc est délimité par son trait, jamais par une élévation. */
-/* ---- Bouton ------------------------------------------------------------- */
+/* ---- boutons --------------------------------------------------------------- */
.btn {
display: inline-flex; align-items: center; justify-content: center; gap: var(--space-2);
- min-height: var(--tap); padding: 0 var(--space-4);
- background: var(--surface-2); color: var(--text);
- border: 1px solid var(--line-strong); border-radius: var(--radius);
- font-size: var(--fs-md); text-decoration: none; text-align: center;
- transition: background-color .12s, border-color .12s, transform .06s;
+ min-height: 56px; padding: 0 var(--space-4);
+ border: var(--b) solid var(--ink); background: var(--bg); color: var(--ink);
+ font-size: var(--fs-lg); line-height: 1; text-decoration: none; text-align: center;
+ touch-action: manipulation; user-select: none;
}
-.btn:hover { border-color: var(--text-muted); }
-.btn:active { transform: scale(.985); }
-.btn:disabled { opacity: .55; cursor: not-allowed; transform: none; }
-.btn--primary { background: var(--primary); border-color: var(--primary); color: var(--on-primary); font-weight: 700; }
-.btn--primary:hover { border-color: var(--text); }
-.btn--ghost { background: transparent; }
-.btn--danger { background: transparent; border-color: var(--danger); color: var(--danger); }
-.btn--work { background: transparent; border-color: var(--work); color: var(--work); }
+.btn:active { background: var(--ink); color: var(--bg); }
+.btn[disabled], .btn[aria-disabled="true"] { border-style: dashed; color: var(--muted); cursor: not-allowed; }
+.btn--primary { background: var(--signal); color: var(--on-signal); border-color: var(--signal-edge); }
+.btn--primary:active { background: var(--ink); color: var(--bg); border-color: var(--ink); }
+.btn--ghost { border-color: var(--muted); }
+.btn--danger { border-style: double; border-width: 6px; }
+.btn--danger::before { content: "✕"; }
.btn--block { display: flex; width: 100%; }
-.btn--lg { min-height: 56px; font-size: var(--fs-lg); letter-spacing: 0.06em; }
-.btn--sm { min-height: 44px; padding: 0 var(--space-3); font-size: var(--fs-sm); }
-
-.link-btn {
- background: none; border: 0; padding: 0 var(--space-2); min-height: 44px; min-width: 44px;
- color: var(--text); text-decoration: underline; text-underline-offset: 3px; font-size: var(--fs-sm);
-}
+.btn--lg { min-height: 64px; font-size: var(--fs-xl); }
+.btn--sm { min-height: var(--tap); font-size: var(--fs-md); padding: 0 var(--space-3); }
+.btn-row { display: grid; grid-template-columns: 1fr 1fr; gap: var(--space-2); }
+.btn-stack { display: grid; gap: var(--space-2); margin-top: var(--space-3); }
.back {
- display: inline-flex; align-items: center; min-height: var(--tap); padding: 0 var(--space-2) 0 0;
- background: none; border: 0; color: var(--text-muted); font-size: var(--fs-sm); letter-spacing: 0.12em;
+ display: inline-flex; align-items: center; gap: 6px; min-height: var(--tap); padding: 0 var(--space-3) 0 0;
+ border: 0; background: none; color: var(--ink);
}
-.back:hover { color: var(--text); }
-/* ---- Barre d'action collée en bas -------------------------------------- */
+/* ---- barre d'action, à portée de pouce ------------------------------------ */
.action-bar {
- position: fixed; left: 0; right: 0; bottom: 0; z-index: 10;
- background: color-mix(in srgb, var(--bg) 92%, transparent);
- border-top: 1px solid var(--line);
- padding-bottom: env(safe-area-inset-bottom);
- backdrop-filter: blur(6px);
-}
-.action-bar__in {
- max-width: var(--max); margin: 0 auto; padding: var(--space-3) var(--gutter);
- display: flex; align-items: center; gap: var(--space-3);
+ position: fixed; left: 0; right: 0; bottom: 0; z-index: 20;
+ background: var(--bg); border-top: var(--b-heavy) solid var(--ink);
+ padding: var(--space-2) var(--gutter) calc(var(--space-2) + env(safe-area-inset-bottom));
}
+.action-bar__in { max-width: var(--max); margin: 0 auto; display: flex; align-items: center; gap: var(--space-3); }
.action-bar__in > .btn { flex: 1; }
-/* Le minuteur s'empile sous la barre d'action : « Terminer la séance » reste
- accessible pendant un repos. */
-body.has-timer .action-bar { bottom: calc(var(--timer-h) + env(safe-area-inset-bottom)); padding-bottom: 0; border-top-color: transparent; }
-.action-bar__meta { color: var(--text-muted); font-family: var(--font-display); font-weight: 600; font-size: var(--fs-md); white-space: nowrap; }
+.action-bar__meta { color: var(--ink); white-space: nowrap; display: grid; line-height: 1.2; }
+.action-bar__meta .combo { color: var(--on-signal); background: var(--signal); padding: 0 4px; justify-self: start; }
+body.has-timer .action-bar { bottom: var(--timer-h); border-top-width: var(--b); }
-/* ---- Cartes ------------------------------------------------------------- */
-.card {
- display: block; position: relative; text-decoration: none; color: inherit;
- background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius);
- padding: var(--space-4);
+/* ---- blocs ------------------------------------------------------------------ */
+.block { border: var(--b) solid var(--ink); padding: var(--space-4); margin-bottom: var(--space-4); }
+.block > * + * { margin-top: var(--space-3); }
+.block--today { border-width: var(--b-heavy); }
+.block--signal { border-color: var(--signal); }
+.block__head { display: flex; align-items: flex-start; gap: var(--space-3); }
+.block__title { font-family: var(--font-display); font-weight: 700; text-transform: uppercase; font-size: var(--fs-2xl); line-height: 0.9; overflow-wrap: anywhere; }
+.block__meta { color: var(--muted); }
+.block__sep { border-top: var(--b) solid var(--ink); padding-top: var(--space-3); }
+
+/* Plaque : la séance, comme un disque marqué de sa lettre et de sa couleur. */
+.plaque {
+ flex: none; width: 56px; height: 56px; display: grid; place-items: center;
+ background: var(--accent); color: var(--accent-ink);
+ font-family: var(--font-display); font-weight: 700; font-size: 2.25rem; line-height: 1;
+ border: var(--b) solid var(--ink);
}
-/* La carte du jour domine l'accueil : plus grande, bordée de la couleur de séance. */
-.card--today {
- border-left: 6px solid var(--accent); padding: var(--space-5) var(--space-4);
+.plaque--sm { width: 40px; height: 40px; font-size: 1.5rem; }
+.plaque--empty { background: var(--bg); color: var(--muted); border-style: dashed; }
+
+/* ---- liste en grille : chaque ligne séparée par un trait ------------------ */
+.rows { border-top: var(--b) solid var(--ink); }
+.row {
+ display: flex; align-items: center; gap: var(--space-3); min-height: 64px;
+ padding: var(--space-2) 0; border-bottom: var(--b) solid var(--ink);
+ text-decoration: none; color: inherit;
}
-a.card--today:hover { border-color: var(--line-strong); border-left-color: var(--accent); }
-.card--proposal { border-left: 6px solid var(--primary); margin-bottom: var(--space-4); }
-.card__eyebrow { display: flex; align-items: center; gap: var(--space-2); margin-top: var(--space-4); font-size: var(--fs-sm); letter-spacing: 0.16em; }
-.card__title { font-size: var(--fs-2xl); line-height: 1; text-transform: uppercase; margin-top: var(--space-1); }
-.card__meta { color: var(--text-muted); font-size: var(--fs-sm); margin-top: var(--space-2); }
-.card__text { margin-top: var(--space-3); font-size: var(--fs-sm); }
-.card__hint { color: var(--text-muted); font-size: var(--fs-xs); margin-top: var(--space-3); }
-.card__actions { display: grid; gap: var(--space-2); margin-top: var(--space-4); }
+a.row:active { background: var(--ink); color: var(--bg); }
+.row__main { flex: 1; min-width: 0; display: grid; gap: 2px; }
+.row__title { font-weight: 700; overflow-wrap: anywhere; }
+.row__meta { color: var(--muted); font-size: var(--fs-sm); }
+a.row:active .row__meta { color: inherit; }
+.row__side { flex: none; text-align: right; }
+.row__actions { flex: none; display: flex; gap: var(--space-2); }
+.row--today { box-shadow: inset 6px 0 0 var(--signal); padding-left: var(--space-3); }
+.row__day { flex: none; width: 52px; display: grid; line-height: 1; }
+.row__day .num { font-size: var(--fs-xl); }
+.chevron::after { content: "→"; font-family: var(--font-mark); font-weight: 700; font-size: var(--fs-lg); }
-.swatch { width: 12px; height: 12px; border-radius: 2px; background: var(--accent); flex: none; }
-
-/* ---- Plaque de séance (liste de l'accueil) ----------------------------- */
-.plates { display: grid; gap: var(--space-2); }
-.plate {
- display: flex; align-items: stretch; min-height: 72px; text-decoration: none; color: inherit;
- background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden;
+/* ---- grille de navigation : la grille se voit -------------------------------- */
+.grid-nav {
+ display: grid; grid-template-columns: 1fr 1fr; gap: var(--b);
+ background: var(--ink); border: var(--b) solid var(--ink); margin-top: var(--space-3);
}
-.plate:hover { border-color: var(--line-strong); }
-.plate__bar { width: 8px; flex: none; background: var(--accent); }
-.plate__body { flex: 1; min-width: 0; padding: var(--space-3) var(--space-4); display: flex; flex-direction: column; }
-.plate__id { font-size: var(--fs-xs); color: var(--text-muted); letter-spacing: 0.16em; }
-.plate__name { font-size: var(--fs-xl); line-height: 1.05; text-transform: uppercase; }
-.plate__meta { color: var(--text-muted); font-size: var(--fs-xs); margin-top: var(--space-1); }
-.plate__last { padding: var(--space-3) var(--space-3) 0 0; font-size: var(--fs-xs); color: var(--text-muted); white-space: nowrap; text-align: right; }
-
-/* ---- Note (cardio, repères) --------------------------------------------- */
-.note { background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); padding: var(--space-3) var(--space-4); margin-bottom: var(--space-2); }
-.note__title { font-size: var(--fs-lg); text-transform: uppercase; letter-spacing: 0.03em; }
-.note__text { color: var(--text-muted); font-size: var(--fs-sm); margin-top: var(--space-1); }
-
-.coach-note { color: var(--warn); border-left: 3px solid var(--warn); padding-left: var(--space-3); font-size: var(--fs-sm); margin: var(--space-3) 0; }
-
-/* ---- Puces (muscles) et étiquettes -------------------------------------- */
-.chips { display: flex; flex-wrap: wrap; gap: var(--space-2); margin: var(--space-3) 0; }
-.chip {
- display: inline-flex; align-items: center; min-height: 28px; padding: 0 var(--space-3);
- border-radius: 999px; font-size: var(--fs-xs); font-weight: 600;
- background: var(--surface-2); color: var(--text); border: 1px solid var(--line-strong);
+.tile {
+ min-height: 88px; background: var(--bg); color: var(--ink); padding: var(--space-3);
+ display: flex; flex-direction: column; justify-content: space-between; text-decoration: none;
}
-.chip--secondary { background: transparent; color: var(--text-muted); border-style: dashed; font-weight: 400; }
-.tag {
- display: inline-block; padding: 1px 6px; margin-right: var(--space-2); border-radius: var(--radius-sm);
- font-size: var(--fs-xs); background: var(--accent); color: var(--accent-ink); letter-spacing: 0.08em; vertical-align: 1px;
-}
-.tag--superset { background: var(--work); color: var(--surface-sunk); }
-.badge {
- display: grid; place-items: center; width: 28px; height: 28px; flex: none; border-radius: var(--radius-sm);
- background: var(--accent); color: var(--accent-ink); font-family: var(--font-display); font-weight: 700; font-size: var(--fs-md);
-}
-.badge--warmup { background: var(--primary); color: var(--on-primary); }
-.inline-code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: var(--fs-xs); background: var(--surface-2); color: var(--text); padding: 2px 6px; border-radius: var(--radius-sm); overflow-wrap: anywhere; }
+.tile:active { background: var(--signal); color: var(--on-signal); }
+.tile__name { font-family: var(--font-display); font-weight: 700; text-transform: uppercase; font-size: var(--fs-xl); line-height: 0.9; }
+.tile__meta { color: var(--muted); font-size: var(--fs-sm); }
+.tile:active .tile__meta { color: inherit; }
-/* ---- Champs ------------------------------------------------------------- */
-.field { display: flex; align-items: center; gap: var(--space-2); }
-.field--inline { justify-content: space-between; margin: var(--space-2) 0; }
-.field__label { font-family: var(--font-display); text-transform: uppercase; font-weight: 600; letter-spacing: 0.1em; font-size: var(--fs-sm); color: var(--text-muted); }
+/* ---- jauges (avancement de la semaine, XP) : des cases, pas de dégradé ------ */
+.cells { display: flex; gap: 3px; height: 20px; }
+.cells > i { flex: 1; border: 2px solid var(--ink); }
+.cells > i[data-state="done"] { background: var(--meter); border-color: var(--meter); }
+.cells > i[data-state="skip"] { border-style: dashed; border-color: var(--muted); }
+.cells--xp { height: 16px; gap: 2px; }
+.cells--xp > i { border-width: 0; background: var(--sunk); }
+.cells--xp > i[data-state="done"] { background: var(--meter); }
+
+/* ---- HUD : niveau, XP, série de semaines ---------------------------------- */
+.hud { display: grid; grid-template-columns: auto 1fr auto; border: var(--b) solid var(--ink); margin-bottom: var(--space-4); text-decoration: none; color: inherit; }
+.hud > * { padding: var(--space-2) var(--space-3); }
+.hud__lvl, .hud__streak { display: grid; place-content: center; text-align: center; line-height: 1; }
+.hud__lvl { background: var(--ink); color: var(--bg); min-width: 64px; }
+.hud__streak { border-left: var(--b) solid var(--ink); min-width: 72px; }
+.hud__big { font-family: var(--font-display); font-weight: 700; font-size: var(--fs-xl); }
+.hud__body { display: grid; gap: 6px; align-content: center; min-width: 0; }
+.hud__title { font-weight: 700; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.hud--pending .hud__body { color: var(--muted); }
+
+/* ---- statistiques ----------------------------------------------------------- */
+.stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: var(--b); background: var(--ink); border: var(--b) solid var(--ink); }
+.stat { background: var(--bg); padding: var(--space-3); display: grid; gap: var(--space-1); align-content: start; }
+.stat__value { font-size: var(--fs-2xl); line-height: 0.9; }
+.stat__value small { font-size: var(--fs-lg); margin-left: 2px; }
+.stat__label { color: var(--muted); }
+.big-number { font-family: var(--font-display); font-weight: 700; font-size: var(--fs-num-xl); line-height: 0.85; font-variant-numeric: tabular-nums; }
+.big-number small { font-size: var(--fs-2xl); margin-left: var(--space-1); }
+
+/* ---- textes ----------------------------------------------------------------- */
+.note { border-left: var(--b-heavy) solid var(--ink); padding: var(--space-1) 0 var(--space-1) var(--space-3); margin-bottom: var(--space-3); }
+.note__title { font-weight: 700; }
+.note__text { color: var(--muted); font-size: var(--fs-sm); }
+.coach-note { border: var(--b) solid var(--ink); border-left-width: 12px; padding: var(--space-2) var(--space-3); font-size: var(--fs-sm); }
+.coach-note::before { content: "NOTE · "; font-family: var(--font-mark); font-weight: 700; font-size: var(--fs-mark); }
+.coach-note--plain::before { content: none; }
+.chips { display: flex; flex-wrap: wrap; gap: var(--space-2); }
+.chip { border: 2px solid var(--ink); padding: 2px 6px; }
+.chip--secondary { border-style: dashed; color: var(--muted); border-color: var(--muted); }
+.tag { display: inline-block; border: 2px solid currentColor; padding: 0 4px; margin-right: var(--space-2); }
+.badge { display: inline-grid; place-items: center; min-width: 32px; height: 32px; padding: 0 4px; border: 2px solid var(--ink); }
+.badge--signal { background: var(--signal); color: var(--on-signal); border-color: var(--signal-edge); }
+.mini-label { display: block; color: var(--muted); margin: var(--space-4) 0 var(--space-2); }
+
+/* ---- champs ----------------------------------------------------------------- */
+.field { display: grid; gap: var(--space-1); margin-bottom: var(--space-3); }
+.field__label { color: var(--ink); }
+.field__hint { color: var(--muted); font-size: var(--fs-sm); }
.field__input {
- min-height: var(--tap); min-width: 0; padding: 0 var(--space-3);
- background: var(--surface-2); color: var(--text);
- border: 1px solid var(--line-strong); border-radius: var(--radius);
- font-family: var(--font-display); font-weight: 600; font-size: var(--fs-lg);
+ min-height: 56px; width: 100%; padding: 0 var(--space-3);
+ border: var(--b) solid var(--ink); background: var(--sunk); color: var(--ink);
+ font-size: var(--fs-lg);
}
-.field__input:focus { outline: 3px solid var(--focus); outline-offset: 0; }
-.field__input[aria-invalid="true"] { border-color: var(--danger); outline-color: var(--danger); }
-.field__input--date { font-size: var(--fs-md); }
-.field__input--area { width: 100%; min-height: 160px; padding: var(--space-3); font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: var(--fs-xs); font-weight: 400; }
-.field--amount .field__input { width: 5.5em; text-align: right; }
-.field--compact .field__input { width: 4.5em; }
-.field__unit { font-family: var(--font-display); font-weight: 600; text-transform: uppercase; color: var(--text-muted); font-size: var(--fs-sm); }
+.field__input[aria-invalid="true"] { border-style: dashed; outline: var(--b) solid var(--ink); outline-offset: 2px; }
+.field__input--area { min-height: 120px; padding: var(--space-3); font-size: var(--fs-md); resize: vertical; font-family: var(--font-body); }
+.field__input--mono { font-family: var(--font-mark); font-size: var(--fs-sm); }
+.field--inline { grid-template-columns: auto 1fr; align-items: center; gap: var(--space-3); }
+.field--amount { grid-template-columns: auto 1fr auto; align-items: center; gap: var(--space-2); margin: 0; }
+.field--amount .field__input { font-family: var(--font-display); font-weight: 700; font-size: var(--fs-2xl); text-align: right; min-height: 64px; }
+.field__unit { font-family: var(--font-mark); font-weight: 700; }
+.field--compact .field__input { min-height: var(--tap); font-size: var(--fs-lg); width: 5.5em; }
+.field-pair { display: grid; grid-template-columns: 1fr 1fr; gap: var(--space-3); }
-/* ---- Choix segmenté (mode de suivi) ------------------------------------ */
-.segmented { display: flex; flex-wrap: wrap; gap: var(--space-2); }
+/* Choix exclusif ou multiple : des boutons carrés collés, la grille se voit. */
+.segmented { display: flex; flex-wrap: wrap; gap: var(--b); background: var(--ink); border: var(--b) solid var(--ink); }
.segmented__opt {
- min-height: 44px; padding: 0 var(--space-3); border-radius: var(--radius);
- background: transparent; border: 1px solid var(--line-strong); color: var(--text-muted); font-size: var(--fs-sm);
+ flex: 1 1 0; min-width: max-content; min-height: var(--tap); padding: 0 var(--space-3); border: 0;
+ background: var(--bg); color: var(--ink); font-family: var(--font-mark); font-size: var(--fs-mark);
+ font-weight: 700; text-transform: uppercase; letter-spacing: 0.04em;
}
-.segmented__opt[aria-pressed="true"] { background: var(--text); border-color: var(--text); color: var(--bg); font-weight: 600; }
+.segmented__opt[aria-pressed="true"] { background: var(--signal); color: var(--on-signal); }
+.segmented--days .segmented__opt { min-width: 0; font-family: var(--font-display); font-size: var(--fs-xl); min-height: 56px; padding: 0; }
-/* ---- Liens de l'accueil, onboarding ------------------------------------ */
-.links { display: grid; gap: var(--space-2); }
-.hero { padding-top: var(--space-6); }
-.how { counter-reset: how; display: grid; gap: var(--space-3); margin-top: var(--space-4); }
-.how__step { counter-increment: how; position: relative; padding-left: 44px; min-height: 32px; font-size: var(--fs-sm); }
-.how__step::before {
- content: counter(how); position: absolute; left: 0; top: -2px; width: 32px; height: 32px; border-radius: 50%;
- display: grid; place-items: center; background: var(--primary); color: var(--on-primary);
- font-family: var(--font-display); font-weight: 700; font-size: var(--fs-lg);
+.choice-list { display: grid; gap: var(--b); background: var(--ink); border: var(--b) solid var(--ink); }
+.choice {
+ min-height: var(--tap); padding: var(--space-2) var(--space-3); border: 0; text-align: left;
+ background: var(--bg); color: var(--ink); font-weight: 700;
}
-.card--onboarding { border-left: 6px solid var(--primary); padding: var(--space-5) var(--space-4); }
-.how__step strong { font-weight: 700; }
-.how__step span { color: var(--text-muted); }
-.status--info { color: var(--text); }
-.copy-line { display: flex; align-items: center; gap: var(--space-2); margin-top: var(--space-2); }
-.copy-line__text {
- flex: 1; min-width: 0; padding: var(--space-2) var(--space-3); border-radius: var(--radius-sm);
- background: var(--surface-sunk); color: var(--text); border: 1px solid var(--line);
- font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: var(--fs-xs); overflow-wrap: anywhere;
-}
-.alt { display: grid; gap: var(--space-2); margin-top: var(--space-5); }
-.manual-copy { margin-top: var(--space-3); display: grid; gap: var(--space-2); }
+.choice[aria-pressed="true"] { background: var(--signal); color: var(--on-signal); }
+.choice[aria-pressed="true"]::after { content: " ✓"; }
-.preview { display: grid; gap: var(--space-3); margin-top: var(--space-4); }
-.preview__session { display: grid; gap: 2px; font-size: var(--fs-sm); }
+.copy-line { display: flex; align-items: stretch; gap: var(--space-2); }
+.copy-line__text { flex: 1; min-width: 0; display: flex; align-items: center; padding: 0 var(--space-3); border: var(--b) dashed var(--ink); font-family: var(--font-mark); font-size: var(--fs-sm); overflow-wrap: anywhere; }
-/* ---- Historique --------------------------------------------------------- */
-.history__list { display: grid; gap: var(--space-2); }
-.history__item {
- display: grid; grid-template-columns: 1fr auto; grid-template-areas: "date chev" "name chev" "meta chev";
- min-height: 72px; padding: var(--space-3) var(--space-4); text-decoration: none; color: inherit;
- background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius);
-}
-.history__item:hover { border-color: var(--line-strong); }
-.history__date { grid-area: date; font-family: var(--font-display); text-transform: uppercase; font-weight: 600; letter-spacing: 0.1em; font-size: var(--fs-xs); color: var(--text-muted); }
-.history__name { grid-area: name; font-family: var(--font-display); font-weight: 700; text-transform: uppercase; font-size: var(--fs-lg); line-height: 1.1; }
-.history__meta { grid-area: meta; color: var(--text-muted); font-size: var(--fs-xs); }
-.history__item .chevron { grid-area: chev; align-self: center; }
+/* ---- courbes (SVG) ---------------------------------------------------------- */
+.chart { border: var(--b) solid var(--ink); padding: var(--space-2); color: var(--ink); }
+.chart svg { width: 100%; height: auto; overflow: visible; }
+.chart__axis { stroke: var(--rule-soft); stroke-width: 1; }
+.chart__line { fill: none; stroke: var(--ink); stroke-width: 2.5; stroke-linejoin: miter; }
+.chart__trend { fill: none; stroke: var(--ink); stroke-width: 2; stroke-dasharray: 6 5; }
+.chart__dot { fill: var(--ink); }
+.chart__bar { fill: var(--ink); }
+.chart__bar--now { fill: var(--meter); }
+.chart__text { fill: var(--muted); font-family: var(--font-mark); font-size: 11px; }
+.chart__caption { color: var(--muted); font-size: var(--fs-sm); margin-top: var(--space-2); }
-.edit-list { display: grid; gap: var(--space-3); }
-.edit-ex { background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); padding: var(--space-3) var(--space-4); display: grid; gap: var(--space-3); }
-.edit-ex__head { display: flex; justify-content: space-between; gap: var(--space-2); align-items: baseline; }
-.edit-sets { display: grid; gap: var(--space-2); }
-.edit-set { display: flex; align-items: center; justify-content: space-between; gap: var(--space-2); }
-.edit-set__n { color: var(--text-muted); font-size: var(--fs-sm); }
-.edit-sets__btns { display: flex; gap: var(--space-2); }
+/* ---- aperçu des changements d'une proposition ------------------------------ */
+.diff { border-top: var(--b) solid var(--ink); }
+.diff__item { border-bottom: var(--b) solid var(--ink); padding: var(--space-3) 0; display: grid; gap: var(--space-2); }
+.diff__head { display: flex; align-items: center; gap: var(--space-3); }
+.diff__what { font-weight: 700; flex: 1; min-width: 0; overflow-wrap: anywhere; }
+.diff__lines > li { padding-left: 1.6em; text-indent: -1.6em; font-size: var(--fs-sm); }
+.diff__lines > li::before, .diff__mark { font-family: var(--font-mark); font-weight: 700; display: inline-block; width: 1.6em; text-indent: 0; }
+.diff__lines > li[data-change="added"]::before { content: "+"; }
+.diff__lines > li[data-change="removed"]::before { content: "−"; }
+.diff__lines > li[data-change="changed"]::before { content: "~"; }
+.diff__lines > li[data-change="removed"] { text-decoration: line-through; text-decoration-thickness: 2px; color: var(--muted); }
+.diff__lines del { color: var(--muted); text-decoration-thickness: 2px; }
+.diff__lines ins { text-decoration: none; font-weight: 700; }
-/* ---- Chevron ------------------------------------------------------------ */
-.chevron { width: 10px; height: 10px; border-right: 2px solid var(--text-muted); border-bottom: 2px solid var(--text-muted); transform: rotate(-45deg); flex: none; margin: 0 var(--space-1); transition: transform .15s; }
-
-/* ---- Dialogue et message bref ------------------------------------------- */
+/* ---- dialogue et message bref ---------------------------------------------- */
.dialog {
- width: min(100% - 2 * var(--gutter), 480px); padding: var(--space-5) var(--space-4) var(--space-4);
- background: var(--surface); color: var(--text); border: 1px solid var(--line-strong); border-radius: var(--radius);
+ border: var(--b-heavy) solid var(--ink); background: var(--bg); color: var(--ink);
+ padding: var(--space-4); width: min(92vw, 440px);
}
-.dialog::backdrop { background: rgb(0 0 0 / .6); }
-.dialog__title { font-size: var(--fs-xl); text-transform: uppercase; line-height: 1.05; margin-bottom: var(--space-3); }
-.dialog__text { color: var(--text-muted); font-size: var(--fs-sm); margin-bottom: var(--space-2); }
+.dialog::backdrop { background: rgb(0 0 0 / 0.8); }
+.dialog__title { font-size: var(--fs-2xl); line-height: 0.95; margin-bottom: var(--space-3); }
+.dialog__text { margin-bottom: var(--space-2); }
.dialog__actions { display: grid; gap: var(--space-2); margin-top: var(--space-4); }
-
.toast {
- position: fixed; left: 50%; bottom: calc(var(--action-bar-h) + var(--space-4) + env(safe-area-inset-bottom)); z-index: 40;
- transform: translate(-50%, 20px); opacity: 0; pointer-events: none;
- max-width: calc(100% - 2 * var(--gutter)); padding: var(--space-3) var(--space-4);
- background: var(--text); color: var(--bg); border-radius: var(--radius); font-size: var(--fs-sm); font-weight: 600;
- transition: opacity .2s, transform .2s;
+ position: fixed; left: 50%; bottom: calc(var(--action-bar-h) + var(--space-3)); z-index: 40;
+ transform: translate(-50%, 200%); max-width: calc(100vw - 32px); visibility: hidden;
+ background: var(--ink); color: var(--bg); padding: var(--space-3) var(--space-4);
+ font-weight: 700; transition: transform 0.15s steps(3); pointer-events: none;
}
-.toast--on { opacity: 1; transform: translate(-50%, 0); }
-body.has-timer .toast { bottom: calc(var(--action-bar-h) + var(--timer-h) + var(--space-4) + env(safe-area-inset-bottom)); }
+.toast--on { transform: translate(-50%, 0); visibility: visible; }
+body.has-timer .toast { bottom: calc(var(--action-bar-h) + var(--timer-h) + var(--space-3)); }
-/* ---- Minuteur ----------------------------------------------------------- */
-.timer {
- position: fixed; left: 0; right: 0; bottom: 0; z-index: 30;
- background: var(--surface); border-top: 1px solid var(--line-strong);
- padding-bottom: env(safe-area-inset-bottom);
- box-shadow: 0 -8px 24px rgb(0 0 0 / .25);
-}
-.timer__bar { height: 4px; background: var(--surface-2); position: relative; overflow: hidden; }
-.timer__bar::after {
- content: ""; position: absolute; inset: 0; background: var(--text);
- transform-origin: left; transform: scaleX(var(--progress, 1)); transition: transform .25s linear;
-}
-.timer__in { max-width: var(--max); height: calc(var(--timer-h) - 4px); margin: 0 auto; padding: 0 var(--gutter); display: flex; align-items: center; gap: var(--space-3); }
-.timer__read { flex: 1; min-width: 0; }
-.timer__label { font-size: var(--fs-xs); color: var(--text-muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
-.timer__time { font-size: 2.75rem; line-height: 1; }
-.timer__btns { display: flex; gap: var(--space-2); }
-.timer__btn { min-width: 64px; }
-.timer--work .timer__time { color: var(--work); }
-.timer--work .timer__bar::after { background: var(--work); }
-.timer--low .timer__time { color: var(--warn); }
-.timer--zero .timer__time { color: var(--primary); }
-.timer--zero .timer__bar::after { background: var(--primary); }
+.manual-copy { display: grid; gap: var(--space-2); }
+.how { counter-reset: how; display: grid; gap: var(--space-3); }
+.how__step { counter-increment: how; display: grid; grid-template-columns: 48px 1fr; gap: var(--space-3); align-items: start; }
+.how__step::before { content: counter(how); display: grid; place-items: center; height: 48px; border: var(--b) solid var(--ink); font-family: var(--font-display); font-weight: 700; font-size: var(--fs-xl); }
diff --git a/app/styles/fonts.css b/app/styles/fonts.css
index d583fa3..b551414 100644
--- a/app/styles/fonts.css
+++ b/app/styles/fonts.css
@@ -1,19 +1,8 @@
-/* Barlow Condensed, SIL Open Font License 1.1 (app/fonts/OFL.txt). Auto-hébergée
- (ADR 0007), sous-ensemble latin, depuis le dépôt google/fonts. */
-@font-face {
- font-family: "Barlow Condensed";
- font-style: normal;
- font-weight: 500;
- font-display: swap;
- src: url("../fonts/barlow-condensed-medium.woff2") format("woff2");
-}
-@font-face {
- font-family: "Barlow Condensed";
- font-style: normal;
- font-weight: 600;
- font-display: swap;
- src: url("../fonts/barlow-condensed-semibold.woff2") format("woff2");
-}
+/* Une seule fonte, une seule graisse : Barlow Condensed Bold, SIL Open Font
+ License 1.1 (app/fonts/OFL.txt). Auto-hébergée (ADR 0007), réduite aux
+ caractères du français (latin de base, latin-1, Œ, guillemets, tirets) :
+ 15 Ko. Elle porte les titres et les grands chiffres ; le texte courant et le
+ marquage utilisent les polices du système (0 octet). */
@font-face {
font-family: "Barlow Condensed";
font-style: normal;
diff --git a/app/styles/screens.css b/app/styles/screens.css
new file mode 100644
index 0000000..6e501d4
--- /dev/null
+++ b/app/styles/screens.css
@@ -0,0 +1,65 @@
+/* Ce qui est propre à un écran : semaine, poids, historique, fin de séance. */
+
+/* ---- semaine ------------------------------------------------------------------ */
+.week__range { margin: var(--space-3) 0 0; color: var(--muted); }
+.week__row > .row { padding: 0; gap: 0; }
+.week__day {
+ flex: 1; min-width: 0; min-height: 72px; display: flex; align-items: center; gap: var(--space-3);
+ padding: var(--space-2) var(--space-2) var(--space-2) 0; border: 0; background: none; color: inherit; text-align: left;
+}
+.week__day[aria-expanded="true"] { background: var(--sunk); }
+
+.week__row--today .row__day { background: var(--signal); color: var(--on-signal); }
+.week__row .row__day { padding: 4px; }
+.week__row .row__actions { padding-left: var(--space-2); }
+.week__row > .choice-list { margin: 0 0 var(--space-3); }
+
+/* ---- poids, analyses ----------------------------------------------------------- */
+.field__input--big { font-family: var(--font-display); font-weight: 700; font-size: var(--fs-2xl); min-height: 64px; }
+.weight__kg, .analysis__kg { font-size: var(--fs-xl); }
+.import { margin-top: var(--space-5); }
+.import > summary { list-style: none; }
+.import > summary::-webkit-details-marker { display: none; }
+.import[open] > summary { margin-bottom: var(--space-3); }
+.import-report { display: grid; gap: var(--space-2); margin-top: var(--space-3); }
+.import-report:empty { margin: 0; }
+.mono-list { font-family: var(--font-mark); font-size: var(--fs-sm); color: var(--muted); }
+.data-gap, .act-gap, .analysis-gap { margin-top: var(--space-3); }
+
+/* ---- historique ------------------------------------------------------------------ */
+.history__date { font-family: var(--font-mark); font-weight: 700; font-size: var(--fs-mark); text-transform: uppercase; }
+.edit-list { display: grid; gap: var(--space-3); }
+.edit-ex { border: var(--b) solid var(--ink); padding: var(--space-3); display: grid; gap: var(--space-3); }
+.edit-ex__head { display: grid; }
+.edit-sets { display: grid; gap: var(--space-2); }
+.edit-set { display: flex; align-items: center; justify-content: space-between; gap: var(--space-3); border-top: 2px solid var(--rule-soft); padding-top: var(--space-2); }
+.edit-set__n { font-family: var(--font-mark); font-weight: 700; font-size: var(--fs-mark); text-transform: uppercase; }
+.edit-sets__btns { display: flex; gap: var(--space-2); }
+
+/* ---- fin de séance : le moment endorphine ----------------------------------------- */
+.reward { border: var(--b-heavy) solid var(--ink); padding: var(--space-4) var(--space-3); margin-bottom: var(--space-4); }
+.reward__big { display: flex; align-items: baseline; flex-wrap: wrap; gap: var(--space-2); }
+.reward__big .big-number { font-size: clamp(4.5rem, 26vw, 8.5rem); }
+.reward__big small { font-family: var(--font-display); font-weight: 700; font-size: var(--fs-2xl); text-transform: uppercase; }
+.reward__xp { background: var(--signal); color: var(--on-signal); padding: var(--space-4) var(--space-3); margin-bottom: var(--space-4); display: grid; gap: var(--space-3); }
+.reward__gain { font-family: var(--font-display); font-weight: 700; font-size: var(--fs-num); line-height: 0.85; }
+.reward__parts { display: grid; border-top: var(--b) solid var(--on-signal); }
+.reward__parts li { display: flex; justify-content: space-between; padding: var(--space-1) 0; border-bottom: 2px solid var(--on-signal); font-weight: 700; }
+.reward__level { display: grid; gap: 6px; }
+.reward__xp .mark.muted { color: var(--on-signal); }
+.reward__cells > i { background: rgb(0 0 0 / 0.18); }
+.reward__cells > i[data-state="done"] { background: var(--on-signal); }
+.reward__streak { margin: var(--space-3) 0; }
+
+/* Tampon « RECORD ! » : il s'imprime une fois, d'un coup sec. */
+.stamp {
+ display: block; text-align: center; margin: var(--space-4) 0; padding: var(--space-3);
+ border: var(--b-heavy) solid var(--ink); font-family: var(--font-display); font-weight: 700;
+ font-size: var(--fs-2xl); line-height: 0.95; text-transform: uppercase;
+ animation: stamp 0.22s steps(3, end) 0.5s both;
+}
+.stamp--record { background: var(--ink); color: var(--bg); font-size: var(--fs-3xl); }
+@keyframes stamp {
+ from { transform: scale(1.35); opacity: 0; }
+ to { transform: scale(1); opacity: 1; }
+}
diff --git a/app/styles/session.css b/app/styles/session.css
index a7f92a7..742b7eb 100644
--- a/app/styles/session.css
+++ b/app/styles/session.css
@@ -1,106 +1,116 @@
-/* Composants de la séance guidée : exercice, superset, séries, ressenti. */
+/* La séance guidée : exercice, superset, séries, ressenti, minuteur. Les
+ chiffres sont énormes : on les lit à un mètre, la barre dans les mains. */
-.exercises { display: grid; gap: var(--space-2); margin-top: var(--space-4); }
+.exercises { display: grid; gap: var(--space-3); margin-top: var(--space-4); }
-/* ---- Exercice (details/summary natif, accessible sans script) ---------- */
-.exercise { background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); }
-.exercise[open] { border-color: var(--line-strong); }
+/* ---- exercice (details/summary natif) --------------------------------------- */
+.exercise { border: var(--b) solid var(--ink); background: var(--bg); }
.exercise__head {
display: flex; align-items: center; gap: var(--space-3);
- min-height: 64px; padding: var(--space-3) var(--space-4); cursor: pointer; list-style: none;
- border-radius: var(--radius);
+ min-height: 72px; padding: var(--space-2) var(--space-3); cursor: pointer; list-style: none;
}
.exercise__head::-webkit-details-marker { display: none; }
/* Piège d'Atelier : combinateur enfant, et pas d'overflow:hidden sur la carte,
sinon l'en-tête collant ne colle plus. */
.exercise[open] > .exercise__head {
- position: sticky; top: 0; z-index: 5; background: var(--surface);
- border-bottom: 1px solid var(--line); border-radius: var(--radius) var(--radius) 0 0;
+ position: sticky; top: 0; z-index: 5; background: var(--bg); border-bottom: var(--b) solid var(--ink);
}
-.exercise[open] > .exercise__head .chevron { transform: rotate(45deg); }
+.exercise[open] > .exercise__head .chevron::after { content: "↓"; }
+.exercise .badge { font-family: var(--font-display); font-size: var(--fs-lg); }
.exercise__name { flex: 1; min-width: 0; display: grid; }
-.exercise__name strong { font-size: var(--fs-md); font-weight: 600; line-height: 1.25; }
-.exercise__sub { color: var(--text-muted); font-size: var(--fs-xs); }
-.exercise__count { font-family: var(--font-display); font-weight: 700; font-size: var(--fs-md); color: var(--text-muted); }
-.exercise__count--done { color: var(--primary); }
-.exercise__body { padding: var(--space-3) var(--space-4) var(--space-4); }
+.exercise__name strong { font-size: var(--fs-lg); line-height: 1.15; }
+.exercise__sub { color: var(--muted); font-family: var(--font-mark); font-size: var(--fs-mark); }
+.exercise__count { font-family: var(--font-display); font-weight: 700; font-size: var(--fs-xl); }
+.exercise__count--done { background: var(--signal); color: var(--on-signal); padding: 0 6px; }
+.exercise__body { padding: var(--space-3); }
+.exercise__body > .coach-note { margin-bottom: var(--space-3); }
-.mini-label { font-family: var(--font-display); text-transform: uppercase; font-weight: 600; letter-spacing: 0.14em; font-size: var(--fs-xs); color: var(--text-muted); margin: var(--space-4) 0 var(--space-2); }
-.cues li, .mistakes li { position: relative; padding-left: 20px; margin-bottom: var(--space-2); font-size: var(--fs-sm); }
-.cues li::before { content: ""; position: absolute; left: 4px; top: .55em; width: 6px; height: 6px; border-radius: 50%; background: var(--text-muted); }
-.mistakes { border-left: 3px solid var(--danger); padding-left: var(--space-1); }
-.mistakes li { color: var(--text-muted); padding-left: var(--space-3); }
-.tutorial { margin-top: var(--space-2); }
+.cues li, .mistakes li { padding-left: 1.4em; text-indent: -1.4em; margin-bottom: var(--space-2); font-size: var(--fs-sm); }
+.cues li::before { content: "▪ "; font-family: var(--font-mark); }
+.mistakes li { color: var(--muted); }
+.mistakes li::before { content: "✕ "; font-family: var(--font-mark); color: var(--ink); }
+.tutorial { margin-top: var(--space-3); }
-.objective { display: flex; align-items: baseline; gap: var(--space-3); margin-top: var(--space-4); padding-top: var(--space-3); border-top: 1px solid var(--line); }
-.objective__value { font-size: var(--fs-xl); line-height: 1; }
-.objective__rest { margin-left: auto; font-family: var(--font-display); text-transform: uppercase; font-weight: 600; letter-spacing: .1em; font-size: var(--fs-sm); color: var(--text-muted); }
+.objective { display: flex; align-items: baseline; gap: var(--space-3); margin-top: var(--space-4); padding-top: var(--space-3); border-top: var(--b) solid var(--ink); }
+.objective__value { font-family: var(--font-display); font-weight: 700; font-size: var(--fs-3xl); line-height: 0.85; }
+.objective__rest { margin-left: auto; font-family: var(--font-mark); font-weight: 700; font-size: var(--fs-mark); text-transform: uppercase; color: var(--muted); }
-/* ---- Zone de saisie ----------------------------------------------------- */
+/* Conseil de progression : « Prêt à monter » */
+.advice { border: var(--b) solid var(--signal); padding: var(--space-3); margin-top: var(--space-3); display: grid; gap: var(--space-2); }
+.advice__head { display: flex; align-items: baseline; justify-content: space-between; gap: var(--space-2); }
+.advice__head .mark { background: var(--signal); color: var(--on-signal); padding: 2px 6px; }
+.advice__kg { font-size: var(--fs-2xl); line-height: 0.9; }
+
+/* ---- saisie ------------------------------------------------------------------- */
.work { display: grid; gap: var(--space-3); margin-top: var(--space-3); }
-.work__fields { display: flex; flex-wrap: wrap; gap: var(--space-3) var(--space-4); align-items: center; }
-.set-row { display: flex; flex-wrap: wrap; gap: var(--space-2); }
+.work__fields { display: grid; gap: var(--space-3); }
+.set-row { display: grid; grid-template-columns: repeat(auto-fill, minmax(64px, 1fr)); gap: var(--space-2); }
.set-btn {
- position: relative; width: 52px; height: 52px; border-radius: var(--radius);
- background: transparent; border: 1px solid var(--line-strong); color: var(--text);
- font-family: var(--font-display); font-weight: 700; font-size: var(--fs-lg);
+ height: 72px; display: grid; place-content: center; gap: 2px; padding: 0;
+ background: var(--bg); border: var(--b) solid var(--ink); color: var(--ink); font-size: var(--fs-2xl); line-height: 0.9;
}
-.set-btn[aria-expanded="true"] { outline: 3px solid var(--text); outline-offset: 1px; }
-.set-btn--done { background: var(--primary); border-color: var(--primary); color: var(--on-primary); }
-/* Pastille du ressenti : la couleur double le texte (aria-label), jamais seule. */
-.set-btn--done::after {
- content: ""; position: absolute; right: 4px; top: 4px; width: 10px; height: 10px; border-radius: 50%;
- border: 2px solid var(--on-primary); background: var(--dot, transparent);
-}
-.set-btn[data-effort="easy"] { --dot: var(--effort-easy); }
-.set-btn[data-effort="ok"] { --dot: var(--effort-ok); }
-.set-btn[data-effort="hard"] { --dot: var(--effort-hard); }
-.set-btn[data-effort="failure"] { --dot: var(--effort-failure); }
+.set-btn[aria-expanded="true"] { outline: var(--b) solid var(--focus); outline-offset: 2px; }
+.set-btn--done { background: var(--ink); color: var(--bg); }
+.set-btn__effort { font-family: var(--font-mark); font-size: 11px; letter-spacing: 0.04em; text-transform: uppercase; }
+/* Un échec se voit : rayé, jamais mis en valeur. */
+.set-btn--done[data-effort="failure"] { background: var(--bg); color: var(--ink); border-style: dashed; }
+.set-btn--done[data-effort="failure"] .set-btn__n { text-decoration: line-through; text-decoration-thickness: 3px; }
-.set-panel { background: var(--surface-sunk); border: 1px solid var(--line-strong); border-radius: var(--radius); padding: var(--space-3); display: grid; gap: var(--space-3); }
-.set-panel__title, .set-panel__ask { font-family: var(--font-display); text-transform: uppercase; font-weight: 600; letter-spacing: .12em; font-size: var(--fs-sm); color: var(--text-muted); }
+.set-panel { border: var(--b) solid var(--ink); background: var(--sunk); padding: var(--space-3); display: grid; gap: var(--space-3); }
+.set-panel__title, .set-panel__ask { font-family: var(--font-mark); font-weight: 700; font-size: var(--fs-mark); text-transform: uppercase; }
-.stepper { display: flex; align-items: center; gap: var(--space-3); }
-.stepper__btn { width: 56px; height: 56px; border-radius: var(--radius); background: var(--surface-2); border: 1px solid var(--line-strong); color: var(--text); font-size: 1.75rem; line-height: 1; }
-.stepper__value { min-width: 2.2ch; text-align: center; font-size: 2.5rem; line-height: 1; }
-.stepper__unit { font-family: var(--font-display); text-transform: uppercase; font-weight: 600; letter-spacing: .1em; font-size: var(--fs-sm); color: var(--text-muted); }
+.stepper { display: grid; grid-template-columns: 64px 1fr 64px; align-items: center; gap: var(--space-2); }
+.stepper__btn { height: 64px; background: var(--bg); border: var(--b) solid var(--ink); color: var(--ink); font-family: var(--font-display); font-size: 2.25rem; line-height: 1; }
+.stepper__btn:active { background: var(--ink); color: var(--bg); }
+.stepper__value { text-align: center; font-size: var(--fs-num); line-height: 0.85; }
+.stepper__unit { grid-column: 1 / -1; text-align: center; font-family: var(--font-mark); font-weight: 700; font-size: var(--fs-mark); text-transform: uppercase; color: var(--muted); }
-.effort-picker { display: grid; grid-template-columns: repeat(2, 1fr); gap: var(--space-2); }
-.effort {
- display: grid; gap: 2px; text-align: left; min-height: 64px; padding: var(--space-2) var(--space-3);
- background: var(--surface); border: 1px solid var(--line-strong); border-left: 6px solid var(--c); border-radius: var(--radius); color: var(--text);
-}
-.effort[data-effort="easy"] { --c: var(--effort-easy); }
-.effort[data-effort="ok"] { --c: var(--effort-ok); }
-.effort[data-effort="hard"] { --c: var(--effort-hard); }
-.effort[data-effort="failure"] { --c: var(--effort-failure); }
-.effort[aria-pressed="true"] { border-color: var(--c); box-shadow: inset 0 0 0 1px var(--c); }
-.effort__label { font-family: var(--font-display); text-transform: uppercase; font-weight: 700; letter-spacing: .06em; font-size: var(--fs-lg); color: var(--c); }
-.effort__hint { font-size: var(--fs-xs); color: var(--text-muted); }
+.effort-picker { display: grid; grid-template-columns: 1fr 1fr; gap: var(--b); background: var(--ink); border: var(--b) solid var(--ink); }
+.effort { display: grid; gap: 2px; text-align: left; min-height: 64px; padding: var(--space-2) var(--space-3); background: var(--bg); border: 0; color: var(--ink); }
+.effort[aria-pressed="true"] { background: var(--ink); color: var(--bg); }
+.effort__label { font-family: var(--font-display); font-weight: 700; text-transform: uppercase; font-size: var(--fs-xl); line-height: 1; }
+.effort__hint { font-size: var(--fs-sm); color: var(--muted); }
+.effort[aria-pressed="true"] .effort__hint { color: inherit; }
+.effort[data-effort="failure"] .effort__label::before { content: "✕ "; }
-.tracking { display: grid; gap: 0; margin-top: var(--space-3); padding-top: var(--space-1); border-top: 1px solid var(--line); }
+.btn--work { border-style: solid; border-width: var(--b-heavy); }
+.tracking { margin-top: var(--space-4); padding-top: var(--space-3); border-top: var(--b) solid var(--ink); }
+.tracking .mini-label { margin-top: 0; }
-/* ---- Superset ----------------------------------------------------------- */
-.superset { border: 1px solid var(--work); border-radius: var(--radius); padding: var(--space-2); display: grid; gap: var(--space-2); }
-.superset__head { padding: var(--space-2); }
-.superset__text { color: var(--text-muted); font-size: var(--fs-xs); margin-top: var(--space-1); }
-.superset .exercise { background: var(--surface); }
+/* ---- superset : deux exercices dans un même cadre épais ------------------------- */
+.superset { border: var(--b-heavy) solid var(--ink); padding: var(--space-2); display: grid; gap: var(--space-2); }
+.superset__head { padding: var(--space-1) var(--space-1) var(--space-2); }
+.tag--superset { background: var(--ink); color: var(--bg); border-color: var(--ink); }
+.superset__text { color: var(--muted); font-size: var(--fs-sm); margin-top: var(--space-1); }
-/* ---- Échauffement ------------------------------------------------------- */
-.exercise--warmup { border-color: var(--primary); }
+/* ---- échauffement ----------------------------------------------------------------- */
+.exercise--warmup { border-style: dashed; }
.steps { display: grid; }
-.step { display: flex; align-items: center; gap: var(--space-3); padding: var(--space-3) 0; border-top: 1px solid var(--line); }
+.step { display: flex; align-items: center; gap: var(--space-3); padding: var(--space-2) 0; border-top: 2px solid var(--rule-soft); }
.step:first-child { border-top: 0; }
.step__text { flex: 1; min-width: 0; display: grid; }
-.step__text strong { font-size: var(--fs-sm); font-weight: 600; }
-.step__text span { color: var(--text-muted); font-size: var(--fs-xs); }
-.tick {
- width: 44px; height: 44px; flex: none; border-radius: var(--radius); background: transparent;
- border: 1px solid var(--line-strong); position: relative;
-}
-.tick[aria-pressed="true"] { background: var(--primary); border-color: var(--primary); }
-.tick[aria-pressed="true"]::after {
- content: ""; position: absolute; left: 15px; top: 9px; width: 10px; height: 18px;
- border-right: 3px solid var(--on-primary); border-bottom: 3px solid var(--on-primary); transform: rotate(45deg);
-}
+.step__text strong { font-size: var(--fs-md); }
+.step__text span { color: var(--muted); font-size: var(--fs-sm); }
+.tick { width: var(--tap); height: var(--tap); flex: none; background: var(--bg); border: var(--b) solid var(--ink); color: var(--bg); font-family: var(--font-display); font-size: var(--fs-xl); }
+.tick[aria-pressed="true"] { background: var(--ink); }
+.tick[aria-pressed="true"]::after { content: "✓"; }
.step__go { flex: none; }
+
+/* ---- minuteur, sous la barre d'action -------------------------------------------- */
+.timer {
+ position: fixed; left: 0; right: 0; bottom: 0; z-index: 30; height: calc(var(--timer-h) + env(safe-area-inset-bottom));
+ background: var(--ink); color: var(--bg); padding-bottom: env(safe-area-inset-bottom);
+}
+.timer__bar { height: 8px; background: var(--bg); }
+.timer__bar::after { content: ""; display: block; height: 100%; width: 100%; background: var(--meter); transform-origin: left; transform: scaleX(var(--progress, 0)); }
+.timer__in { max-width: var(--max); margin: 0 auto; padding: var(--space-1) var(--gutter); display: flex; align-items: center; gap: var(--space-3); height: calc(var(--timer-h) - 8px); }
+.timer__read { flex: 1; min-width: 0; display: grid; }
+.timer__label { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.timer__time { font-size: 3.75rem; line-height: 0.85; }
+.timer__btns { display: flex; gap: var(--space-2); }
+.timer .btn { border-color: var(--bg); background: var(--ink); color: var(--bg); min-height: 56px; font-size: var(--fs-lg); }
+.timer .btn--primary { background: var(--signal); color: var(--on-signal); border-color: var(--signal); }
+.timer--work .timer__bar::after { background: var(--signal); }
+.timer--low .timer__time { text-decoration: underline; text-decoration-thickness: 4px; text-underline-offset: 4px; }
+.timer--zero { background: var(--signal); color: var(--on-signal); }
+.timer--zero .btn { border-color: var(--on-signal); background: var(--signal); color: var(--on-signal); }
diff --git a/app/styles/tokens.css b/app/styles/tokens.css
index 61508a3..ac852de 100644
--- a/app/styles/tokens.css
+++ b/app/styles/tokens.css
@@ -1,88 +1,76 @@
-/* Jetons de design (docs/design.md). Toute couleur de l'interface passe par
- eux ; les ratios de contraste y sont notés. Thème sombre par défaut (« fonte et
- craie »), thème clair selon la préférence du système. */
+/* Jetons de design (docs/design.md) : noir, blanc, une couleur signal.
+ Toute couleur de l'interface passe par eux ; les ratios WCAG sont notés.
+ Sombre par défaut (noir pur : écrans OLED éteints), clair si le système le
+ demande ou si l'utilisateur le choisit (data-theme sur ). */
:root {
color-scheme: dark;
+ --bg: #000000;
+ --ink: #F2F2EC; /* 18,7 sur bg */
+ --muted: #A3A3A3; /* 8,3 sur bg, 7,2 sur sunk */
+ --sunk: #161616; /* champs de saisie ; ink 16,1 dessus */
+ --rule-soft: #5C5C5C; /* filets décoratifs de la grille (3,1) */
+ --signal: #FFD60A; /* jaune ruban : 14,9 sur bg */
+ --on-signal: #000000; /* 14,9 sur signal */
+ --meter: #FFD60A; /* remplissage des jauges (XP, semaine) */
+ --signal-edge: #FFD60A; /* bord d'un aplat signal : invisible sur noir, noir sur clair */
+ --focus: #FFD60A;
- /* Surfaces */
- --bg: #14171A; /* iron */
- --surface: #1E2328; /* cartes */
- --surface-2: #272D33; /* champs, boutons secondaires */
- --surface-sunk: #0E1113; /* zones en creux */
-
- /* Texte : AA sur toutes les surfaces */
- --text: #EDEAE3; /* chalk : 15,0 bg, 13,2 surface, 11,6 surface-2 */
- --text-muted: #A3AAB1; /* 7,7 bg, 6,7 surface, 5,9 surface-2 */
-
- /* Traits */
- --line: #333A41; /* séparateurs décoratifs */
- --line-strong: #6B737B; /* bord des contrôles : 3,7 bg, 3,3 surface (≥ 3:1) */
-
- /* Rôles */
- --primary: #3FA06A; /* action principale, séries faites */
- --on-primary: #0E1113; /* 5,8 sur primary */
- --warn: #E3B505; /* note du coach : 8,2 surface */
- --danger: #E0787C; /* 5,4 surface, 6,1 bg */
- --work: #7FB6CB; /* chrono de série : 7,1 surface */
- --focus: #7FB6CB;
-
- /* Ressenti */
- --effort-easy: #3FA06A; /* 4,9 surface */
- --effort-ok: #E3B505; /* 8,2 surface */
- --effort-hard: #D9762B; /* 5,0 surface */
- --effort-failure: #EF6B70;/* 5,1 surface */
-
- /* Couleur de la séance, posée par le programme (setAccent) */
+ /* Couleur d'une séance (donnée du programme, setAccent) : seulement sur sa
+ plaque, avec un texte calculé (inkOn). */
--accent: #8A9199;
- --accent-ink: #0E1113;
+ --accent-ink: #000000;
- /* Typographie */
- --font-display: "Barlow Condensed", "Arial Narrow", "Roboto Condensed", sans-serif-condensed, sans-serif;
+ --font-display: "Barlow Condensed", "Arial Narrow", "Roboto Condensed", sans-serif-condensed, Impact, sans-serif;
+ --font-mark: ui-monospace, "SF Mono", "Cascadia Mono", "Roboto Mono", Menlo, Consolas, "Liberation Mono", monospace;
--font-body: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
- --fs-xs: 0.8125rem; /* 13 px */
- --fs-sm: 0.875rem; /* 14 px */
- --fs-md: 1rem; /* 16 px */
- --fs-lg: 1.25rem;
- --fs-xl: 1.75rem;
- --fs-2xl: 2.25rem;
- --fs-3xl: 2.75rem;
- /* Espaces, rayons, tailles */
+ --fs-mark: 0.8125rem; /* 13 px, marquage */
+ --fs-sm: 0.9375rem; /* 15 px */
+ --fs-md: 1rem;
+ --fs-lg: 1.375rem;
+ --fs-xl: 2rem;
+ --fs-2xl: 2.75rem;
+ --fs-3xl: 3.5rem;
+ --fs-num: 4.5rem; /* charges, répétitions */
+ --fs-num-xl: 6.5rem; /* chrono, chiffre de fin de séance */
+
+ --b: 3px; /* bordure franche */
+ --b-heavy: 6px; /* filet sous un titre, barre d'action */
--space-1: 4px;
--space-2: 8px;
--space-3: 12px;
--space-4: 16px;
--space-5: 24px;
- --space-6: 32px;
- --radius: 6px;
- --radius-sm: 4px;
- --tap: 48px; /* cible tactile minimale (≥ 44 px) */
+ --space-6: 40px;
+ --tap: 48px; /* cible tactile minimale */
--gutter: 16px;
--max: 560px;
- --action-bar-h: 80px;
- --timer-h: 80px; /* minuteur, barre de progression comprise */
+ --action-bar-h: 84px;
+ --timer-h: 96px;
}
+/* Thème clair : celui du système, sauf choix explicite du sombre. */
@media (prefers-color-scheme: light) {
- :root {
+ :root:not([data-theme="dark"]) {
color-scheme: light;
- --bg: #F3F1EC;
- --surface: #FFFFFF;
- --surface-2: #E8E5DE;
- --surface-sunk: #ECE9E2;
- --text: #14171A; /* 15,9 bg, 18,0 surface, 14,3 surface-2 */
- --text-muted: #555D65; /* 5,9 bg, 6,7 surface, 5,3 surface-2 */
- --line: #D6D2C9;
- --line-strong: #8A857B; /* 3,3 bg, 3,7 surface */
- --primary: #2B7A4B;
- --on-primary: #FFFFFF; /* 5,3 */
- --warn: #806200; /* 5,0 bg, 5,6 surface */
- --danger: #B3262C; /* 6,5 surface */
- --work: #2E6E8A; /* 5,7 surface */
- --focus: #2E6E8A;
- --effort-easy: #2B7A4B;
- --effort-ok: #806200;
- --effort-hard: #A9531A;
- --effort-failure: #B3262C;
+ --bg: #F2F2EC;
+ --ink: #000000; /* 18,7 sur bg */
+ --muted: #555555; /* 6,6 sur bg, 5,8 sur sunk */
+ --sunk: #E4E4DD;
+ --rule-soft: #8F8F8F;
+ --meter: #000000; /* le jaune sur blanc ferait 1,3:1 : la jauge passe au noir */
+ --signal-edge: #000000; /* et un aplat jaune reçoit un bord noir */
+ --focus: #000000;
}
}
+:root[data-theme="light"] {
+ color-scheme: light;
+ --bg: #F2F2EC;
+ --ink: #000000;
+ --muted: #555555;
+ --sunk: #E4E4DD;
+ --rule-soft: #8F8F8F;
+ --meter: #000000;
+ --signal-edge: #000000;
+ --focus: #000000;
+}
diff --git a/app/ui/chart.js b/app/ui/chart.js
new file mode 100644
index 0000000..49b69b3
--- /dev/null
+++ b/app/ui/chart.js
@@ -0,0 +1,100 @@
+// Petites courbes en SVG, sans bibliothèque : poids, charge, répétitions,
+// assiduité. Une seule série par courbe (jamais deux échelles), un trait plein
+// à angles vifs, des repères carrés. Les valeurs sont aussi dans une liste ou
+// un tableau à côté : la courbe n'est jamais la seule source.
+// La géométrie (pure, testée) est séparée du dessin (DOM).
+
+const NS = "http://www.w3.org/2000/svg";
+
+/**
+ * @typedef {object} Geometry
+ * @property {string} path « M x,y L x,y … »
+ * @property {{x: number, y: number}[]} dots
+ * @property {{y: number, value: number}[]} ticks trois repères horizontaux
+ * @property {(x: number, value: number) => {x: number, y: number}} at
+ */
+
+/**
+ * Place des points (x quelconque, croissant ; y en unité) dans un cadre.
+ * @param {{x: number, y: number}[]} points
+ * @param {{width: number, height: number, left?: number, right?: number, top?: number, bottom?: number, minSpan?: number}} box
+ * @returns {Geometry}
+ */
+export function lineGeometry(points, { width, height, left = 36, right = 8, top = 10, bottom = 20, minSpan = 1 }) {
+ const xs = points.map((p) => p.x), ys = points.map((p) => p.y);
+ const x0 = Math.min(...xs), x1 = Math.max(...xs);
+ let y0 = Math.min(...ys), y1 = Math.max(...ys);
+ const margin = Math.max(minSpan / 2, (y1 - y0) * 0.15);
+ y0 -= margin;
+ y1 += margin;
+ const px = (/** @type {number} */ x) => left + (width - left - right) * (x1 === x0 ? 0.5 : (x - x0) / (x1 - x0));
+ const py = (/** @type {number} */ y) => top + (height - top - bottom) * (1 - (y - y0) / (y1 - y0));
+ const round = (/** @type {number} */ n) => Math.round(n * 10) / 10;
+ const dots = points.map((p) => ({ x: round(px(p.x)), y: round(py(p.y)) }));
+ return {
+ path: dots.map((d, i) => `${i ? "L" : "M"}${d.x},${d.y}`).join(" "),
+ dots,
+ ticks: [0, 0.5, 1].map((f) => ({ value: y0 + (y1 - y0) * f, y: round(py(y0 + (y1 - y0) * f)) })),
+ at: (x, value) => ({ x: round(px(x)), y: round(py(value)) }),
+ };
+}
+
+/**
+ * @param {string} tag
+ * @param {Record} attrs
+ * @param {string} [text]
+ */
+function el(tag, attrs, text) {
+ const e = document.createElementNS(NS, tag);
+ for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, String(v));
+ if (text !== undefined) e.textContent = text;
+ return e;
+}
+
+/**
+ * Courbe d'une série dans le temps.
+ * @param {{points: {x: number, y: number}[], label: string, format: (v: number) => string, xLabels: [string, string], trend?: {from: number, to: number}|null, minSpan?: number}} o
+ * x : jours depuis une origine ; trend : valeurs de la tendance au premier et au dernier x
+ * @returns {SVGSVGElement}
+ */
+export function lineChart({ points, label, format, xLabels, trend = null, minSpan = 1 }) {
+ const W = 340, H = 160;
+ const g = lineGeometry(points, { width: W, height: H, minSpan });
+ const svg = /** @type {SVGSVGElement} */ (el("svg", { viewBox: `0 0 ${W} ${H}`, role: "img", "aria-label": label }));
+ for (const t of g.ticks) {
+ svg.append(el("line", { class: "chart__axis", x1: 36, x2: W - 8, y1: t.y, y2: t.y }));
+ svg.append(el("text", { class: "chart__text", x: 30, y: t.y + 4, "text-anchor": "end" }, format(t.value)));
+ }
+ if (trend && points.length > 2) {
+ const a = g.at(points[0].x, trend.from), b = g.at(points[points.length - 1].x, trend.to);
+ svg.append(el("line", { class: "chart__trend", x1: a.x, y1: a.y, x2: b.x, y2: b.y }));
+ }
+ svg.append(el("path", { class: "chart__line", d: g.path }));
+ for (const d of g.dots) svg.append(el("rect", { class: "chart__dot", x: d.x - 3, y: d.y - 3, width: 6, height: 6 }));
+ svg.append(el("text", { class: "chart__text", x: 36, y: H - 4 }, xLabels[0]));
+ svg.append(el("text", { class: "chart__text", x: W - 8, y: H - 4, "text-anchor": "end" }, xLabels[1]));
+ return svg;
+}
+
+/**
+ * Barres verticales (une par semaine) : des blocs, comme des disques empilés.
+ * @param {{values: number[], label: string, labels: [string, string], highlightLast?: boolean}} o
+ * @returns {SVGSVGElement}
+ */
+export function barChart({ values, label, labels, highlightLast = true }) {
+ const W = 340, H = 130, top = 8, bottom = 20, left = 4, right = 4;
+ const max = Math.max(1, ...values);
+ const step = (W - left - right) / values.length;
+ const svg = /** @type {SVGSVGElement} */ (el("svg", { viewBox: `0 0 ${W} ${H}`, role: "img", "aria-label": label }));
+ svg.append(el("line", { class: "chart__axis", x1: left, x2: W - right, y1: H - bottom, y2: H - bottom }));
+ values.forEach((v, i) => {
+ const h = ((H - top - bottom) * v) / max;
+ if (v > 0) svg.append(el("rect", {
+ class: `chart__bar${highlightLast && i === values.length - 1 ? " chart__bar--now" : ""}`,
+ x: Math.round(left + i * step + 2), y: Math.round(H - bottom - h), width: Math.max(2, Math.round(step - 4)), height: Math.round(h),
+ }));
+ });
+ svg.append(el("text", { class: "chart__text", x: left, y: H - 4 }, labels[0]));
+ svg.append(el("text", { class: "chart__text", x: W - right, y: H - 4, "text-anchor": "end" }, labels[1]));
+ return svg;
+}
diff --git a/app/ui/color.js b/app/ui/color.js
index 7ef812e..5979e4b 100644
--- a/app/ui/color.js
+++ b/app/ui/color.js
@@ -15,7 +15,7 @@ export function contrastRatio(a, b) {
return (hi + 0.05) / (lo + 0.05);
}
-export const INK_DARK = "#0E1113";
+export const INK_DARK = "#000000";
export const INK_LIGHT = "#FFFFFF";
/**
diff --git a/app/ui/dom.js b/app/ui/dom.js
index 7011ee0..a74b03d 100644
--- a/app/ui/dom.js
+++ b/app/ui/dom.js
@@ -69,6 +69,38 @@ export function setAccent(el, color, ink) {
el.style.setProperty("--accent-ink", ink);
}
+/**
+ * Repeint une zone à chaque changement de l'état, sauf pendant une saisie :
+ * piège d'Atelier, on ne reconstruit jamais une zone qui contient le champ en
+ * cours de saisie. Le repeint attend alors que le champ perde le focus.
+ * @param {HTMLElement} zone
+ * @param {() => void} paint
+ * @returns {() => void} à appeler à chaque changement
+ */
+export function paintWhenIdle(zone, paint) {
+ let pending = false;
+ zone.addEventListener("focusout", () => {
+ if (!pending) return;
+ // Le focus peut passer à un autre champ de la même zone.
+ setTimeout(() => {
+ if (pending && !isTyping(zone)) {
+ pending = false;
+ paint();
+ }
+ }, 0);
+ });
+ return () => {
+ if (isTyping(zone)) pending = true;
+ else paint();
+ };
+}
+
+/** @param {HTMLElement} zone */
+function isTyping(zone) {
+ const el = document.activeElement;
+ return !!el && zone.contains(el) && (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement);
+}
+
/** Vibration courte, si l'appareil sait le faire. @param {number[]} pattern */
export function vibrate(pattern) {
try {
diff --git a/app/ui/exercise-card.js b/app/ui/exercise-card.js
index f2e76ce..2ca6638 100644
--- a/app/ui/exercise-card.js
+++ b/app/ui/exercise-card.js
@@ -11,10 +11,12 @@ import { TRACKING_MODES, EFFORTS } from "../domain/vocabulary.js";
import { resolveExercise, trackingFor } from "../domain/program.js";
import { EFFORT_LABELS, TRACKING_LABELS } from "./labels.js";
import { kg, parseAmount, restLabel } from "./format.js";
-import { doneCount, draftExercise, proposedReps, targetLabel, targetReps, usesLoad, usesTime } from "./session-draft.js";
+import { doneCount, draftExercise, markSet, proposedReps, targetLabel, targetReps, usesLoad, usesTime } from "./session-draft.js";
+import { progressionAdvice } from "../domain/progression.js";
/**
* @typedef {object} ExerciseCardOptions
+ * @property {import("./session-draft.js").Draft} draft
* @property {import("./session-draft.js").DraftExercise} ex exercice du brouillon (modifié sur place)
* @property {import("../domain/program.js").ProgramExercise} item
* @property {string} sessionKey
@@ -59,13 +61,17 @@ export function exerciseCard(o) {
let openPanel = null;
/** @type {HTMLButtonElement|null} */
let chronoBtn = null;
+ /** @type {HTMLInputElement|null} */
+ let loadInput = null;
const paintSets = () => {
setButtons.forEach((b, i) => {
const s = ex.done[i];
b.classList.toggle("set-btn--done", s !== null);
b.dataset.effort = s?.effort ?? "";
- b.textContent = s === null ? String(i + 1) : typeof s.reps === "number" ? String(s.reps) : "✓";
+ replace(b,
+ h("span", { class: "set-btn__n" }, s === null ? String(i + 1) : typeof s.reps === "number" ? String(s.reps) : "✓"),
+ s?.effort ? h("span", { class: "set-btn__effort" }, EFFORT_LABELS[s.effort].short) : null);
const what = s === null ? "à faire"
: [typeof s.reps === "number" ? `${s.reps} répétitions` : "faite", s.effort ? EFFORT_LABELS[s.effort].label.toLowerCase() : null]
.filter(Boolean).join(", ");
@@ -105,7 +111,7 @@ export function exerciseCard(o) {
type: "button", class: "effort", data: { effort },
"aria-pressed": String(existing?.effort === effort),
on: { click: () => {
- ex.done[i] = { reps: timed ? null : reps, effort };
+ markSet(o.draft, ex, i, { reps: timed ? null : reps, effort });
closePanel();
changed();
// Le repos démarre au ressenti.
@@ -130,7 +136,7 @@ export function exerciseCard(o) {
timer.startWork(seconds, `${ex.name} · série ${i + 1}`, () => {
// Fin du chrono : la série est cochée (bug d'Atelier : « cocher » n'existait
// pas), puis on demande le ressenti, qui lancera le repos.
- if (ex.done[i] === null) ex.done[i] = { reps: null, effort: null };
+ if (ex.done[i] === null) markSet(o.draft, ex, i, { reps: null, effort: null });
changed();
openPanel = null;
showPanel(i);
@@ -163,6 +169,7 @@ export function exerciseCard(o) {
refreshChrono();
o.onChange();
});
+ if (isLoad) loadInput = input;
input.addEventListener("change", () => {
const v = parseAmount(input.value);
if (v === undefined || (field === "seconds" && !v)) return;
@@ -178,6 +185,7 @@ export function exerciseCard(o) {
const drawWork = () => {
openPanel = null;
chronoBtn = null;
+ loadInput = null;
setButtons = Array.from({ length: ex.sets }, (_, i) =>
h("button", { type: "button", class: "set-btn", on: { click: () => showPanel(i) } }, String(i + 1)));
const fields = h("div", { class: "work__fields" },
@@ -210,12 +218,34 @@ export function exerciseCard(o) {
ex.loadKg = fresh.loadKg;
ex.seconds = fresh.seconds;
drawWork();
+ paintAdvice();
changed();
/** @type {HTMLElement|null} */ (tracking.querySelector("[aria-pressed=true]"))?.focus();
} },
}, TRACKING_LABELS[mode])));
};
+ // ---- conseil de progression (double progression) ------------------------------
+ const advice = h("div", { class: "advice", hidden: true });
+ const paintAdvice = () => {
+ const a = usesLoad(ex.tracking) ? progressionAdvice(store.getState(), o.sessionKey, item) : null;
+ if (!a || ex.loadKg === a.newLoadKg) {
+ advice.hidden = true;
+ return;
+ }
+ advice.hidden = false;
+ replace(advice,
+ h("p", { class: "advice__head" }, h("span", { class: "mark" }, "Prêt à monter"), h("span", { class: "num advice__kg" }, `${kg(a.newLoadKg)} kg`)),
+ h("p", { class: "muted" }, `Dernière fois : ${a.reason}.`),
+ h("button", { type: "button", class: "btn btn--primary btn--block", on: { click: () => {
+ store.dispatch("WorkingLoadSet", { key: ex.key, loadKg: a.newLoadKg });
+ ex.loadKg = a.newLoadKg;
+ if (loadInput) { loadInput.value = kg(a.newLoadKg); loadInput.setAttribute("aria-invalid", "false"); }
+ advice.hidden = true;
+ changed();
+ } } }, `Adopter ${kg(a.newLoadKg)} kg`));
+ };
+
// ---- consignes ---------------------------------------------------------------
const muscles = library
? h("ul", { class: "chips", "aria-label": "Muscles sollicités" },
@@ -241,12 +271,12 @@ export function exerciseCard(o) {
h("a", { class: "btn btn--ghost btn--sm tutorial", href: resolved.tutorial, target: "_blank", rel: "noopener noreferrer" },
"Voir un tutoriel", h("span", { class: "visually-hidden" }, " (nouvel onglet)"), h("span", { "aria-hidden": "true" }, " ↗")),
h("p", { class: "objective" }, objective, h("span", { class: "objective__rest" }, `Repos ${restLabel(ex.rest)}`)),
- // À brancher : progression (domaine, sous-lot 1b) pour le conseil « prêt à
- // monter à X kg » au-dessus des séries.
+ advice,
work,
h("div", { class: "tracking" }, h("span", { class: "mini-label" }, "Je suis"), tracking)));
drawWork();
refreshLabels();
+ paintAdvice();
return card;
}
diff --git a/app/ui/files.js b/app/ui/files.js
new file mode 100644
index 0000000..41224b6
--- /dev/null
+++ b/app/ui/files.js
@@ -0,0 +1,49 @@
+// Fichiers et presse-papiers : téléchargement (instantané, .ics), lecture d'un
+// fichier choisi, copie d'un texte.
+
+import { h } from "./dom.js";
+
+/**
+ * Télécharge un texte. La libération de l'adresse est différée de 30 s : la
+ * révoquer aussitôt interrompt le téléchargement sur certains mobiles
+ * (piège d'Atelier, docs/lot-1.md).
+ * @param {string} name
+ * @param {string} content
+ * @param {string} type
+ */
+export function download(name, content, type) {
+ const url = URL.createObjectURL(new Blob([content], { type }));
+ const a = h("a", { href: url, download: name, rel: "noopener", class: "visually-hidden" });
+ document.body.append(a);
+ a.click();
+ a.remove();
+ setTimeout(() => URL.revokeObjectURL(url), 30_000);
+}
+
+/** @param {File} file @returns {Promise} */
+export function readFile(file) {
+ return file.text();
+}
+
+/**
+ * Copie un texte. Si le presse-papiers est refusé (http, navigateur ancien), le
+ * texte s'affiche dans `fallback`, sélectionné, pour une copie à la main.
+ * @param {string} text
+ * @param {HTMLElement} fallback
+ * @param {string} label nom du champ pour les lecteurs d'écran
+ * @returns {Promise} vrai si le texte est dans le presse-papiers
+ */
+export async function copyText(text, fallback, label) {
+ try {
+ await navigator.clipboard.writeText(text);
+ fallback.hidden = true;
+ return true;
+ } catch {
+ const area = h("textarea", { class: "field__input field__input--area field__input--mono", readonly: true, "aria-label": label });
+ area.value = text;
+ fallback.replaceChildren(h("p", { class: "muted" }, "Copie ce texte à la main :"), area);
+ fallback.hidden = false;
+ area.select();
+ return false;
+ }
+}
diff --git a/app/ui/format.js b/app/ui/format.js
index e4c7590..d8dda41 100644
--- a/app/ui/format.js
+++ b/app/ui/format.js
@@ -1,13 +1,34 @@
// Mise en forme pour l'affichage, en français. Fonctions pures, testées.
-// À brancher : dates.js (domaine, sous-lot 1b) fournira les calculs de jours ;
-// ici, seulement ce que l'interface affiche.
+// Les calculs de jours sont ceux du domaine (dates.js).
+
+import { localISO } from "../domain/dates.js";
/**
* Jour local AAAA-MM-JJ (pas UTC : une séance faite à 23 h reste le bon jour).
* @param {Date} [d]
*/
export function localDay(d = new Date()) {
- return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
+ return localISO(d);
+}
+
+/** « lun. 16/11 » @param {string} day */
+export function weekdayShort(day) {
+ return noon(day).toLocaleDateString("fr-FR", { weekday: "short", day: "2-digit", month: "2-digit" });
+}
+
+/** Une décimale au plus, à la française : 82.456 → « 82,5 ». @param {number} n */
+export function dec1(n) {
+ return kg(Math.round(n * 10) / 10);
+}
+
+/** Durée lisible : 20 → « 20 jours », 400 → « 1 an et 1 mois ». @param {number} days */
+export function durationLabel(days) {
+ if (days < 45) return plural(days, "jour");
+ let months = Math.round(days / 30.44);
+ const years = Math.floor(months / 12);
+ months -= years * 12;
+ if (!years) return `${months} mois`;
+ return plural(years, "an") + (months ? ` et ${months} mois` : "");
}
/** @param {string} day AAAA-MM-JJ */
diff --git a/app/ui/game.js b/app/ui/game.js
new file mode 100644
index 0000000..9dc01fe
--- /dev/null
+++ b/app/ui/game.js
@@ -0,0 +1,233 @@
+// La gamification dans l'interface : tout l'usage de app/domain/gamification.js
+// passe par ce module (HUD de l'accueil, combo de la séance, écran de fin de
+// séance). Codes du jeu vidéo, avec mesure : on récompense la régularité et la
+// progression, jamais l'échec ni l'excès (les règles sont dans le domaine).
+// Animations courtes, une seule fois, coupées par prefers-reduced-motion.
+
+import { gameStats, sessionCombo, sessionRewards } from "../domain/gamification.js";
+import { h } from "./dom.js";
+import { href } from "./router.js";
+
+/** @typedef {import("../domain/state.js").State} State */
+/** @typedef {import("../domain/gamification.js").SessionRewards} SessionRewards */
+
+/** Nombre de cases de la jauge d'XP. */
+export const XP_CELLS = 20;
+
+/**
+ * Jauge en cases : `filled` cases pleines sur `total`.
+ * @param {number} filled
+ * @param {number} total
+ * @param {string} [cls]
+ */
+export function cells(filled, total, cls = "cells") {
+ return h("span", { class: cls, "aria-hidden": "true" },
+ Array.from({ length: total }, (_, i) => h("i", { data: { state: i < filled ? "done" : "todo" } })));
+}
+
+/**
+ * Bandeau de l'accueil : niveau, XP, série de semaines. Il mène au détail
+ * (succès, records).
+ * @param {State} state
+ * @param {string} today
+ */
+export function hud(state, today) {
+ const stats = gameStats(state, { today });
+ const { level, streak } = stats;
+ const filled = Math.floor(level.progress * XP_CELLS);
+ return h("a", {
+ class: "hud", href: href.progress(),
+ "aria-label": `${level.label}. ${level.xpForNext} XP avant le niveau suivant. ${streak.label}. Voir tes succès.`,
+ },
+ h("span", { class: "hud__lvl" }, h("span", { class: "mark" }, "Niv."), h("span", { class: "hud__big num" }, String(level.level))),
+ h("span", { class: "hud__body" },
+ h("span", { class: "hud__title" }, level.title),
+ cells(filled, XP_CELLS, "cells cells--xp"),
+ h("span", { class: "mark muted" }, `${level.xpInLevel} / ${level.xpInLevel + level.xpForNext} XP`)),
+ h("span", { class: "hud__streak" },
+ h("span", { class: "hud__big num" }, String(streak.current)),
+ h("span", { class: "mark" }, streak.current > 1 ? "semaines" : "semaine"),
+ streak.atStake && h("span", { class: "mark muted" }, "en jeu")));
+}
+
+/**
+ * Combo de la séance en cours, à partir des séries du brouillon (dans l'ordre
+ * où elles ont été validées, voir session-draft.setsInOrder).
+ * @param {(import("../domain/events.js").LoggedSet|null)[]} sets
+ * @returns {string} « Combo ×4 », ou vide
+ */
+export function comboLabel(sets) {
+ return sessionCombo(sets).label;
+}
+
+/** @type {{rewards: SessionRewards, summary: SessionSummary}|null} */
+let lastFinish = null;
+
+/**
+ * @typedef {object} SessionSummary
+ * @property {string} name
+ * @property {string} date
+ * @property {number} sets
+ * @property {number} reps
+ * @property {number} volumeKg somme des répétitions × charge
+ */
+
+/**
+ * À la fin d'une séance : calcule et garde ce qu'elle rapporte, pour l'écran de
+ * fin. Rien n'est stocké : un rechargement de la page ramène à l'accueil.
+ * @param {State} before
+ * @param {State} after
+ * @param {string} today
+ * @param {SessionSummary} summary
+ */
+export function recordFinish(before, after, today, summary) {
+ lastFinish = { rewards: sessionRewards(before, after, { today }), summary };
+}
+
+export function takeFinish() {
+ return lastFinish;
+}
+
+/** L'utilisateur a demandé moins de mouvement. */
+const reducedMotion = () => typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
+
+/**
+ * Compteur qui monte jusqu'à sa valeur en moins d'une seconde, une fois.
+ * @param {HTMLElement} el
+ * @param {number} to
+ * @param {(n: number) => string} format
+ */
+function countUp(el, to, format) {
+ if (reducedMotion() || to <= 0) {
+ el.textContent = format(to);
+ return;
+ }
+ const start = performance.now();
+ const duration = 700;
+ el.textContent = format(0);
+ const step = (/** @type {number} */ now) => {
+ const t = Math.min(1, (now - start) / duration);
+ el.textContent = format(Math.round(to * (1 - (1 - t) ** 3)));
+ if (t < 1) requestAnimationFrame(step);
+ };
+ requestAnimationFrame(step);
+}
+
+/** « 1 840 » @param {number} n */
+const thousands = (n) => String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, " ");
+
+/**
+ * Écran de fin de séance : le moment endorphine. Un grand chiffre, l'XP qui
+ * monte, le niveau, les records et les succès.
+ * @param {{nav: import("./router.js").Navigation}} ctx
+ * @returns {import("./router.js").Screen}
+ */
+export function finishScreen({ nav }) {
+ const done = lastFinish;
+ if (!done) {
+ queueMicrotask(() => nav.go(href.home(), { replace: true }));
+ return { node: h("div", { class: "screen" }), title: "" };
+ }
+ const { rewards, summary } = done;
+ const big = h("span", { class: "big-number" });
+ const xp = h("span", { class: "num" });
+ const lvl = rewards.levelAfter;
+ const filled = Math.floor(lvl.progress * XP_CELLS);
+ const volume = summary.volumeKg > 0;
+
+ const node = h("div", { class: "screen screen--finish" },
+ h("header", { class: "screen-head" },
+ h("p", { class: "kicker" }, "Séance terminée · ", summary.name),
+ h("h1", { class: "title title--hero" }, "Bien joué.")),
+ h("section", { class: "reward", "aria-label": "Ce que tu as fait" },
+ h("p", { class: "reward__big" }, big, h("small", null, volume ? "kg" : "séries")),
+ h("p", { class: "mark" }, volume
+ ? `soulevés · ${summary.sets} séries · ${summary.reps} répétitions`
+ : `${summary.reps} répétitions`)),
+ h("section", { class: "reward__xp", "aria-label": "Expérience" },
+ h("p", { class: "reward__gain" }, "+", xp, " XP"),
+ h("ul", { class: "reward__parts" }, rewards.parts.map((p) =>
+ h("li", null, h("span", null, p.label), h("span", { class: "num" }, `+${p.xp}`)))),
+ h("div", { class: "reward__level" },
+ h("span", { class: "mark" }, lvl.label),
+ cells(filled, XP_CELLS, "cells cells--xp reward__cells"),
+ h("span", { class: "mark muted" }, `${lvl.xpForNext} XP avant le niveau ${lvl.level + 1}`))),
+ rewards.levelUp && h("p", { class: "stamp", role: "status" }, "Niveau supérieur ! ", h("br"), rewards.levelUp.text),
+ rewards.records.length > 0 && h("section", { class: "reward__records" },
+ h("p", { class: "stamp stamp--record" }, rewards.records.length > 1 ? `${rewards.records.length} records !` : "Record !"),
+ h("ul", { class: "rows" }, rewards.records.map((r) =>
+ h("li", { class: "row" }, h("span", { class: "row__main" }, h("span", { class: "row__title" }, r.text)))))),
+ rewards.achievements.length > 0 && h("section", null,
+ h("h2", { class: "tape" }, "Succès débloqué"),
+ h("ul", { class: "rows" }, rewards.achievements.map((a) =>
+ h("li", { class: "row" },
+ h("span", { class: "badge badge--signal", "aria-hidden": "true" }, "★"),
+ h("span", { class: "row__main" }, h("span", { class: "row__title" }, a.title), h("span", { class: "row__meta" }, a.description)))))),
+ 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." : ""),
+ 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"))));
+
+ countUp(big, volume ? summary.volumeKg : summary.sets, thousands);
+ countUp(xp, rewards.xp, String);
+ return { node, title: "Bien joué", destroy: () => { lastFinish = null; } };
+}
+
+/**
+ * Écran « Progression » : niveau, série, records et succès.
+ * @param {{store: import("./store.js").Store, nav: import("./router.js").Navigation, today: string}} ctx
+ * @returns {import("./router.js").Screen}
+ */
+export function progressScreen({ store, nav, today }) {
+ const stats = gameStats(store.getState(), { today });
+ const { level, streak } = stats;
+ const unlocked = stats.achievements.filter((a) => a.unlocked);
+ const locked = stats.achievements.filter((a) => !a.unlocked);
+ const recent = stats.streak.weeks.slice(-8);
+ const node = h("div", { class: "screen" },
+ h("header", { class: "screen-head" },
+ h("button", { type: "button", class: "back", on: { click: () => nav.back(href.home()) } }, "← Accueil"),
+ h("p", { class: "kicker" }, level.label),
+ h("h1", { class: "title" }, "Progression")),
+ h("div", { class: "stats" },
+ stat(String(level.level), "niveau"),
+ stat(thousands(stats.xp), "XP au total"),
+ stat(String(streak.current), `semaine${streak.current > 1 ? "s" : ""} de série`),
+ stat(String(stats.records.beaten), "records battus")),
+ h("div", { class: "block" },
+ h("p", { class: "mark" }, `${level.xpInLevel} / ${level.xpInLevel + level.xpForNext} XP · niveau ${level.level + 1} ensuite`),
+ cells(Math.floor(level.progress * XP_CELLS), XP_CELLS, "cells cells--xp"),
+ h("p", { class: "muted" }, "Une séance de force rapporte 100 XP, un cardio ou une activité 50. Bonus : séance complète, faite le jour prévu, record battu. Une série en échec ne rapporte rien de plus : écoute ton corps.")),
+ h("h2", { class: "tape" }, "Semaines", h("span", { class: "tape__hint" }, streak.thisWeek.label)),
+ recent.length
+ ? h("ul", { class: "rows" }, [...recent].reverse().map((w) =>
+ h("li", { class: "row" },
+ h("span", { class: "row__main" }, h("span", { class: "row__title" }, `Semaine du ${dayMonth(w.monday)}`), h("span", { class: "row__meta" }, w.label)),
+ h("span", { class: "row__side mark" }, WEEK_STATUS[w.status] ?? w.status))))
+ : h("p", { class: "empty" }, "Ta première séance lance la série."),
+ h("h2", { class: "tape" }, "Succès", h("span", { class: "tape__hint" }, `${unlocked.length} / ${stats.achievements.length}`)),
+ h("ul", { class: "rows" },
+ unlocked.map((a) => h("li", { class: "row" },
+ h("span", { class: "badge badge--signal", "aria-hidden": "true" }, "★"),
+ h("span", { class: "row__main" }, h("span", { class: "row__title" }, a.title), h("span", { class: "row__meta" }, a.description)),
+ h("span", { class: "row__side mark" }, a.date ? dayMonth(a.date) : ""))),
+ locked.map((a) => h("li", { class: "row" },
+ h("span", { class: "badge", "aria-hidden": "true" }, "·"),
+ h("span", { class: "row__main" }, h("span", { class: "row__title muted" }, a.title), h("span", { class: "row__meta" }, a.description)),
+ h("span", { class: "row__side mark muted" }, "à débloquer")))));
+ return { node, title: "Progression" };
+}
+
+/** @type {Record} */
+const WEEK_STATUS = { met: "✓ atteinte", missed: "manquée", rest: "repos", start: "départ", inPlay: "en jeu" };
+
+/** @param {string} value @param {string} label */
+function stat(value, label) {
+ return h("div", { class: "stat" }, h("span", { class: "stat__value" }, value), h("span", { class: "stat__label" }, label));
+}
+
+/** @param {string} day */
+function dayMonth(day) {
+ return new Date(day + "T12:00:00").toLocaleDateString("fr-FR", { day: "numeric", month: "short" });
+}
diff --git a/app/ui/home-model.js b/app/ui/home-model.js
index 5e0dc21..f3907dc 100644
--- a/app/ui/home-model.js
+++ b/app/ui/home-model.js
@@ -1,14 +1,26 @@
-// Ce que l'accueil affiche, calculé à partir de l'état. Module pur, testé.
-//
-// À brancher : planning.weekPlan(state, monday) (domaine, sous-lot 1b). Tant
-// qu'il n'existe pas, la carte du jour propose la séance faite le moins
-// récemment (rotation simple) et le dit à l'utilisateur.
+// Ce que l'accueil et l'écran Semaine affichent, calculé à partir de l'état et
+// du planning (domaine). Module pur, testé (tests/ui/home-model.test.js).
-import { groupBlocks, resolveExercise, targetSeconds } from "../domain/program.js";
+import { addDays, dayIndex, mondayOf } from "../domain/dates.js";
+import { lateSlots, settingsForWeek, slotRef, weekPlan, weekStatus } from "../domain/planning.js";
+
+/** @typedef {import("../domain/state.js").State} State */
+/** @typedef {import("../domain/planning.js").Slot} Slot */
+/** @typedef {import("../domain/program.js").Program} Program */
+
+/** Jours de la semaine, du lundi au dimanche. */
+export const DAY_SHORT = ["Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"];
+export const DAY_LETTERS = ["L", "M", "M", "J", "V", "S", "D"];
+export const DAY_NAMES = ["lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", "dimanche"];
+
+/** @type {Record} */
+export const ZONE_LABELS = { cardio: "Cardio", lower: "Bas du corps", upper: "Haut du corps", core: "Tronc" };
+/** @type {Record} */
+export const INTENSITY_LABELS = { light: "Légère", moderate: "Modérée", hard: "Intense" };
/**
* Dernière date (AAAA-MM-JJ) où chaque séance de force a été faite.
- * @param {import("../domain/state.js").State} state
+ * @param {State} state
* @returns {Record}
*/
export function lastDoneByKey(state) {
@@ -20,9 +32,9 @@ export function lastDoneByKey(state) {
}
/**
- * Prochaine séance par rotation : une séance jamais faite d'abord (dans l'ordre
- * du programme), sinon celle faite le moins récemment.
- * @param {import("../domain/state.js").State} state
+ * Prochaine séance par rotation, quand aucun planning n'est réglé : une séance
+ * jamais faite d'abord (dans l'ordre du programme), sinon la moins récente.
+ * @param {State} state
* @returns {import("../domain/program.js").ProgramSession|null}
*/
export function nextByRotation(state) {
@@ -35,19 +47,207 @@ export function nextByRotation(state) {
}
/**
- * Durée estimée d'une séance, en minutes, arrondie à 5 : dix minutes
- * d'échauffement, puis pour chaque bloc le travail des séries et les repos
- * (40 s par série quand l'objectif est en répétitions). Reprise d'Atelier.
- * @param {import("../domain/program.js").ProgramSession} session
+ * Nom et détail d'un créneau, pour l'affichage.
+ * @param {Slot} slot
+ * @param {Program|null} program
+ * @returns {{title: string, detail: string, color: string|undefined, key: string|null}}
*/
-export function estimateMinutes(session) {
- let total = 10 * 60;
- for (const block of groupBlocks(session.exercises)) {
- const items = block.items.map(resolveExercise);
- const rounds = Math.max(...items.map((x) => x.sets));
- const work = items.reduce((n, x) => n + (targetSeconds(x.reps) ?? 40), 0);
- const rest = items.reduce((n, x) => n + x.rest, 0);
- total += rounds * work + (rounds - 1) * rest + 45 * items.length;
+export function slotLabel(slot, program) {
+ if (slot.kind === "strength") {
+ const s = program?.sessions.find((x) => x.key === slot.sessionKey);
+ return { title: `Séance ${slot.sessionKey}`, detail: s?.name ?? "", color: s?.color, key: slot.sessionKey ?? null };
}
- return Math.round(total / 60 / 5) * 5;
+ if (slot.kind === "activity") {
+ const a = program?.activities?.find((x) => x.id === slot.activityId);
+ return {
+ title: a?.name ?? "Activité",
+ detail: a ? `${a.zones.map((z) => ZONE_LABELS[z]).join(", ")} · ${a.minutes} min` : "",
+ color: a?.color, key: null,
+ };
+ }
+ const c = program?.cardio?.[slot.cardioIndex ?? -1];
+ return { title: "Cardio", detail: c?.name ?? "", color: undefined, key: null };
}
+
+/**
+ * Le contenu d'un SessionLogged pour un cardio ou une activité marqué fait.
+ * @param {Slot} slot
+ * @param {Program|null} program
+ * @param {string} date
+ * @returns {import("../domain/events.js").SessionData}
+ */
+export function loggedForSlot(slot, program, date) {
+ const { kind, ref } = slotRef(slot, program);
+ const name = slot.kind === "activity" ? slotLabel(slot, program).title : ref;
+ return { date, kind, ref, name, warmup: null, exercises: [] };
+}
+
+/**
+ * @typedef {object} TodayModel
+ * @property {boolean} planned un planning est réglé pour cette semaine
+ * @property {Slot|null} slot le créneau du jour
+ * @property {"none"|"rest"|"todo"|"done"|"skipped"} status
+ * @property {Slot|null} next le prochain créneau de la semaine, après aujourd'hui
+ * @property {Slot[]} late créneaux passés, ni faits ni marqués non faits
+ * @property {{state: "done"|"skip"|"todo"}[]} cells un par créneau de la semaine
+ * @property {number} done
+ * @property {number} skipped
+ * @property {number} extra séances faites hors planning cette semaine
+ * @property {import("../domain/state.js").LoggedSession[]} doneToday
+ */
+
+/**
+ * La carte du jour.
+ * @param {State} state
+ * @param {string} today
+ * @returns {TodayModel}
+ */
+export function todayModel(state, today) {
+ const monday = mondayOf(today);
+ const plan = weekPlan(state, monday);
+ const planned = settingsForWeek(state, monday) !== null && plan.slots.length > 0;
+ const { bySlot, extra } = weekStatus(state, plan);
+ const skipped = new Set(state.skippedDays);
+ const slot = planned ? plan.slots.find((s) => s.date === today) ?? null : null;
+ const doneToday = state.sessions.filter((s) => s.date === today);
+ /** @type {TodayModel["status"]} */
+ let status = "none";
+ if (planned) {
+ if (!slot) status = "rest";
+ else if (bySlot.get(slot)?.done) status = "done";
+ else if (skipped.has(today)) status = "skipped";
+ else status = "todo";
+ }
+ const cells = plan.slots.map((s) => ({
+ state: /** @type {"done"|"skip"|"todo"} */ (bySlot.get(s)?.done ? "done" : skipped.has(s.date) ? "skip" : "todo"),
+ }));
+ return {
+ planned,
+ slot,
+ status,
+ next: plan.slots.find((s) => s.date > today) ?? null,
+ late: planned ? lateSlots(state, today) : [],
+ cells,
+ done: cells.filter((c) => c.state === "done").length,
+ skipped: cells.filter((c) => c.state === "skip").length,
+ extra: extra.length,
+ doneToday,
+ };
+}
+
+/**
+ * @typedef {object} WeekRow
+ * @property {number} day
+ * @property {string} date
+ * @property {Slot|null} slot
+ * @property {boolean} available jour disponible ou imposé
+ * @property {string|null} lock
+ * @property {{done: boolean, date: string|null, shifted: boolean}|null} status
+ * @property {boolean} skipped
+ * @property {boolean} isToday
+ * @property {("done"|"skip"|"unskip"|"remove")[]} actions
+ */
+
+/**
+ * Les sept lignes de l'écran Semaine. Les actions « Faite », « Non fait »,
+ * « Annuler » et « Retirer » ne valent que pour les jours passés ou le jour
+ * même de la semaine en cours.
+ * @param {State} state
+ * @param {string} monday
+ * @param {string} today
+ * @returns {{plan: import("../domain/planning.js").WeekPlan, rows: WeekRow[], extra: import("../domain/state.js").LoggedSession[]}}
+ */
+export function weekRows(state, monday, today) {
+ const current = mondayOf(today);
+ const plan = weekPlan(state, monday, { today });
+ const { bySlot, extra } = weekStatus(state, plan);
+ const skippedDays = new Set(state.skippedDays);
+ const rows = Array.from({ length: 7 }, (_, day) => {
+ const date = addDays(monday, day);
+ const slot = plan.slots.find((s) => s.day === day) ?? null;
+ const status = slot ? bySlot.get(slot) ?? null : null;
+ const done = !!status?.done;
+ const skipped = !done && skippedDays.has(date);
+ /** @type {WeekRow["actions"]} */
+ const actions = [];
+ if (slot && monday === current && date <= today) {
+ if (done) actions.push("remove");
+ else if (skipped) actions.push("unskip");
+ else actions.push("done", "skip");
+ }
+ return {
+ day, date, slot, status, skipped, actions,
+ available: plan.days.includes(day) || plan.locks[day] !== undefined,
+ lock: plan.locks[day] ?? null,
+ isToday: date === today,
+ };
+ });
+ return { plan, rows, extra };
+}
+
+/**
+ * Séance enregistrée qui a rempli un créneau (pour « Retirer »).
+ * @param {State} state
+ * @param {Slot} slot
+ * @param {{date: string|null}} status
+ */
+export function sessionForSlot(state, slot, status) {
+ const { kind, ref } = slotRef(slot, state.program);
+ return state.sessions.find((s) => s.kind === kind && s.ref === ref && s.date === status.date) ?? null;
+}
+
+/**
+ * Ce qu'on peut imposer à un jour.
+ * @param {Program|null} program
+ * @returns {{value: string, label: string}[]}
+ */
+export function lockOptions(program) {
+ return [
+ { value: "", label: "Automatique" },
+ { value: "strength", label: "Une séance de force" },
+ ...(program?.sessions ?? []).map((s) => ({ value: `strength:${s.key}`, label: `Séance ${s.key} · ${s.name}` })),
+ ...(program?.cardio ?? []).map((c, i) => ({ value: `cardio:${i}`, label: `Cardio · ${c.name}` })),
+ ...(program?.activities ?? []).map((a) => ({ value: `activity:${a.id}`, label: a.name })),
+ { value: "rest", label: "Repos" },
+ ];
+}
+
+/**
+ * Nouveaux jours disponibles : les jours imposés des jours retirés tombent.
+ * @param {{days: number[], locks: Record}|null} settings
+ * @param {number[]} days
+ */
+export function withDays(settings, days) {
+ /** @type {Record} */
+ const locks = {};
+ for (const [d, lock] of Object.entries(settings?.locks ?? {})) if (days.includes(Number(d))) locks[d] = lock;
+ return { days: [...new Set(days)].sort((a, b) => a - b), locks };
+}
+
+/**
+ * Impose (ou libère, valeur vide) un jour ; un jour imposé devient disponible.
+ * @param {{days: number[], locks: Record}|null} settings
+ * @param {number} day
+ * @param {string} value
+ */
+export function withLock(settings, day, value) {
+ const locks = { ...(settings?.locks ?? {}) };
+ if (value) locks[day] = value;
+ else delete locks[day];
+ const days = [...new Set([...(settings?.days ?? []), ...(value ? [day] : [])])].sort((a, b) => a - b);
+ return { days, locks };
+}
+
+/**
+ * Retire d'un réglage les jours imposés qui désignent une activité supprimée.
+ * @param {{days: number[], locks: Record}} settings
+ * @param {string} activityId
+ * @returns {{days: number[], locks: Record}|null} null si rien ne change
+ */
+export function withoutActivity(settings, activityId) {
+ const locks = Object.fromEntries(Object.entries(settings.locks).filter(([, l]) => l !== `activity:${activityId}`));
+ return Object.keys(locks).length === Object.keys(settings.locks).length ? null : { days: [...settings.days], locks };
+}
+
+/** Jour de la semaine d'une date. @param {string} date */
+export const dayName = (date) => DAY_NAMES[dayIndex(date)];
diff --git a/app/ui/labels.js b/app/ui/labels.js
index 36b7ab6..f88a673 100644
--- a/app/ui/labels.js
+++ b/app/ui/labels.js
@@ -10,11 +10,13 @@ export const TRACKING_LABELS = {
/**
* Ressenti d'une série. Glossaire : docs/glossaire/ressenti.md
- * @type {Record}
+ * `short` s'affiche sous les répétitions d'une série faite : le ressenti se lit
+ * en toutes lettres, jamais par la seule couleur.
+ * @type {Record}
*/
export const EFFORT_LABELS = {
- easy: { label: "Facile", hint: "3 répétitions ou plus en réserve" },
- ok: { label: "Correct", hint: "1 ou 2 répétitions en réserve" },
- hard: { label: "Dur", hint: "Rien en réserve" },
- failure: { label: "Échec", hint: "Série non terminée" },
+ easy: { label: "Facile", hint: "3 répétitions ou plus en réserve", short: "facile" },
+ ok: { label: "Correct", hint: "1 ou 2 répétitions en réserve", short: "ok" },
+ hard: { label: "Dur", hint: "Rien en réserve", short: "dur" },
+ failure: { label: "Échec", hint: "Série non terminée", short: "échec" },
};
diff --git a/app/ui/layout.js b/app/ui/layout.js
index 5c13edf..d6905f6 100644
--- a/app/ui/layout.js
+++ b/app/ui/layout.js
@@ -16,12 +16,12 @@ export function screenHeader({ kicker, title, sub, back }) {
}
/**
- * Titre de section.
+ * Titre de section : un ruban adhésif.
* @param {string} text
* @param {string} [hint]
*/
export function sectionLabel(text, hint) {
- return h("h2", { class: "section-label" }, text, hint && h("span", { class: "section-label__hint" }, hint));
+ return h("h2", { class: "tape" }, text, hint && h("span", { class: "tape__hint" }, hint));
}
/**
diff --git a/app/ui/onboarding.js b/app/ui/onboarding.js
index ce7da4d..b2bbc2b 100644
--- a/app/ui/onboarding.js
+++ b/app/ui/onboarding.js
@@ -1,11 +1,14 @@
// Premier lancement : pas de programme, pas de proposition en attente.
// But : un programme dans l'app en moins de deux minutes, construit avec l'IA
-// de l'utilisateur (ADR 0005, point 7 : le circuit par lien).
+// de l'utilisateur (ADR 0008 ; ADR 0005, point 7 : le circuit par lien).
import { h } from "./dom.js";
import { actionBar } from "./layout.js";
import { toast } from "./feedback.js";
-import { exampleProgram, onboardingBrief } from "./pending.js";
+import { copyText } from "./files.js";
+import { href } from "./router.js";
+import { buildOnboardingBrief } from "../domain/ai-brief.js";
+import { EXAMPLE_PROGRAM } from "../domain/example-program.js";
/** Consigne courte pour une IA qui sait lire une page web. */
export const AI_GUIDE_URL = "https://ia-fit.sans.pub/ia.md";
@@ -14,47 +17,21 @@ export const AI_GUIDE_URL = "https://ia-fit.sans.pub/ia.md";
* @param {{store: import("./store.js").Store}} o
*/
export function onboarding({ store }) {
- const status = h("p", { class: "status status--info", role: "status", "aria-live": "polite" });
+ const status = h("p", { class: "status status--ok", role: "status", "aria-live": "polite" });
const manual = h("div", { class: "manual-copy", hidden: true });
const copyBrief = async () => {
- const text = await onboardingBrief(location.origin);
- if (!text) {
- // À brancher : ai-brief.buildOnboardingBrief({baseUrl}) (autre sous-agent).
- status.textContent = "Le texte à donner à ton IA arrive bientôt. En attendant, dis-lui de lire " + AI_GUIDE_URL + ".";
- return;
- }
- try {
- await navigator.clipboard.writeText(text);
- status.textContent = "Copié. Colle-le maintenant dans ton IA.";
- toast("Texte copié.");
- } catch {
- // Presse-papiers refusé (http, navigateur ancien) : copie à la main.
- const area = h("textarea", { class: "field__input field__input--area", readonly: true, "aria-label": "Texte à copier dans ton IA" });
- area.value = text;
- manual.replaceChildren(h("p", { class: "muted" }, "Copie ce texte à la main :"), area);
- manual.hidden = false;
- area.select();
- status.textContent = "";
- }
+ const ok = await copyText(buildOnboardingBrief({ baseUrl: location.origin }), manual, "Texte à copier dans ton IA");
+ status.textContent = ok ? "Copié. Colle-le dans ton IA." : "";
+ if (ok) toast("Texte copié.");
};
- const startFromExample = async () => {
- const program = await exampleProgram();
- if (!program) {
- // À brancher : example-program.EXAMPLE_PROGRAM (autre sous-agent).
- toast("Le programme d'exemple arrive bientôt.");
- return;
- }
- try {
- store.dispatch("ProgramProposed", {
- program,
- source: /** @type {any} */ ("example"),
- reason: "Programme d'exemple : trois séances à domicile avec barre, haltères, banc et élastiques. Ton IA pourra l'adapter ensuite.",
- });
- } catch (e) {
- toast("Le programme d'exemple n'a pas pu être proposé : " + (e instanceof Error ? e.message : String(e)));
- }
+ const startFromExample = () => {
+ store.dispatch("ProgramProposed", {
+ program: structuredClone(EXAMPLE_PROGRAM),
+ source: "example",
+ reason: "Programme d'exemple : trois séances à domicile avec barre, haltères, banc et élastiques. Ton IA pourra l'adapter ensuite.",
+ });
};
const copyGuide = async () => {
@@ -67,32 +44,30 @@ export function onboarding({ store }) {
};
return h("div", { class: "onboarding" },
- h("header", { class: "screen-head hero" },
- h("p", { class: "kicker" }, "IA-Fit"),
- h("h1", { class: "title title--hero" }, "Ton programme, construit avec ton IA"),
- h("p", { class: "lede" }, "Puis suivi séance par séance : séries, charges, repos. Tes données restent sur ton appareil, sans compte.")),
+ h("header", { class: "screen-head" },
+ h("p", { class: "kicker" }, "IA-Fit · sans compte"),
+ h("h1", { class: "title title--hero" }, "Ton programme. Ton IA."),
+ h("p", { class: "lede" }, "Elle le construit, tu le suis ici, série par série. Tes données restent sur ton appareil.")),
- h("section", { class: "card card--onboarding", "aria-labelledby": "onb-how" },
- h("h2", { class: "card__title", id: "onb-how" }, "En trois gestes"),
+ h("section", { class: "block", "aria-labelledby": "onb-how" },
+ h("h2", { class: "h2", id: "onb-how" }, "Trois gestes"),
h("ol", { class: "how" },
- h("li", { class: "how__step" }, h("strong", null, "Copie le texte"), h("span", null, " et colle-le dans ton IA : Claude, ChatGPT, Le Chat…")),
- h("li", { class: "how__step" }, h("strong", null, "Réponds à ses questions"), h("span", null, ", ou montre-lui ton programme actuel : export d'une autre app, texte, captures d'écran.")),
- h("li", { class: "how__step" }, h("strong", null, "Touche le lien qu'elle te renvoie"), h("span", null, " : ton programme s'affiche ici, et tu le valides."))),
+ h("li", { class: "how__step" }, h("span", null, h("strong", null, "Copie le texte"), " et colle-le dans ton IA : Claude, ChatGPT, Le Chat…")),
+ h("li", { class: "how__step" }, h("span", null, h("strong", null, "Réponds à ses questions"), ", ou montre-lui ton programme actuel.")),
+ h("li", { class: "how__step" }, h("span", null, h("strong", null, "Touche le lien qu'elle renvoie."), " Ton programme s'affiche ici. Tu valides."))),
status,
manual,
- h("p", { class: "card__hint" }, "Ou, si ton IA sait lire une page web, dis-lui simplement :"),
+ h("p", { class: "muted" }, "Ton IA lit les pages web ? Dis-lui :"),
h("div", { class: "copy-line" },
h("code", { class: "copy-line__text" }, `lis ${AI_GUIDE_URL}`),
- h("button", { type: "button", class: "btn btn--sm btn--ghost", on: { click: copyGuide } }, "Copier")),
- h("p", { class: "card__hint" }, "Connecteur MCP pour ton IA : bientôt.")),
+ h("button", { type: "button", class: "btn btn--sm", on: { click: copyGuide } }, "Copier"))),
- h("section", { class: "alt", "aria-label": "Autres façons de commencer" },
- h("button", { type: "button", class: "btn btn--block", on: { click: startFromExample } }, "Partir d'un programme d'exemple"),
- // À brancher : import d'un instantané (snapshot.js, autre sous-agent).
- h("button", { type: "button", class: "btn btn--block btn--ghost", disabled: true, "aria-describedby": "onb-restore" }, "Restaurer une sauvegarde"),
- h("p", { class: "muted", id: "onb-restore" }, "Restaurer une sauvegarde : bientôt.")),
+ h("h2", { class: "tape" }, "Ou bien"),
+ h("div", { class: "btn-stack" },
+ h("button", { type: "button", class: "btn btn--block", on: { click: startFromExample } }, "Programme d'exemple"),
+ h("a", { class: "btn btn--block btn--ghost", href: href.data() }, "Restaurer une sauvegarde")),
- h("footer", { class: "foot" }, "Rien ne part sur un serveur : ce que tu colles dans ton IA, c'est toi qui le choisis."),
+ h("p", { class: "foot" }, "Rien ne part sur un serveur. Ce que tu colles dans ton IA, c'est toi qui le choisis."),
- actionBar(h("button", { type: "button", class: "btn btn--primary btn--block btn--lg", on: { click: copyBrief } }, "Créer mon programme avec mon IA")));
+ actionBar(h("button", { type: "button", class: "btn btn--primary btn--block btn--lg", on: { click: copyBrief } }, "Créer mon programme")));
}
diff --git a/app/ui/pending.js b/app/ui/pending.js
deleted file mode 100644
index b447603..0000000
--- a/app/ui/pending.js
+++ /dev/null
@@ -1,13 +0,0 @@
-// Modules du domaine utilisés par l'accueil.
-import { buildOnboardingBrief } from "../domain/ai-brief.js";
-import { EXAMPLE_PROGRAM } from "../domain/example-program.js";
-
-/** Le prompt d'onboarding à coller dans son IA. @param {string} baseUrl */
-export async function onboardingBrief(baseUrl) {
- return buildOnboardingBrief({ baseUrl });
-}
-
-/** Le programme d'exemple (celui d'Atelier). */
-export async function exampleProgram() {
- return structuredClone(EXAMPLE_PROGRAM);
-}
diff --git a/app/ui/program-diff.js b/app/ui/program-diff.js
new file mode 100644
index 0000000..2c46413
--- /dev/null
+++ b/app/ui/program-diff.js
@@ -0,0 +1,204 @@
+// Aperçu d'une proposition : ce qui change par rapport au programme courant
+// (ADR 0005, point 6). Module pur, testé (tests/ui/program-diff.test.js).
+//
+// Les séances se rapprochent par leur clé (« A »), les exercices d'une séance
+// par leur identifiant stable (la ref, sinon le nom ; un exercice présent deux
+// fois se rapproche dans l'ordre), les activités par leur id, le cardio et les
+// repères par leur nom.
+
+import { resolveExercise } from "../domain/program.js";
+
+/** @typedef {import("../domain/program.js").Program} Program */
+/** @typedef {import("../domain/program.js").ProgramSession} ProgramSession */
+/** @typedef {import("../domain/program.js").ProgramExercise} ProgramExercise */
+/** @typedef {import("../domain/profile.js").Profile} Profile */
+
+/** @typedef {"added"|"removed"|"changed"|"same"} Change */
+
+/**
+ * Une valeur qui change.
+ * @typedef {object} FieldChange
+ * @property {string} field
+ * @property {string} label
+ * @property {unknown} from
+ * @property {unknown} to
+ */
+
+/**
+ * @typedef {object} ExerciseDiff
+ * @property {Change} change
+ * @property {string} id
+ * @property {string} name
+ * @property {ProgramExercise} item l'exercice proposé (ou retiré)
+ * @property {FieldChange[]} fields
+ */
+
+/**
+ * @typedef {object} SessionDiff
+ * @property {Change} change
+ * @property {string} key
+ * @property {string} name
+ * @property {string|undefined} color
+ * @property {FieldChange[]} fields
+ * @property {ExerciseDiff[]} exercises
+ */
+
+/**
+ * @typedef {object} ItemDiff
+ * @property {Change} change
+ * @property {string} name
+ * @property {FieldChange[]} fields
+ */
+
+/**
+ * @typedef {object} ProgramDiff
+ * @property {boolean} isNew pas de programme courant
+ * @property {FieldChange|null} name
+ * @property {SessionDiff[]} sessions dans l'ordre proposé, puis les séances retirées
+ * @property {ItemDiff[]} activities
+ * @property {ItemDiff[]} cardio
+ * @property {ItemDiff[]} rules
+ * @property {{added: number, removed: number, changed: number}} counts séances et exercices
+ * @property {boolean} identical
+ */
+
+/** Champs comparés d'un exercice. */
+const EXERCISE_FIELDS = /** @type {const} */ ([
+ ["sets", "séries"], ["reps", "répétitions"], ["rest", "repos"], ["group", "superset"],
+ ["tracking", "suivi"], ["note", "note du coach"], ["name", "nom"],
+]);
+
+/** @param {unknown} a @param {unknown} b */
+const same = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
+
+/**
+ * @param {Record} from
+ * @param {Record} to
+ * @param {readonly (readonly [string, string])[]} fields
+ * @returns {FieldChange[]}
+ */
+function compareFields(from, to, fields) {
+ return fields
+ .filter(([f]) => !same(from[f], to[f]))
+ .map(([field, label]) => ({ field, label, from: from[field] ?? null, to: to[field] ?? null }));
+}
+
+/**
+ * Rapproche deux listes par une clé ; à clé égale, dans l'ordre.
+ * @template T
+ * @param {T[]} before
+ * @param {T[]} after
+ * @param {(x: T) => string} keyOf
+ * @returns {{before: T|null, after: T|null}[]} dans l'ordre de `after`, puis les retirés
+ */
+function pair(before, after, keyOf) {
+ /** @type {Map} */
+ const pool = new Map();
+ for (const x of before) pool.set(keyOf(x), [...(pool.get(keyOf(x)) ?? []), x]);
+ /** @type {{before: T|null, after: T|null}[]} */
+ const out = after.map((x) => {
+ const list = pool.get(keyOf(x));
+ return { before: list?.shift() ?? null, after: x };
+ });
+ for (const list of pool.values()) for (const x of list) out.push({ before: x, after: null });
+ return out;
+}
+
+/** @param {{before: unknown, after: unknown}} p @param {boolean} changed @returns {Change} */
+const changeOf = (p, changed) => (!p.before ? "added" : !p.after ? "removed" : changed ? "changed" : "same");
+
+/**
+ * @param {ProgramSession|null} before
+ * @param {ProgramSession|null} after
+ * @returns {SessionDiff}
+ */
+function diffSession(before, after) {
+ const s = /** @type {ProgramSession} */ (after ?? before);
+ const exercises = pair(before?.exercises ?? [], after?.exercises ?? [], (x) => resolveExercise(x).id).map((p) => {
+ const item = /** @type {ProgramExercise} */ (p.after ?? p.before);
+ const fields = p.before && p.after ? compareFields(p.before, p.after, EXERCISE_FIELDS) : [];
+ return { change: changeOf(p, fields.length > 0), id: resolveExercise(item).id, name: resolveExercise(item).name, item, fields };
+ });
+ const fields = before && after ? compareFields(before, after, [["name", "nom"], ["subtitle", "sous-titre"]]) : [];
+ const moved = before && after && !same(before.exercises.map((x) => resolveExercise(x).id), after.exercises.map((x) => resolveExercise(x).id));
+ if (moved && exercises.every((x) => x.change !== "added" && x.change !== "removed"))
+ fields.push({ field: "order", label: "ordre des exercices", from: null, to: null });
+ const changed = fields.length > 0 || exercises.some((x) => x.change !== "same");
+ return { change: changeOf({ before, after }, changed), key: s.key, name: s.name, color: s.color, fields, exercises };
+}
+
+/**
+ * @template T
+ * @param {T[]} before
+ * @param {T[]} after
+ * @param {(x: T) => string} keyOf
+ * @param {(x: T) => string} nameOf
+ * @param {readonly (readonly [string, string])[]} fields
+ * @returns {ItemDiff[]}
+ */
+function diffItems(before, after, keyOf, nameOf, fields) {
+ return pair(before, after, keyOf).map((p) => {
+ const f = p.before && p.after ? compareFields(/** @type {any} */ (p.before), /** @type {any} */ (p.after), fields) : [];
+ return { change: changeOf(p, f.length > 0), name: nameOf(/** @type {T} */ (p.after ?? p.before)), fields: f };
+ });
+}
+
+/**
+ * Différence entre le programme courant (ou rien) et un programme proposé.
+ * @param {Program|null} current
+ * @param {Program} proposed
+ * @returns {ProgramDiff}
+ */
+export function diffProgram(current, proposed) {
+ const sessions = pair(current?.sessions ?? [], proposed.sessions, (s) => s.key).map((p) => diffSession(p.before, p.after));
+ const activities = diffItems(current?.activities ?? [], proposed.activities ?? [], (a) => a.id, (a) => a.name,
+ [["name", "nom"], ["zones", "zones"], ["intensity", "intensité"], ["minutes", "durée"]]);
+ const cardio = diffItems(current?.cardio ?? [], proposed.cardio ?? [], (c) => c.name, (c) => c.name,
+ [["inPlan", "au planning"], ["text", "consigne"]]);
+ const rules = diffItems(current?.rules ?? [], proposed.rules ?? [], (r) => r.name, (r) => r.name, [["text", "texte"]]);
+ const counts = { added: 0, removed: 0, changed: 0 };
+ for (const s of sessions) {
+ if (s.change === "added" || s.change === "removed") counts[s.change]++;
+ else for (const x of s.exercises) if (x.change !== "same") counts[x.change]++;
+ if (s.change === "changed" && s.fields.length) counts.changed++;
+ }
+ const name = current && current.name !== proposed.name ? { field: "name", label: "nom", from: current.name, to: proposed.name } : null;
+ const identical = !!current && !name && [...sessions, ...activities, ...cardio, ...rules].every((x) => x.change === "same")
+ && same(current.subtitle, proposed.subtitle);
+ return { isNew: !current, name, sessions, activities, cardio, rules, counts, identical };
+}
+
+/** Champs du profil, dans l'ordre d'affichage. */
+export const PROFILE_FIELDS = /** @type {const} */ ([
+ ["goal", "Objectif"], ["context", "Contexte"], ["equipment", "Matériel"], ["constraints", "Contraintes"],
+ ["heightCm", "Taille (cm)"], ["sessionMinutes", "Durée d'une séance (min)"],
+]);
+
+/**
+ * @typedef {object} ProfileChange
+ * @property {string} field
+ * @property {string} label
+ * @property {unknown} from
+ * @property {unknown} to
+ * @property {string[]} [added] pour une liste
+ * @property {string[]} [removed]
+ */
+
+/**
+ * Ce qui change dans le profil.
+ * @param {Profile} current
+ * @param {Profile} proposed
+ * @returns {ProfileChange[]}
+ */
+export function diffProfile(current, proposed) {
+ /** @type {ProfileChange[]} */
+ const out = [];
+ for (const [field, label] of PROFILE_FIELDS) {
+ const from = current[field], to = proposed[field];
+ if (same(from, to)) continue;
+ if (Array.isArray(from) && Array.isArray(to))
+ out.push({ field, label, from, to, added: to.filter((x) => !from.includes(x)), removed: from.filter((x) => !to.includes(x)) });
+ else out.push({ field, label, from, to });
+ }
+ return out;
+}
diff --git a/app/ui/proposal-card.js b/app/ui/proposal-card.js
index c22df95..0d9402c 100644
--- a/app/ui/proposal-card.js
+++ b/app/ui/proposal-card.js
@@ -1,55 +1,203 @@
-// Une proposition de programme en attente : un aperçu simple, « Adopter » ou
-// « Refuser ». Glossaire : docs/glossaire/proposition.md
-//
-// À brancher (sous-lot 1e) : l'écran de proposition avec l'aperçu détaillé des
-// changements (exercices ajoutés, retirés, modifiés). Ce rendu provisoire montre
-// le programme proposé tel quel.
+// Une proposition de programme : raison, source, aperçu de ce qui change par
+// rapport au programme courant, puis « Adopter » ou « Refuser ».
+// Glossaire : docs/glossaire/proposition.md
-import { h } from "./dom.js";
-import { plural } from "./format.js";
-import { resolveExercise } from "../domain/program.js";
+import { append, h, setAccent } from "./dom.js";
+import { inkOn, sessionColor } from "./color.js";
+import { mediumDay, plural, restLabel } from "./format.js";
+import { TRACKING_LABELS } from "./labels.js";
+import { diffProfile, diffProgram } from "./program-diff.js";
import { toast } from "./feedback.js";
+import { href } from "./router.js";
+import { INTENSITY_LABELS, ZONE_LABELS } from "./home-model.js";
/** @type {Record} */
-const SOURCE_LABELS = {
+export const SOURCE_LABELS = {
ai: "Proposé par ton IA",
link: "Reçu par un lien",
- import: "Venu d'une sauvegarde",
+ import: "Venu d'un fichier importé",
atelier: "Repris d'Atelier",
example: "Programme d'exemple",
- default: "Programme de départ",
app: "Modifié dans l'app",
};
/**
- * @param {{proposal: import("../domain/state.js").Proposal, store: import("./store.js").Store}} o
+ * Ce qu'est devenue une proposition, d'après le journal : son id est stable
+ * (tiré de son contenu), rouvrir le même lien retrouve donc la même.
+ * @param {readonly import("../domain/events.js").DomainEvent[]} events
+ * @param {string} id
+ * @returns {{event: Extract|null, outcome: "pending"|"adopted"|"rejected", at: string|null}}
*/
-export function proposalCard({ proposal, store }) {
- const p = proposal.program;
- // Le profil proposé est facultatif (onboarding par l'IA) : adopté avec le programme.
- const profile = /** @type {any} */ (proposal).profile;
+export function proposalOutcome(events, id) {
+ const event = /** @type {any} */ (events.find((e) => e.id === id && e.type === "ProgramProposed") ?? null);
+ for (const e of events) {
+ if (e.type === "ProgramAdopted" && e.data.proposalId === id) return { event, outcome: "adopted", at: e.at };
+ if (e.type === "ProposalRejected" && e.data.proposalId === id) return { event, outcome: "rejected", at: e.at };
+ }
+ return { event, outcome: "pending", at: null };
+}
+/**
+ * Une valeur lisible dans l'aperçu.
+ * @param {string} field
+ * @param {unknown} v
+ */
+function show(field, v) {
+ if (v === null || v === undefined || v === "") return "—";
+ if (field === "rest" && typeof v === "number") return restLabel(v);
+ if (field === "tracking") return TRACKING_LABELS[/** @type {keyof TRACKING_LABELS} */ (v)] ?? String(v);
+ if (field === "zones" && Array.isArray(v)) return v.map((z) => ZONE_LABELS[z] ?? z).join(", ");
+ if (field === "intensity") return INTENSITY_LABELS[String(v)] ?? String(v);
+ if (field === "minutes") return `${v} min`;
+ if (field === "inPlan") return v ? "oui" : "non";
+ if (Array.isArray(v)) return v.join(", ");
+ return String(v);
+}
+
+/** @param {import("./program-diff.js").FieldChange} f */
+const fieldLine = (f) => f.field === "order"
+ ? h("li", { data: { change: "changed" } }, "Ordre des exercices revu")
+ : h("li", { data: { change: "changed" } }, `${f.label} : `, h("del", null, show(f.field, f.from)), " → ", h("ins", null, show(f.field, f.to)));
+
+/** @param {import("../domain/program.js").ProgramExercise} x */
+const target = (x) => `${x.sets} × ${x.reps}, repos ${restLabel(x.rest)}`;
+
+/** @type {Record} */
+const CHANGE_WORD = { added: "Nouvelle", removed: "Retirée", changed: "Modifiée", same: "Inchangée" };
+
+/**
+ * L'aperçu des changements.
+ * @param {import("../domain/program.js").Program|null} current
+ * @param {import("../domain/program.js").Program} proposed
+ * @param {import("../domain/profile.js").Profile} currentProfile
+ * @param {import("../domain/profile.js").Profile|null} proposedProfile
+ */
+export function diffView(current, proposed, currentProfile, proposedProfile) {
+ const d = diffProgram(current, proposed);
+ const profile = proposedProfile ? diffProfile(currentProfile, proposedProfile) : [];
+ const summary = d.isNew
+ ? `${plural(proposed.sessions.length, "séance")}, ${plural(proposed.sessions.reduce((n, s) => n + s.exercises.length, 0), "exercice")}.`
+ : d.identical ? "Identique à ton programme actuel."
+ : [d.counts.added && `${d.counts.added} ajout${d.counts.added > 1 ? "s" : ""}`,
+ d.counts.removed && `${d.counts.removed} retrait${d.counts.removed > 1 ? "s" : ""}`,
+ d.counts.changed && `${d.counts.changed} modification${d.counts.changed > 1 ? "s" : ""}`].filter(Boolean).join(" · ") || "Petits changements.";
+
+ const sessions = d.sessions.map((s) => {
+ const plaque = h("span", { class: "plaque plaque--sm", "aria-hidden": "true" }, s.key);
+ const color = sessionColor(s.color);
+ setAccent(plaque, color, inkOn(color));
+ const lines = s.change === "same" ? [] : [
+ ...s.fields.map(fieldLine),
+ ...s.exercises.filter((x) => d.isNew || s.change !== "changed" || x.change !== "same").map((x) => {
+ if (d.isNew || s.change === "added") return h("li", { data: { change: "added" } }, `${x.name} · ${target(x.item)}`);
+ if (x.change === "added") return h("li", { data: { change: "added" } }, `${x.name} · ${target(x.item)}`);
+ if (x.change === "removed") return h("li", { data: { change: "removed" } }, x.name);
+ return h("li", { data: { change: "changed" } }, x.name, " · ",
+ x.fields.map((f, i) => [i ? ", " : "", `${f.label} `, h("del", null, show(f.field, f.from)), " → ", h("ins", null, show(f.field, f.to))]));
+ }),
+ ];
+ return h("li", { class: "diff__item" },
+ h("div", { class: "diff__head" }, plaque,
+ h("span", { class: "diff__what" }, `Séance ${s.key} · ${s.name}`),
+ !d.isNew && h("span", { class: "mark" }, CHANGE_WORD[s.change])),
+ lines.length > 0 && h("ul", { class: "diff__lines" }, lines));
+ });
+
+ /** @param {string} title @param {import("./program-diff.js").ItemDiff[]} items */
+ const others = (title, items) => {
+ const changed = items.filter((x) => d.isNew || x.change !== "same");
+ if (!changed.length) return null;
+ return h("li", { class: "diff__item" },
+ h("div", { class: "diff__head" }, h("span", { class: "diff__what" }, title)),
+ h("ul", { class: "diff__lines" }, changed.map((x) => x.change === "changed"
+ ? h("li", { data: { change: "changed" } }, x.name, " · ", x.fields.map((f, i) => [i ? ", " : "", `${f.label} `, h("del", null, show(f.field, f.from)), " → ", h("ins", null, show(f.field, f.to))]))
+ : h("li", { data: { change: d.isNew ? "added" : x.change } }, x.name))));
+ };
+
+ return h("div", { class: "proposal-diff" },
+ h("p", { class: "mark" }, d.isNew ? "Nouveau programme · " : "Par rapport à ton programme · ", summary),
+ h("ul", { class: "diff" },
+ d.name && h("li", { class: "diff__item" }, h("ul", { class: "diff__lines" }, fieldLine(d.name))),
+ sessions,
+ others("Activités", d.activities),
+ others("Cardio", d.cardio),
+ others("Repères", d.rules),
+ profile.length > 0 && h("li", { class: "diff__item" },
+ h("div", { class: "diff__head" }, h("span", { class: "diff__what" }, "Ton profil")),
+ h("ul", { class: "diff__lines" }, profile.map((p) => p.added
+ ? [...p.added.map((x) => h("li", { data: { change: "added" } }, `${p.label} : ${x}`)),
+ ...(p.removed ?? []).map((x) => h("li", { data: { change: "removed" } }, `${p.label} : ${x}`))]
+ : h("li", { data: { change: "changed" } }, `${p.label} : `, h("del", null, show(p.field, p.from)), " → ", h("ins", null, show(p.field, p.to))))))));
+}
+
+/**
+ * Une proposition en attente, avec ses deux actions.
+ * @param {{proposal: import("../domain/state.js").Proposal, store: import("./store.js").Store, nav?: import("./router.js").Navigation, headingLevel?: "h1"|"h2"}} o
+ */
+export function proposalCard({ proposal, store, nav, headingLevel = "h2" }) {
+ const state = store.getState();
+ const p = proposal.program;
const adopt = () => {
store.dispatch("ProgramAdopted", { program: p, source: proposal.source, proposalId: proposal.id, ...(proposal.reason ? { reason: proposal.reason } : {}) });
- if (profile) store.dispatch("ProfileUpdated", { profile });
+ if (proposal.profile) store.dispatch("ProfileUpdated", { profile: proposal.profile });
toast(`Programme « ${p.name} » adopté.`);
+ nav?.go(href.home(), { replace: true });
};
const reject = () => {
store.dispatch("ProposalRejected", { proposalId: proposal.id });
toast("Proposition refusée.");
+ nav?.go(href.home(), { replace: true });
};
-
- return h("section", { class: "card card--proposal", "aria-labelledby": `prop-${proposal.id}` },
- h("p", { class: "kicker" }, "À valider · ", SOURCE_LABELS[proposal.source] ?? proposal.source),
- h("h2", { class: "card__title", id: `prop-${proposal.id}` }, p.name),
- p.subtitle && h("p", { class: "card__text" }, p.subtitle),
+ const id = `prop-${proposal.id}`;
+ return h("section", { class: "block block--today proposal", "aria-labelledby": id },
+ h("p", { class: "kicker" }, "À valider · ", SOURCE_LABELS[proposal.source] ?? proposal.source, " · ", mediumDay(proposal.at.slice(0, 10))),
+ h(headingLevel, { class: headingLevel === "h1" ? "title" : "block__title", id }, p.name),
+ p.subtitle && h("p", null, p.subtitle),
proposal.reason && h("p", { class: "coach-note" }, proposal.reason),
- h("ul", { class: "preview" }, p.sessions.map((s) =>
- h("li", { class: "preview__session" },
- h("strong", null, `Séance ${s.key} · ${s.name}`),
- h("span", { class: "muted" }, `${plural(s.exercises.length, "exercice")} : ${s.exercises.map((x) => resolveExercise(x).name).join(", ")}`)))),
- profile && h("p", { class: "muted" }, "Ton profil (objectif, matériel, contraintes) sera aussi mis à jour."),
- h("div", { class: "card__actions" },
- h("button", { type: "button", class: "btn btn--primary btn--block btn--lg", on: { click: adopt } }, "Adopter ce programme"),
+ diffView(state.program, p, state.profile, proposal.profile),
+ h("div", { class: "btn-stack" },
+ h("button", { type: "button", class: "btn btn--primary btn--block btn--lg", on: { click: adopt } }, "Adopter"),
h("button", { type: "button", class: "btn btn--ghost btn--block", on: { click: reject } }, "Refuser")));
}
+
+/**
+ * L'écran d'une proposition, retrouvée par son id (lien rouvert, accueil).
+ * @param {{store: import("./store.js").Store, nav: import("./router.js").Navigation, id: string}} ctx
+ * @returns {import("./router.js").Screen}
+ */
+export function proposalScreen({ store, nav, id }) {
+ const node = h("div", { class: "screen" });
+ const back = h("button", { type: "button", class: "back", on: { click: () => nav.back(href.home()) } }, "← Accueil");
+ const pending = store.getState().proposals.find((x) => x.id === id);
+ if (pending) {
+ node.append(h("header", { class: "screen-head" }, back, h("p", { class: "kicker" }, "Proposition"), h("h1", { class: "title" }, "À valider")),
+ proposalCard({ proposal: pending, store, nav }));
+ return { node, title: "Proposition" };
+ }
+ const { event, outcome, at } = proposalOutcome(store.getEvents(), id);
+ if (!event) {
+ node.append(h("header", { class: "screen-head" }, back, h("h1", { class: "title" }, "Proposition introuvable")),
+ h("p", { class: "empty" }, "Elle n'est pas dans ton journal."));
+ return { node, title: "Proposition introuvable" };
+ }
+ const state = store.getState();
+ const reopen = () => {
+ const fresh = store.dispatch("ProgramProposed", { ...event.data });
+ nav.go(href.proposal(fresh.id), { replace: true });
+ };
+ append(node, [
+ h("header", { class: "screen-head" }, back,
+ h("p", { class: "kicker" }, SOURCE_LABELS[event.data.source] ?? event.data.source),
+ h("h1", { class: "title" }, outcome === "adopted" ? "Déjà adoptée" : "Déjà refusée")),
+ h("p", { class: "coach-note coach-note--plain" },
+ outcome === "adopted"
+ ? `Tu as adopté cette proposition le ${mediumDay(/** @type {string} */ (at).slice(0, 10))}. Ce lien ne change plus rien.`
+ : `Tu as refusé cette proposition le ${mediumDay(/** @type {string} */ (at).slice(0, 10))}. Le lien est le même : c'est la même proposition.`),
+ h("section", { class: "block" },
+ h("h2", { class: "block__title" }, event.data.program.name),
+ event.data.reason && h("p", { class: "coach-note" }, event.data.reason),
+ diffView(state.program, event.data.program, state.profile, event.data.profile ?? null)),
+ outcome === "rejected" && h("div", { class: "action-bar" }, h("div", { class: "action-bar__in" },
+ h("button", { type: "button", class: "btn btn--primary btn--block btn--lg", on: { click: reopen } }, "La réexaminer")))]);
+ return { node, title: "Proposition" };
+}
diff --git a/app/ui/router.js b/app/ui/router.js
index 264cbfc..0ebd07b 100644
--- a/app/ui/router.js
+++ b/app/ui/router.js
@@ -3,13 +3,22 @@
//
// 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. À brancher : link.js (#import=), appariement (#pair=).
+// les réécrit pas : main.js lit #import= (link.js) ; #pair= attend le lot 2.
/**
* @typedef {{name: "home"}
- * | {name: "session", key: string}
+ * | {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
*/
@@ -29,18 +38,40 @@ export function parseRoute(hash) {
const parts = path.split("/").map((p) => {
try { return decodeURIComponent(p); } catch { return p; }
});
- if (parts[0] === "seance" && parts.length === 2 && parts[1]) return { name: "session", key: parts[1] };
- if (parts[0] === "historique" && parts.length === 1) return { name: "history" };
- if (parts[0] === "historique" && parts.length === 2 && parts[1]) return { name: "history-edit", id: parts[1] };
+ 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} */
+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) => "#/seance/" + encodeURIComponent(key),
+ 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/" + encodeURIComponent(id),
+ 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),
};
/**
diff --git a/app/ui/screens/activities.js b/app/ui/screens/activities.js
new file mode 100644
index 0000000..92c2bf1
--- /dev/null
+++ b/app/ui/screens/activities.js
@@ -0,0 +1,188 @@
+// Activités : sports en dehors du programme (foot, escalade…), avec leurs zones
+// sollicitées, leur intensité et leur durée. Elles font partie du programme :
+// les modifier adopte une nouvelle version du programme (ProgramAdopted, source
+// « app »), qui garde tout le reste à l'identique.
+
+import { h, paintWhenIdle, replace } from "../dom.js";
+import { ZONES, INTENSITIES } from "../../domain/vocabulary.js";
+import { mondayOf } from "../../domain/dates.js";
+import { INTENSITY_LABELS, ZONE_LABELS, withoutActivity } from "../home-model.js";
+import { screenHeader } from "../layout.js";
+import { href } from "../router.js";
+import { confirmDialog, toast } from "../feedback.js";
+
+/** @typedef {import("../../domain/program.js").Activity} Activity */
+/** @typedef {import("../../domain/program.js").Program} Program */
+
+/**
+ * Identifiant d'une activité tiré de son nom : minuscules, chiffres et tirets.
+ * @param {string} name
+ * @param {string[]} taken
+ */
+export function activityId(name, taken) {
+ const base = name.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 28) || "activite";
+ let id = base, n = 2;
+ while (taken.includes(id)) id = `${base}-${n++}`;
+ return id;
+}
+
+/**
+ * Le programme avec une activité ajoutée, remplacée ou retirée. Les autres
+ * champs du programme sont gardés tels quels.
+ * @param {Program} program
+ * @param {{id: string, activity: Activity|null}} change activity null : retrait
+ * @returns {Program}
+ */
+export function withActivity(program, { id, activity }) {
+ const list = program.activities ?? [];
+ const next = activity
+ ? (list.some((a) => a.id === id) ? list.map((a) => (a.id === id ? activity : a)) : [...list, activity])
+ : list.filter((a) => a.id !== id);
+ return { ...structuredClone(program), activities: structuredClone(next) };
+}
+
+/**
+ * @param {{store: import("../store.js").Store, nav: import("../router.js").Navigation, today: () => string}} ctx
+ * @returns {import("../router.js").Screen}
+ */
+export function activitiesScreen({ store, nav, today }) {
+ const list = h("div");
+ const back = { label: "Accueil", onClick: () => nav.back(href.home()) };
+ if (!store.getState().program) {
+ return {
+ title: "Activités",
+ node: h("div", { class: "screen" }, screenHeader({ back, title: "Activités" }),
+ h("p", { class: "empty" }, "Adopte d'abord un programme : les activités en font partie.")),
+ };
+ }
+
+ // ---- formulaire (jamais reconstruit pendant la saisie) ----------------------
+ /** @type {string|null} */
+ let editing = null;
+ const zones = new Set(["cardio"]);
+ let intensity = "moderate";
+ const formTitle = h("h2", { class: "tape" }, "Ajouter");
+ const name = h("input", { id: "act-name", class: "field__input", type: "text", autocomplete: "off", maxlength: "40" });
+ const minutes = h("input", { id: "act-min", class: "field__input", type: "text", inputmode: "numeric", value: "90" });
+ const status = h("p", { class: "status", role: "status", "aria-live": "polite" });
+ const zoneBtns = ZONES.map((z) => h("button", { type: "button", class: "segmented__opt", "aria-pressed": "false", data: { zone: z } }, ZONE_LABELS[z]));
+ const intBtns = INTENSITIES.map((i) => h("button", { type: "button", class: "segmented__opt", "aria-pressed": "false", data: { intensity: i } }, INTENSITY_LABELS[i]));
+ const paintChoices = () => {
+ zoneBtns.forEach((b) => b.setAttribute("aria-pressed", String(zones.has(/** @type {string} */ (b.dataset.zone)))));
+ intBtns.forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.intensity === intensity)));
+ };
+ zoneBtns.forEach((b) => b.addEventListener("click", () => {
+ const z = /** @type {string} */ (b.dataset.zone);
+ if (zones.has(z)) zones.delete(z); else zones.add(z);
+ paintChoices();
+ }));
+ intBtns.forEach((b) => b.addEventListener("click", () => { intensity = /** @type {string} */ (b.dataset.intensity); paintChoices(); }));
+ const cancel = h("button", { type: "button", class: "btn btn--ghost btn--block", hidden: true }, "Annuler la modification");
+
+ const reset = () => {
+ editing = null;
+ zones.clear();
+ zones.add("cardio");
+ intensity = "moderate";
+ name.value = "";
+ minutes.value = "90";
+ formTitle.textContent = "Ajouter";
+ cancel.hidden = true;
+ paintChoices();
+ };
+ cancel.addEventListener("click", reset);
+
+ /** @param {Activity} a */
+ const load = (a) => {
+ editing = a.id;
+ zones.clear();
+ a.zones.forEach((z) => zones.add(z));
+ intensity = a.intensity;
+ name.value = a.name;
+ minutes.value = String(a.minutes);
+ formTitle.textContent = `Modifier · ${a.name}`;
+ cancel.hidden = false;
+ paintChoices();
+ name.focus();
+ };
+
+ const submit = () => {
+ const program = /** @type {Program} */ (store.getState().program);
+ const label = name.value.trim();
+ const min = Math.round(Number(minutes.value.replace(",", ".")));
+ status.className = "status status--err";
+ if (!label) { status.textContent = "Donne un nom à l'activité."; return; }
+ if (!zones.size) { status.textContent = "Choisis au moins une zone."; return; }
+ if (!(min >= 5 && min <= 600)) { status.textContent = "Durée : de 5 à 600 minutes."; return; }
+ const ids = (program.activities ?? []).map((a) => a.id);
+ const old = editing ? program.activities?.find((a) => a.id === editing) : null;
+ const id = editing ?? activityId(label, ids);
+ /** @type {Activity} */
+ const activity = { ...(old ?? {}), id, name: label, zones: /** @type {any} */ ([...zones]), intensity: /** @type {any} */ (intensity), minutes: min };
+ try {
+ store.dispatch("ProgramAdopted", { program: withActivity(program, { id, activity }), source: "app", reason: `${editing ? "Activité modifiée" : "Activité ajoutée"} : ${label}` });
+ } catch (e) {
+ status.textContent = e instanceof Error ? e.message : String(e);
+ return;
+ }
+ status.className = "status status--ok";
+ status.textContent = editing ? `« ${label} » mise à jour.` : `« ${label} » ajoutée. Place-la dans ta semaine.`;
+ reset();
+ };
+
+ /** @param {Activity} a */
+ const remove = async (a) => {
+ const ok = await confirmDialog({
+ title: `Supprimer « ${a.name} » ?`, lines: ["Les jours qui lui étaient réservés redeviennent automatiques. L'historique reste."],
+ confirm: "Supprimer", cancel: "Garder", danger: true,
+ });
+ if (!ok) return;
+ const state = store.getState();
+ store.dispatch("ProgramAdopted", { program: withActivity(/** @type {Program} */ (state.program), { id: a.id, activity: null }), source: "app", reason: `Activité retirée : ${a.name}` });
+ // Les jours imposés qui la désignaient tombent : réglage par défaut et semaines à venir.
+ const monday = mondayOf(today());
+ if (state.planSettings) {
+ const next = withoutActivity(state.planSettings, a.id);
+ if (next) store.dispatch("PlanSettingsChanged", { week: null, ...next });
+ }
+ for (const [week, settings] of Object.entries(state.weekPlanSettings)) {
+ if (week < monday) continue;
+ const next = withoutActivity(settings, a.id);
+ if (next) store.dispatch("PlanSettingsChanged", { week, ...next });
+ }
+ if (editing === a.id) reset();
+ toast(`« ${a.name} » supprimée.`);
+ };
+
+ const paint = () => {
+ const activities = store.getState().program?.activities ?? [];
+ replace(list, activities.length
+ ? h("ul", { class: "rows" }, activities.map((a) => h("li", { class: "row" },
+ h("span", { class: "row__main" },
+ h("span", { class: "row__title" }, a.name),
+ h("span", { class: "row__meta" }, `${a.zones.map((z) => ZONE_LABELS[z]).join(", ")} · ${INTENSITY_LABELS[a.intensity].toLowerCase()} · ${a.minutes} min`)),
+ h("span", { class: "row__actions" },
+ h("button", { type: "button", class: "btn btn--sm", "aria-label": `Modifier ${a.name}`, on: { click: () => load(a) } }, "Modifier"),
+ h("button", { type: "button", class: "btn btn--sm btn--ghost", "aria-label": `Supprimer ${a.name}`, on: { click: () => void remove(a) } }, "✕")))))
+ : h("p", { class: "empty" }, "Aucune activité. Ajoute-la ci-dessous, puis place-la dans ta semaine."));
+ };
+ paint();
+ paintChoices();
+
+ const node = h("div", { class: "screen" },
+ screenHeader({ back, kicker: "Hors programme", title: "Activités", sub: "Foot, escalade, vélo… Le planning en tient compte : une activité cardio remplace une sortie, une activité intense éloigne la séance qui travaille les mêmes zones." }),
+ list,
+ formTitle,
+ h("div", { class: "field" }, h("label", { class: "field__label", for: "act-name" }, "Nom"), name),
+ h("p", { class: "field__label", id: "act-zones" }, "Zones sollicitées"),
+ h("div", { class: "segmented", role: "group", "aria-labelledby": "act-zones" }, zoneBtns),
+ h("p", { class: "field__label act-gap", id: "act-int" }, "Intensité"),
+ h("div", { class: "segmented", role: "group", "aria-labelledby": "act-int" }, intBtns),
+ h("div", { class: "field act-gap" }, h("label", { class: "field__label", for: "act-min" }, "Durée (minutes)"), minutes),
+ status,
+ h("div", { class: "btn-stack" },
+ h("button", { type: "button", class: "btn btn--primary btn--block", on: { click: submit } }, "Enregistrer l'activité"),
+ cancel));
+ return { node, title: "Activités", destroy: store.subscribe(paintWhenIdle(list, paint)) };
+}
diff --git a/app/ui/screens/analysis.js b/app/ui/screens/analysis.js
new file mode 100644
index 0000000..97762d2
--- /dev/null
+++ b/app/ui/screens/analysis.js
@@ -0,0 +1,114 @@
+// Analyses simples (ADR 0006, point 6) : assiduité des douze dernières
+// semaines, et pour chaque exercice la courbe de la charge et des répétitions.
+// Calculs du domaine : analysis.js.
+
+import { h } from "../dom.js";
+import { addDays, daysBetween, mondayOf } from "../../domain/dates.js";
+import { attendance, exerciseHistory } from "../../domain/analysis.js";
+import { dec1, kg, mediumDay, plural, shortDay } from "../format.js";
+import { screenHeader } from "../layout.js";
+import { href } from "../router.js";
+import { barChart, lineChart } from "../chart.js";
+import { EFFORT_LABELS } from "../labels.js";
+
+/** Semaines affichées dans l'assiduité. */
+export const ATTENDANCE_WEEKS = 12;
+
+/**
+ * Les exercices faits au moins une fois, du plus récent au plus ancien.
+ * @param {import("../../domain/state.js").State} state
+ * @returns {{id: string, name: string, count: number, last: string}[]}
+ */
+export function exercisesDone(state) {
+ /** @type {Map} */
+ const map = new Map();
+ for (const s of state.sessions) {
+ if (s.kind !== "strength") continue;
+ for (const x of s.exercises) {
+ if (!x.sets.length) continue;
+ const cur = map.get(x.id) ?? { id: x.id, name: x.name, count: 0, last: s.date };
+ cur.count++;
+ if (s.date >= cur.last) { cur.last = s.date; cur.name = x.name; }
+ map.set(x.id, cur);
+ }
+ }
+ return [...map.values()].sort((a, b) => (a.last < b.last ? 1 : a.last > b.last ? -1 : a.name.localeCompare(b.name)));
+}
+
+/**
+ * @param {{store: import("../store.js").Store, nav: import("../router.js").Navigation, today: () => string, exercise: string|null}} ctx
+ * @returns {import("../router.js").Screen}
+ */
+export function analysisScreen({ store, nav, today, exercise }) {
+ return exercise ? exerciseScreen({ store, nav, exercise }) : overview({ store, nav, today });
+}
+
+/** @param {{store: import("../store.js").Store, nav: import("../router.js").Navigation, today: () => string}} ctx */
+function overview({ store, nav, today }) {
+ const state = store.getState();
+ const to = today();
+ const from = addDays(mondayOf(to), -7 * (ATTENDANCE_WEEKS - 1));
+ const { weeks, totals } = attendance(state, from, to);
+ const list = exercisesDone(state);
+ const node = h("div", { class: "screen" },
+ screenHeader({ back: { label: "Accueil", onClick: () => nav.back(href.home()) }, kicker: "Ton parcours", title: "Analyses" }),
+ h("h2", { class: "tape" }, "Assiduité", h("span", { class: "tape__hint" }, `${ATTENDANCE_WEEKS} semaines`)),
+ h("div", { class: "stats" },
+ h("div", { class: "stat" }, h("span", { class: "stat__value" }, String(totals.strength)), h("span", { class: "stat__label" }, "force")),
+ h("div", { class: "stat" }, h("span", { class: "stat__value" }, String(totals.cardio)), h("span", { class: "stat__label" }, "cardio")),
+ h("div", { class: "stat" }, h("span", { class: "stat__value" }, String(totals.activity)), h("span", { class: "stat__label" }, "activités")),
+ h("div", { class: "stat" }, h("span", { class: "stat__value" }, dec1(totals.total / ATTENDANCE_WEEKS)), h("span", { class: "stat__label" }, "par semaine"))),
+ h("figure", { class: "chart analysis-gap" },
+ barChart({
+ values: weeks.map((w) => w.total),
+ label: `Séances par semaine : ${weeks.map((w) => `semaine du ${shortDay(w.monday)}, ${w.total}`).join(" ; ")}`,
+ labels: [shortDay(weeks[0].monday), "cette semaine"],
+ }),
+ h("figcaption", { class: "chart__caption" }, "Séances par semaine, toutes natures. En couleur : la semaine en cours.")),
+ h("h2", { class: "tape" }, "Par exercice"),
+ list.length
+ ? h("ul", { class: "rows" }, list.map((x) => h("li", null, h("a", { class: "row", href: href.analysis(x.id) },
+ h("span", { class: "row__main" }, h("span", { class: "row__title" }, x.name), h("span", { class: "row__meta" }, `${x.count} fois · dernière le ${shortDay(x.last)}`)),
+ h("span", { class: "chevron", "aria-hidden": "true" })))))
+ : h("p", { class: "empty" }, "Aucun exercice fait pour l'instant."));
+ return { node, title: "Analyses" };
+}
+
+/** @param {{store: import("../store.js").Store, nav: import("../router.js").Navigation, exercise: string}} ctx */
+function exerciseScreen({ store, nav, exercise }) {
+ const state = store.getState();
+ const points = exerciseHistory(state, exercise);
+ const name = exercisesDone(state).find((x) => x.id === exercise)?.name ?? exercise;
+ const back = { label: "Analyses", onClick: () => nav.back(href.analysis()) };
+ const withLoad = points.filter((p) => p.loadKg !== null && p.loadKg > 0);
+ const withReps = points.filter((p) => p.bestReps !== null);
+ const origin = points[0]?.date;
+ /** @param {typeof points} pts @param {(p: typeof points[number]) => number} y @param {string} what @param {(v: number) => string} format */
+ const chart = (pts, y, what, format) => pts.length > 1
+ ? h("figure", { class: "chart" }, lineChart({
+ points: pts.map((p) => ({ x: daysBetween(/** @type {string} */ (origin), p.date), y: y(p) })),
+ label: `${what}, du ${mediumDay(pts[0].date)} au ${mediumDay(pts[pts.length - 1].date)}`,
+ format, xLabels: [shortDay(pts[0].date), shortDay(pts[pts.length - 1].date)], minSpan: 2,
+ }))
+ : h("p", { class: "muted" }, "Deux séances suffisent pour une courbe.");
+ const best = withLoad.length ? Math.max(...withLoad.map((p) => /** @type {number} */ (p.loadKg))) : null;
+ const node = h("div", { class: "screen" },
+ screenHeader({ back, kicker: plural(points.length, "séance"), title: name }),
+ h("div", { class: "stats" },
+ h("div", { class: "stat" }, h("span", { class: "stat__value" }, best !== null ? kg(best) : "—", best !== null && h("small", null, "kg")), h("span", { class: "stat__label" }, "meilleure charge")),
+ h("div", { class: "stat" }, h("span", { class: "stat__value" }, withReps.length ? String(Math.max(...withReps.map((p) => /** @type {number} */ (p.bestReps)))) : "—"), h("span", { class: "stat__label" }, "meilleure série"))),
+ withLoad.length > 0 && [h("h2", { class: "tape" }, "Charge"), chart(withLoad, (p) => /** @type {number} */ (p.loadKg), "Charge en kg", (v) => dec1(v))],
+ h("h2", { class: "tape" }, "Répétitions", h("span", { class: "tape__hint" }, "meilleure série")),
+ chart(withReps, (p) => /** @type {number} */ (p.bestReps), "Répétitions de la meilleure série", (v) => String(Math.round(v))),
+ h("h2", { class: "tape" }, "Séance par séance"),
+ h("ul", { class: "rows" }, [...points].reverse().map((p) => h("li", { class: "row" },
+ h("span", { class: "row__main" },
+ h("span", { class: "row__title" }, mediumDay(p.date)),
+ h("span", { class: "row__meta" }, [
+ `séance ${p.sessionRef}`, plural(p.sets, "série"),
+ p.bestReps !== null ? `meilleure ${p.bestReps}` : null,
+ p.effort ? EFFORT_LABELS[p.effort].label.toLowerCase() : null,
+ ].filter(Boolean).join(" · "))),
+ h("span", { class: "row__side num analysis__kg" }, p.loadKg ? `${kg(p.loadKg)} kg` : p.seconds ? `${p.seconds} s` : "")))));
+ return { node, title: name };
+}
diff --git a/app/ui/screens/data.js b/app/ui/screens/data.js
new file mode 100644
index 0000000..80671d2
--- /dev/null
+++ b/app/ui/screens/data.js
@@ -0,0 +1,141 @@
+// Données : sauvegarde (instantané), import (instantané, fichier d'Atelier,
+// programme seul), texte pour l'IA, réinitialisation.
+// Règle d'Atelier : rien n'est écrit avant le choix explicite de l'utilisateur.
+
+import { h, replace } from "../dom.js";
+import { createSnapshot, readImport } from "../../domain/snapshot.js";
+import { buildEvolutionBrief } from "../../domain/ai-brief.js";
+import { plural } from "../format.js";
+import { screenHeader } from "../layout.js";
+import { href } from "../router.js";
+import { confirmDialog, toast } from "../feedback.js";
+import { copyText, download, readFile } from "../files.js";
+import { clearDraft } from "../draft-storage.js";
+
+/** @typedef {import("../../domain/events.js").DomainEvent} DomainEvent */
+
+/**
+ * Écritures du journal en bloc (IndexedDB puis magasin), fournies par main.js.
+ * @typedef {object} Journal
+ * @property {(events: DomainEvent[]) => Promise} merge union : renvoie le nombre d'événements nouveaux
+ * @property {(events: DomainEvent[]) => Promise} replace remplace tout le journal
+ */
+
+/**
+ * @param {{store: import("../store.js").Store, nav: import("../router.js").Navigation, journal: Journal, today: () => string}} ctx
+ * @returns {import("../router.js").Screen}
+ */
+export function dataScreen({ store, nav, journal, today }) {
+ // ---- sauvegarde -----------------------------------------------------------------
+ const exportSnapshot = () => {
+ const snapshot = createSnapshot(store.getEvents(), { now: new Date() });
+ download(`ia-fit-${today()}.json`, JSON.stringify(snapshot, null, 1), "application/json");
+ toast("Sauvegarde téléchargée.");
+ };
+
+ // ---- texte pour l'IA --------------------------------------------------------------
+ const briefFallback = h("div", { class: "manual-copy", hidden: true });
+ const copyBrief = async () => {
+ const text = buildEvolutionBrief(store.getState(), { today: today(), baseUrl: location.origin });
+ if (await copyText(text, briefFallback, "Texte pour ton IA")) toast("Texte copié : colle-le dans ton IA.");
+ };
+
+ // ---- import -----------------------------------------------------------------------
+ const file = h("input", { id: "imp-file", class: "visually-hidden", type: "file", accept: ".json,application/json,text/plain" });
+ const pasted = h("textarea", { id: "imp-text", class: "field__input field__input--area field__input--mono", placeholder: "{ \"format\": \"ia-fit-snapshot\", … }" });
+ const report = h("div", { class: "import-report", role: "status", "aria-live": "polite" });
+
+ /** @param {string} text */
+ const read = (text) => {
+ let result;
+ try {
+ result = readImport(text, { device: store.device, now: new Date() });
+ } catch (e) {
+ replace(report, h("p", { class: "status status--err" }, e instanceof Error ? e.message : String(e)));
+ return;
+ }
+ const known = new Set(store.getEvents().map((e) => e.id));
+ const fresh = result.events.filter((e) => !known.has(e.id)).length;
+ const kind = { snapshot: "Sauvegarde IA-Fit", atelier: "Données d'Atelier, converties", program: "Programme seul" }[result.kind];
+ const merge = async () => {
+ const added = await journal.merge(result.events);
+ replace(report, h("p", { class: "status status--ok" }, added ? `${plural(added, "événement")} ajouté${added > 1 ? "s" : ""}.` : "Rien de nouveau : tout était déjà là."));
+ pasted.value = "";
+ if (result.kind === "program") nav.go(href.home());
+ };
+ const replaceAll = async () => {
+ const ok = await confirmDialog({
+ title: "Remplacer tout ?",
+ lines: [`Ton journal actuel (${plural(store.getEvents().length, "événement")}) sera effacé et remplacé par celui du fichier.`, "Exporte d'abord une sauvegarde si tu as un doute."],
+ confirm: "Remplacer", cancel: "Annuler", danger: true,
+ });
+ if (!ok) return;
+ await journal.replace(result.events);
+ clearDraft();
+ replace(report, h("p", { class: "status status--ok" }, "Journal remplacé."));
+ pasted.value = "";
+ };
+ replace(report,
+ h("div", { class: "block" },
+ h("p", { class: "mark" }, kind),
+ h("ul", { class: "diff__lines" }, result.report.map((line) => h("li", null, line))),
+ h("p", { class: "muted" }, fresh === result.events.length
+ ? `${plural(fresh, "événement")} à ajouter.`
+ : `${plural(fresh, "événement")} nouveau${fresh > 1 ? "x" : ""} sur ${result.events.length} : le reste est déjà dans ton journal.`),
+ h("div", { class: "btn-stack" },
+ h("button", { type: "button", class: "btn btn--primary btn--block", on: { click: () => void merge() } },
+ result.kind === "program" ? "Ajouter la proposition" : "Fusionner avec mes données"),
+ result.kind !== "program" && h("button", { type: "button", class: "btn btn--ghost btn--block", on: { click: () => void replaceAll() } }, "Remplacer mes données"),
+ h("button", { type: "button", class: "btn btn--ghost btn--block", on: { click: () => replace(report) } }, "Ne rien importer"))));
+ };
+ file.addEventListener("change", async () => {
+ const f = file.files?.[0];
+ if (f) read(await readFile(f));
+ file.value = "";
+ });
+
+ // ---- réinitialisation ---------------------------------------------------------------
+ const reset = async () => {
+ const n = store.getEvents().length;
+ const first = await confirmDialog({
+ title: "Tout effacer ?",
+ lines: [`Les ${plural(n, "événement")} de cet appareil seront effacés : programme, séances, pesées, réglages.`, "Exporte d'abord une sauvegarde."],
+ confirm: "Continuer", cancel: "Annuler", danger: true,
+ });
+ if (!first) return;
+ const second = await confirmDialog({
+ title: "Vraiment ?", lines: ["Impossible de revenir en arrière sans sauvegarde."],
+ confirm: "Tout effacer", cancel: "Non, garder", danger: true,
+ });
+ if (!second) return;
+ await journal.replace([]);
+ clearDraft();
+ toast("Données effacées.");
+ nav.go(href.home(), { replace: true });
+ };
+
+ const node = h("div", { class: "screen" },
+ screenHeader({ back: { label: "Accueil", onClick: () => nav.back(href.home()) }, kicker: "Sans compte", title: "Données", sub: "Tout vit sur cet appareil. Une sauvegarde te protège d'une perte." }),
+ h("p", { class: "mark" }, `${plural(store.getEvents().length, "événement")} au journal`),
+
+ h("h2", { class: "tape" }, "Ton IA"),
+ h("p", { class: "muted" }, "Ton historique, ton profil et ton programme, à coller dans ton IA. Elle répond par un lien : ta proposition s'ouvre ici."),
+ h("button", { type: "button", class: "btn btn--primary btn--block", on: { click: () => void copyBrief() } }, "Copier le texte pour mon IA"),
+ briefFallback,
+
+ h("h2", { class: "tape" }, "Sauvegarde"),
+ h("button", { type: "button", class: "btn btn--block", on: { click: exportSnapshot } }, "Exporter une sauvegarde"),
+ h("p", { class: "muted" }, "Un fichier .json : le journal complet et un résumé lisible."),
+
+ h("h2", { class: "tape", id: "import" }, "Restaurer · importer"),
+ h("p", { class: "muted" }, "Une sauvegarde IA-Fit, un fichier d'Atelier (converti) ou un programme seul (proposé à validation)."),
+ h("label", { class: "btn btn--block", for: "imp-file" }, "Choisir un fichier"),
+ file,
+ h("div", { class: "field data-gap" }, h("label", { class: "field__label", for: "imp-text" }, "Ou colle le texte"), pasted),
+ h("button", { type: "button", class: "btn btn--block", on: { click: () => read(pasted.value) } }, "Lire le texte"),
+ report,
+
+ h("h2", { class: "tape" }, "Zone dangereuse"),
+ h("button", { type: "button", class: "btn btn--danger btn--block", on: { click: () => void reset() } }, "Tout effacer"));
+ return { node, title: "Données" };
+}
diff --git a/app/ui/screens/history.js b/app/ui/screens/history.js
index e253e55..b2e6802 100644
--- a/app/ui/screens/history.js
+++ b/app/ui/screens/history.js
@@ -20,11 +20,12 @@ export function historyScreen({ store, nav }) {
replace(list, h("p", { class: "empty" }, "Aucune séance enregistrée pour l'instant. Termine ta première séance : elle apparaîtra ici."));
return;
}
- replace(list, h("ul", { class: "history__list" }, sessions.map((s) =>
- h("li", null, h("a", { class: "history__item", href: href.historyEdit(s.id) },
- h("span", { class: "history__date" }, mediumDay(s.date)),
- h("span", { class: "history__name" }, s.name),
- h("span", { class: "history__meta" }, sessionSummary(s) || kindLabel(s.kind)),
+ replace(list, h("ul", { class: "rows history__list" }, sessions.map((s) =>
+ h("li", null, h("a", { class: "row history__item", href: href.historyEdit(s.id) },
+ h("span", { class: "row__main" },
+ h("span", { class: "history__date" }, mediumDay(s.date)),
+ h("span", { class: "row__title history__name" }, s.name),
+ h("span", { class: "row__meta history__meta" }, sessionSummary(s) || kindLabel(s.kind))),
h("span", { class: "chevron", "aria-hidden": "true" }))))));
};
paint();
diff --git a/app/ui/screens/home.js b/app/ui/screens/home.js
index 0160745..c302e1d 100644
--- a/app/ui/screens/home.js
+++ b/app/ui/screens/home.js
@@ -1,112 +1,242 @@
// Accueil. Par priorité : une proposition en attente, sinon l'onboarding s'il
-// n'y a pas encore de programme, sinon la carte du jour, les séances, le
-// cardio et les repères.
+// n'y a pas encore de programme, sinon le HUD (niveau, série), la carte du
+// jour tirée du planning, les séances, le cardio, les repères et la grille des
+// autres écrans.
-import { h, setAccent } from "../dom.js";
+import { h, paintWhenIdle, setAccent } from "../dom.js";
import { inkOn, sessionColor } from "../color.js";
-import { longDay, localDay, shortDay, plural } from "../format.js";
-import { estimateMinutes, lastDoneByKey, nextByRotation } from "../home-model.js";
-import { actionBar, note, screenHeader, sectionLabel } from "../layout.js";
+import { longDay, plural, shortDay } from "../format.js";
+import { dayName, lastDoneByKey, loggedForSlot, nextByRotation, slotLabel, todayModel } from "../home-model.js";
+import { actionBar, note } from "../layout.js";
import { href } from "../router.js";
import { onboarding } from "../onboarding.js";
import { proposalCard } from "../proposal-card.js";
+import { estimatedMinutes } from "../../domain/progression.js";
+import { hud } from "../game.js";
+import { toast } from "../feedback.js";
+
+/** @typedef {import("../../domain/state.js").State} State */
+/** @typedef {import("../../domain/planning.js").Slot} Slot */
+/** @typedef {import("../store.js").Store} Store */
/**
* Un programme a-t-il été adopté ? Il n'y a pas de programme par défaut
- * (décision du porteur du projet, 2026-11-18) : tant qu'aucun ProgramAdopted
- * n'est au journal, l'accueil montre l'onboarding.
- * @param {import("../../domain/state.js").State} state
+ * (ADR 0008) : tant qu'aucun ProgramAdopted n'est au journal, l'accueil montre
+ * l'onboarding.
+ * @param {State} state
*/
export const hasProgram = (state) => !!state.program && state.programVersions.length > 0;
/**
- * @param {{store: import("../store.js").Store}} ctx
+ * @param {{store: Store, nav: import("../router.js").Navigation, today: () => string}} ctx
* @returns {import("../router.js").Screen}
*/
-export function homeScreen({ store }) {
+export function homeScreen({ store, nav, today }) {
const node = h("div", { class: "screen screen--home" });
- // L'accueil n'a aucun champ de saisie : le reconstruire à chaque changement est sans risque.
- const paint = () => node.replaceChildren(homeContent(store));
+ const paint = () => node.replaceChildren(homeContent(store, nav, today()));
paint();
- return { node, title: "", destroy: store.subscribe(paint) };
+ return { node, title: "", destroy: store.subscribe(paintWhenIdle(node, paint)) };
}
/**
- * @param {import("../store.js").Store} store
+ * Plaque d'une séance : sa lettre sur sa couleur.
+ * @param {string} key
+ * @param {string|undefined} color
+ * @param {string} [cls]
+ */
+export function plaque(key, color, cls = "plaque") {
+ const el = h("span", { class: cls, "aria-hidden": "true" }, key);
+ const c = sessionColor(color);
+ setAccent(el, c, inkOn(c));
+ return el;
+}
+
+/**
+ * @param {Store} store
+ * @param {import("../router.js").Navigation} nav
+ * @param {string} today
* @returns {Node}
*/
-function homeContent(store) {
+function homeContent(store, nav, today) {
const state = store.getState();
- // Une proposition en attente passe avant tout le reste.
if (state.proposals.length) {
+ const [first, ...others] = state.proposals;
return h("div", null,
h("header", { class: "screen-head" }, h("p", { class: "kicker" }, "IA-Fit"), h("h1", { class: "title" }, "Un programme t'attend")),
- state.proposals.map((proposal) => proposalCard({ proposal, store })));
+ proposalCard({ proposal: first, store }),
+ others.length > 0 && h("p", { class: "muted" }, `Et ${plural(others.length, "autre proposition")} ensuite.`));
}
if (!hasProgram(state)) return onboarding({ store });
const program = /** @type {import("../../domain/program.js").Program} */ (state.program);
+ const model = todayModel(state, today);
const last = lastDoneByKey(state);
- const today = localDay();
+ /** @type {Node|null} */
+ let primary = null;
- // À brancher : planning.weekPlan(state, monday) donnera le créneau du jour
- // (séance, cardio, activité, repos), les créneaux en retard et l'avancement de
- // la semaine. En attendant : rotation simple, annoncée comme telle.
- const next = nextByRotation(state);
+ /** @param {Slot} slot @param {string} date */
+ const markDone = (slot, date) => {
+ const data = loggedForSlot(slot, program, date);
+ if (state.skippedDays.includes(date)) store.dispatch("DayUnskipped", { date });
+ store.dispatch("SessionLogged", data);
+ toast(`${data.name} : fait.`);
+ };
- const todayCard = next
- ? sessionLink(next, "card card--today", [
- h("p", { class: "kicker" }, "Aujourd'hui · ", longDay(today)),
- h("p", { class: "card__eyebrow" }, h("span", { class: "swatch", "aria-hidden": "true" }), `Séance ${next.key}`),
- h("h2", { class: "card__title" }, next.name),
- h("p", { class: "card__meta" },
- `${plural(next.exercises.length, "exercice")} · environ ${estimateMinutes(next)} min`,
- last[next.key] ? ` · faite le ${shortDay(last[next.key])}` : " · jamais faite"),
- next.subtitle && h("p", { class: "card__text" }, next.subtitle),
- h("p", { class: "card__hint" },
- "Proposée par rotation : la séance faite le moins récemment. Le planning de la semaine arrive bientôt."),
- ])
- : h("div", { class: "card card--today" }, h("p", { class: "card__text" }, "Le programme ne contient aucune séance."));
+ // ---- carte du jour -----------------------------------------------------------
+ const kicker = h("p", { class: "kicker" }, "Aujourd'hui · ", longDay(today));
+ /** @type {import("../dom.js").Child[]} */
+ let body = [];
+ if (!model.planned) {
+ const next = nextByRotation(state);
+ if (next) {
+ body = [
+ h("div", { class: "block__head" }, plaque(next.key, next.color),
+ h("div", null, h("h2", { class: "block__title" }, next.name),
+ h("p", { class: "block__meta" }, `${plural(next.exercises.length, "exercice")} · ${estimatedMinutes(next)} min · ${last[next.key] ? "faite le " + shortDay(last[next.key]) : "jamais faite"}`))),
+ h("p", { class: "muted" }, "Pas de planning : la séance faite le moins récemment. "),
+ h("a", { class: "btn btn--block", href: href.week() }, "Planifier ma semaine"),
+ ];
+ primary = h("a", { class: "btn btn--primary btn--block btn--lg", href: href.session(next.key) }, `Commencer · séance ${next.key}`);
+ }
+ } else if (model.status === "rest") {
+ body = [h("h2", { class: "block__title" }, "Repos"), h("p", { class: "block__meta" }, nextText(model.next, program))];
+ } else if (model.status === "done") {
+ body = [h("h2", { class: "block__title" }, "C'est fait."), h("p", { class: "block__meta" }, nextText(model.next, program))];
+ } else if (model.status === "skipped") {
+ body = [
+ h("h2", { class: "block__title" }, "Passée"),
+ h("p", { class: "block__meta" }, `Marquée non faite. ${nextText(model.next, program)}`),
+ h("button", { type: "button", class: "btn btn--block", on: { click: () => store.dispatch("DayUnskipped", { date: today }) } }, "Annuler, je la fais"),
+ ];
+ } else if (model.slot) {
+ const slot = model.slot;
+ const label = slotLabel(slot, program);
+ const session = slot.kind === "strength" ? program.sessions.find((s) => s.key === slot.sessionKey) : null;
+ body = [
+ h("div", { class: "block__head" },
+ session ? plaque(session.key, session.color) : h("span", { class: "plaque plaque--empty", "aria-hidden": "true" }, slot.kind === "cardio" ? "C" : "A"),
+ h("div", null,
+ h("h2", { class: "block__title" }, session ? session.name : label.title),
+ h("p", { class: "block__meta" }, session
+ ? `Séance ${session.key} · ${plural(session.exercises.length, "exercice")} · ${estimatedMinutes(session)} min`
+ : label.detail))),
+ session?.subtitle && h("p", null, session.subtitle),
+ slot.kind === "cardio" && program.cardio?.[slot.cardioIndex ?? -1]?.text && h("p", { class: "muted" }, program.cardio[slot.cardioIndex ?? -1].text),
+ h("button", { type: "button", class: "btn btn--ghost btn--block", on: { click: () => store.dispatch("DaySkipped", { date: today }) } }, "Pas aujourd'hui"),
+ ];
+ primary = session
+ ? h("a", { class: "btn btn--primary btn--block btn--lg", href: href.session(session.key) }, "Commencer")
+ : h("button", { type: "button", class: "btn btn--primary btn--block btn--lg", on: { click: () => markDone(slot, today) } }, "Marquer comme fait");
+ }
+
+ const late = model.late.length > 0 && h("div", { class: "block__sep" },
+ h("p", { class: "mark" }, "En retard cette semaine"),
+ h("ul", { class: "rows" }, model.late.map((slot) => {
+ const label = slotLabel(slot, program);
+ return h("li", { class: "row" },
+ h("span", { class: "row__main" },
+ h("span", { class: "row__title" }, label.title + (label.detail ? ` · ${label.detail}` : "")),
+ h("span", { class: "row__meta" }, `Prévue ${dayName(slot.date)}`)),
+ slot.kind === "strength"
+ ? h("a", { class: "btn btn--sm", href: href.session(/** @type {string} */ (slot.sessionKey)) }, "Faire")
+ : h("button", { type: "button", class: "btn btn--sm", on: { click: () => markDone(slot, slot.date) } }, "Marquer faite"));
+ })));
+
+ const progress = model.planned && h("div", { class: "block__sep" },
+ h("p", { class: "mark" }, `Semaine · ${model.done}/${model.cells.length} fait`,
+ model.skipped ? ` · ${model.skipped} manqué${model.skipped > 1 ? "s" : ""}` : "",
+ model.extra ? ` · ${model.extra} en plus` : ""),
+ h("span", { class: "cells", "aria-hidden": "true" }, model.cells.map((c) => h("i", { data: { state: c.state } }))));
+
+ const doneToday = model.doneToday.length > 0 && h("p", { class: "muted" },
+ "Déjà fait aujourd'hui : ", model.doneToday.map((s) => s.name).join(", "), ".");
+
+ const todayBlock = h("section", { class: "block block--today", "aria-label": "Aujourd'hui" },
+ kicker, ...body, otherActivity(store, today), doneToday, late, progress);
return h("div", null,
- screenHeader({ kicker: "IA-Fit", title: program.name, sub: program.subtitle }),
- todayCard,
+ hud(state, today),
+ h("header", { class: "visually-hidden" }, h("h1", null, program.name)),
+ todayBlock,
- sectionLabel("Séances"),
- h("ul", { class: "plates" }, program.sessions.map((s) =>
- h("li", null, sessionLink(s, "plate", [
- h("span", { class: "plate__bar", "aria-hidden": "true" }),
- h("span", { class: "plate__body" },
- h("span", { class: "plate__id" }, `Séance ${s.key}${s.tag ? " · " + s.tag : ""}`),
- h("span", { class: "plate__name" }, s.name),
- h("span", { class: "plate__meta" }, `${plural(s.exercises.length, "exercice")} · environ ${estimateMinutes(s)} min`)),
- h("span", { class: "plate__last" }, last[s.key] ? `Faite le ${shortDay(last[s.key])}` : "Jamais faite"),
- ])))),
+ h("h2", { class: "tape" }, "Séances"),
+ h("ul", { class: "rows" }, program.sessions.map((s) =>
+ h("li", null, h("a", { class: "row", href: href.session(s.key) },
+ plaque(s.key, s.color),
+ h("span", { class: "row__main" },
+ h("span", { class: "row__title" }, s.name),
+ h("span", { class: "row__meta" }, `${plural(s.exercises.length, "exercice")} · ${estimatedMinutes(s)} min · ${last[s.key] ? "faite le " + shortDay(last[s.key]) : "jamais faite"}`)),
+ h("span", { class: "chevron", "aria-hidden": "true" }))))),
- program.cardio?.length ? [sectionLabel("Cardio"), program.cardio.map((c) => note(c.name, c.text))] : null,
- program.rules?.length ? [sectionLabel("Repères"), program.rules.map((r) => note(r.name, r.text))] : null,
+ program.cardio?.length ? [h("h2", { class: "tape" }, "Cardio"), program.cardio.map((c) => note(c.name, c.text))] : null,
+ program.rules?.length ? [h("h2", { class: "tape" }, "Repères"), program.rules.map((r) => note(r.name, r.text))] : null,
- sectionLabel("Aller plus loin"),
- h("nav", { class: "links", "aria-label": "Autres écrans" },
- h("a", { class: "btn btn--block btn--ghost", href: href.history() }, "Historique des séances"),
- // À brancher (sous-lot 1d) : semaine, activités, poids, données, profil.
- h("p", { class: "muted" }, "Semaine, activités, poids et sauvegarde : bientôt.")),
+ h("h2", { class: "tape" }, "Tout le reste"),
+ h("nav", { class: "grid-nav", "aria-label": "Autres écrans" },
+ tile(href.week(), "Semaine", "jours, planning, agenda"),
+ tile(href.history(), "Historique", plural(state.sessions.length, "séance")),
+ tile(href.weight(), "Poids", state.weights.length ? `${String(state.weights[state.weights.length - 1].kg).replace(".", ",")} kg` : "première pesée"),
+ tile(href.analysis(), "Analyses", "charges, assiduité"),
+ tile(href.progress(), "Succès", "niveau, records"),
+ tile(href.activities(), "Activités", plural(program.activities?.length ?? 0, "activité")),
+ tile(href.profile(), "Profil", "objectif, mode"),
+ tile(href.data(), "Données", "sauvegarde, IA")),
- h("footer", { class: "foot" }, "Tes données restent sur cet appareil."),
+ h("p", { class: "foot" }, `${program.name} · tes données restent sur cet appareil.`),
+ primary && actionBar(primary));
+}
- next && actionBar(h("a", { class: "btn btn--primary btn--block btn--lg", href: href.session(next.key) },
- `Commencer la séance ${next.key}`)));
+/** @param {string} link @param {string} name @param {string} meta */
+function tile(link, name, meta) {
+ return h("a", { class: "tile", href: link }, h("span", { class: "tile__name" }, name), h("span", { class: "tile__meta" }, meta));
}
/**
- * Lien vers une séance, coloré par sa couleur.
- * @param {import("../../domain/program.js").ProgramSession} s
- * @param {string} cls
- * @param {import("../dom.js").Child[]} children
+ * @param {Slot|null} next
+ * @param {import("../../domain/program.js").Program} program
*/
-function sessionLink(s, cls, children) {
- const a = h("a", { class: cls, href: href.session(s.key) }, ...children);
- const color = sessionColor(s.color);
- setAccent(a, color, inkOn(color));
- return a;
+function nextText(next, program) {
+ if (!next) return "Plus rien de prévu cette semaine.";
+ const l = slotLabel(next, program);
+ return `Ensuite : ${dayName(next.date)}, ${l.title.toLowerCase()}${l.detail ? " · " + l.detail : ""}.`;
}
+
+/**
+ * « Autre activité » : enregistrer n'importe quelle séance, cardio ou activité,
+ * à une date choisie avant.
+ * @param {Store} store
+ * @param {string} today
+ */
+function otherActivity(store, today) {
+ const program = /** @type {import("../../domain/program.js").Program} */ (store.getState().program);
+ const panel = h("div", { class: "other", hidden: true });
+ const toggle = h("button", { type: "button", class: "btn btn--ghost btn--block", "aria-expanded": "false" }, "Autre activité");
+ toggle.addEventListener("click", () => {
+ panel.hidden = !panel.hidden;
+ toggle.setAttribute("aria-expanded", String(!panel.hidden));
+ });
+ const date = h("input", { id: "other-date", class: "field__input", type: "date", max: today, value: today });
+ const day = () => (/^\d{4}-\d{2}-\d{2}$/.test(date.value) && date.value <= today ? date.value : today);
+ /** @param {"cardio"|"activity"} kind @param {string} ref @param {string} name */
+ const log = (kind, ref, name) => {
+ const d = day();
+ if (store.getState().sessions.some((s) => s.kind === kind && s.ref === ref && s.date === d)) {
+ toast(`${name} est déjà enregistré à cette date.`);
+ return;
+ }
+ if (store.getState().skippedDays.includes(d)) store.dispatch("DayUnskipped", { date: d });
+ store.dispatch("SessionLogged", { date: d, kind, ref, name, warmup: null, exercises: [] });
+ toast(`${name} : enregistré le ${shortDay(d)}.`);
+ };
+ const session = (/** @type {string} */ key) => {
+ location.hash = href.session(key, day() === today ? null : day());
+ };
+ panel.append(
+ h("div", { class: "field field--inline" }, h("label", { class: "field__label", for: "other-date" }, "Le"), date),
+ h("div", { class: "choice-list" },
+ program.sessions.map((s) => h("button", { type: "button", class: "choice", on: { click: () => session(s.key) } }, `Séance ${s.key} · ${s.name}`)),
+ (program.cardio ?? []).map((c) => h("button", { type: "button", class: "choice", on: { click: () => log("cardio", c.name, c.name) } }, `Cardio · ${c.name}`)),
+ (program.activities ?? []).map((a) => h("button", { type: "button", class: "choice", on: { click: () => log("activity", a.id, a.name) } }, a.name))));
+ return h("div", null, toggle, panel);
+}
+
diff --git a/app/ui/screens/profile.js b/app/ui/screens/profile.js
new file mode 100644
index 0000000..38b84e8
--- /dev/null
+++ b/app/ui/screens/profile.js
@@ -0,0 +1,121 @@
+// 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).
+
+import { h } from "../dom.js";
+import { MODES } from "../../domain/vocabulary.js";
+import { validateProfile } from "../../domain/profile.js";
+import { screenHeader } from "../layout.js";
+import { href } from "../router.js";
+import { toast } from "../feedback.js";
+import { getTheme, setTheme } from "../theme-pref.js";
+
+/** @type {Record} */
+export const MODE_LABELS = {
+ progression: { label: "Progression", text: "Les charges montent dès que toutes les séries atteignent le haut de la fourchette, sans « dur » ni « échec »." },
+ maintenance: { label: "Maintien", text: "Garder le niveau : les charges restent stables." },
+ recovery: { label: "Récupération", text: "Reprise ou fatigue : rien ne monte, l'IA allège." },
+};
+
+/**
+ * Lit le formulaire. Les listes s'écrivent une ligne par élément.
+ * @param {{goal: string, context: string, equipment: string, constraints: string, heightCm: string, sessionMinutes: string}} form
+ * @returns {{profile: import("../../domain/profile.js").Profile, errors: string[]}}
+ */
+export function profileFromForm(form) {
+ const lines = (/** @type {string} */ t) => t.split(/\r?\n/).map((l) => l.replace(/^\s*[-•*]\s*/, "").trim()).filter(Boolean);
+ // Un nombre illisible devient NaN, que validateProfile refuse.
+ const height = form.heightCm.trim() === "" ? null : Math.round(Number(form.heightCm.replace(",", ".")));
+ const profile = {
+ goal: form.goal.trim(),
+ context: form.context.trim(),
+ equipment: lines(form.equipment),
+ constraints: lines(form.constraints),
+ heightCm: height,
+ sessionMinutes: Math.round(Number(form.sessionMinutes.replace(",", "."))),
+ };
+ /** @type {Record} */
+ const plain = {
+ heightCm: "Taille : un nombre de centimètres entre 50 et 260, ou vide.",
+ sessionMinutes: "Durée d'une séance : de 10 à 240 minutes.",
+ };
+ const errors = validateProfile(profile).map((e) => Object.entries(plain).find(([k]) => e.includes(`'${k}'`))?.[1] ?? e);
+ return { profile, errors };
+}
+
+/**
+ * @param {{store: import("../store.js").Store, nav: import("../router.js").Navigation}} ctx
+ * @returns {import("../router.js").Screen}
+ */
+export function profileScreen({ store, nav }) {
+ const p = store.getState().profile;
+ /** @param {string} id @param {string} label @param {HTMLElement} input @param {string} [hint] */
+ const field = (id, label, input, hint) => h("div", { class: "field" },
+ h("label", { class: "field__label", for: id }, label), input, hint && h("p", { class: "field__hint" }, hint));
+ const area = (/** @type {string} */ id, /** @type {string} */ value) => h("textarea", { id, class: "field__input field__input--area", value });
+ const goal = area("p-goal", p.goal);
+ const context = area("p-context", p.context);
+ const equipment = area("p-equipment", p.equipment.join("\n"));
+ const constraints = area("p-constraints", p.constraints.join("\n"));
+ const height = h("input", { id: "p-height", class: "field__input", type: "text", inputmode: "numeric", value: p.heightCm ?? "" });
+ const minutes = h("input", { id: "p-minutes", class: "field__input", type: "text", inputmode: "numeric", value: String(p.sessionMinutes) });
+ const status = h("p", { class: "status", role: "status", "aria-live": "polite" });
+
+ const save = () => {
+ const { profile, errors } = profileFromForm({
+ goal: goal.value, context: context.value, equipment: equipment.value, constraints: constraints.value,
+ heightCm: height.value, sessionMinutes: minutes.value,
+ });
+ if (errors.length) {
+ status.className = "status status--err";
+ status.textContent = errors.join(" ");
+ return;
+ }
+ store.dispatch("ProfileUpdated", { profile });
+ status.className = "status status--ok";
+ status.textContent = "Profil enregistré.";
+ };
+
+ // Le mode change d'un geste : seul l'état des boutons est mis à jour.
+ const modeText = h("p", { class: "muted" });
+ const modeBtns = MODES.map((m) => h("button", { type: "button", class: "segmented__opt", data: { mode: m } }, MODE_LABELS[m].label));
+ const paintMode = () => {
+ const mode = store.getState().mode;
+ modeBtns.forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.mode === mode)));
+ modeText.textContent = MODE_LABELS[mode].text;
+ };
+ modeBtns.forEach((b) => b.addEventListener("click", () => {
+ const mode = /** @type {import("../../domain/vocabulary.js").Mode} */ (b.dataset.mode);
+ if (mode === store.getState().mode) return;
+ store.dispatch("ModeChanged", { mode });
+ paintMode();
+ toast(`Mode : ${MODE_LABELS[mode].label.toLowerCase()}.`);
+ }));
+ paintMode();
+
+ const themes = /** @type {const} */ ([["auto", "Système"], ["dark", "Sombre"], ["light", "Clair"]]);
+ const themeBtns = themes.map(([value, label]) => h("button", { type: "button", class: "segmented__opt", data: { theme: value } }, label));
+ const paintTheme = () => themeBtns.forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.theme === getTheme())));
+ themeBtns.forEach((b) => b.addEventListener("click", () => { setTheme(/** @type {any} */ (b.dataset.theme)); paintTheme(); }));
+ paintTheme();
+
+ const node = h("div", { class: "screen" },
+ screenHeader({ back: { label: "Accueil", onClick: () => nav.back(href.home()) }, kicker: "Pour ton IA", title: "Profil", sub: "Ton IA lit ce profil pour construire et ajuster ton programme." }),
+ h("h2", { class: "tape" }, "Mode"),
+ h("div", { class: "segmented", role: "group", "aria-label": "Mode du programme" }, modeBtns),
+ modeText,
+ h("h2", { class: "tape" }, "Toi"),
+ field("p-goal", "Objectif", goal, "En une phrase."),
+ field("p-context", "Contexte", context, "Pratique passée, lieu d'entraînement."),
+ field("p-equipment", "Matériel", equipment, "Un élément par ligne."),
+ field("p-constraints", "Contraintes", constraints, "Sécurité, blessures, organisation. Une par ligne."),
+ h("div", { class: "field-pair" },
+ field("p-height", "Taille (cm)", height),
+ field("p-minutes", "Séance (min)", minutes)),
+ status,
+ h("button", { type: "button", class: "btn btn--primary btn--block", on: { click: save } }, "Enregistrer le profil"),
+ 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."));
+ return { node, title: "Profil" };
+}
diff --git a/app/ui/screens/session.js b/app/ui/screens/session.js
index ab57b9b..1787092 100644
--- a/app/ui/screens/session.js
+++ b/app/ui/screens/session.js
@@ -5,20 +5,22 @@ import { h, setAccent } from "../dom.js";
import { groupBlocks, resolveExercise } from "../../domain/program.js";
import { inkOn, sessionColor } from "../color.js";
import { localDay, longDay, plural } from "../format.js";
-import { estimateMinutes } from "../home-model.js";
+import { estimatedMinutes } from "../../domain/progression.js";
import { actionBar, screenHeader } from "../layout.js";
import { href } from "../router.js";
-import { buildSessionData, completion, createDraft, doneCount, draftMatches } from "../session-draft.js";
+import { buildSessionData, completion, createDraft, doneCount, draftMatches, draftTotals, setsInOrder } from "../session-draft.js";
import { clearDraft, loadDraft, saveDraft } from "../draft-storage.js";
import { exerciseCard } from "../exercise-card.js";
-import { WARMUP_STEPS, warmupCard } from "../warmup-card.js";
+import { warmupCard, warmupSteps } from "../warmup-card.js";
import { confirmDialog, toast } from "../feedback.js";
+import { comboLabel, recordFinish } from "../game.js";
/**
- * @param {{store: import("../store.js").Store, key: string, nav: import("../router.js").Navigation, timer: import("../timer.js").Timer}} ctx
+ * @param {{store: import("../store.js").Store, key: string, date: string|null, nav: import("../router.js").Navigation, timer: import("../timer.js").Timer}} ctx
+ * date : séance saisie pour un autre jour (« Autre activité », un créneau passé)
* @returns {import("../router.js").Screen}
*/
-export function sessionScreen({ store, key, nav, timer }) {
+export function sessionScreen({ store, key, date, nav, timer }) {
const state = store.getState();
const session = state.program?.sessions.find((s) => s.key === key);
const back = { label: "Accueil", onClick: () => nav.back(href.home()) };
@@ -31,18 +33,21 @@ export function sessionScreen({ store, key, nav, timer }) {
}
const today = localDay();
+ const warmup = warmupSteps(state, session);
const stored = loadDraft();
- const draft = draftMatches(stored, session, WARMUP_STEPS.length)
+ const draft = draftMatches(stored, session, warmup.steps.length)
? stored
- : createDraft(session, state, today, WARMUP_STEPS.length);
+ : createDraft(session, state, date && date <= today ? date : today, warmup.steps.length);
const resumed = draft === stored;
+ if (resumed && date && date <= today) draft.date = date;
const progress = h("span", { class: "action-bar__meta", "aria-live": "polite" });
const status = h("p", { class: "status", role: "alert" });
const totalSets = draft.exercises.reduce((n, ex) => n + ex.sets, 0);
const paintProgress = () => {
const done = draft.exercises.reduce((n, ex) => n + doneCount(ex), 0);
- progress.textContent = `${done}/${totalSets} séries`;
+ const combo = comboLabel(setsInOrder(draft));
+ progress.replaceChildren(h("span", null, `${done}/${totalSets} séries`), combo ? h("span", { class: "combo" }, combo) : "");
};
// Le brouillon n'est gardé qu'au premier changement : ouvrir une séance pour
// la regarder n'écrase pas celle qu'on a commencée.
@@ -76,7 +81,7 @@ export function sessionScreen({ store, key, nav, timer }) {
const cards = block.items.map((item, k) => {
const i = index++;
return exerciseCard({
- ex: draft.exercises[i], item, sessionKey: session.key, number: String(i + 1),
+ draft, ex: draft.exercises[i], item, sessionKey: session.key, number: String(i + 1),
letter: block.items.length > 1 ? String.fromCharCode(65 + k) : null,
open: resumed && i === firstOpen, store, timer, onChange,
});
@@ -106,6 +111,7 @@ export function sessionScreen({ store, key, nav, timer }) {
const ok = await confirmDialog({ title: "La séance n'est pas finie", lines, confirm: "Enregistrer quand même", cancel: "Continuer la séance" });
if (!ok) return;
}
+ const before = store.getState();
try {
store.dispatch("SessionLogged", buildSessionData(draft));
} catch (e) {
@@ -114,14 +120,15 @@ export function sessionScreen({ store, key, nav, timer }) {
}
clearDraft();
timer.stop();
- toast(draft.date === today ? "Séance enregistrée." : `Séance enregistrée au ${longDay(draft.date)}.`);
- nav.go(href.home(), { replace: true });
+ if (draft.date !== today) toast(`Séance enregistrée au ${longDay(draft.date)}.`);
+ recordFinish(before, store.getState(), today, { name: draft.name, date: draft.date, ...draftTotals(draft) });
+ nav.go(href.finish(), { replace: true });
};
const node = h("div", { class: "screen screen--session" },
screenHeader({
back,
- kicker: `Séance ${session.key}${session.tag ? " · " + session.tag : ""} · environ ${estimateMinutes(session)} min`,
+ kicker: `Séance ${session.key}${session.tag ? " · " + session.tag : ""} · environ ${estimatedMinutes(session)} min`,
title: session.name,
sub: session.subtitle,
}),
@@ -131,7 +138,7 @@ export function sessionScreen({ store, key, nav, timer }) {
dateInput),
dateNotice,
h("div", { class: "exercises" },
- warmupCard({ done: draft.warmup, timer, onChange, open: !resumed }),
+ warmupCard({ plan: warmup, done: draft.warmup, timer, onChange, open: !resumed }),
blocks),
status,
h("p", { class: "foot" }, "Touche une série pour noter tes répétitions et ton ressenti : le repos démarre tout seul."),
diff --git a/app/ui/screens/week.js b/app/ui/screens/week.js
new file mode 100644
index 0000000..1fda1d3
--- /dev/null
+++ b/app/ui/screens/week.js
@@ -0,0 +1,172 @@
+// Semaine : jours disponibles, jours imposés, créneaux de la semaine en cours
+// ou suivante, « Faite », « Non fait », « Retirer », export .ics.
+// Le planning est calculé (planning.js), jamais stocké : seuls les réglages
+// (PlanSettingsChanged) et les faits (SessionLogged, DaySkipped…) sont au journal.
+
+import { h, paintWhenIdle, replace } from "../dom.js";
+import { addDays, mondayOf } from "../../domain/dates.js";
+import { settingsForWeek } from "../../domain/planning.js";
+import { buildIcs } from "../../domain/ics.js";
+import { DAY_LETTERS, DAY_NAMES, DAY_SHORT, dayName, lockOptions, loggedForSlot, sessionForSlot, slotLabel, weekRows, withDays, withLock } from "../home-model.js";
+import { mediumDay, shortDay } from "../format.js";
+import { screenHeader } from "../layout.js";
+import { href } from "../router.js";
+import { confirmDialog, toast } from "../feedback.js";
+import { download } from "../files.js";
+import { plaque } from "./home.js";
+
+/** @typedef {import("../home-model.js").WeekRow} WeekRow */
+
+/**
+ * @param {{store: import("../store.js").Store, nav: import("../router.js").Navigation, today: () => string}} ctx
+ * @returns {import("../router.js").Screen}
+ */
+export function weekScreen({ store, nav, today }) {
+ let tab = 0;
+ /** @type {number|null} */
+ let lockOpen = null;
+ const zone = h("div", { class: "week" });
+ const status = h("p", { class: "status status--ok", role: "status", "aria-live": "polite" });
+
+ const monday = () => addDays(mondayOf(today()), tab * 7);
+ /** Où écrire : la semaine suivante a toujours son propre réglage ; la semaine en cours écrit le réglage par défaut, sauf si elle a le sien. */
+ const target = () => {
+ const m = monday();
+ if (tab === 1) return m;
+ return store.getState().weekPlanSettings[m] ? m : null;
+ };
+ /** @param {{days: number[], locks: Record}} settings */
+ const save = (settings) => store.dispatch("PlanSettingsChanged", { week: target(), days: settings.days, locks: settings.locks });
+
+ const paint = () => {
+ const state = store.getState();
+ const program = state.program;
+ const m = monday();
+ const settings = settingsForWeek(state, m);
+ const { plan, rows, extra } = weekRows(state, m, today());
+ const selected = new Set(settings?.days ?? []);
+
+ const tabs = h("div", { class: "segmented", role: "group", "aria-label": "Semaine affichée" },
+ ["Cette semaine", "Semaine suivante"].map((label, i) => h("button", {
+ type: "button", class: "segmented__opt", "aria-pressed": String(tab === i),
+ on: { click: () => { tab = i; lockOpen = null; status.textContent = ""; paint(); } },
+ }, label)));
+
+ const days = h("div", { class: "segmented segmented--days", role: "group", "aria-label": "Jours où je peux m'entraîner" },
+ DAY_LETTERS.map((letter, d) => h("button", {
+ type: "button", class: "segmented__opt", "aria-pressed": String(selected.has(d)), "aria-label": DAY_NAMES[d],
+ on: { click: () => {
+ const next = selected.has(d) ? [...selected].filter((x) => x !== d) : [...selected, d];
+ save(withDays(settings, next));
+ const strength = weekRows(store.getState(), m, today()).plan.slots.filter((s) => s.kind === "strength").length;
+ const need = program?.sessions.length ?? 0;
+ status.textContent = next.length === 0 ? "Aucun jour retenu."
+ : strength < need ? `${strength} séance${strength > 1 ? "s" : ""} de force sur ${need} : la rotation rattrapera la semaine suivante.`
+ : `${strength} séances de force, espacées au maximum.`;
+ } },
+ }, letter)));
+
+ /** @param {WeekRow} r */
+ const row = (r) => {
+ const label = r.slot ? slotLabel(r.slot, program) : null;
+ const title = label ? label.title : r.lock === "rest" ? "Repos imposé" : r.available ? "Libre" : "Off";
+ let detail = label ? label.detail : r.lock === "rest" ? "" : r.available ? "disponible, rien à placer" : "";
+ if (r.lock && r.slot) detail += " · imposé";
+ if (r.status?.done && r.status.shifted && r.status.date) detail += ` · faite ${dayName(r.status.date)}`;
+ const state = r.status?.done ? "✓ Fait" : r.skipped ? "✕ Non fait" : "";
+ const mark = r.slot?.kind === "strength" && label?.key
+ ? plaque(label.key, label.color, "plaque plaque--sm")
+ : h("span", { class: "plaque plaque--sm plaque--empty", "aria-hidden": "true" }, r.slot ? (r.slot.kind === "cardio" ? "C" : "A") : "·");
+ const actions = r.actions.map((a) => h("button", {
+ type: "button", class: "btn btn--sm",
+ on: { click: (/** @type {Event} */ e) => { e.stopPropagation(); void act(a, r); } },
+ }, ACTION_LABELS[a]));
+ const head = h("button", {
+ type: "button", class: "week__day", "aria-expanded": String(lockOpen === r.day),
+ "aria-label": `${DAY_NAMES[r.day]} ${shortDay(r.date)} : ${title}${detail ? ", " + detail : ""}${state ? ", " + state : ""}. Choisir ce que porte ce jour.`,
+ on: { click: () => { lockOpen = lockOpen === r.day ? null : r.day; paint(); } },
+ },
+ h("span", { class: "row__day" }, h("span", { class: "mark" }, DAY_SHORT[r.day]), h("span", { class: "num" }, r.date.slice(8))),
+ mark,
+ h("span", { class: "row__main" }, h("span", { class: "row__title" }, title), detail && h("span", { class: "row__meta" }, detail)),
+ state && h("span", { class: "row__side mark" }, state));
+ return h("li", { class: `week__row${r.isToday ? " week__row--today" : ""}` },
+ h("div", { class: "row" }, head, actions.length > 0 && h("span", { class: "row__actions" }, actions)),
+ lockOpen === r.day && h("div", { class: "choice-list", role: "group", "aria-label": `Ce que porte ${DAY_NAMES[r.day]}` },
+ lockOptions(program).map((o) => h("button", {
+ type: "button", class: "choice", "aria-pressed": String((r.lock ?? "") === o.value),
+ on: { click: () => {
+ save(withLock(settings, r.day, o.value));
+ status.textContent = `${DAY_NAMES[r.day]} : ${o.label.toLowerCase()}.`;
+ lockOpen = null;
+ paint();
+ } },
+ }, o.label))));
+ };
+
+ replace(zone,
+ tabs,
+ h("p", { class: "mark week__range" }, `${mediumDay(m)} → ${mediumDay(addDays(m, 6))}`, plan.isOverride ? " · réglage propre à cette semaine" : ""),
+ h("h2", { class: "tape" }, "Jours dispo"),
+ days,
+ status,
+ !program && h("p", { class: "coach-note coach-note--plain" }, "Pas encore de programme : les jours sont gardés, les séances viendront avec le programme."),
+ h("h2", { class: "tape" }, "Planning", h("span", { class: "tape__hint" }, "touche un jour pour l'imposer")),
+ settings
+ ? h("ul", { class: "rows week__rows" }, rows.map(row))
+ : h("p", { class: "empty" }, tab === 1 ? "Choisis les jours de la semaine suivante ci-dessus." : "Choisis tes jours ci-dessus : les séances se placent toutes seules."),
+ extra.length > 0 && h("p", { class: "muted" }, `En plus du planning : ${extra.map((s) => s.name).join(", ")}.`),
+ h("p", { class: "muted" }, tab === 1
+ ? "Ces réglages ne valent que pour la semaine suivante. La rotation poursuit celle de cette semaine."
+ : "« Non fait » marque un créneau manqué sans toucher à ton historique."));
+ };
+
+ /** @param {"done"|"skip"|"unskip"|"remove"} action @param {WeekRow} r */
+ const act = async (action, r) => {
+ const state = store.getState();
+ const slot = /** @type {import("../../domain/planning.js").Slot} */ (r.slot);
+ if (action === "skip") store.dispatch("DaySkipped", { date: r.date });
+ else if (action === "unskip") store.dispatch("DayUnskipped", { date: r.date });
+ else if (action === "done") {
+ if (slot.kind === "strength") {
+ nav.go(href.session(/** @type {string} */ (slot.sessionKey), r.date === today() ? null : r.date));
+ return;
+ }
+ const data = loggedForSlot(slot, state.program, r.date);
+ store.dispatch("SessionLogged", data);
+ toast(`${data.name} : fait le ${shortDay(r.date)}.`);
+ } else if (action === "remove") {
+ const session = r.status ? sessionForSlot(state, slot, r.status) : null;
+ if (!session) return;
+ const ok = await confirmDialog({
+ title: "Retirer cette séance ?",
+ lines: [`${session.name}, ${mediumDay(session.date)}.`, "Elle disparaît de l'historique et des calculs."],
+ confirm: "Retirer", cancel: "Garder", danger: true,
+ });
+ if (ok) store.dispatch("SessionDeleted", { sessionId: session.id });
+ }
+ };
+
+ // ---- export .ics --------------------------------------------------------------
+ const time = h("input", { id: "ics-time", class: "field__input", type: "time", value: "18:00", step: "900" });
+ const exportIcs = () => {
+ const [hour, minute] = (time.value || "18:00").split(":").map(Number);
+ const state = store.getState();
+ const { plan } = weekRows(state, monday(), today());
+ download(`ia-fit-semaine-${plan.monday}.ics`, buildIcs(state, plan, { hour, minute, now: new Date() }), "text/calendar;charset=utf-8");
+ toast("Agenda téléchargé.");
+ };
+
+ paint();
+ const node = h("div", { class: "screen" },
+ screenHeader({ back: { label: "Accueil", onClick: () => nav.back(href.home()) }, kicker: "Planning", title: "Semaine" }),
+ zone,
+ h("h2", { class: "tape" }, "Agenda"),
+ h("div", { class: "field field--inline" }, h("label", { class: "field__label", for: "ics-time" }, "Départ à"), time),
+ h("button", { type: "button", class: "btn btn--block", on: { click: exportIcs } }, "Télécharger le .ics"),
+ h("p", { class: "muted" }, "Un événement par créneau à faire, avec un rappel 30 minutes avant."));
+ return { node, title: "Semaine", destroy: store.subscribe(paintWhenIdle(zone, paint)) };
+}
+
+/** @type {Record} */
+const ACTION_LABELS = { done: "Faite", skip: "Non fait", unskip: "Annuler", remove: "Retirer" };
diff --git a/app/ui/screens/weight.js b/app/ui/screens/weight.js
new file mode 100644
index 0000000..748d3f7
--- /dev/null
+++ b/app/ui/screens/weight.js
@@ -0,0 +1,147 @@
+// Poids : pesée, courbe (3 mois, 1 an, tout), tendance, repères, import en
+// texte libre et liste. Calculs du domaine : weight.js.
+
+import { h, replace } from "../dom.js";
+import { addDays, daysBetween } from "../../domain/dates.js";
+import { parseWeightLines, weightMilestones, weightTrend } from "../../domain/weight.js";
+import { dec1, durationLabel, kg, mediumDay, parseAmount, plural, shortDay } from "../format.js";
+import { screenHeader } from "../layout.js";
+import { href } from "../router.js";
+import { lineChart } from "../chart.js";
+import { toast } from "../feedback.js";
+
+/** Périodes de la courbe, en jours (Infinity : tout). */
+const PERIODS = [{ days: 90, label: "3 mois" }, { days: 365, label: "1 an" }, { days: Infinity, label: "Tout" }];
+
+/**
+ * @param {{store: import("../store.js").Store, nav: import("../router.js").Navigation, today: () => string}} ctx
+ * @returns {import("../router.js").Screen}
+ */
+export function weightScreen({ store, nav, today }) {
+ let period = 90;
+ const summary = h("div");
+ const chartZone = h("div");
+ const milestones = h("div");
+ const list = h("div");
+
+ // ---- pesée ----------------------------------------------------------------------
+ const date = h("input", { id: "w-date", class: "field__input", type: "date", max: today(), value: today() });
+ const amount = h("input", { id: "w-kg", class: "field__input field__input--big", type: "text", inputmode: "decimal", autocomplete: "off", placeholder: "—" });
+ const status = h("p", { class: "status", role: "status", "aria-live": "polite" });
+ const add = () => {
+ const v = parseAmount(amount.value);
+ status.className = "status status--err";
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date.value) || date.value > today()) { status.textContent = "Date invalide."; return; }
+ if (typeof v !== "number" || v < 20 || v > 400) { status.textContent = "Poids invalide (20 à 400 kg)."; return; }
+ store.dispatch("WeightRecorded", { date: date.value, kg: v });
+ status.className = "status status--ok";
+ status.textContent = `${kg(v)} kg le ${shortDay(date.value)}.`;
+ amount.value = "";
+ };
+ amount.addEventListener("keydown", (e) => { if (e.key === "Enter") add(); });
+
+ // ---- import en texte libre ------------------------------------------------------
+ const text = h("textarea", { id: "w-import", class: "field__input field__input--area field__input--mono", placeholder: "2026-11-02 82,4\n09/11/2026 ; 82,1" });
+ const report = h("div", { class: "import-report" });
+ const read = () => {
+ const { entries, rejected } = parseWeightLines(text.value);
+ if (!entries.length && !rejected.length) { replace(report, h("p", { class: "status status--err" }, "Colle d'abord tes pesées.")); return; }
+ replace(report,
+ h("p", { class: entries.length ? "status status--ok" : "status status--err" },
+ entries.length ? `${plural(entries.length, "pesée")} lisible${entries.length > 1 ? "s" : ""}.` : "Aucune ligne lisible : une date puis un poids par ligne."),
+ rejected.length > 0 && [h("p", { class: "muted" }, `${plural(rejected.length, "ligne")} ignorée${rejected.length > 1 ? "s" : ""} :`),
+ h("ul", { class: "mono-list" }, rejected.slice(0, 5).map((l) => h("li", null, l)))],
+ entries.length > 0 && h("button", { type: "button", class: "btn btn--primary btn--block", on: { click: () => {
+ for (const e of entries) store.dispatch("WeightRecorded", e);
+ toast(`${plural(entries.length, "pesée")} importée${entries.length > 1 ? "s" : ""}.`);
+ text.value = "";
+ replace(report);
+ } } }, `Importer ${plural(entries.length, "pesée")}`));
+ };
+
+ const paint = () => {
+ const weights = store.getState().weights;
+ const last = weights[weights.length - 1];
+ const trend = weightTrend(weights, { today: today() });
+ const sens = !trend ? "" : trend.kgPerWeek < -0.05 ? "en baisse" : trend.kgPerWeek > 0.05 ? "en hausse" : "stable";
+ replace(summary, last
+ ? h("div", { class: "stats" },
+ h("div", { class: "stat" }, h("span", { class: "stat__value" }, kg(last.kg), h("small", null, "kg")), h("span", { class: "stat__label" }, `le ${shortDay(last.date)}`)),
+ h("div", { class: "stat" },
+ h("span", { class: "stat__value" }, trend ? `${trend.kgPerWeek > 0 ? "+" : ""}${dec1(trend.kgPerWeek)}` : "—", trend && h("small", null, "kg/sem")),
+ h("span", { class: "stat__label" }, trend ? `${sens} · 8 semaines` : "tendance : 2 pesées")))
+ : h("p", { class: "empty" }, "Aucune pesée pour l'instant. Saisis la première."));
+ if (trend?.staleDays && trend.staleDays > 14) summary.append(h("p", { class: "muted" }, `Dernière pesée il y a ${durationLabel(trend.staleDays)}.`));
+
+ // Courbe
+ const from = period === Infinity ? "" : addDays(today(), -period);
+ const inPeriod = weights.filter((w) => w.date >= from);
+ const pts = inPeriod.length > 1 ? inPeriod : weights;
+ replace(chartZone,
+ h("div", { class: "segmented", role: "group", "aria-label": "Période de la courbe" }, PERIODS.map((p) =>
+ h("button", { type: "button", class: "segmented__opt", "aria-pressed": String(p.days === period), on: { click: () => { period = p.days; paint(); } } }, p.label))),
+ pts.length > 1
+ ? h("figure", { class: "chart" },
+ lineChart({
+ points: pts.map((w) => ({ x: daysBetween(pts[0].date, w.date), y: w.kg })),
+ label: `Courbe du poids, du ${mediumDay(pts[0].date)} au ${mediumDay(pts[pts.length - 1].date)}`,
+ format: (v) => dec1(v), xLabels: [shortDay(pts[0].date), shortDay(pts[pts.length - 1].date)], minSpan: 1.2,
+ }),
+ inPeriod.length < 2 && h("figcaption", { class: "chart__caption" }, "Pas assez de pesées sur la période : tout l'historique."))
+ : h("p", { class: "empty" }, "Deux pesées suffisent pour tracer la courbe."));
+
+ // Repères
+ const m = weightMilestones(weights);
+ replace(milestones, m
+ ? h("ul", { class: "rows" },
+ h("li", { class: "row" }, h("span", { class: "row__main" },
+ m.lastBelow
+ ? [h("span", { class: "row__title" }, `La dernière fois sous ${kg(m.current.kg)} kg`),
+ h("span", { class: "row__meta" }, `Le ${mediumDay(m.lastBelow.date)}, à ${kg(m.lastBelow.kg)} kg : il y a ${durationLabel(/** @type {number} */ (m.daysSinceLastBelow))}.`)]
+ : [h("span", { class: "row__title" }, "Ton point le plus bas"),
+ h("span", { class: "row__meta" }, `${kg(m.current.kg)} kg : aucune pesée enregistrée n'est plus basse.`)])),
+ m.minimum.date !== m.current.date && h("li", { class: "row" }, h("span", { class: "row__main" },
+ h("span", { class: "row__title" }, `Minimum : ${kg(m.minimum.kg)} kg`),
+ h("span", { class: "row__meta" }, `Le ${mediumDay(m.minimum.date)}, il y a ${durationLabel(m.daysSinceMinimum)}. ${dec1(m.current.kg - m.minimum.kg)} kg au-dessus aujourd'hui.`))))
+ : h("p", { class: "muted" }, "Les repères viennent avec deux pesées."));
+
+ // Liste
+ const recent = [...weights].reverse().slice(0, 40);
+ replace(list, recent.length
+ ? h("ul", { class: "rows" }, recent.map((w, i) => {
+ const prev = recent[i + 1];
+ const delta = prev ? w.kg - prev.kg : null;
+ return h("li", { class: "row" },
+ h("span", { class: "row__main" }, h("span", { class: "row__title" }, mediumDay(w.date)),
+ delta !== null && h("span", { class: "row__meta" }, `${delta > 0 ? "+" : ""}${dec1(delta)} kg`)),
+ h("span", { class: "row__side num weight__kg" }, kg(w.kg)),
+ h("button", { type: "button", class: "btn btn--sm btn--ghost", "aria-label": `Supprimer la pesée du ${mediumDay(w.date)}`, on: { click: () => store.dispatch("WeightDeleted", { date: w.date }) } }, "✕"));
+ }))
+ : null);
+ };
+ paint();
+
+ const node = h("div", { class: "screen" },
+ screenHeader({ back: { label: "Accueil", onClick: () => nav.back(href.home()) }, kicker: "Suivi", title: "Poids" }),
+ summary,
+ h("h2", { class: "tape" }, "Pesée"),
+ h("div", { class: "field-pair" },
+ h("div", { class: "field" }, h("label", { class: "field__label", for: "w-kg" }, "Poids (kg)"), amount),
+ h("div", { class: "field" }, h("label", { class: "field__label", for: "w-date" }, "Date"), date)),
+ h("button", { type: "button", class: "btn btn--primary btn--block", on: { click: add } }, "Enregistrer"),
+ status,
+ h("h2", { class: "tape" }, "Courbe"),
+ chartZone,
+ h("h2", { class: "tape" }, "Repères"),
+ milestones,
+ h("h2", { class: "tape" }, "Pesées"),
+ list,
+ h("details", { class: "import" },
+ h("summary", { class: "btn btn--ghost btn--block" }, "Importer des pesées"),
+ h("div", { class: "field" }, h("label", { class: "field__label", for: "w-import" }, "Une pesée par ligne : date puis poids"), text),
+ h("button", { type: "button", class: "btn btn--block", on: { click: read } }, "Lire"),
+ report));
+ // Les champs (pesée, import) ne sont jamais dans une zone repeinte : on repeint tout de suite.
+ return { node, title: "Poids", destroy: store.subscribe(paint) };
+}
+
diff --git a/app/ui/session-draft.js b/app/ui/session-draft.js
index 521233a..6761f10 100644
--- a/app/ui/session-draft.js
+++ b/app/ui/session-draft.js
@@ -19,7 +19,13 @@ import { resolveExercise, exerciseKey, trackingFor, targetSeconds } from "../dom
* @property {TrackingMode} tracking
* @property {number|null} loadKg charge du jour (modes avec charge)
* @property {number|null} seconds durée d'une série (modes au temps)
- * @property {(LoggedSet|null)[]} done une case par série prévue, null tant qu'elle n'est pas faite
+ * @property {(DraftSet|null)[]} done une case par série prévue, null tant qu'elle n'est pas faite
+ */
+
+/**
+ * Série faite dans le brouillon : `n` est son rang de validation dans la séance
+ * (pour le combo), absent des brouillons plus anciens.
+ * @typedef {LoggedSet & {n?: number}} DraftSet
*/
/**
@@ -94,12 +100,16 @@ export function createDraft(session, state, date, warmupSteps) {
export function draftMatches(draft, session, warmupSteps) {
const d = /** @type {any} */ (draft);
if (!d || d.sessionKey !== session.key || !Array.isArray(d.exercises) || !Array.isArray(d.warmup)) return false;
- if (d.warmup.length !== warmupSteps || d.exercises.length !== session.exercises.length) return false;
- return session.exercises.every((item, i) => {
+ if (d.exercises.length !== session.exercises.length) return false;
+ const ok = session.exercises.every((item, i) => {
const ex = resolveExercise(item);
const x = d.exercises[i];
return x && x.id === ex.id && Array.isArray(x.done) && x.done.length === ex.sets;
});
+ // Le nombre d'étapes d'échauffement suit la charge saisie (séries d'approche) :
+ // un écart ne fait pas perdre la séance, les cases sont ajustées.
+ if (ok && d.warmup.length !== warmupSteps) d.warmup = Array.from({ length: warmupSteps }, (_, i) => d.warmup[i] === true);
+ return ok;
}
/**
@@ -138,6 +148,46 @@ export function proposedReps(ex, index) {
return targetReps(ex.reps)?.high ?? 0;
}
+/**
+ * Valide une série : elle prend le rang suivant dans la séance.
+ * @param {Draft} draft
+ * @param {DraftExercise} ex
+ * @param {number} index
+ * @param {LoggedSet} set
+ */
+export function markSet(draft, ex, index, set) {
+ const n = 1 + Math.max(0, ...draft.exercises.flatMap((x) => x.done.map((s) => s?.n ?? 0)));
+ ex.done[index] = { reps: set.reps, effort: set.effort, n };
+}
+
+/**
+ * Les séries faites, dans l'ordre où elles ont été validées (à défaut, dans
+ * l'ordre de la séance).
+ * @param {Draft} draft
+ * @returns {LoggedSet[]}
+ */
+export function setsInOrder(draft) {
+ const all = draft.exercises.flatMap((x) => x.done.filter((s) => s !== null));
+ return /** @type {DraftSet[]} */ (all).map((s, i) => ({ s, k: s.n ?? i / 1000 })).sort((a, b) => a.k - b.k).map(({ s }) => s);
+}
+
+/**
+ * Résumé chiffré du brouillon, pour l'écran de fin : séries, répétitions et
+ * volume (répétitions × charge).
+ * @param {Draft} draft
+ */
+export function draftTotals(draft) {
+ let sets = 0, reps = 0, volumeKg = 0;
+ for (const ex of draft.exercises)
+ for (const s of ex.done) {
+ if (!s) continue;
+ sets++;
+ reps += s.reps ?? 0;
+ if (usesLoad(ex.tracking) && ex.loadKg) volumeKg += (s.reps ?? 0) * ex.loadKg;
+ }
+ return { sets, reps, volumeKg };
+}
+
/** @param {DraftExercise} ex */
export const doneCount = (ex) => ex.done.filter((s) => s !== null).length;
diff --git a/app/ui/theme-pref.js b/app/ui/theme-pref.js
new file mode 100644
index 0000000..275c554
--- /dev/null
+++ b/app/ui/theme-pref.js
@@ -0,0 +1,35 @@
+// Thème choisi sur cet appareil : « auto » (celui du système), « dark » ou
+// « light ». Préférence d'affichage, gardée dans le stockage local, jamais un
+// événement. theme.js (script classique, chargé avant le premier affichage)
+// lit la même clé pour éviter un flash de l'autre thème.
+
+const KEY = "ia-fit.theme";
+
+/** @returns {"auto"|"dark"|"light"} */
+export function getTheme() {
+ try {
+ const v = localStorage.getItem(KEY);
+ return v === "dark" || v === "light" ? v : "auto";
+ } catch {
+ return "auto";
+ }
+}
+
+/** @param {"auto"|"dark"|"light"} theme */
+export function setTheme(theme) {
+ try {
+ if (theme === "auto") localStorage.removeItem(KEY);
+ else localStorage.setItem(KEY, theme);
+ } catch {
+ // stockage interdit : le choix vaut pour cette visite
+ }
+ applyTheme(theme);
+}
+
+/** @param {"auto"|"dark"|"light"} theme */
+export function applyTheme(theme) {
+ if (theme === "auto") document.documentElement.removeAttribute("data-theme");
+ else document.documentElement.setAttribute("data-theme", theme);
+ const dark = theme === "dark" || (theme === "auto" && !matchMedia("(prefers-color-scheme: light)").matches);
+ for (const meta of document.querySelectorAll('meta[name="theme-color"]')) meta.setAttribute("content", dark ? "#000000" : "#F2F2EC");
+}
diff --git a/app/ui/theme.js b/app/ui/theme.js
new file mode 100644
index 0000000..f2b269a
--- /dev/null
+++ b/app/ui/theme.js
@@ -0,0 +1,12 @@
+// Script classique (pas un module), chargé dans avant le premier
+// affichage : il pose le thème choisi sur cet appareil (voir theme-pref.js)
+// sans attendre les modules, donc sans flash de l'autre thème. Aucun script en
+// ligne : la CSP stricte l'interdit.
+(function () {
+ try {
+ var theme = localStorage.getItem("ia-fit.theme");
+ if (theme === "dark" || theme === "light") document.documentElement.setAttribute("data-theme", theme);
+ } catch (e) {
+ // stockage interdit : thème du système
+ }
+})();
diff --git a/app/ui/warmup-card.js b/app/ui/warmup-card.js
index 59ada2c..2063e7a 100644
--- a/app/ui/warmup-card.js
+++ b/app/ui/warmup-card.js
@@ -1,25 +1,38 @@
-// L'échauffement guidé, en tête de séance. Glossaire : docs/glossaire/echauffement.md
-//
-// À brancher : warmup.warmupPlan (domaine, sous-lot 1b) calculera les étapes et
-// les séries d'approche à partir de la charge de travail du premier exercice.
-// En attendant, les étapes de mobilité sont codées ici (reprises d'Atelier) et
-// les séries d'approche ne sont pas chiffrées.
+// L'échauffement guidé, en tête de séance : un peu de cardio, la mobilité
+// (warmup.MOBILITY), puis les séries d'approche du premier exercice, chiffrées à
+// partir de sa charge de travail (warmup.warmupPlan).
+// Glossaire : docs/glossaire/echauffement.md, docs/glossaire/approche.md
import { h } from "./dom.js";
import { restLabel } from "./format.js";
+import { MOBILITY, warmupPlan } from "../domain/warmup.js";
-/** @typedef {{title: string, detail: string, seconds: number}} WarmupStep */
+/** @typedef {{title: string, detail: string, seconds: number|null, approach: boolean}} WarmupStep */
-/** @type {WarmupStep[]} */
-export const WARMUP_STEPS = [
- { title: "Vélo, marche ou corde légère", detail: "Allure tranquille, juste de quoi avoir chaud et le souffle un peu plus court.", seconds: 360 },
- { title: "Cercles de bras et rotations d'épaules", detail: "Bras tendus, 10 cercles en avant puis 10 en arrière. Puis les épaules qui montent et descendent.", seconds: 45 },
- { title: "Balancements de jambe", detail: "Appuie-toi au mur. 10 balancements avant-arrière par jambe, puis 10 latéraux.", seconds: 60 },
- { title: "Squats au poids du corps", detail: "10 répétitions, descente lente, en cherchant un peu plus de profondeur à chaque fois.", seconds: 60 },
-];
+/** Mise en route, avant la mobilité (reprise d'Atelier). */
+const GENERAL = { title: "Vélo, marche ou corde légère", detail: "Allure tranquille, juste de quoi avoir chaud et le souffle un peu plus court.", seconds: 360 };
/**
- * @param {{done: boolean[], timer: import("./timer.js").Timer, onChange: () => void, open: boolean}} o
+ * Les étapes de l'échauffement d'une séance.
+ * @param {import("../domain/state.js").State} state
+ * @param {import("../domain/program.js").ProgramSession} session
+ * @returns {{steps: WarmupStep[], exerciseName: string|null, note: string|null}}
+ */
+export function warmupSteps(state, session) {
+ const plan = warmupPlan(state, session);
+ return {
+ steps: [
+ { ...GENERAL, approach: false },
+ ...MOBILITY.map((m) => ({ ...m, approach: false })),
+ ...(plan?.lines ?? []).map((l) => ({ title: l.title, detail: l.detail, seconds: null, approach: true })),
+ ],
+ exerciseName: plan?.exerciseName ?? null,
+ note: plan?.note ?? null,
+ };
+}
+
+/**
+ * @param {{plan: ReturnType, done: boolean[], timer: import("./timer.js").Timer, onChange: () => void, open: boolean}} o
* done : étapes cochées, modifié sur place
*/
export function warmupCard(o) {
@@ -30,11 +43,9 @@ export function warmupCard(o) {
count.classList.toggle("exercise__count--done", n === o.done.length);
};
- const steps = WARMUP_STEPS.map((step, i) => {
- const tick = h("button", {
- type: "button", class: "tick", "aria-pressed": String(o.done[i]),
- "aria-label": `Fait : ${step.title}`,
- });
+ /** @param {WarmupStep} step @param {number} i */
+ const row = (step, i) => {
+ const tick = h("button", { type: "button", class: "tick", "aria-pressed": String(!!o.done[i]), "aria-label": `Fait : ${step.title}` });
tick.addEventListener("click", () => {
o.done[i] = !o.done[i];
tick.setAttribute("aria-pressed", String(o.done[i]));
@@ -44,25 +55,29 @@ export function warmupCard(o) {
return h("li", { class: "step" },
tick,
h("div", { class: "step__text" }, h("strong", null, step.title), h("span", null, step.detail)),
- h("button", {
+ step.seconds && h("button", {
type: "button", class: "btn btn--sm step__go", "aria-label": `Lancer ${restLabel(step.seconds)} : ${step.title}`,
- on: { click: () => o.timer.startRest(step.seconds, step.title, "Étape terminée") },
+ on: { click: () => o.timer.startRest(/** @type {number} */ (step.seconds), step.title, "Étape terminée") },
}, restLabel(step.seconds)));
- });
+ };
+ const steps = o.plan.steps;
+ const general = steps.filter((s) => !s.approach);
+ const approach = steps.filter((s) => s.approach);
const card = h("details", { class: "exercise exercise--warmup", open: o.open },
h("summary", { class: "exercise__head" },
- h("span", { class: "badge badge--warmup", "aria-hidden": "true" }, "0"),
+ h("span", { class: "badge", "aria-hidden": "true" }, "0"),
h("span", { class: "exercise__name" },
h("strong", null, "Échauffement"),
- h("span", { class: "exercise__sub" }, "À faire en premier · environ 10 min")),
+ h("span", { class: "exercise__sub" }, "En premier · environ 10 min")),
count,
h("span", { class: "chevron", "aria-hidden": "true" })),
h("div", { class: "exercise__body" },
- h("ol", { class: "steps" }, steps),
- h("h3", { class: "mini-label" }, "Séries d'approche"),
- h("p", { class: "muted" },
- "Monte progressivement jusqu'à ta charge du jour sur le premier exercice. Le calcul chiffré des séries d'approche arrive bientôt.")));
+ h("ol", { class: "steps" }, general.map((s, i) => row(s, i))),
+ approach.length > 0 && [
+ h("h3", { class: "mini-label" }, `Séries d'approche · ${o.plan.exerciseName ?? ""}`),
+ h("ol", { class: "steps" }, approach.map((s, i) => row(s, general.length + i)))],
+ o.plan.note && h("p", { class: "coach-note" }, o.plan.note)));
refresh();
return card;
}
diff --git a/docs/design.md b/docs/design.md
index f5a189f..e126b9a 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -1,89 +1,164 @@
-# Design
+# Design : « fonte brute »
-L'identité d'Atelier, « fonte et craie », reprise et rendue plus lisible : fond
-sombre couleur de fonte, texte couleur de craie, titres en capitales condensées,
-une couleur par séance. Pas d'illustration (ADR 0004). Les styles sont dans
-`app/styles/`, les jetons dans `app/styles/tokens.css`.
+Seconde version de l'identité, après le retour du porteur du projet sur la première
+(« ça ressemble beaucoup à du Claude ») : de l'anti-design simple et carré, le langage
+d'une salle de fonte, quelques codes du jeu vidéo, et le moins d'octets possible.
+Les styles sont dans `app/styles/`, les jetons dans `app/styles/tokens.css`. Pas
+d'illustration (ADR 0004).
-## Règles
+## Principes
-- **Contraste AA partout** : 4,5:1 minimum pour le texte, 3:1 pour le bord des
- contrôles. Toute nouvelle couleur passe par un jeton, avec son ratio noté.
-- **Deux thèmes** : sombre par défaut, clair si le système le demande
- (`prefers-color-scheme`). Les composants n'utilisent que des jetons.
-- **D'une main, à la salle** : cibles tactiles de 44 px minimum (48 px par défaut),
- action principale dans une barre collée en bas de l'écran (`.action-bar`), le
- minuteur s'empile sous cette barre.
-- **Chiffres tabulaires** (`font-variant-numeric: tabular-nums`) pour les charges,
- les répétitions et le chrono.
-- **Hiérarchie** : la carte du jour (`.card--today`) domine l'accueil ; un écran a
- un seul titre `h1`.
-- **Aucun style en ligne, aucun script en ligne** (CSP stricte au sous-lot 1f).
- Seule exception, par le CSSOM : la couleur d'une séance, donnée du programme,
- posée en variables `--accent` et `--accent-ink` (`setAccent`). La couleur du
- texte posé dessus est calculée (`inkOn`) pour rester lisible (test : AA).
-- **La couleur ne porte jamais seule une information** : le ressenti d'une série
- est aussi dans son libellé (`aria-label`).
-- **Polices** : Barlow Condensed auto-hébergée (500, 600, 700 ; sous-ensemble latin ;
- SIL OFL 1.1, `app/fonts/OFL.txt`) pour les titres et les libellés ; police
- système pour le texte courant. Aucune ressource tierce.
-- **Mouvement** : transitions courtes, coupées si `prefers-reduced-motion`.
+1. **Carré et franc.** Angles droits partout (`border-radius: 0`), bordures pleines
+ de 3 px (6 px sous un titre, autour de la carte du jour et de la barre d'action).
+ Aucun dégradé, aucune ombre, aucune carte qui « flotte » : un bloc est délimité
+ par son trait.
+2. **La grille se voit.** Les listes sont des lignes séparées par un trait ; les
+ choix (jours, ressenti, modes) et la grille de navigation sont des cases collées
+ dont les joints sont l'encre elle-même (`gap` sur fond d'encre).
+3. **Peu de couleurs.** Noir, blanc cassé, des gris, et **une** couleur signal : le
+ jaune « ruban de salle ». Seule exception : la couleur de chaque séance (donnée du
+ programme), réduite à sa plaque.
+4. **Les chiffres d'abord.** Charges, répétitions et chrono sont énormes, en fonte
+ condensée : on les lit à un mètre, la barre dans les mains.
+5. **Textes courts et impératifs.** « Commencer », « Pas aujourd'hui », « Faire »,
+ « Adopter ». Une phrase d'aide au plus.
+6. **Sobre.** Une seule fonte, aucune image matricielle, aucune animation
+ permanente, aucun appel réseau en tâche de fond.
+
+## Codes de la salle (par la typographie et les bordures, jamais par des images)
+
+| Code | Traduction dans l'interface |
+| --- | --- |
+| Plaque de disque | `.plaque` : la lettre de la séance, énorme, sur sa couleur, dans un carré cerclé d'encre |
+| Chiffres de barre | `.num`, `.big-number`, `.stepper__value`, `.timer__time` : fonte condensée, chiffres tabulaires, 60 à 136 px |
+| Marquage industriel, pochoir | `.mark`, `.kicker`, libellés : chasse fixe du système, capitales, interlettrage, comme un chiffre frappé |
+| Ruban adhésif | `.tape` : le titre de section, aplat jaune, texte noir |
+| Rack, casiers | `.grid-nav`, `.segmented`, `.stats` : cases collées, joints visibles |
+
+## Codes du jeu vidéo, avec mesure
+
+Tout passe par `app/ui/game.js`, qui seul appelle `app/domain/gamification.js` (les
+règles et le barème y sont). L'interface ne fait qu'afficher.
+
+| Code | Où |
+| --- | --- |
+| Niveau, titre, barre d'XP | HUD en tête de l'accueil (`.hud`), lien vers l'écran Progression. La barre est en 20 cases, pas en dégradé |
+| Série de semaines (streak) | HUD et Progression : semaines atteintes d'affilée, « en jeu » tant que la semaine en cours n'est pas finie |
+| Combo | Barre d'action de la séance : « Combo ×4 » dès deux séries validées d'affilée ; une série « échec » le remet à zéro |
+| Moment endorphine | Écran de fin de séance (`#/bravo`) : le grand chiffre (kg soulevés, sinon séries), l'XP qui monte en moins d'une seconde, le décompte, la jauge du niveau, « Niveau supérieur ! » |
+| « RECORD ! » | Tampon qui s'imprime une fois, d'un coup sec (3 pas, 0,22 s), puis la liste des records battus |
+| Succès | Débloqués à la fin d'une séance, et tous listés dans Progression (les verrouillés en gris) |
+
+**Garde-fous** : jamais de récompense à l'échec (une série notée « échec » est
+rayée en pointillés, jamais mise en valeur, et casse le combo) ; aucune incitation à
+dépasser le programme ; le repos planifié ne fait rien perdre. Les animations sont
+courtes, une seule fois, et toutes coupées par `prefers-reduced-motion` (le chiffre
+s'affiche alors directement). Aucune animation ne tourne en boucle.
## Jetons de couleur et contrastes
-Ratios WCAG mesurés (texte sur fond).
+Ratios WCAG calculés avec `app/ui/color.js` (texte sur fond).
-| Jeton | Sombre | Clair | Ratios sombre | Ratios clair |
+| Jeton | Sombre (défaut) | Clair | Ratios sombre | Ratios clair |
| --- | --- | --- | --- | --- |
-| `--bg` | #14171A | #F3F1EC | | |
-| `--surface` (cartes) | #1E2328 | #FFFFFF | | |
-| `--surface-2` (champs) | #272D33 | #E8E5DE | | |
-| `--surface-sunk` (creux) | #0E1113 | #ECE9E2 | | |
-| `--text` | #EDEAE3 | #14171A | 15,0 bg · 13,2 surface · 11,6 surface-2 | 15,9 bg · 18,0 surface · 14,3 surface-2 |
-| `--text-muted` | #A3AAB1 | #555D65 | 7,7 bg · 6,7 surface · 5,9 surface-2 · 8,1 creux | 5,9 bg · 6,7 surface · 5,3 surface-2 · 5,5 creux |
-| `--primary` | #3FA06A | #2B7A4B | 5,5 bg · 4,9 surface | 4,7 bg · 5,3 surface |
-| `--on-primary` | #0E1113 | #FFFFFF | 5,8 sur primary | 5,3 sur primary |
-| `--warn` (note du coach) | #E3B505 | #806200 | 9,3 bg · 8,2 surface | 5,1 bg · 5,7 surface |
-| `--danger` | #E0787C | #B3262C | 6,1 bg · 5,4 surface | 5,8 bg · 6,5 surface |
-| `--work` (chrono, superset) | #7FB6CB | #2E6E8A | 8,1 bg · 7,1 surface | 5,0 bg · 5,7 surface |
-| `--effort-easy` | #3FA06A | #2B7A4B | 4,9 surface | 5,3 surface |
-| `--effort-ok` | #E3B505 | #806200 | 8,2 surface | 5,7 surface |
-| `--effort-hard` | #D9762B | #A9531A | 5,0 surface | 5,3 surface |
-| `--effort-failure` | #EF6B70 | #B3262C | 5,3 surface | 6,5 surface |
-| `--line-strong` (bord des contrôles) | #6B737B | #8A857B | 3,7 bg · 3,3 surface | 3,3 bg · 3,7 surface |
-| `--line` (séparateurs décoratifs) | #333A41 | #D6D2C9 | décoratif | décoratif |
+| `--bg` | #000000 | #F2F2EC | | |
+| `--ink` (texte, traits) | #F2F2EC | #000000 | 18,7 bg · 16,1 sunk | 18,7 bg · 16,4 sunk |
+| `--muted` (texte secondaire, bord des boutons discrets) | #A3A3A3 | #555555 | 8,3 bg · 7,2 sunk | 6,6 bg · 5,8 sunk |
+| `--sunk` (champs) | #161616 | #E4E4DD | | |
+| `--signal` (aplats : ruban, bouton principal, choix actif) | #FFD60A | #FFD60A | texte noir dessus : 14,9 | texte noir dessus : 14,9 |
+| `--on-signal` | #000000 | #000000 | 14,9 sur signal | 14,9 sur signal |
+| `--signal-edge` (bord d'un aplat signal) | #FFD60A | #000000 | | le jaune sur clair ferait 1,3:1 : l'aplat reçoit un bord noir |
+| `--meter` (jauges : XP, semaine, minuteur) | #FFD60A (14,9) | #000000 (18,7) | | |
+| `--focus` (anneau de focus, 3 px) | #FFD60A (14,9) | #000000 (18,7) | | |
+| `--rule-soft` (filets décoratifs seulement) | #5C5C5C (3,1) | #8F8F8F (2,9) | décoratif | décoratif |
-Pour mémoire, le gris secondaire d'Atelier (#5C646C sur #14171A) faisait 3,0:1 ; le
-nouveau `--text-muted` fait 7,7:1. Les couleurs de séance du programme d'exemple
-reçoivent un texte à 4,6 (bleu A), 9,8 (jaune B) et 5,1 (rouge C).
+Règles :
+- le jaune n'est **jamais** une couleur de texte sur fond clair : c'est un aplat, avec
+ du texte noir ;
+- le bord d'un contrôle est en `--ink` (18,7) ou `--muted` (≥ 5,8), jamais en
+ `--rule-soft` ;
+- la couleur ne porte jamais seule une information : le ressenti d'une série est
+ écrit sous le nombre de répétitions (« facile », « ok », « dur », « échec ») et dans
+ son `aria-label` ; une série en échec est en plus rayée ; un jour non fait porte
+ « ✕ Non fait » ;
+- couleurs de séance (programme) : texte noir ou blanc choisi par `inkOn` (test AA) ;
+ séances du programme d'exemple : 5,1 (bleu A), 10,9 (jaune B), 5,0 (rouge C).
-## Typographie et tailles
+## Typographie
-- `--font-display` : Barlow Condensed, capitales, interlettrage 0,1 à 0,16 em pour
- les surtitres et libellés ; 700 pour les titres.
-- `--font-body` : police système, 16 px, interligne 1,5.
-- Échelle : 13, 14, 16, 20, 28, 36, 44 px (`--fs-xs` à `--fs-3xl`).
-- Espaces : 4, 8, 12, 16, 24, 32 px (`--space-1` à `--space-6`), marge latérale
- 16 px, largeur maximale 560 px.
+- **Affichage** (`--font-display`) : Barlow Condensed **Bold**, seule fonte chargée,
+ seule graisse (SIL OFL 1.1, `app/fonts/OFL.txt`). Réduite aux caractères du français
+ (latin de base, latin-1, Œ, guillemets, tirets) : **15 Ko** (la première version
+ chargeait trois graisses, 58 Ko). Capitales, pour les titres et les grands chiffres.
+- **Marquage** (`--font-mark`) : chasse fixe du système (`ui-monospace`, SF Mono,
+ Roboto Mono, Menlo, Consolas…), capitales, 13 px, gras. 0 octet.
+- **Texte courant** (`--font-body`) : police du système, 16 px. 0 octet.
+- Échelle : 13, 15, 16, 22, 32, 44, 56 px ; chiffres 72 et 104 px ; titre d'accueil
+ 64 px. Espaces : 4, 8, 12, 16, 24, 40 px ; marge latérale 16 px ; largeur maximale
+ 560 px.
+
+## Ergonomie
+
+- **Cibles de 48 px au moins** (56 par défaut, 64 pour les actions principales et
+ les boutons ±, 72 pour les séries).
+- **D'une main** : l'action principale de chaque écran est dans la barre collée en
+ bas (`.action-bar`) ; le minuteur s'empile sous elle, en négatif (encre pleine).
+- **Thème** : sombre par défaut (noir pur : les pixels d'un écran OLED sont éteints),
+ clair si le système le demande, ou choisi dans Profil (préférence de l'appareil,
+ posée avant le premier affichage par `app/ui/theme.js`, sans script en ligne).
+- **Saisie** : on ne reconstruit jamais une zone qui contient le champ en cours de
+ saisie (`paintWhenIdle` dans `app/ui/dom.js`, piège d'Atelier).
+- **CSP stricte** : aucun style ni script en ligne, aucun `innerHTML` de données,
+ aucune ressource tierce. Seules exceptions, par le CSSOM : la couleur d'une séance
+ (`setAccent`) et l'avancement du minuteur (`--progress`).
+- Courbes (poids, charge, répétitions) en SVG dessiné par `app/ui/chart.js` : une
+ seule série par courbe, trait plein, repères carrés ; les valeurs sont aussi en
+ liste à côté.
+
+## Poids du site
+
+Mesuré par `make test-browser` (`build/shots/poids.txt`), le 18 novembre 2026 :
+
+| Mesure | Valeur |
+| --- | --- |
+| Premier chargement (onboarding) | 63 fichiers, 417 Ko bruts, **157 Ko** compressés (gzip -9) |
+| dont la fonte | 15 Ko (woff2, déjà compressée) |
+| dont le CSS (6 feuilles) | 36 Ko bruts, 10 Ko compressés |
+| Site complet (tous les fichiers de `app/`) | 433 Ko bruts, 168 Ko compressés |
+| Visites suivantes | 0 octet : tout est servi par le service worker, hors ligne |
+| Images matricielles | aucune (icônes en SVG, 0,4 Ko) |
+
+Le JavaScript domine (modules ES sans build, ADR 0007) : `gamification.js`,
+`atelier.js`, `planning.js`, `exercises.js` et `ai-brief.js` font à eux seuls 36 Ko
+compressés. Piste si le poids devient un sujet : charger à la demande les modules
+rares (`atelier.js` et `snapshot.js` à l'import, `ai-brief.js` à la copie), soit
+environ 17 Ko compressés de moins au premier chargement.
## Composants
| Composant | Rôle |
| --- | --- |
-| `.btn` (`--primary`, `--ghost`, `--danger`, `--work`, `--block`, `--lg`, `--sm`) | Bouton ; 48 px de haut, 56 px en `--lg`, 44 px en `--sm` |
-| `.action-bar` | Barre collée en bas, porte l'action principale de l'écran |
-| `.card` (`--today`, `--proposal`, `--onboarding`) | Carte ; la carte du jour porte la couleur de sa séance |
-| `.plate` | Séance dans la liste de l'accueil (barre de couleur, nom, dernière fois) |
-| `.note` | Texte court : cardio, repères |
-| `.coach-note` | Remarque du coach ou avertissement doux, filet jaune |
-| `.chip` (`--secondary`) | Muscle sollicité : plein = principal, pointillé = secondaire |
-| `.tag`, `.badge` | Lettre de superset, numéro d'exercice (couleur de séance) |
-| `.exercise` | Exercice repliable (`details`/`summary`), en-tête collant une fois ouvert |
-| `.superset` | Bloc d'exercices enchaînés, filet `--work` |
-| `.set-row`, `.set-btn` (`--done`) | Séries : 52 px, la série faite montre ses répétitions et une pastille de ressenti |
-| `.set-panel`, `.stepper`, `.effort-picker`, `.effort` | Saisie d'une série : répétitions ± et ressenti en quatre boutons |
-| `.field` (`--amount`, `--inline`, `--compact`) | Champ de saisie (charge, durée, date) |
-| `.segmented` | Choix exclusif (mode de suivi) |
-| `.timer` (`--work`, `--low`, `--zero`) | Minuteur fixé en bas : repos, ou chrono d'une série au temps |
-| `.dialog`, `.toast` | Confirmation (`