WTC-48: скрытые кнопки убираются со страницы, поле и списки названы

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Peppa 2026-11-16 17:21:20 +05:00
parent 6f528c42dc
commit d8c41f012d
7 changed files with 113 additions and 5 deletions

View File

@ -0,0 +1,6 @@
## Decisions
- **Скрытые кнопки убираются из DOM, а не прячутся `hidden`.** Стори разрешает оба варианта («название или убрать со страницы»); удаление закрывает обе претензии приёмки — и «кнопка без названия», и «лишний текст скрытых кнопок» (WTC-42). При старте app.js заменяет кнопки комментариями-якорями и держит элементы в памяти; `mount(id, on)` вставляет кнопку после якоря или удаляет её. `$` сначала смотрит в эту карту, поэтому остальной код и обработчики не меняются.
- Разметка index.html остаётся прежней (кнопки с aria-label) — до запуска скрипта у них всё равно есть название.
- Поле: оставляем `label for` и добавляем `aria-labelledby` — так подпись видят и инструменты, которые не разбирают `for`.
- Списки `#list`, `#ingredients`, `#steps` — `aria-labelledby` на свои заголовки.
- Проверка: headless Chrome, дерево доступности (Accessibility.getFullAXTree) и обход DOM: ни одной кнопки/поля без названия на пустом экране, с блюдами и в рецепте.

View File

@ -0,0 +1,14 @@
## Why
На приёмке (WTC-48) в тексте рабочей версии остались пять кнопок без названия, а поле ввода значилось «без подписи». Кнопки «Рецепт», «Полегче», «Посложнее» и «Назад» лежат на странице скрытыми и с пустым текстом (название у них только в aria-label), а список блюд не назван. Инструменты, которые читают страницу как текст, видят их безымянными.
## What Changes
- Кнопок, которых сейчас нет на экране («Рецепт» в выдаче, «Полегче/Посложнее» при пустом списке, «Назад» вне рецепта), нет и на странице: app.js вставляет кнопку только когда она нужна, всегда с текстом.
- Поле ввода связано с подписью дважды: `label for` и `aria-labelledby="nameLabel"`.
- Списки получают названия по своим заголовкам («Ваши блюда», «Ингредиенты», «Шаги»).
## Capabilities
### Modified Capabilities
- `accessibility`: на странице нет кнопок, полей и списков без названия.
## Impact
src/index.html, src/app.js, тесты test/no-unnamed-controls.test.js и правки старых проверок разметки.

View File

@ -0,0 +1,26 @@
## ADDED Requirements
### Requirement: На странице нет кнопок и полей без названия
Каждая кнопка, поле ввода и список, которые есть на странице, SHALL иметь название; кнопка, которой сейчас нет на экране, SHALL отсутствовать на странице.
#### Scenario: Пустой экран
- **GIVEN** список блюд пуст
- **WHEN** пользователь открывает страницу
- **THEN** на странице нет кнопок «Рецепт», «Полегче», «Посложнее» и «Назад»
- **AND** у каждой кнопки на странице есть текст, например «Добавить «Плов»»
#### Scenario: Поле ввода с подписью
- **GIVEN** страница открыта
- **WHEN** программа чтения экрана читает поле ввода
- **THEN** она называет его «Название блюда»
#### Scenario: Блюдо выбрано
- **GIVEN** в списке «Плов», и выбрано блюдо «Плов»
- **WHEN** пользователь смотрит на выдачу
- **THEN** на странице есть кнопки «Рецепт», «Полегче», «Посложнее» с текстом
- **AND** кнопки «Назад» на странице нет
#### Scenario: Открыт рецепт и возврат назад
- **GIVEN** открыт рецепт «Плов»
- **WHEN** пользователь нажимает «Назад»
- **THEN** кнопки «Назад» на странице больше нет

View File

@ -0,0 +1,7 @@
## 1. Страница
- [x] 1.1 app.js: убирать со страницы кнопки «Рецепт», «Полегче», «Посложнее», «Назад», когда их нет на экране
- [x] 1.2 index.html: aria-labelledby у поля и списков
## 2. Проверка
- [x] 2.1 Тест test/no-unnamed-controls.test.js по сценариям, поправить старые проверки
- [x] 2.2 Проверить экран в headless Chrome (дерево доступности и DOM)

View File

