169 lines
9.7 KiB
JavaScript
169 lines
9.7 KiB
JavaScript
// 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<number>} merge union : renvoie le nombre d'événements nouveaux
|
|
* @property {(events: DomainEvent[]) => Promise<void>} replace remplace tout le journal
|
|
*/
|
|
|
|
/**
|
|
* @param {{store: import("../store.js").Store, nav: import("../router.js").Navigation, journal: Journal, today: () => string,
|
|
* sync?: import("../sync-service.js").SyncService}} ctx
|
|
* sync : la synchro ; activée, « Tout effacer » se décline pour cet appareil ou partout (2d)
|
|
* @returns {import("../router.js").Screen}
|
|
*/
|
|
export function dataScreen({ store, nav, journal, today, sync }) {
|
|
// ---- 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 ---------------------------------------------------------------
|
|
/**
|
|
* Efface, après deux confirmations. Synchro activée (2d) : « cet appareil » coupe
|
|
* d'abord la synchro, pour que rien ne revienne ; « partout » vide aussi le journal
|
|
* du serveur, et les autres appareils s'effacent à leur prochaine synchro.
|
|
* @param {"device"|"everywhere"|"alone"} scope
|
|
*/
|
|
const reset = async (scope) => {
|
|
const n = store.getEvents().length;
|
|
const what = `programme, séances, pesées, réglages`;
|
|
const lines = scope === "everywhere"
|
|
? [`Les ${plural(n, "événement")} seront effacés sur tous tes appareils reliés : ${what}.`, "Les autres appareils s'effaceront à leur prochaine synchro.", "Exporte d'abord une sauvegarde."]
|
|
: scope === "device"
|
|
? [`Les ${plural(n, "événement")} de cet appareil seront effacés : ${what}.`, "La synchro est coupée sur cet appareil ; tes autres appareils gardent tout.", "Exporte d'abord une sauvegarde."]
|
|
: [`Les ${plural(n, "événement")} de cet appareil seront effacés : ${what}.`, "Exporte d'abord une sauvegarde."];
|
|
const first = await confirmDialog({
|
|
title: scope === "everywhere" ? "Tout effacer partout ?" : scope === "device" ? "Effacer cet appareil ?" : "Tout effacer ?",
|
|
lines, 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: scope === "everywhere" ? "Tout effacer partout" : scope === "device" ? "Effacer cet appareil" : "Tout effacer", cancel: "Non, garder", danger: true,
|
|
});
|
|
if (!second) return;
|
|
try {
|
|
if (scope === "everywhere") await sync?.eraseEverywhere();
|
|
if (scope === "device") await sync?.detach();
|
|
} catch {
|
|
toast("Serveur injoignable : rien n'a été effacé. Réessaie une fois connecté.");
|
|
return;
|
|
}
|
|
await journal.replace([]);
|
|
clearDraft();
|
|
toast(scope === "everywhere" ? "Données effacées sur tous tes appareils." : "Données de cet appareil effacées.");
|
|
nav.go(href.home(), { replace: true });
|
|
};
|
|
const synced = !!sync?.getStatus().hasKey;
|
|
|
|
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"),
|
|
synced
|
|
? [
|
|
h("button", { type: "button", class: "btn btn--danger btn--block", on: { click: () => void reset("device") } }, "Effacer cet appareil"),
|
|
h("p", { class: "muted" }, "Coupe la synchro ici ; tes autres appareils gardent tout."),
|
|
h("button", { type: "button", class: "btn btn--danger btn--block", on: { click: () => void reset("everywhere") } }, "Tout effacer partout"),
|
|
h("p", { class: "muted" }, "Efface aussi le serveur et tes autres appareils reliés.")]
|
|
: h("button", { type: "button", class: "btn btn--danger btn--block", on: { click: () => void reset("alone") } }, "Tout effacer"));
|
|
return { node, title: "Données" };
|
|
}
|