diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b7ff1b..9e37f8f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,12 @@ Formato basado en [Keep a Changelog](https://keepachangelog.com/es-ES/1.1.0/). o con red lenta, arranca desde caché (#5). ### Corregido +- 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 + `0` en `candidateMinOverlap` y en los topes. Los valores inválidos se + avisan en vez de sustituirse en silencio (#20). +- Admin: los avisos (toasts) se anuncian a lectores de pantalla. - El service worker ya no guarda en caché respuestas de error (404/500), y la app vuelve a arrancar sin conexión. El precache avisa en consola de qué fichero falló en vez de silenciarlo (#5). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 119a6d4..55d25c7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -59,8 +59,10 @@ No hace falta tocar código: → sustituir el fichero. Si el ingrediente introduce una categoría (`cat`) nueva, añade también su -tope en `data/types//config.json → categoryCaps`, o el mazo de esa -ronda la ignorará al repartir cupos. +tope en `data/types//config.json → categoryCaps` (en `admin.html`, +pestaña Reglas: aparece una fila por cada categoría en uso). Sin tope, todos +los ingredientes de esa categoría entran al mazo y rompen el balanceo; la CI +(`tests/data.test.mjs`) lo rechaza. ## Añadir un tipo de cena nuevo Ver `README.md` sección "Añadir un tipo de cena nuevo" — resumen: crea diff --git a/README.md b/README.md index d92922a..d1a4dae 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,8 @@ Dos formas, sin tocar código JS: y `visualStyle`. 2. Cambia a las pestañas Ingredientes / Recetas / Reglas (aparecerá seleccionado el tipo nuevo en el desplegable) y da de alta su contenido. + En Reglas aparece una fila por cada categoría de sus ingredientes: ponle + un tope a cada una (vacío = sin límite, pero la CI exige tope). 3. Exporta los 4 ficheros (`dish-types.json` + los 3 del tipo) y colócalos: `data/dish-types.json` y `data/types/pasta/{ingredients,recipes,config}.json`. diff --git a/js/admin.js b/js/admin.js index df0a669..b68980a 100644 --- a/js/admin.js +++ b/js/admin.js @@ -50,15 +50,20 @@ async function ensureTypeLoaded(id) { render(); } +// 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"); +toastHost.setAttribute("aria-label", "Avisos"); +toastHost.innerHTML = ``; +document.body.appendChild(toastHost); +let toastTimer; + function toast(msg) { - let el = document.getElementById("toast"); - if (el) el.remove(); - el = document.createElement("div"); - el.id = "toast"; - el.className = "toast"; + const el = document.getElementById("toast"); el.textContent = msg; - document.body.appendChild(el); - setTimeout(() => el.remove(), 2200); + el.hidden = false; + clearTimeout(toastTimer); + toastTimer = setTimeout(() => { el.hidden = true; el.textContent = ""; }, 2200); } function download(filename, obj) { @@ -236,19 +241,37 @@ function configTab() { if (!t) return `

Cargando…

`; const c = t.config; const caps = c.categoryCaps || {}; - const catsInUse = [...new Set(t.ingredients.map((i) => i.cat))]; - const missing = catsInUse.filter((cat) => !(cat in caps)); + const countByCat = {}; + for (const i of t.ingredients) countByCat[i.cat] = (countByCat[i.cat] || 0) + 1; + // Una fila por cada categoría en uso (tenga tope o no) y, al final, las que + // tienen tope pero ya no usa ningún ingrediente, con opción de quitarlas. + const inUse = Object.keys(countByCat).sort((a, b) => a.localeCompare(b, "es")); + const unused = Object.keys(caps).filter((cat) => !countByCat[cat]).sort((a, b) => a.localeCompare(b, "es")); + const missing = inUse.filter((cat) => !(cat in caps)); + const capRow = (cat) => { + const n = countByCat[cat] || 0; + const value = cat in caps ? caps[cat] : ""; + return ` +
+ ${n ? `${n} ingr.` : "sin ingredientes"} + + + ${n ? "" : ``} + +
`; + }; return ` ${typeSelectorHTML()}
-
-
-
+
+
+
Tope de ingredientes por categoría
-
- ${Object.keys(caps).map((cat) => `
${esc(cat)}
`).join("") || `

Sin categorías todavía.

`} - ${missing.length ? `

Categorías usadas en ingredientes pero sin tope definido: ${missing.map(esc).join(", ")}. Se incluirán con tope "sin límite" hasta que les pongas uno.

` : ""} +
+ ${[...inUse, ...unused].map(capRow).join("") || `

Sin categorías todavía: añade ingredientes a este tipo.

`} + ${missing.length ? `

Sin tope: ${missing.map(esc).join(", ")}. Vacío = sin límite (entran todos sus ingredientes al mazo). Ponles un tope antes de publicar: la CI lo exige.

` : ""}
`; @@ -410,15 +433,43 @@ document.getElementById("app").addEventListener("click", async (e) => { } // -- Config -- + else if (action === "remove-cap") { + // Solo en el formulario: se aplica al pulsar "Guardar reglas", así no se + // pierden otros cambios sin guardar. + const row = btn.closest("[data-cap-row]"); + const next = row.nextElementSibling?.querySelector("input") || document.querySelector('[data-action="save-config"]'); + row.remove(); + next?.focus(); + toast(`Tope de «${btn.dataset.cat}» quitado (pulsa Guardar reglas)`); + } else if (action === "save-config") { const t = currentType(); - t.config.ingredientPoolSize = +document.getElementById("cfg-pool").value || 0; - t.config.candidateMax = +document.getElementById("cfg-candmax").value || 6; - t.config.candidateMinOverlap = +document.getElementById("cfg-candmin").value || 2; + // Enteros >= min; vacío → valor por defecto (o "sin tope" en categorías). + // Un valor inválido no se sustituye en silencio: se avisa y no se guarda. + const errors = []; + const readInt = (input, label, min, fallback) => { + const raw = input.value.trim(); + if (raw === "") return fallback; + const n = Number(raw); + if (!Number.isInteger(n) || n < min) { errors.push(`${label} debe ser un entero ≥ ${min}`); input.setAttribute("aria-invalid", "true"); return undefined; } + input.removeAttribute("aria-invalid"); + return n; + }; + const pool = readInt(document.getElementById("cfg-pool"), "Tamaño del mazo", 0, 0); + const candMax = readInt(document.getElementById("cfg-candmax"), "Recetas candidatas", 1, 6); + const candMin = readInt(document.getElementById("cfg-candmin"), "Solapamiento mínimo", 0, 2); const caps = {}; - document.querySelectorAll("[data-cap-cat]").forEach((inp) => { caps[inp.dataset.capCat] = +inp.value || 0; }); - t.config.categoryCaps = caps; - saveDraft(); toast("Reglas guardadas"); + document.querySelectorAll("[data-cap-cat]").forEach((inp) => { + const v = readInt(inp, `Tope de ${inp.dataset.capCat}`, 0, null); + if (v !== null && v !== undefined) caps[inp.dataset.capCat] = v; + }); + if (errors.length) { + toast(errors[0]); + document.querySelector('[aria-invalid="true"]')?.focus(); + return; + } + Object.assign(t.config, { ingredientPoolSize: pool, candidateMax: candMax, candidateMinOverlap: candMin, categoryCaps: caps }); + saveDraft(); render(); toast("Reglas guardadas"); } // -- Export --