@ -5,7 +5,20 @@ import { messages, pickLang } from "./i18n.js";
const KEY = "wtc:v1";
const t = messages[pickLang(navigator.language)];
const $ = (id) => document.getElementById(id);
// Кнопки, которых сейчас нет на экране, убираются со страницы целиком (WTC-48):
// на их месте остаётся комментарий-якорь, mount() вставляет кнопку обратно.
const conditional = {};
const anchors = {};
for (const id of ["recipeToday", "easier", "harder", "back"]) {
conditional[id] = document.getElementById(id);
anchors[id] = document.createComment(id);
conditional[id].replaceWith(anchors[id]);
}
const $ = (id) => conditional[id] ?? document.getElementById(id);
function mount(id, on) {
if (on && !conditional[id].isConnected) anchors[id].after(conditional[id]);
else if (!on) conditional[id].remove();
}
let state = { dishes: [], last: null };
try { state = parseState(localStorage.getItem(KEY)); } catch {}
@ -39,6 +52,7 @@ function render() {
$("noRecipeToday").textContent = t.noRecipe;
$("recipeToday").textContent = !$("recipeToday").hidden ? t.recipe : "";
$("recipeToday").setAttribute("aria-label", show ? t.recipeLabel.replace("{name}", state.last) : t.recipe);
mount("recipeToday", !$("recipeToday").hidden);
const lvl = state.last ? difficultyOf(state.last) : null;
$("level").hidden = lvl === null;
$("level").textContent = lvl === null ? "" : t.difficulty.replace("{level}", t[LEVEL_KEYS[lvl]]);
@ -49,6 +63,8 @@ function render() {
// Пока список пуст, кнопок нет и в тексте страницы.
$("easier").textContent = n === 0 ? "" : t.easier;
$("harder").textContent = n === 0 ? "" : t.harder;
mount("easier", n !== 0);
mount("harder", n !== 0);
$("empty").textContent = t.listEmpty;
$("empty").hidden = n !== 0;
@ -121,6 +137,7 @@ function openRecipe(name, from) {
opener = from;
$("recipeTitle").textContent = r.name;
$("back").textContent = t.back;
mount("back", true);
$("ingTitle").textContent = t.ingredients;
$("stepsTitle").textContent = t.steps;
const items = (arr) => arr.map((x) => Object.assign(document.createElement("li"), { textContent: x }));
@ -136,6 +153,7 @@ $("back").addEventListener("click", () => {
$("recipe").hidden = true;
$("home").hidden = false;
$("back").textContent = "";
mount("back", false);
if (opener && opener.isConnected) opener.focus();
});

View File

@ -14,7 +14,7 @@
<form id="form" novalidate>
<label id="nameLabel" for="name">Название блюда</label>
<div class="row">
<input id="name" type="text" maxlength="80" autocomplete="off" aria-describedby="nameError">
<input id="name" type="text" maxlength="80" autocomplete="off" aria-labelledby="nameLabel" aria-describedby="nameError">
<button id="add" type="submit">Добавить</button>
</div>
<p id="suggestHint" class="hint"></p>
@ -48,7 +48,7 @@
<div id="examples" class="examples"></div>
<p id="examplesNote" class="hint"></p>
</div>
<ul id="list"></ul>
<ul id="list" aria-labelledby="listTitle"></ul>
<p id="noRecipeHint" class="hint" hidden></p>
</section>
</div>
@ -56,9 +56,9 @@
<button id="back" type="button" aria-label="Назад"></button>
<h1 id="recipeTitle"></h1>
<h2 id="ingTitle"></h2>
<ul id="ingredients" class="plain"></ul>
<ul id="ingredients" class="plain" aria-labelledby="ingTitle"></ul>
<h2 id="stepsTitle"></h2>
<ol id="steps"></ol>
<ol id="steps" aria-labelledby="stepsTitle"></ol>
</article>
</main>
<script type="module" src="app.js"></script>

View File

@ -0,0 +1,37 @@
import test from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
const html = readFileSync(new URL("../src/index.html", import.meta.url), "utf8");
const app = readFileSync(new URL("../src/app.js", import.meta.url), "utf8");
test("Сценарий: Пустой экран — скрытые кнопки убираются со страницы", () => {
assert.match(app, /for \(const id of \["recipeToday", "easier", "harder", "back"\]\)/);
assert.match(app, /conditional\[id\]\.replaceWith\(anchors\[id\]\)/);
assert.match(app, /else if \(!on\) conditional\[id\]\.remove\(\)/);
assert.match(app, /mount\("easier", n !== 0\)/);
assert.match(app, /mount\("harder", n !== 0\)/);
});
test("Сценарий: Поле ввода с подписью — подпись связана двумя способами", () => {
assert.match(html, /<label id="nameLabel" for="name">Название блюда<\/label>/);
assert.match(html, /<input id="name"[^>]*aria-labelledby="nameLabel"/);
});
test("Сценарий: Блюдо выбрано — кнопка «Рецепт» появляется вместе с текстом", () => {
assert.match(app, /\$\("recipeToday"\)\.textContent = !\$\("recipeToday"\)\.hidden \? t\.recipe : ""/);
assert.match(app, /mount\("recipeToday", !\$\("recipeToday"\)\.hidden\)/);
});
test("Сценарий: Открыт рецепт и возврат назад — «Назад» есть только в рецепте", () => {
const open = app.slice(app.indexOf("function openRecipe"), app.indexOf('$("back").addEventListener'));
assert.match(open, /mount\("back", true\)/);
const back = app.slice(app.indexOf('$("back").addEventListener'), app.indexOf('$("recipeToday").addEventListener'));
assert.match(back, /mount\("back", false\)/);
});
test("Сценарий: списки названы по своим заголовкам", () => {
assert.match(html, /<ul id="list" aria-labelledby="listTitle">/);
assert.match(html, /<ul id="ingredients"[^>]*aria-labelledby="ingTitle"/);
assert.match(html, /<ol id="steps" aria-labelledby="stepsTitle">/);
});