WTC-27: несколько примеров блюд из базы на пустом экране

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Peppa 2026-11-16 06:30:06 +05:00
parent 059bd56908
commit d165ed076e
10 changed files with 80 additions and 17 deletions

View File

@ -0,0 +1,3 @@
## Решения
- `recipeExamples(dishes, catalog, findRecipe, limit=4)` в logic.js вместо одного `recipeExample`; кнопки строятся в `#examples`, клик — делегированием.
- Условие показа прежнее: пока в списке нет блюда с кнопкой «Рецепт». Подпись — i18n `examplesNote` (ru/kk/en).

View File

@ -0,0 +1,7 @@
## Why
На пустом экране предложен один пример блюда — кажется, что в базе только оно.
## What Changes
- Показываем до 4 блюд из базы, каждое добавляется одним нажатием.
- Добавленное блюдо из примеров пропадает.
- Подпись: это только примеры, можно вписать своё блюдо.

View File

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

View File

@ -0,0 +1,3 @@
- [x] recipeExamples в logic.js
- [x] Кнопки примеров и подпись на экране, тексты на трёх языках
- [x] Тесты

View File

@ -1,4 +1,4 @@
import { submitDish, addDish, removeDish, pickDish, parseState, suggest, inCatalog, difficultyOf, pickByDifficulty, placeholderFor, hasRecipe, hasNoRecipe, recipeExample } from "./logic.js";
import { submitDish, addDish, removeDish, pickDish, parseState, suggest, inCatalog, difficultyOf, pickByDifficulty, placeholderFor, hasRecipe, hasNoRecipe, recipeExamples } from "./logic.js";
import { catalog, LEVEL_KEYS } from "./catalog.js";
import { findRecipe } from "./recipes.js";
import { messages, pickLang } from "./i18n.js";
@ -47,11 +47,18 @@ function render() {
$("empty").hidden = n !== 0;
$("recipesHint").textContent = t.listRecipes;
$("recipesHint").hidden = !hasRecipe(state.dishes, findRecipe);
const example = hasRecipe(state.dishes, findRecipe) ? null : recipeExample(state.dishes, catalog, findRecipe);
$("recipeExample").hidden = example === null;
const examples = hasRecipe(state.dishes, findRecipe) ? [] : recipeExamples(state.dishes, catalog, findRecipe);
$("recipeExample").hidden = examples.length === 0;
$("recipeExampleHint").textContent = t.recipeExampleHint;
$("addExample").textContent = example === null ? "" : t.addExample.replace("{name}", example);
$("addExample").dataset.name = example ?? "";
$("examplesNote").textContent = t.examplesNote;
$("examples").replaceChildren(...examples.map((name) => {
const b = document.createElement("button");
b.type = "button";
b.className = "add-example";
b.dataset.name = name;
b.textContent = t.addExample.replace("{name}", name);
return b;
}));
$("noRecipeHint").textContent = t.noRecipeHint;
$("noRecipeHint").hidden = n !== 0 && !hasNoRecipe(state.dishes, findRecipe);
const ul = $("list");
@ -123,10 +130,10 @@ $("back").addEventListener("click", () => {
$("recipeToday").addEventListener("click", () => openRecipe(state.last, $("recipeToday")));
// Пример из подсказки добавляется одним нажатием; фокус — на кнопку «Рецепт» нового блюда.
$("addExample").addEventListener("click", () => {
const name = $("addExample").dataset.name;
if (!name) return;
state.dishes = addDish(state.dishes, name);
$("examples").addEventListener("click", (e) => {
const btn = e.target.closest(".add-example");
if (!btn || !btn.dataset.name) return;
state.dishes = addDish(state.dishes, btn.dataset.name);
save(); renderSuggest(); render();
const btns = $("list").querySelectorAll(".recipe-btn");
if (btns.length) btns[btns.length - 1].focus();

View File

@ -16,6 +16,7 @@ export const messages = {
listRecipes: "У блюд из нашей базы есть рецепт — он откроется кнопкой «Рецепт».",
recipeExampleHint: "Хотите увидеть рецепт? Добавьте блюдо из нашей базы — рядом с ним появится кнопка «Рецепт». Например:",
addExample: "Добавить «{name}»",
examplesNote: "Это только примеры из нашей базы — можно вписать и своё блюдо.",
noRecipeHint: "Пометка «Рецепта нет» стоит у блюд, которых нет в нашей базе. Рецепты есть только у блюд из базы.",
pick: "Что приготовить?",
yourDishes: "Ваши блюда",
@ -53,6 +54,7 @@ export const messages = {
listRecipes: "Біздің қордағы тағамдардың рецепті бар — оны «Рецепт» түймесімен ашасыз.",
recipeExampleHint: "Рецептті көргіңіз келе ме? Біздің қордағы тағамды қосыңыз — қасында «Рецепт» түймесі пайда болады. Мысалы:",
addExample: "«{name}» қосу",
examplesNote: "Бұл біздің қордағы мысалдар ғана — өз тағамыңызды да жаза аласыз.",
noRecipeHint: "«Рецепт жоқ» белгісі біздің қорда жоқ тағамдарда тұрады. Рецепт тек қордағы тағамдарда бар.",
pick: "Не дайындаймыз?",
yourDishes: "Сіздің тағамдарыңыз",
@ -90,6 +92,7 @@ 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}”",
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?",
yourDishes: "Your dishes",

View File

@ -40,7 +40,8 @@
<p id="recipesHint" class="hint" hidden></p>
<div id="recipeExample" class="example" hidden>
<p id="recipeExampleHint" class="hint"></p>
<button id="addExample" type="button"></button>
<div id="examples" class="examples"></div>
<p id="examplesNote" class="hint"></p>
</div>
<ul id="list"></ul>
<p id="noRecipeHint" class="hint" hidden></p>

View File

@ -41,6 +41,13 @@ export function recipeExample(dishes, catalog, findRecipe) {
return catalog.find((c) => typeof c === "string" && c.trim() && !have.has(fold(c)) && findRecipe(c)) ?? null;
}
// Несколько примеров из базы (с рецептом), которых ещё нет в списке: уже добавленные не показываются.
export function recipeExamples(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() && !have.has(fold(c)) && findRecipe(c)).slice(0, limit);
}
// Подсказки: блюда базы, у которых любое слово начинается с введённого; уже добавленные скрыты.
export function suggest(query, dishes, catalog, limit = 5) {
const q = fold(query);

View File

@ -38,5 +38,6 @@ li button { padding: 6px 14px; min-height: 48px; min-width: 48px; flex-shrink: 0
.recipe ul.plain li, .recipe ol li { display: list-item; border: 0; padding: 4px 0; }
.recipe ul.plain { list-style: disc; padding-left: 1.2rem; }
.recipe ol { padding-left: 1.4rem; margin: 12px 0; }
.example button { width: 100%; margin-top: 8px; background: #fff3e0; border-color: #b4500c; color: #7a3a06; font-weight: 600; }
.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; } }

View File

@ -1,7 +1,7 @@
import test from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { recipeExample, hasNoRecipe, hasRecipe, addDish } from "../src/logic.js";
import { recipeExample, recipeExamples, hasNoRecipe, hasRecipe, addDish } from "../src/logic.js";
import { catalog } from "../src/catalog.js";
import { findRecipe } from "../src/recipes.js";
import { messages } from "../src/i18n.js";
@ -15,7 +15,7 @@ test("Сценарий: Пустой список — подсказка и пр
assert.match(messages.ru.recipeExampleHint, /появится кнопка «Рецепт»/);
const html = read("index.html");
assert.ok(html.indexOf('id="listTitle"') < html.indexOf('id="recipeExampleHint"'));
assert.ok(html.indexOf('id="recipeExampleHint"') < html.indexOf('id="addExample"'));
assert.ok(html.indexOf('id="recipeExampleHint"') < html.indexOf('id="examples"'));
for (const l of ["ru", "kk", "en"]) {
for (const k of ["recipeExampleHint", "noRecipeHint"]) assert.ok(messages[l][k].length > 20, `${l}.${k}`);
assert.match(messages[l].addExample, /\{name\}/, l);
@ -27,8 +27,8 @@ test("Сценарий: Пример добавляется одним нажа
assert.deepEqual(dishes, ["Бешбармак"]);
assert.equal(hasRecipe(dishes, findRecipe), true);
const app = read("app.js");
const click = app.slice(app.indexOf('$("addExample").addEventListener'), app.indexOf("function showNameError"));
assert.match(click, /addDish\(state\.dishes, name\)/);
const click = app.slice(app.indexOf('$("examples").addEventListener'), app.indexOf("function showNameError"));
assert.match(click, /addDish\(state\.dishes, btn\.dataset\.name\)/);
assert.match(click, /save\(\);.*render\(\)/);
});
test("Сценарий: В списке только своё блюдо", () => {
@ -37,8 +37,8 @@ test("Сценарий: В списке только своё блюдо", () =>
});
test("Сценарий: Блюдо с рецептом уже есть", () => {
assert.equal(hasRecipe(["Плов"], findRecipe), true);
assert.match(read("app.js"), /const example = hasRecipe\(state\.dishes, findRecipe\) \? null : recipeExample\(/);
assert.match(read("app.js"), /\$\("recipeExample"\)\.hidden = example === null/);
assert.match(read("app.js"), /const examples = hasRecipe\(state\.dishes, findRecipe\) \? \[\] : recipeExamples\(/);
assert.match(read("app.js"), /\$\("recipeExample"\)\.hidden = examples.length === 0/);
});
test("Граница: пример не повторяет блюдо из списка, пустая база — примера нет", () => {
assert.equal(recipeExample(["бешбармак"], catalog, findRecipe), "Плов");
@ -61,3 +61,20 @@ test("Сценарий: Все блюда из базы", () => {
assert.equal(hasNoRecipe(["Бешбармак"], findRecipe), false);
assert.equal(hasNoRecipe([], findRecipe), false);
});
// WTC-27: несколько примеров из базы
test("Сценарий: Пустой экран — 4 примера, уже добавленные скрыты", () => {
const four = recipeExamples([], catalog, findRecipe);
assert.equal(four.length, 4);
assert.ok(four.every((n) => findRecipe(n)));
const rest = recipeExamples([four[0].toLowerCase()], catalog, findRecipe);
assert.ok(!rest.includes(four[0]));
assert.equal(rest.length, 4);
assert.deepEqual(recipeExamples([], [], findRecipe), []);
assert.deepEqual(recipeExamples([], undefined, findRecipe), []);
});
test("Сценарий: Подпись — только примеры, можно своё", () => {
for (const l of ["ru", "kk", "en"]) assert.ok(messages[l].examplesNote.length > 20, l);
assert.match(messages.ru.examplesNote, /только примеры/);
assert.match(read("index.html"), /id="examplesNote"/);
});