From 2a2e207026154bc16f3da6a7216391d4b6a911ad Mon Sep 17 00:00:00 2001 From: Pablo Date: Wed, 4 Nov 2026 20:05:40 +0100 Subject: [PATCH] fix(admin): el borrador ya no oculta los cambios de /data (#21) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Antes, con un borrador en localStorage, init() no volvía a leer /data, y el borrador se creaba con solo abrir el admin: cualquier cambio posterior en el repo quedaba oculto en ese navegador. Si no había borrador y fallaba /data, la página quedaba en blanco. - El borrador (v2) guarda una huella FNV-1a del contenido de /data de cada fichero al entrar al borrador. - Al abrir, se relee /data y se compara fichero a fichero: sin cambios en /data → se mantiene; cambiado en /data y sin ediciones locales → se actualiza solo (toast); cambiado en ambos → aviso role=alert con los ficheros y "Usar la versión de /data" (solo esos ficheros) o "Mantener mi borrador" (la referencia pasa al /data actual). - Tipos eliminados en /data sin ediciones salen del borrador; tipos que siguen listados pero no cargan quedan sin comprobar (no se borran). - Borradores antiguos sin huellas: aviso específico con las mismas opciones. - /data caído: sin borrador → pantalla de error con Reintentar; con borrador → se trabaja sobre él con aviso. - Si un tipo no carga, se avisa del motivo en vez de mostrarlo vacío sin más. Docs: PROJECT.md §6 y CHANGELOG. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 ++ PROJECT.md | 12 +++ js/admin.js | 204 ++++++++++++++++++++++++++++++++++++++++++++++++--- 3 files changed, 211 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e37f8f..53dd200 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,11 @@ Formato basado en [Keep a Changelog](https://keepachangelog.com/es-ES/1.1.0/). o con red lenta, arranca desde caché (#5). ### Corregido +- Admin: el borrador local ya no oculta para siempre los cambios de `/data`. + Al abrir el admin se compara cada fichero con `/data`: lo que no has + editado se actualiza solo y, si hay conflicto, un aviso permite usar la + versión de `/data` o mantener el borrador. Si `/data` no carga, se muestra + un error con "Reintentar" en vez de una página en blanco (#21). - Admin, pestaña Reglas: ahora muestra un tope por cada categoría en uso (antes solo las que ya tenían tope, así que un tipo nuevo nunca podía tenerlos), permite quitar topes de categorías sin ingredientes y guardar diff --git a/PROJECT.md b/PROJECT.md index 57ec339..d575365 100644 --- a/PROJECT.md +++ b/PROJECT.md @@ -164,6 +164,18 @@ en `admin.html` → descargar → sustituir el fichero en `/data` (o `/data/types//`) → commit al repo. No hay persistencia de servidor en esta fase. +El borrador guarda también una huella (hash) del contenido de `/data` de +cada fichero en el momento en que entró al borrador. Al reabrir el admin se +vuelve a leer `/data` y, por fichero: +- si `/data` no ha cambiado, se mantiene el borrador; +- si `/data` ha cambiado y el borrador no tiene ediciones en ese fichero, + se actualiza solo; +- si han cambiado ambos, se avisa (conflicto) para elegir entre la versión + de `/data` (solo en esos ficheros) o mantener el borrador. + +Si `/data` no carga, el admin muestra un error con "Reintentar" (sin +borrador) o trabaja sobre el borrador avisando de que no pudo comprobarlo. + ## 7. Roadmap (fuera de esta fase) 1. **Multijugador remoto real**: cada jugador entra desde su móvil con un diff --git a/js/admin.js b/js/admin.js index b68980a..f060fbf 100644 --- a/js/admin.js +++ b/js/admin.js @@ -15,26 +15,133 @@ const state = { editingDishType: null, editingIngredient: null, editingRecipe: null, + // Huella del contenido de /data de cada fichero cuando entró al borrador + // ({ "data/dish-types.json": "9f3a…", ... }). Permite saber, al volver a + // abrir el admin, si /data ha cambiado desde entonces y si el borrador + // tiene ediciones propias en ese fichero. + base: {}, + draftNotice: null, // { kind: "conflict" | "legacy" | "unchecked", files?, error? } + loadError: null, // fallo al cargar /data sin borrador: pantalla de error }; +let remoteSnapshot = null; // { files: { [fichero]: contenido }, prints: { [fichero]: huella } } + +const TYPE_FILES = ["ingredients", "recipes", "config"]; +const F_TYPES = "data/dish-types.json"; +const F_GAME = "data/game-config.json"; +const typeFile = (id, kind) => `data/types/${id}/${kind}.json`; +const parseTypeFile = (f) => f.match(/^data\/types\/([^/]+)\/(ingredients|recipes|config)\.json$/)?.slice(1); + +// FNV-1a de 32 bits sobre el JSON: basta para detectar cambios, no es criptográfico. +function fingerprint(value) { + const s = JSON.stringify(value); + let h = 0x811c9dc5; + for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 0x01000193) >>> 0; } + return h.toString(16).padStart(8, "0"); +} + +function getDraftFile(f) { + if (f === F_TYPES) return state.dishTypes; + if (f === F_GAME) return state.gameConfig; + const [id, kind] = parseTypeFile(f) || []; + return state.typeCache[id]?.[kind]; +} +function setDraftFile(f, value) { + if (f === F_TYPES) state.dishTypes = value; + else if (f === F_GAME) state.gameConfig = value; + else { + const [id, kind] = parseTypeFile(f); + state.typeCache[id] = state.typeCache[id] || { ingredients: [], recipes: [], config: emptyTypeConfig() }; + state.typeCache[id][kind] = value; + } +} +const emptyTypeConfig = () => ({ ingredientPoolSize: 0, categoryCaps: {}, candidateMax: 6, candidateMinOverlap: 2 }); + +function readDraft() { + try { return JSON.parse(localStorage.getItem(DRAFT_KEY) || "null"); } catch { return null; } +} async function init() { - const draft = JSON.parse(localStorage.getItem(DRAFT_KEY) || "null"); - if (draft) { - Object.assign(state, draft); - toast("Borrador cargado desde este navegador"); + const draft = readDraft(); + let remote = null; + let remoteError = null; + try { remote = await loadGameConfig(); } catch (e) { remoteError = e; } + + if (!draft) { + if (!remote) { state.loadError = remoteError.message; render(); return; } + state.dishTypes = remote.dishTypes; + state.gameConfig = remote.gameConfig; + state.base = { [F_TYPES]: fingerprint(remote.dishTypes), [F_GAME]: fingerprint(remote.gameConfig) }; } else { - const loaded = await loadGameConfig(); - state.dishTypes = loaded.dishTypes; - state.gameConfig = loaded.gameConfig; + state.gameConfig = draft.gameConfig; + state.dishTypes = draft.dishTypes; + state.typeCache = draft.typeCache || {}; + state.base = draft.base || {}; + if (remote) await reconcileWithData(draft, remote); + else state.draftNotice = { kind: "unchecked", error: remoteError.message }; } if (!state.selectedTypeId && state.dishTypes.length) state.selectedTypeId = state.dishTypes[0].id; render(); if (state.selectedTypeId) await ensureTypeLoaded(state.selectedTypeId); } +// Compara el borrador con /data fichero a fichero: +// - /data no cambió desde que entró al borrador → se mantiene el borrador. +// - /data cambió y el borrador no tenía ediciones en ese fichero → se +// actualiza solo (aviso breve). +// - /data cambió y el borrador también → conflicto: aviso visible para +// elegir entre la versión de /data o mantener el borrador. +// Un borrador anterior a este mecanismo (sin `base`) no permite distinguir +// ediciones propias, así que se avisa siempre. +async function reconcileWithData(draft, remote) { + const files = { [F_TYPES]: remote.dishTypes, [F_GAME]: remote.gameConfig }; + const remoteIds = new Set(remote.dishTypes.map((t) => t.id)); + const draftIds = Object.keys(state.typeCache); + const hadBase = (id) => TYPE_FILES.some((k) => typeFile(id, k) in state.base); + const unreadable = new Set(); // listados en /data pero que no cargan: sin comprobar, no "eliminados" + await Promise.all(draftIds.filter((id) => remoteIds.has(id) || hadBase(id)).map(async (id) => { + try { + const d = await loadTypeData(id); + for (const k of TYPE_FILES) files[typeFile(id, k)] = d[k]; + } catch { + if (remoteIds.has(id)) unreadable.add(id); // si no está en dish-types.json, se trata como eliminado + } + })); + const prints = Object.fromEntries(Object.entries(files).map(([f, v]) => [f, fingerprint(v)])); + remoteSnapshot = { files, prints }; + + if (!draft.base) { + state.draftNotice = { kind: "legacy", files: Object.keys(files) }; + return; + } + const updated = []; + const conflicts = []; + for (const [f, basePrint] of Object.entries(state.base)) { + if (prints[f] === basePrint) continue; // /data no ha cambiado + if (unreadable.has(parseTypeFile(f)?.[0])) continue; // no se pudo leer: sin comprobar + const localEdits = fingerprint(getDraftFile(f)) !== basePrint; + if (!localEdits) { + if (f in files) { setDraftFile(f, files[f]); state.base[f] = prints[f]; } + else { delete state.base[f]; } // eliminado en /data, sin ediciones + updated.push(f); + } else { + conflicts.push({ file: f, removed: !(f in files) }); + } + } + // Tipos que ya no están en /data ni en el borrador: fuera de la caché. + for (const id of Object.keys(state.typeCache)) { + if (!state.dishTypes.some((t) => t.id === id) && !hadBase(id)) delete state.typeCache[id]; + } + if (updated.length) saveDraft(); + if (conflicts.length) state.draftNotice = { kind: "conflict", files: conflicts }; + else toast(updated.length + ? `Borrador cargado. Actualizado desde /data (sin ediciones tuyas): ${updated.join(", ")}` + : "Borrador cargado desde este navegador"); +} + function saveDraft() { localStorage.setItem(DRAFT_KEY, JSON.stringify({ - gameConfig: state.gameConfig, dishTypes: state.dishTypes, typeCache: state.typeCache, + version: 2, + gameConfig: state.gameConfig, dishTypes: state.dishTypes, typeCache: state.typeCache, base: state.base, })); } @@ -43,13 +150,51 @@ async function ensureTypeLoaded(id) { try { const data = await loadTypeData(id); state.typeCache[id] = { ingredients: data.ingredients, recipes: data.recipes, config: data.config }; + for (const k of TYPE_FILES) state.base[typeFile(id, k)] = fingerprint(data[k]); saveDraft(); - } catch { - state.typeCache[id] = { ingredients: [], recipes: [], config: { ingredientPoolSize: 0, categoryCaps: {}, candidateMax: 6, candidateMinOverlap: 2 } }; + } catch (e) { + // Se muestra vacío para poder darle contenido, pero avisando del motivo. + state.typeCache[id] = { ingredients: [], recipes: [], config: emptyTypeConfig() }; + toast(`No se pudo cargar el tipo «${id}» de /data: ${e.message}. Se muestra vacío.`); } render(); } +function draftNoticeHTML() { + const n = state.draftNotice; + if (!n) return ""; + const list = (files) => `
    ${files.map((f) => + `
  • ${esc(f.file || f)}${f.removed ? " (eliminado en /data)" : ""}
  • `).join("")}
`; + const body = n.kind === "conflict" + ? `

Estos ficheros han cambiado en /data desde que empezaste el borrador, y también los has editado aquí:

+ ${list(n.files)} +

Si usas la versión de /data, perderás tus cambios en esos ficheros (el resto del borrador se mantiene).

` + : n.kind === "legacy" + ? `

Este borrador es de una versión anterior del admin y no se puede saber si /data ha cambiado desde entonces. Si no recuerdas haber editado nada, usa la versión de /data.

` + : `

No se pudo leer /data para comprobar si ha cambiado (${esc(n.error)}). Estás trabajando sobre el borrador guardado en este navegador.

`; + const actions = n.kind === "unchecked" + ? ` + ` + : ` + `; + return ` + `; +} + +function renderLoadError() { + document.getElementById("app").innerHTML = ` +
+

${emo("⚙️")} Configurar Dinner Match

+ + + ← Volver al juego +
`; +} + // Región de avisos persistente (creada al cargar, no con el primer aviso, // para que los lectores de pantalla anuncien también el primero). const toastHost = document.createElement("aside"); @@ -278,6 +423,7 @@ function configTab() { } function render() { + if (state.loadError) return renderLoadError(); const app = document.getElementById("app"); const tabContent = state.tab === "dishtypes" ? dishTypesTab() : state.tab === "ingredients" ? ingredientsTab() @@ -289,6 +435,7 @@ function render() {

${emo("⚙️")} Configurar Dinner Match

← Volver al juego + ${draftNoticeHTML()}