WTC-32: пометить уже добавленные примеры блюд
All checks were successful
peppa/lint lint: success за 0с
peppa/test test: success за 0с
peppa/build build: success за 0с
ci / checks (pull_request) Successful in 4s
deploy / deploy (pull_request) Successful in 13s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Peppa 2026-11-16 06:36:29 +05:00
parent 352f3b1bcf
commit d7efc86a47
12 changed files with 102 additions and 7 deletions

View File

@ -21,6 +21,7 @@
- WTC-29: подсказка под полем — #suggestHint (i18n suggestHint), всегда видна; suggest(query, dishes, catalog) — порядок аргументов именно такой.
- WTC-30: подсказка у кнопки — постоянный абзац #pickInfo (i18n pickHint, всегда виден); #hint теперь только emptyHint/oneHint и пуст в остальных случаях.
- WTC-31: подписи кнопок и поля прописаны в index.html (ru по умолчанию), app.js их перезаписывает; test/labels.test.js проверяет, что пустых кнопок в разметке нет.
- WTC-32: примеры на экране — постоянный набор exampleStates() (4 блюда, флаг added); добавленный — disabled «— добавлено», все добавлены — текст examplesAllAdded.
## Соглашения
- Цвета кнопки: доступная #b4500c, недоступная #e8dccb/#5c4a35 (контраст ≥4.5:1, проверяется тестом); opacity для disabled не используем.

View File

@ -0,0 +1,4 @@
## Решения
- `exampleStates()` в logic.js возвращает фиксированные первые 4 блюда базы с рецептом и флаг `added`.
- Блок виден всегда; добавленный пример — `disabled` с текстом `exampleAdded`; все добавлены — текст `examplesAllAdded`.
- Тексты на ru/kk/en в i18n.js.

View File

@ -0,0 +1,6 @@
## Why
После добавления одного примера блюда весь блок примеров пропадал: непонятно, что уже в списке, а остальные примеры недоступны.
## What Changes
- Четыре примера остаются на месте; добавленный — неактивен с пометкой «Добавлено».
- Когда добавлены все, вместо кнопок короткий текст.

View File

@ -0,0 +1,14 @@
## ADDED Requirements
### Requirement: Добавленные примеры помечены
Система SHALL показывать примеры блюд постоянным набором, помечая уже добавленные.
#### Scenario: Добавлен один пример
- **GIVEN** в списке нет блюд
- **WHEN** пользователь нажимает «Добавить «Плов»»
- **THEN** кнопка «Плов» неактивна с пометкой «добавлено»
- **AND** остальные примеры доступны для добавления
#### Scenario: Добавлены все четыре
- **GIVEN** в списке три из четырёх примеров
- **WHEN** пользователь добавляет четвёртый
- **THEN** вместо кнопок виден текст, что все примеры добавлены и можно вписать своё блюдо

View File

@ -0,0 +1,4 @@
## 1. Реализация
- [x] 1.1 exampleStates и отрисовка в app.js
- [x] 1.2 Тексты ru/kk/en, стиль неактивной кнопки
- [x] 1.3 Тесты test/example-added.test.js

View File

@ -0,0 +1,20 @@
# examples Specification
## Purpose
TBD - created by archiving change wtc-32-mark-added-examples. Update Purpose after archive.
## Requirements
### Requirement: Добавленные примеры помечены
Система SHALL показывать примеры блюд постоянным набором, помечая уже добавленные.
#### Scenario: Добавлен один пример
- **GIVEN** в списке нет блюд
- **WHEN** пользователь нажимает «Добавить «Плов»»
- **THEN** кнопка «Плов» неактивна с пометкой «добавлено»
- **AND** остальные примеры доступны для добавления
#### Scenario: Добавлены все четыре
- **GIVEN** в списке три из четырёх примеров
- **WHEN** пользователь добавляет четвёртый
- **THEN** вместо кнопок виден текст, что все примеры добавлены и можно вписать своё блюдо

View File

