diff --git a/.gitignore b/.gitignore index 2b7f95a..58fab34 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,6 @@ output/ __pycache__/ src/config.json src/config.json.bak +src/config.draft.json +src/config.tmp +src/config.draft.tmp diff --git a/README.md b/README.md index 8ef037c..0e7452b 100644 --- a/README.md +++ b/README.md @@ -91,12 +91,18 @@ make serve "Épinglées" (tout en haut, en dehors de tout groupe), réordonner les groupes (poignée `⠿`), les renommer (clic sur le nom), cocher "replié par défaut", ajouter (`+`) ou supprimer (`✕`) une application ou un groupe. - - Le bouton **Enregistrer** écrit dans `src/config.json`. + - Chaque modification est écrite aussitôt dans un **brouillon** + (`src/config.draft.json`, ignoré par git) : rien n'est perdu si tu + fermes ou recharges l'éditeur, et `src/config.json` reste intact. + - Le bouton **Enregistrer** transforme le brouillon en `src/config.json`. + - Le bouton **Rétablir l'original** abandonne le brouillon et revient à + la dernière version enregistrée. - Le bouton **Exporter** enregistre puis copie les fichiers déployables (`index.html`, `style.css`, `app.js`, `config.json`) dans `output/` — c'est ce dossier, pas `src/`, qui est envoyé sur le serveur. - **`http://localhost:8000/`** — aperçu de la page finale (celle de - `src/`), avec rechargement automatique dès qu'un fichier change. + `src/`), avec rechargement automatique dès qu'un fichier change. Tant + qu'un brouillon existe, l'aperçu l'affiche à la place de `config.json`. Cette partie ne nécessite aucune information sur ton serveur : tout est local. diff --git a/scripts/preview.py b/scripts/preview.py index 54dcd53..b7aa0ad 100755 --- a/scripts/preview.py +++ b/scripts/preview.py @@ -12,7 +12,7 @@ import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) -from yunohost_sync import build_app_list, fetch_remote_apps, known_urls, load_env, sync_target +from yunohost_sync import build_app_list, fetch_remote_apps, load_env, sync_target PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8000 @@ -21,8 +21,13 @@ PROJECT_ROOT = SCRIPT_DIR.parent SRC_DIR = PROJECT_ROOT / "src" OUTPUT_DIR = PROJECT_ROOT / "output" DEMO_CATALOG_PATH = SRC_DIR / "catalog.demo.json" +CONFIG_PATH = SRC_DIR / "config.json" +# Brouillon de l'editeur : ecrit a chaque modification, sert de config a +# l'apercu tant qu'il existe, devient config.json au clic sur Enregistrer +# et est supprime par "Retablir l'original". +DRAFT_PATH = SRC_DIR / "config.draft.json" -WATCHED_FILES = ["index.html", "style.css", "app.js", "config.json"] +WATCHED_FILES = ["index.html", "style.css", "app.js", "config.json", "config.draft.json"] EXPORTED_FILES = ["index.html", "style.css", "app.js", "config.json"] RELOAD_SNIPPET = b""" @@ -80,6 +85,16 @@ class ReloadingHandler(http.server.SimpleHTTPRequestHandler): self._send_catalog() return + route = self.path.split("?", 1)[0] + if route == "/config.json": + draft = DRAFT_PATH.exists() + self._send_file(DRAFT_PATH if draft else CONFIG_PATH, draft) + return + + if route == "/__original": + self._send_file(CONFIG_PATH, False) + return + if self.path in ("/", "/index.html"): try: html = (SRC_DIR / "index.html").read_bytes() @@ -96,17 +111,20 @@ class ReloadingHandler(http.server.SimpleHTTPRequestHandler): super().do_GET() def do_POST(self): - if self.path == "/__save": - length = int(self.headers.get("Content-Length", 0)) - raw = self.rfile.read(length) - try: - data = json.loads(raw) - except json.JSONDecodeError as exc: - self.send_error(400, f"JSON invalide: {exc}") + if self.path in ("/__save", "/__draft"): + data = self._read_json_body() + if data is None: return - with open(SRC_DIR / "config.json", "w", encoding="utf-8") as f: - json.dump(data, f, ensure_ascii=False, indent=2) - f.write("\n") + if self.path == "/__save": + self._write_json(CONFIG_PATH, data) + DRAFT_PATH.unlink(missing_ok=True) + else: + self._write_json(DRAFT_PATH, data) + self._send_json({"ok": True}) + return + + if self.path == "/__discard": + DRAFT_PATH.unlink(missing_ok=True) self._send_json({"ok": True}) return @@ -139,16 +157,46 @@ class ReloadingHandler(http.server.SimpleHTTPRequestHandler): if not ssh_target or not domain: self._send_json({"error": "SYNC_SSH_HOST (ou REMOTE_HOST) et PORTAL_DOMAIN manquants dans .env"}) return + # Liste complete : l'editeur filtre lui-meme les apps deja placees, + # pour que le catalogue suive les ajouts/suppressions sans recharger. try: - with open(SRC_DIR / "config.json", encoding="utf-8") as f: - config = json.load(f) remote = fetch_remote_apps(ssh_target, domain) - apps = build_app_list(remote, domain, self_app_id, exclude_urls=known_urls(config)) + apps = build_app_list(remote, domain, self_app_id) except Exception as exc: # SSH/JSON/reseau : on remonte un message lisible self._send_json({"error": str(exc)}) return self._send_json({"apps": apps}) + def _read_json_body(self): + length = int(self.headers.get("Content-Length", 0)) + raw = self.rfile.read(length) + try: + return json.loads(raw) + except json.JSONDecodeError as exc: + self.send_error(400, f"JSON invalide: {exc}") + return None + + @staticmethod + def _write_json(path, data): + tmp = path.with_suffix(".tmp") + with open(tmp, "w", encoding="utf-8") as f: + json.dump(data, f, ensure_ascii=False, indent=2) + f.write("\n") + tmp.replace(path) + + def _send_file(self, path, is_draft): + try: + body = path.read_bytes() + except OSError: + self.send_error(404) + return + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.send_header("X-Homepage-Draft", "1" if is_draft else "0") + self.end_headers() + self.wfile.write(body) + def _send_json(self, payload): body = json.dumps(payload).encode() self.send_response(200) diff --git a/src/editor.css b/src/editor.css index b08069d..c42415e 100644 --- a/src/editor.css +++ b/src/editor.css @@ -78,6 +78,11 @@ body { border-color: var(--purple); } +.btn:disabled { + opacity: 0.4; + cursor: default; +} + #editor-root { max-width: 1500px; margin: 0 auto; diff --git a/src/editor.html b/src/editor.html index f35eec9..fdaa626 100644 --- a/src/editor.html +++ b/src/editor.html @@ -12,6 +12,7 @@
Aperçu ↗ +
diff --git a/src/editor.js b/src/editor.js index f24acf2..3ed8e28 100644 --- a/src/editor.js +++ b/src/editor.js @@ -1,7 +1,7 @@ let state = null; let dirty = false; let dragSource = null; // { appId }, { groupId } or { catalogApp } currently being dragged -let catalog = []; // apps YunoHost pas encore dans le portail (voir /__catalog) +let catalog = []; // toutes les apps installees sur YunoHost (voir /__catalog) let catalogError = null; const PALETTE = [ @@ -32,9 +32,53 @@ function setStatus(text, kind) { el.className = "status" + (kind ? " " + kind : ""); } +// Les modifications sont ecrites dans un brouillon (config.draft.json) que +// l'apercu utilise ; config.json ne change qu'au clic sur Enregistrer. +let draftTimer = null; +let draftWrite = Promise.resolve(); + +function setDirty(value) { + dirty = value; + document.getElementById("revert-btn").disabled = !value; + if (value) setStatus("Brouillon non enregistré"); +} + +function writeDraft() { + draftTimer = null; + const body = JSON.stringify(state, null, 2); + draftWrite = draftWrite + .then(() => fetch("/__draft", { method: "POST", headers: { "Content-Type": "application/json" }, body })) + .then((res) => { if (!res.ok) throw new Error(res.statusText); }) + .catch((err) => { + setStatus("Erreur d'écriture du brouillon", "error"); + console.error(err); + }); + return draftWrite; +} + +function cancelPendingDraft() { + if (draftTimer) clearTimeout(draftTimer); + draftTimer = null; +} + function markDirty() { - dirty = true; - setStatus("Modifications non enregistrées"); + setDirty(true); + cancelPendingDraft(); + draftTimer = setTimeout(writeDraft, 300); +} + +function normalizeUrl(url) { + return (url || "").replace(/^https?:\/\//, "").replace(/\/+$/, "").toLowerCase(); +} + +// Apps du catalogue YunoHost pas encore presentes dans le portail. Calcule +// a chaque rendu depuis l'etat courant : une app supprimee avec la croix +// y reapparait aussitot, une app ajoutee en disparait. +function availableCatalog() { + const used = new Set(); + const all = [...(state.pinned || []), ...state.ungrouped, ...state.groups.flatMap((g) => g.apps)]; + all.forEach((a) => used.add(normalizeUrl(a.url))); + return catalog.filter((a) => !used.has(normalizeUrl(a.url))); } function findAppLocation(appId) { @@ -108,7 +152,7 @@ function renderTile(app) { removeBtn.textContent = "✕"; removeBtn.title = "Supprimer cette application"; removeBtn.addEventListener("click", () => { - if (!confirm(`Supprimer "${app.name}" définitivement ?`)) return; + if (!confirm(`Retirer "${app.name}" de la page ?`)) return; const loc = findAppLocation(app.id); if (loc) loc.list.splice(loc.index, 1); markDirty(); @@ -166,7 +210,6 @@ function attachGridDropzone(gridEl, targetListGetter) { if (dragSource.catalogApp) { const app = { ...dragSource.catalogApp }; targetList.splice(Math.min(dropIndex, targetList.length), 0, app); - catalog = catalog.filter((a) => a.id !== app.id); markDirty(); render(); return; @@ -185,7 +228,6 @@ function attachGridDropzone(gridEl, targetListGetter) { function addCatalogAppTo(app, targetList) { targetList.push({ ...app }); - catalog = catalog.filter((a) => a.id !== app.id); markDirty(); render(); } @@ -424,9 +466,10 @@ function render() { const layout = document.createElement("div"); layout.className = "editor-layout"; - const half = Math.ceil(catalog.length / 2); - const leftCatalog = renderCatalogColumn("Catalogue YunoHost", catalog.slice(0, half)); - const rightCatalog = renderCatalogColumn("Catalogue YunoHost", catalog.slice(half)); + const available = availableCatalog(); + const half = Math.ceil(available.length / 2); + const leftCatalog = renderCatalogColumn("Catalogue YunoHost", available.slice(0, half)); + const rightCatalog = renderCatalogColumn("Catalogue YunoHost", available.slice(half)); const center = document.createElement("div"); center.className = "editor-center"; @@ -517,11 +560,33 @@ async function loadCatalog() { async function load() { const res = await fetch("config.json", { cache: "no-store" }); state = await res.json(); + setDirty(res.headers.get("X-Homepage-Draft") === "1"); await loadCatalog(); render(); } +async function revert() { + if (!confirm("Abandonner toutes les modifications non enregistrées et revenir à la dernière version enregistrée ?")) return; + cancelPendingDraft(); + try { + await draftWrite; + const res = await fetch("/__discard", { method: "POST" }); + if (!res.ok) throw new Error(await res.text()); + const orig = await fetch("/__original", { cache: "no-store" }); + state = await orig.json(); + setDirty(false); + render(); + setStatus("Original rétabli ✓", "saved"); + setTimeout(() => setStatus(""), 2000); + } catch (err) { + setStatus("Erreur lors du rétablissement", "error"); + console.error(err); + } +} + async function save() { + cancelPendingDraft(); + await draftWrite; try { const res = await fetch("/__save", { method: "POST", @@ -529,7 +594,7 @@ async function save() { body: JSON.stringify(state, null, 2), }); if (!res.ok) throw new Error(await res.text()); - dirty = false; + setDirty(false); setStatus("Enregistré ✓", "saved"); setTimeout(() => setStatus(""), 2000); } catch (err) { @@ -553,12 +618,14 @@ async function exportToOutput() { document.getElementById("save-btn").addEventListener("click", save); document.getElementById("export-btn").addEventListener("click", exportToOutput); +document.getElementById("revert-btn").addEventListener("click", revert); -window.addEventListener("beforeunload", (e) => { - if (dirty) { - e.preventDefault(); - e.returnValue = ""; - } +// Le brouillon est sur disque : fermer ou recharger l'editeur ne perd rien, +// il suffit d'envoyer la derniere modification si elle est encore en attente. +window.addEventListener("pagehide", () => { + if (!draftTimer) return; + cancelPendingDraft(); + navigator.sendBeacon("/__draft", new Blob([JSON.stringify(state)], { type: "application/json" })); }); load();