- Écran Synchro (#/synchro) : activer, « J'ai déjà une clé » (pull d'abord, faute de frappe signalée), état, clé masquée, QR code, désactiver, brancher son IA (adresse du connecteur et mode d'emploi). - Appariement #pair=<clé> : la clé quitte l'adresse aussitôt, confirmation, fusion des données locales. - Page #/connecter-ia?… : autoriser (POST /oauth/authorize) ou refuser, erreurs traduites ; le routeur accepte « ? » dans le fragment. - Synchro automatique sans scrutation (ouverture, 3 s après une saisie, online, visibilitychange), indicateur dans l'en-tête. - QR code : qrcode-generator 2.0.4 (MIT) vendorisé, dessiné en SVG par le DOM. - Magasin : dates strictement croissantes pour les événements de l'appareil (cause du flottement de test-browser : deux PlanSettingsChanged de la même milliseconde départagés par leur identifiant aléatoire). - test-browser : parcours de la synchro contre server/main.js (données temporaires), QR décodé par jsQR dans la capture. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
305 lines
15 KiB
JavaScript
305 lines
15 KiB
JavaScript
// Synchro (ADR 0005, points 2 à 5) : activer la clé, la retrouver, apparier un
|
|
// autre appareil par QR code, brancher une IA. Plus l'indicateur de l'en-tête
|
|
// et l'écran de confirmation d'un lien d'appariement (#pair=).
|
|
|
|
import { h, paintWhenIdle, replace } from "../dom.js";
|
|
import { screenHeader, actionBar } from "../layout.js";
|
|
import { href } from "../router.js";
|
|
import { confirmDialog, toast } from "../feedback.js";
|
|
import { copyText } from "../files.js";
|
|
import { plural } from "../format.js";
|
|
import { maskKey, pairUrl, syncView } from "../sync-model.js";
|
|
import { generateSyncKey, normalizeSyncKey } from "../../domain/sync-crypto.js";
|
|
|
|
/** @typedef {import("../sync-service.js").SyncService} SyncService */
|
|
|
|
/** Adresse du connecteur MCP, sur la même origine que l'app (docs/mcp.md). */
|
|
export const mcpUrl = () => `${location.origin}/mcp`;
|
|
|
|
/**
|
|
* Indicateur discret de l'en-tête : absent tant que la synchro n'est pas
|
|
* activée, puis « à jour », « en cours », « hors ligne » ou « en erreur ».
|
|
* @param {SyncService} service
|
|
*/
|
|
export function syncIndicator(service) {
|
|
const text = h("span", { class: "sync-flag__text" });
|
|
const link = h("a", { class: "sync-flag", href: href.sync() }, h("span", { class: "sync-flag__dot", "aria-hidden": "true" }), text);
|
|
const bar = h("div", { class: "topline" }, link);
|
|
const paint = () => {
|
|
const v = syncView(service.getStatus(), new Date());
|
|
bar.hidden = v.state === "off";
|
|
link.dataset.state = v.state;
|
|
text.textContent = v.label;
|
|
link.setAttribute("aria-label", `${v.label} : ouvrir l'écran Synchro`);
|
|
};
|
|
service.subscribe(paint);
|
|
paint();
|
|
return bar;
|
|
}
|
|
|
|
/**
|
|
* @param {{service: SyncService, store: import("../store.js").Store, nav: import("../router.js").Navigation}} ctx
|
|
* @returns {import("../router.js").Screen}
|
|
*/
|
|
export function syncScreen({ service, store, nav }) {
|
|
const zone = h("div");
|
|
let hasKey = !!service.getKey();
|
|
/** @type {(() => void)[]} */
|
|
let cleanups = [];
|
|
const clean = () => { cleanups.forEach((fn) => fn()); cleanups = []; };
|
|
const paint = () => {
|
|
clean();
|
|
hasKey = !!service.getKey();
|
|
replace(zone, hasKey ? withKey(service, store, cleanups) : withoutKey(service));
|
|
};
|
|
paint();
|
|
// On ne repeint tout que si la clé change ; l'état seul se met à jour dans
|
|
// son bloc (statusBlock).
|
|
const repaint = paintWhenIdle(zone, paint);
|
|
const unsubscribe = service.subscribe(() => { if (!!service.getKey() !== hasKey) repaint(); });
|
|
const node = h("div", { class: "screen" },
|
|
screenHeader({ back: { label: "Accueil", onClick: () => nav.back(href.home()) }, kicker: "Sans compte", title: "Synchro", sub: "Tes appareils et ton IA partagent ton journal, chiffré." }),
|
|
zone);
|
|
return { node, title: "Synchro", destroy: () => { unsubscribe(); clean(); } };
|
|
}
|
|
|
|
/** @param {SyncService} service */
|
|
function withoutKey(service) {
|
|
const status = h("p", { class: "status", role: "status", "aria-live": "polite" });
|
|
const busy = (/** @type {HTMLButtonElement} */ b, /** @type {boolean} */ on) => { b.disabled = on; };
|
|
|
|
const activate = async () => {
|
|
busy(start, true);
|
|
const s = await service.enable(generateSyncKey());
|
|
toast(s.error && s.error !== "offline" ? "Synchro activée, mais pas encore faite." : "Synchro activée.");
|
|
};
|
|
const start = h("button", { type: "button", class: "btn btn--primary btn--block btn--lg", on: { click: () => void activate() } }, "Activer la synchro");
|
|
|
|
const input = h("input", {
|
|
id: "sync-key", class: "field__input field__input--mono", type: "text", autocomplete: "off", autocapitalize: "characters",
|
|
spellcheck: "false", placeholder: "XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XX",
|
|
});
|
|
const link = async () => {
|
|
const key = normalizeSyncKey(input.value);
|
|
if (!key) {
|
|
input.setAttribute("aria-invalid", "true");
|
|
status.className = "status status--err";
|
|
status.textContent = "Clé invalide : 26 caractères, chiffres et lettres (sans I, L, O ni U).";
|
|
return;
|
|
}
|
|
input.removeAttribute("aria-invalid");
|
|
status.className = "status";
|
|
status.textContent = "Lecture du relais…";
|
|
busy(join, true);
|
|
let found;
|
|
try {
|
|
found = await service.probe(key);
|
|
} catch (e) {
|
|
busy(join, false);
|
|
status.className = "status status--err";
|
|
status.textContent = e instanceof Error ? e.message : String(e);
|
|
return;
|
|
}
|
|
if (!found.exists) {
|
|
const ok = await confirmDialog({
|
|
title: "Clé inconnue",
|
|
lines: ["Aucun journal ne correspond à cette clé sur le relais : une faute de frappe est probable.",
|
|
"Vérifie-la. Sinon, un nouveau journal sera créé avec cette clé et les données de cet appareil."],
|
|
confirm: "Créer un nouveau journal", cancel: "Corriger la clé",
|
|
});
|
|
if (!ok) {
|
|
busy(join, false);
|
|
status.textContent = "";
|
|
input.focus();
|
|
return;
|
|
}
|
|
}
|
|
await service.enable(key);
|
|
toast(found.added ? `Appareil relié : ${plural(found.added, "événement")} reçu${found.added > 1 ? "s" : ""}.` : "Appareil relié.");
|
|
};
|
|
const join = h("button", { type: "button", class: "btn btn--block", on: { click: () => void link() } }, "Relier avec cette clé");
|
|
|
|
return h("div", null,
|
|
h("h2", { class: "tape" }, "Comment ça marche"),
|
|
h("ul", { class: "rows sync-facts" },
|
|
fact("Sans compte", "Une clé tirée au hasard relie tes appareils et ton IA. Ni e-mail, ni mot de passe."),
|
|
fact("Chiffré", "Le serveur ne garde que des blocs chiffrés avec ta clé : il ne peut pas les lire."),
|
|
fact("Un secret", "Qui a la clé a tout : garde-la comme un mot de passe.")),
|
|
h("p", { class: "muted sync-gap" }, "Sans synchro, tout reste sur cet appareil : l'app marche aussi bien hors ligne."),
|
|
h("h2", { class: "tape" }, "J'ai déjà une clé"),
|
|
h("p", { class: "muted" }, "Celle d'un autre appareil : écran Synchro, « Afficher » puis « Copier ». Ou scanne son QR code."),
|
|
h("div", { class: "field sync-gap" }, h("label", { class: "field__label", for: "sync-key" }, "Ma clé de synchro"), input),
|
|
join,
|
|
status,
|
|
aiSection(false),
|
|
actionBar(start));
|
|
}
|
|
|
|
/**
|
|
* @param {SyncService} service
|
|
* @param {import("../store.js").Store} store
|
|
* @param {(() => void)[]} cleanups désabonnements, appelés quand la zone est repeinte
|
|
*/
|
|
function withKey(service, store, cleanups) {
|
|
const key = /** @type {string} */ (service.getKey());
|
|
|
|
// ---- état ---------------------------------------------------------------------
|
|
const state = h("p", { class: "sync-state__label" });
|
|
const detail = h("p", { class: "muted" });
|
|
const now = h("button", { type: "button", class: "btn btn--block", on: { click: () => void syncNow() } }, "Synchroniser maintenant");
|
|
const block = h("section", { class: "block sync-state", "aria-label": "État de la synchro", "aria-live": "polite" }, state, detail, now);
|
|
const paintState = () => {
|
|
const s = service.getStatus();
|
|
const v = syncView(s, new Date());
|
|
block.dataset.state = v.state;
|
|
state.textContent = v.label;
|
|
detail.textContent = v.detail;
|
|
now.disabled = s.running;
|
|
};
|
|
const syncNow = async () => {
|
|
const s = await service.syncNow();
|
|
if (!s.error) toast("Synchro faite.");
|
|
};
|
|
cleanups.push(service.subscribe(paintState));
|
|
paintState();
|
|
|
|
// ---- la clé -------------------------------------------------------------------
|
|
let shown = false;
|
|
const keyText = h("code", { class: "sync-key sync-keybox", "aria-label": "Clé de synchro, masquée" }, maskKey(key));
|
|
const show = h("button", { type: "button", class: "btn btn--block", "aria-pressed": "false" }, "Afficher");
|
|
show.addEventListener("click", () => {
|
|
shown = !shown;
|
|
keyText.textContent = shown ? key : maskKey(key);
|
|
keyText.setAttribute("aria-label", shown ? "Clé de synchro" : "Clé de synchro, masquée");
|
|
show.textContent = shown ? "Masquer" : "Afficher";
|
|
show.setAttribute("aria-pressed", String(shown));
|
|
});
|
|
const fallback = h("div", { class: "manual-copy", hidden: true });
|
|
const copy = h("button", { type: "button", class: "btn btn--block", on: { click: async () => {
|
|
if (await copyText(key, fallback, "Clé de synchro")) toast("Clé copiée. Garde-la secrète.");
|
|
} } }, "Copier la clé");
|
|
|
|
// ---- QR code (module chargé à la demande) -------------------------------------
|
|
const link = pairUrl(location.origin, key);
|
|
const qr = h("div", { class: "qr-frame" }, h("p", { class: "muted" }, "QR code…"));
|
|
import("../qr.js")
|
|
.then((m) => qr.replaceChildren(m.qrSvg(link, "QR code d'appariement : il ouvre IA-Fit et relie l'appareil à ton journal")))
|
|
.catch(() => qr.replaceChildren(h("p", { class: "status status--err" }, "QR code indisponible : recopie la clé à la main.")));
|
|
|
|
// ---- désactiver ---------------------------------------------------------------
|
|
const disable = async () => {
|
|
const ok = await confirmDialog({
|
|
title: "Désactiver ici ?",
|
|
lines: ["Cet appareil oublie la clé et ne se synchronise plus.",
|
|
`Ses données restent ici (${plural(store.getEvents().length, "événement")}), et le journal chiffré reste sur le relais pour tes autres appareils et ton IA.`,
|
|
"Note la clé avant si tu veux relier l'appareil plus tard."],
|
|
confirm: "Désactiver", cancel: "Garder la synchro", danger: true,
|
|
});
|
|
if (!ok) return;
|
|
await service.disable();
|
|
toast("Synchro désactivée sur cet appareil.");
|
|
};
|
|
|
|
return h("div", null,
|
|
block,
|
|
h("h2", { class: "tape" }, "Ta clé"),
|
|
h("p", { class: "muted" }, "Qui a la clé a tout : ne la donne qu'à tes appareils."),
|
|
keyText,
|
|
h("div", { class: "btn-row sync-gap" }, show, copy),
|
|
fallback,
|
|
h("h2", { class: "tape" }, "Autre appareil"),
|
|
qr,
|
|
h("p", { class: "sync-gap" }, h("strong", null, "Scanne-le avec l'appareil photo de ton téléphone."), " Le lien ouvre IA-Fit et relie le téléphone à ton journal."),
|
|
h("p", { class: "muted" }, "Sans appareil photo : ouvre IA-Fit sur l'autre appareil, écran Synchro, « J'ai déjà une clé »."),
|
|
aiSection(true),
|
|
h("h2", { class: "tape" }, "Cet appareil"),
|
|
h("button", { type: "button", class: "btn btn--danger btn--block", on: { click: () => void disable() } }, "Désactiver sur cet appareil"));
|
|
}
|
|
|
|
/** Une ligne « titre : explication ». @param {string} title @param {string} text */
|
|
export function fact(title, text) {
|
|
return h("li", { class: "row" }, h("span", { class: "row__main" }, h("span", { class: "row__title" }, title), h("span", { class: "row__meta" }, text)));
|
|
}
|
|
|
|
/**
|
|
* « Brancher mon IA » : l'adresse du connecteur et le mode d'emploi (docs/mcp.md).
|
|
* @param {boolean} ready la synchro est activée
|
|
*/
|
|
function aiSection(ready) {
|
|
const url = mcpUrl();
|
|
const fallback = h("div", { class: "manual-copy", hidden: true });
|
|
const copy = h("button", { type: "button", class: "btn btn--sm", on: { click: async () => {
|
|
if (await copyText(url, fallback, "Adresse du connecteur")) toast("Adresse copiée.");
|
|
} } }, "Copier");
|
|
/** @param {string} who @param {string} how */
|
|
const step = (who, how) => h("li", { class: "how__step" }, h("span", null, h("strong", null, who), " : ", how));
|
|
return [
|
|
h("h2", { class: "tape" }, "Brancher mon IA"),
|
|
h("p", { class: "muted" }, ready
|
|
? "Ton IA lit ton programme et propose des changements ; chaque proposition se valide ici."
|
|
: "Active d'abord la synchro : ton IA lit le journal chiffré du relais."),
|
|
h("div", { class: "copy-line sync-gap" }, h("code", { class: "copy-line__text" }, url), copy),
|
|
fallback,
|
|
h("ol", { class: "how sync-gap" },
|
|
step("Claude", "Réglages → Connecteurs → Ajouter un connecteur personnalisé, colle l'adresse."),
|
|
step("ChatGPT", "Réglages → Applications et connecteurs → Paramètres avancés → mode développeur, puis « Créer » : l'adresse, authentification OAuth."),
|
|
h("li", { class: "how__step" }, h("span", null, h("strong", null, "Claude Code"), " : ",
|
|
h("code", { class: "sync-cmd" }, `claude mcp add --transport http ia-fit ${url}`), ", puis /mcp."))),
|
|
h("p", { class: "muted sync-gap" }, "Ton IA ouvre ensuite une page d'IA-Fit : touche « Autoriser »."),
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Lien d'appariement ouvert (#pair=) : la clé a déjà quitté l'adresse
|
|
* (main.js), elle arrive ici en mémoire.
|
|
* @param {{service: SyncService, store: import("../store.js").Store, nav: import("../router.js").Navigation, key: string|null}} ctx
|
|
* @returns {import("../router.js").Screen}
|
|
*/
|
|
export function pairScreen({ service, store, nav, key }) {
|
|
const home = () => nav.go(href.home(), { replace: true });
|
|
const head = (/** @type {string|null} */ sub) => screenHeader({ kicker: "Synchro", title: "Relier cet appareil ?", sub });
|
|
if (!key) {
|
|
return {
|
|
title: "Relier",
|
|
node: h("div", { class: "screen" }, head("Ce lien d'appariement n'est plus valable ici (page rechargée ?). Scanne de nouveau le QR code."),
|
|
h("a", { class: "btn btn--block", href: href.home() }, "Accueil")),
|
|
};
|
|
}
|
|
const current = service.getKey();
|
|
if (current === key) {
|
|
return {
|
|
title: "Relier",
|
|
node: h("div", { class: "screen" }, head("Cet appareil est déjà relié à ce journal."),
|
|
h("button", { type: "button", class: "btn btn--primary btn--block", on: { click: home } }, "Accueil")),
|
|
};
|
|
}
|
|
const n = store.getEvents().length;
|
|
const status = h("p", { class: "status", role: "status", "aria-live": "polite" });
|
|
const go = h("button", { type: "button", class: "btn btn--primary btn--block btn--lg" }, "Relier");
|
|
go.addEventListener("click", async () => {
|
|
go.disabled = true;
|
|
status.className = "status";
|
|
status.textContent = "Synchro…";
|
|
const s = await service.enable(key);
|
|
if (s.error && s.error !== "offline") {
|
|
// La clé est gardée : la synchro réessaiera ; l'écran Synchro dit pourquoi.
|
|
toast("Appareil relié, mais la synchro a échoué : voir l'écran Synchro.");
|
|
} else toast(s.error ? "Appareil relié : la synchro se fera au retour du réseau." : "Appareil relié à ton journal.");
|
|
home();
|
|
});
|
|
return {
|
|
title: "Relier",
|
|
node: h("div", { class: "screen" },
|
|
head("Relier cet appareil à ton journal ? Il recevra ton programme et tes séances, et ce que tu saisis ici rejoindra tes autres appareils."),
|
|
h("p", { class: "mark" }, "Clé ", maskKey(key)),
|
|
current && h("p", { class: "coach-note coach-note--plain sync-gap" },
|
|
`Cet appareil est relié à un autre journal (clé ${maskKey(current)}) : il passera à celui-ci, et ses données y seront recopiées.`),
|
|
n > 0 && h("p", { class: "coach-note coach-note--plain sync-gap" },
|
|
`Cet appareil a déjà des données (${plural(n, "événement")}) : elles seront fusionnées avec le journal. Rien n'est effacé.`),
|
|
h("p", { class: "muted sync-gap" }, "Qui a la clé a tout : ne relie que tes propres appareils."),
|
|
status,
|
|
h("button", { type: "button", class: "btn btn--ghost btn--block sync-gap", on: { click: home } }, "Annuler"),
|
|
actionBar(go)),
|
|
};
|
|
}
|