From 03fab87055a753a0cd8c72f7147d658b9914f8f2 Mon Sep 17 00:00:00 2001 From: Pablo Date: Wed, 4 Nov 2026 16:56:58 +0100 Subject: [PATCH 1/2] feat(a11y): teclado, aria-live, foco y contraste AA (#4) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Juego (js/app.js, index.html): - Flechas ← → para votar no/sí (ignorando auto-repeat y modificadores). - Foco gestionado: cada pantalla/carta enfoca su control principal (data-autofocus) y el foco se conserva al re-renderizar (stepper); no se roba el foco al abrir la app. - Región aria-live que anuncia turno, resumen de ronda y resultado (data-announce, sin leer los emojis); nº de jugadores al usar el stepper. - Cartas con tabindex, role=group y aria-label (nombre, ingredientes y posición); botones ✕/♥ y −/+ con aria-label; inputs de nombre con aria-label; progressbar; h1/h2, listas y
semánticos; error con role=alert; banner de instalación como diff --git a/js/admin.js b/js/admin.js index e7821f1..df0a669 100644 --- a/js/admin.js +++ b/js/admin.js @@ -1,5 +1,8 @@ import { loadGameConfig, loadTypeData, esc, slugify, indexById } from "./shared.js"; +// Emoji decorativo: el nombre va siempre en texto al lado. +const emo = (e) => ``; + const DRAFT_KEY = "dinnerMatchAdminDraft"; const VISUAL_STYLES = ["round", "bowl", "stack"]; @@ -72,8 +75,8 @@ function currentType() { return state.typeCache[state.selectedTypeId]; } function typeSelectorHTML() { return `
- + ${state.dishTypes.map((t) => ``).join("")} ${esc(state.selectedTypeId || "")}
`; @@ -87,10 +90,10 @@ function dishTypeForm(dt) {
${isNew ? "Nuevo tipo de cena" : "Editar tipo de cena"}
- - + +
- ${VISUAL_STYLES.map((s) => ``).join("")}

visualStyle controla cómo se dibuja el plato final: round (pizza/sushi), bowl (ensalada/pasta/sopa), stack (hamburguesa/tacos).

@@ -104,11 +107,11 @@ function dishTypeForm(dt) { function dishTypesTab() { const rows = state.dishTypes.map((t) => `
- ${t.emoji} +
${esc(t.name)}
${esc(t.id)} · visual: ${esc(t.visualStyle)}
- - + +
`).join(""); const formHTML = state.editingDishType === "new" @@ -120,8 +123,8 @@ function dishTypesTab() { return `
Ajustes globales
-
Jugadores mínimo
-
Jugadores máximo
+
+
${formHTML} @@ -139,10 +142,10 @@ function ingredientForm(ing) {
${isNew ? "Nuevo ingrediente" : "Editar ingrediente"}
- - + +
- +

La categoría debe coincidir con una clave en las Reglas de este tipo para que el balanceo la tenga en cuenta.

@@ -156,11 +159,11 @@ function ingredientsTab() { if (!t) return `

Cargando…

`; const rows = t.ingredients.map((ing) => `
- ${ing.emoji} +
${esc(ing.name)}
${esc(ing.cat)} · ${esc(ing.id)}
- - + +
`).join(""); const formHTML = state.editingIngredient === "new" @@ -183,14 +186,14 @@ function recipeForm(recipe) { const isNew = !recipe; const v = recipe || { id: "", name: "", ingredients: [] }; const tags = t.ingredients.map((ing) => ` - ${ing.emoji} ${esc(ing.name)} + `).join(""); return `
${isNew ? "Nueva receta" : "Editar receta"}
- -
Ingredientes
-
${tags}
+ +
Ingredientes
+
${tags}
@@ -206,11 +209,11 @@ function recipesTab() {
${esc(r.name)}
-
${r.ingredients.map((id) => byId[id]?.emoji || "?").join(" ")} · ${r.ingredients.length} ingr.
+
${esc(r.ingredients.map((id) => byId[id]?.name || `¿${id}?`).join(", "))} · ${r.ingredients.length} ingr.
- - + +
`).join(""); const formHTML = state.editingRecipe === "new" @@ -238,13 +241,13 @@ function configTab() { return ` ${typeSelectorHTML()}
-
Tamaño del mazo de ingredientes
-
Recetas candidatas (máx)
-
Solapamiento mínimo candidata
+
+
+
Tope de ingredientes por categoría
- ${Object.keys(caps).map((cat) => `
${esc(cat)}
`).join("") || `

Sin categorías todaví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.

` : ""}
@@ -260,15 +263,15 @@ function render() { app.innerHTML = `
- ⚙️ Configurar Dinner Match +

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

← Volver al juego
-
- - - - -
+ ${tabContent}
Exportar

Es un sitio estático: descarga estos ficheros y sustitúyelos en el repo para publicar los cambios (los del tipo van en data/types/<id>/).

@@ -384,7 +387,10 @@ document.getElementById("app").addEventListener("click", async (e) => { saveDraft(); render(); } } - else if (action === "toggle-recipe-ing") { btn.classList.toggle("selected"); } + else if (action === "toggle-recipe-ing") { + const on = btn.classList.toggle("selected"); + btn.setAttribute("aria-pressed", String(on)); + } else if (action === "save-recipe") { const t = currentType(); const name = document.getElementById("f-recipe-name").value.trim(); diff --git a/js/app.js b/js/app.js index 6b7aec1..fa9c496 100644 --- a/js/app.js +++ b/js/app.js @@ -68,6 +68,7 @@ function setNumPlayersClamped(n) { while (state.names.length < c) state.names.push(`Jugador ${state.names.length + 1}`); state.names = state.names.slice(0, c); render(); + announce(`${c} jugadores`); } function startRound1() { @@ -193,6 +194,15 @@ document.addEventListener("pointerup", () => { }); // ---- Render pieces ---- +// Accesibilidad: +// - Los emojis son decorativos (aria-hidden): el nombre siempre va en texto. +// - [data-autofocus] recibe el foco al cambiar de pantalla (o de carta), para +// que teclado y lectores de pantalla sigan el flujo sin perderse en . +// - [data-announce] es lo que se lee por la región aria-live al llegar a una +// pantalla (turno, resumen de ronda, resultado). +const emo = (e) => ``; +const namesOf = (ings) => ings.map((i) => i.name).join(", "); + function dishVisualHTML(ingredients, style, size = 240) { const toppings = ingredients.map((ing, i) => { const h = hashStr(ing.id); @@ -200,13 +210,15 @@ function dishVisualHTML(ingredients, style, size = 240) { const radius = 22 + (h % 55); const left = 50 + radius * Math.cos(angle) * 0.42; const top = 50 + radius * Math.sin(angle) * 0.42; - return `${ing.emoji}`; + return `${esc(ing.emoji)}`; }).join(""); - return `
${toppings}
`; + return ``; } +const chipsHTML = (ings) => `
    ${ings.map((ing) => `
  • ${emo(ing.emoji)}${esc(ing.name)}
  • `).join("")}
`; + function renderLoading() { - return `

Cargando…

`; + return `

Cargando…

`; } function renderError() { const hint = location.protocol === "file:" @@ -214,33 +226,33 @@ function renderError() { : ""; return `
-
${esc(state.errorTitle)}
${esc(state.errorMsg)}${hint}
- - ${state.errorRetry === "round2" ? `` : ""} + + + ${state.errorRetry === "round2" ? `` : ""}
`; } function renderSetup() { return `
-
🍽️Dinner Match
+

${emo("🍽️")}Dinner Match

Tres rondas: primero el tipo de cena, luego sus ingredientes, y por último el plato concreto.

-
Jugadores
-
- +
Jugadores
+
+ ${state.numPlayers} - +
Nombres
- ${state.names.map((n, i) => ``).join("")} + ${state.names.map((n, i) => ``).join("")}
Tipos de cena en juego
-
- ${dishTypes.map((t) => `
${t.emoji}${esc(t.name)}
`).join("")} -
+
    + ${dishTypes.map((t) => `
  • ${emo(t.emoji)}${esc(t.name)}
  • `).join("")} +
- - ⚙️ Configurar tipos, ingredientes y recetas + + ${emo("⚙️")} Configurar tipos, ingredientes y recetas
`; } @@ -252,21 +264,22 @@ function roundLabel() { } function renderHandoff() { + const typeName = esc(state.dishTypeResult?.chosen?.name || ""); const sub = state.round === 1 ? "Pasa el móvil y toca cuando estés listo/a. Nadie más debería ver tus elecciones." : state.round === 2 - ? `Ahora vas a votar ingredientes de ${state.dishTypeResult.chosen.name}.` - : `Ahora vas a votar platos completos de ${state.dishTypeResult.chosen.name} propuestos a partir de la ronda anterior.`; + ? `Ahora vas a votar ingredientes de ${typeName}.` + : `Ahora vas a votar platos completos de ${typeName} propuestos a partir de la ronda anterior.`; const color = PLAYER_COLORS[state.playerIdx % PLAYER_COLORS.length]; const name = state.names[state.playerIdx] || "?"; return `
-
${roundLabel()}
+
${esc(roundLabel())}
Jugador ${state.playerIdx + 1} de ${state.numPlayers}
-
${esc(name.charAt(0).toUpperCase() || "?")}
-
Turno de ${esc(name)}
+ +

Turno de ${esc(name)}

${sub}
- +
`; } @@ -275,38 +288,45 @@ function renderSwipe() { if (!currentCard) return `
`; const nextCard = state.deck[state.cardIdx + 1]; const simpleCard = state.round === 1 || state.round === 2; + const pos = `${state.cardIdx + 1} de ${state.deck.length}`; const behindHTML = nextCard ? ( simpleCard - ? `
${nextCard.emoji}
${esc(nextCard.name)}
` - : `
${esc(nextCard.name)}
` + ? `` + : `` ) : ""; + const recipeIngs = simpleCard ? [] : ingObjs(currentCard.ingredients, typeData.ingById); const topInner = simpleCard - ? `
${currentCard.emoji}
${esc(currentCard.name)}
` + ? `
${esc(currentCard.name)}
` : `
${esc(currentCard.name)}
-
${ingObjs(currentCard.ingredients, typeData.ingById).map((ing) => `${ing.emoji}${esc(ing.name)}`).join("")}
+
${recipeIngs.map((ing) => `${emo(ing.emoji)}${esc(ing.name)}`).join("")}
${currentCard.custom ? `
Todo lo de la ronda anterior
` : ""}`; + const cardLabel = simpleCard + ? `${currentCard.name}. Carta ${pos}` + : `${currentCard.name}: ${namesOf(recipeIngs)}. Carta ${pos}`; return `
+

${esc(roundLabel())}: turno de ${esc(state.names[state.playerIdx])}

${esc(state.names[state.playerIdx])} · ${state.cardIdx + 1}/${state.deck.length} -
+
${behindHTML} -
-
SÍ
-
NO
+
+ + ${topInner}
- - + +
-
Desliza la carta o usa los botones
+
Desliza la carta, usa los botones o las flechas ← (no) y → (sí) del teclado
`; } @@ -316,77 +336,102 @@ function renderSummary1() { return `
Ronda 1 completada
-
Sin coincidencias…
-
No hubo ni un tipo de cena en el que todos dijerais que sí.
- +

Sin coincidencias…

+
No hubo ni un tipo de cena en el que todos dijerais que sí.
+
`; } const r = state.dishTypeResult; return `
Ronda 1 completada
-
Toca ${esc(r.chosen.name)} ${r.chosen.emoji}
-
+

Toca ${esc(r.chosen.name)} ${emo(r.chosen.emoji)}

+
${state.round1Matches.length > 1 - ? `Coincidisteis en ${state.round1Matches.length} tipos (${state.round1Matches.map((t) => t.name).join(", ")}) — sorteado entre ellos.` + ? `Coincidisteis en ${state.round1Matches.length} tipos (${esc(state.round1Matches.map((t) => t.name).join(", "))}) — sorteado entre ellos.` : `Los ${state.numPlayers} coincidisteis en este tipo de cena.`}
- - + +
`; } function renderSummary2() { const has = state.round2Matches.length > 0; - const typeName = state.dishTypeResult.chosen.name; + const typeName = esc(state.dishTypeResult.chosen.name); return `
Ronda 2 completada
-
${has ? "Ingredientes en común" : "Sin coincidencias…"}
-
${has - ? `Los ${state.numPlayers} coincidisteis en ${state.round2Matches.length} ingrediente${state.round2Matches.length > 1 ? "s" : ""} de ${typeName}. Ahora toca elegir el plato.` +

${has ? "Ingredientes en común" : "Sin coincidencias…"}

+
${has + ? `Los ${state.numPlayers} coincidisteis en ${state.round2Matches.length} ingrediente${state.round2Matches.length > 1 ? "s" : ""} de ${typeName}: ${esc(namesOf(state.round2Matches))}. Ahora toca elegir el plato.` : `No hubo ni un ingrediente de ${typeName} en el que todos dijerais que sí.`}
${has ? ` -
${state.round2Matches.map((ing) => `
${ing.emoji}${esc(ing.name)}
`).join("")}
- - - ` : ``} + ${chipsHTML(state.round2Matches)} + + + ` : ``}
`; } function renderResults() { const has = state.round3Matches.length > 0; const style = state.dishTypeResult.chosen.visualStyle || "round"; + const typeName = esc(state.dishTypeResult.chosen.name); if (!has) { return `
Ronda 3 completada
-
Tampoco hubo acuerdo…
-
Ninguna propuesta de ${esc(state.dishTypeResult.chosen.name)} convenció a todo el grupo.
+

Tampoco hubo acuerdo…

+
Ninguna propuesta de ${typeName} convenció a todo el grupo.
Consuelo: esto era lo que teníais en común en la ronda de ingredientes.
${dishVisualHTML(state.round2Matches, style, 200)} - + ${chipsHTML(state.round2Matches)} +
`; } const main = state.round3Matches[0]; + const mainIngs = ingObjs(main.ingredients, typeData.ingById); const rest = state.round3Matches.slice(1); return `
Ronda 3 completada
-
¡Esta es vuestra cena!
-
Coincidisteis los ${state.numPlayers} en ${state.round3Matches.length} propuesta${state.round3Matches.length > 1 ? "s" : ""} de ${esc(state.dishTypeResult.chosen.name)}.
- ${dishVisualHTML(ingObjs(main.ingredients, typeData.ingById), style)} -
${esc(main.name)}
-
${ingObjs(main.ingredients, typeData.ingById).map((ing) => `
${ing.emoji}${esc(ing.name)}
`).join("")}
+

¡Esta es vuestra cena!

+
Coincidisteis los ${state.numPlayers} en ${state.round3Matches.length} propuesta${state.round3Matches.length > 1 ? "s" : ""} de ${typeName}.
+ ${dishVisualHTML(mainIngs, style)} +

${esc(main.name)}

+ ${chipsHTML(mainIngs)} ${rest.length > 0 ? ` -
También coincidisteis en
-
- ${rest.map((r) => `
${esc(r.name)}${ingObjs(r.ingredients, typeData.ingById).map((i) => i.emoji).join(" ")}
`).join("")} -
` : ""} - +

También coincidisteis en

+
    + ${rest.map((r) => { + const ings = ingObjs(r.ingredients, typeData.ingById); + return `
  • ${esc(r.name)}${ings.map((i) => `${emo(i.emoji)} ${esc(i.name)}`).join(" · ")}
  • `; + }).join("")} +
` : ""} +
`; } +let lastStage = null; +let lastCardIdx = null; + +// Texto tal como lo leería un lector de pantalla: sin lo marcado aria-hidden (emojis). +function spokenText(el) { + const copy = el.cloneNode(true); + copy.querySelectorAll("[aria-hidden='true']").forEach((n) => n.remove()); + return copy.textContent.trim().replace(/\s+/g, " "); +} + +function announce(msg) { + const el = document.getElementById("announcer"); + if (!el || !msg) return; + // Vaciar y reescribir en el siguiente tick para que se anuncie aunque el + // texto coincida con el anterior. + el.textContent = ""; + setTimeout(() => { el.textContent = msg; }, 50); +} + function render() { const app = document.getElementById("app"); const renderers = { @@ -394,8 +439,33 @@ function render() { handoff: renderHandoff, swipe: renderSwipe, summary1: renderSummary1, summary2: renderSummary2, results: renderResults, }; + // innerHTML destruye el elemento con foco: recordar cuál era para + // devolvérselo a su equivalente (p. ej. el botón + del stepper). + const prevFocus = document.activeElement?.closest?.("#app [data-action], #app [data-name-idx]"); + const prevFocusSel = prevFocus + ? (prevFocus.dataset.nameIdx !== undefined ? `[data-name-idx="${prevFocus.dataset.nameIdx}"]` : `[data-action="${prevFocus.dataset.action}"]`) + : null; + app.innerHTML = (renderers[state.stage] || renderLoading)(); + const stageChanged = state.stage !== lastStage; + const cardChanged = state.stage === "swipe" && state.cardIdx !== lastCardIdx; + const firstScreen = lastStage === null; // no robar el foco al abrir la app + lastStage = state.stage; + lastCardIdx = state.stage === "swipe" ? state.cardIdx : null; + + const restore = prevFocusSel && app.querySelector(prevFocusSel); + if ((stageChanged || cardChanged) && !firstScreen) { + app.querySelector("[data-autofocus]")?.focus({ preventScroll: state.stage === "swipe" }); + } else if (restore) { + // Si el botón quedó deshabilitado (p. ej. + al llegar al máximo), al otro del stepper. + (restore.disabled ? app.querySelector(".step-btn:not([disabled])") : restore)?.focus(); + } + if (stageChanged && !firstScreen) { + announce([...app.querySelectorAll("[data-announce]")].map(spokenText).filter(Boolean) + .map((t) => (/[.!?…:]$/.test(t) ? t : `${t}.`)).join(" ")); + } + if (state.stage === "swipe") { const card = app.querySelector(".ing-card.top"); if (card) { @@ -409,6 +479,15 @@ function render() { } } +// Teclado en el swipe: ← no, → sí (sin auto-repetición, para no votar +// varias cartas por mantener la tecla pulsada). +document.addEventListener("keydown", (e) => { + if (state.stage !== "swipe" || e.repeat || e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) return; + if (e.target.closest?.("input, textarea, select")) return; + if (e.key === "ArrowRight") { e.preventDefault(); triggerSwipe(true); } + else if (e.key === "ArrowLeft") { e.preventDefault(); triggerSwipe(false); } +}); + document.getElementById("app").addEventListener("click", (e) => { const btn = e.target.closest("[data-action]"); if (!btn) return; From 8f89ab679183ccf5b0954a5f8fe4f328c42d4a8b Mon Sep 17 00:00:00 2001 From: Pablo Date: Wed, 4 Nov 2026 17:09:36 +0100 Subject: [PATCH 2/2] chore(backlog): seguimientos de accesibilidad detectados en #4 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - #34 El banner de instalación tapa el último botón en pantallas largas - #35 Admin: el foco se pierde al cambiar de pestaña o guardar Co-Authored-By: Claude Opus 5.5 --- backlog/issues.json | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/backlog/issues.json b/backlog/issues.json index 7d19fc5..5fce4e5 100644 --- a/backlog/issues.json +++ b/backlog/issues.json @@ -234,5 +234,25 @@ "documentation" ], "milestone": "v1.0 – Deploy & Polish" + }, + { + "title": "El banner de instalación tapa el último botón en pantallas largas", + "body": "`.install-banner` es `position: fixed` abajo y no reserva espacio, así que en pantallas con scroll (resultado con varias coincidencias, setup con 8 jugadores) tapa el último botón (\"Jugar otra ronda\"). Ya pasaba antes de #4.\n\n**Aceptación**\n- [ ] Mientras el banner está visible, el contenido reserva su altura abajo (padding en `body` o similar) y el último botón queda accesible\n- [ ] Opción de cerrar el banner (✕ con `aria-label`), recordada en `localStorage`\n- [ ] Probado en móvil (400×860) en las pantallas de setup y resultado\n\n_Detectado durante #4 (accesibilidad)._", + "labels": [ + "bug", + "pwa", + "a11y" + ], + "milestone": "v1.2 – Calidad de vida" + }, + { + "title": "Admin: el foco se pierde al cambiar de pestaña o guardar", + "body": "`admin.js` re-renderiza todo `#app` con `innerHTML` en cada acción, así que al cambiar de pestaña, abrir un formulario o guardar, el foco vuelve a `` y quien usa teclado o lector de pantalla tiene que empezar a tabular desde arriba.\n\n**Aceptación**\n- [ ] Al cambiar de pestaña, el foco queda en la pestaña activa\n- [ ] Al abrir un formulario (nuevo/editar), el foco va a su primer input; al guardar o cancelar, vuelve al botón que lo abrió (o a la fila editada)\n- [ ] Los toasts se anuncian por una región `aria-live` (`role=\"status\"`)\n- [ ] Mismo patrón que el juego (`data-autofocus` / conservar foco por `data-action`), ver `CONTRIBUTING.md` → Accesibilidad\n\n_Detectado durante #4 (accesibilidad)._", + "labels": [ + "enhancement", + "a11y", + "admin" + ], + "milestone": "v1.2 – Calidad de vida" } ] \ No newline at end of file