@ -1,4 +1,4 @@
import { submitDish, addDish, removeDish, pickDish, parseState, suggest, inCatalog, difficultyOf, pickByDifficulty, placeholderFor, hasRecipe, hasNoRecipe, recipeExamples } from "./logic.js";
import { submitDish, addDish, removeDish, pickDish, parseState, suggest, inCatalog, difficultyOf, pickByDifficulty, placeholderFor, hasRecipe, hasNoRecipe, recipeExamples, exampleStates } from "./logic.js";
import { catalog, LEVEL_KEYS } from "./catalog.js";
import { findRecipe } from "./recipes.js";
import { messages, pickLang } from "./i18n.js";
@ -48,19 +48,22 @@ function render() {
$("empty").hidden = n !== 0;
$("recipesHint").textContent = t.listRecipes;
$("recipesHint").hidden = !hasRecipe(state.dishes, findRecipe);
const examples = hasRecipe(state.dishes, findRecipe) ? [] : recipeExamples(state.dishes, catalog, findRecipe);
const examples = exampleStates(state.dishes, catalog, findRecipe);
const allAdded = examples.length > 0 && examples.every((x) => x.added);
$("recipeExample").hidden = examples.length === 0;
$("recipeExampleHint").textContent = t.recipeExampleHint;
$("recipeExampleHint").hidden = allAdded;
$("suggestHint").textContent = t.suggestHint;
$("examplesNote").textContent = t.examplesNote;
$("examples").replaceChildren(...examples.map((name) => {
$("examplesNote").textContent = allAdded ? t.examplesAllAdded : t.examplesNote;
$("examples").replaceChildren(...(allAdded ? [] : examples.map(({ name, added }) => {
const b = document.createElement("button");
b.type = "button";
b.className = "add-example";
b.dataset.name = name;
b.textContent = t.addExample.replace("{name}", name);
b.disabled = added;
b.textContent = added ? t.exampleAdded.replace("{name}", name) : t.addExample.replace("{name}", name);
return b;
}));
})));
$("noRecipeHint").textContent = t.noRecipeHint;
$("noRecipeHint").hidden = n !== 0 && !hasNoRecipe(state.dishes, findRecipe);
const ul = $("list");

View File

@ -16,6 +16,8 @@ export const messages = {
listRecipes: "У блюд из нашей базы есть рецепт — он откроется кнопкой «Рецепт».",
recipeExampleHint: "Хотите увидеть рецепт? Добавьте блюдо из нашей базы — рядом с ним появится кнопка «Рецепт». Например:",
addExample: "Добавить «{name}»",
exampleAdded: "«{name}» — добавлено",
examplesAllAdded: "Все примеры добавлены. Впишите своё блюдо в поле выше.",
examplesNote: "Это только примеры из нашей базы — можно вписать и своё блюдо.",
noRecipeHint: "Пометка «Рецепта нет» стоит у блюд, которых нет в нашей базе. Рецепты есть только у блюд из базы.",
pick: "Что приготовить?",
@ -55,6 +57,8 @@ export const messages = {
listRecipes: "Біздің қордағы тағамдардың рецепті бар — оны «Рецепт» түймесімен ашасыз.",
recipeExampleHint: "Рецептті көргіңіз келе ме? Біздің қордағы тағамды қосыңыз — қасында «Рецепт» түймесі пайда болады. Мысалы:",
addExample: "«{name}» қосу",
exampleAdded: "«{name}» — қосылды",
examplesAllAdded: "Барлық мысал қосылды. Өз тағамыңызды жоғарыдағы жолға жазыңыз.",
examplesNote: "Бұл біздің қордағы мысалдар ғана — өз тағамыңызды да жаза аласыз.",
noRecipeHint: "«Рецепт жоқ» белгісі біздің қорда жоқ тағамдарда тұрады. Рецепт тек қордағы тағамдарда бар.",
pick: "Не дайындаймыз?",
@ -94,6 +98,8 @@ export const messages = {
listRecipes: "Dishes from our collection come with a recipe — open it with the “Recipe” button.",
recipeExampleHint: "Want to see a recipe? Add a dish from our collection — a “Recipe” button will appear next to it. For example:",
addExample: "Add “{name}”",
exampleAdded: "“{name}” — added",
examplesAllAdded: "All examples are added. Type your own dish in the field above.",
examplesNote: "These are just examples from our collection — you can type your own dish too.",
noRecipeHint: "“No recipe” marks dishes that are not in our collection. Only dishes from the collection have a recipe.",
pick: "What to cook?",

View File

@ -48,6 +48,14 @@ export function recipeExamples(dishes, catalog, findRecipe, limit = 4) {
return catalog.filter((c) => typeof c === "string" && c.trim() && !have.has(fold(c)) && findRecipe(c)).slice(0, limit);
}
// Фиксированный набор примеров (первые блюда базы с рецептом) и отметка, какие уже в списке.
export function exampleStates(dishes, catalog, findRecipe, limit = 4) {
if (!Array.isArray(catalog)) return [];
const have = new Set(dishes.map(fold));
return catalog.filter((c) => typeof c === "string" && c.trim() && findRecipe(c)).slice(0, limit)
.map((name) => ({ name, added: have.has(fold(name)) }));
}
// Подсказки: блюда базы, у которых любое слово начинается с введённого; уже добавленные скрыты.
export function suggest(query, dishes, catalog, limit = 5) {
const q = fold(query);

View File

@ -41,3 +41,4 @@ li button { padding: 6px 14px; min-height: 48px; min-width: 48px; flex-shrink: 0
.example .examples { display: flex; flex-direction: column; gap: 8px; }
.example button { width: 100%; background: #fff3e0; border-color: #b4500c; color: #7a3a06; font-weight: 600; }
@media (max-width: 400px) { li { flex-wrap: wrap; } }
button.add-example:disabled { background: #e8dccb; color: #5c4a35; border: 2px dashed #9c8466; }

View File

@ -0,0 +1,28 @@
import test from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { exampleStates, addDish } from "../src/logic.js";
import { catalog } from "../src/catalog.js";
import { findRecipe } from "../src/recipes.js";
import { messages } from "../src/i18n.js";
// WTC-32
test("Сценарий: Добавленный пример помечен, остальные доступны", () => {
const all = exampleStates([], catalog, findRecipe);
assert.equal(all.length, 4);
assert.ok(all.every((x) => !x.added));
const st = exampleStates(addDish([], all[1].name), catalog, findRecipe);
assert.deepEqual(st.map((x) => x.added), [false, true, false, false]);
assert.deepEqual(st.map((x) => x.name), all.map((x) => x.name));
});
test("Сценарий: Добавлены все четыре — короткий текст", () => {
let d = [];
for (const x of exampleStates([], catalog, findRecipe)) d = addDish(d, x.name);
assert.ok(exampleStates(d, catalog, findRecipe).every((x) => x.added));
for (const l of ["ru", "kk", "en"]) {
assert.ok(messages[l].examplesAllAdded.length > 10, l);
assert.match(messages[l].exampleAdded, /\{name\}/, l);
}
const app = readFileSync(new URL("../src/app.js", import.meta.url), "utf8");
assert.match(app, /b\.disabled = added/);
});

View File

@ -37,7 +37,7 @@ test("Сценарий: В списке только своё блюдо", () =>
});
test("Сценарий: Блюдо с рецептом уже есть", () => {
assert.equal(hasRecipe(["Плов"], findRecipe), true);
assert.match(read("app.js"), /const examples = hasRecipe\(state\.dishes, findRecipe\) \? \[\] : recipeExamples\(/);
assert.match(read("app.js"), /const examples = exampleStates\(state\.dishes, catalog, findRecipe\)/);
assert.match(read("app.js"), /\$\("recipeExample"\)\.hidden = examples.length === 0/);
});
test("Граница: пример не повторяет блюдо из списка, пустая база — примера нет", () => {