diff --git a/assets/README.md b/assets/README.md new file mode 100644 index 0000000..c8abf53 --- /dev/null +++ b/assets/README.md @@ -0,0 +1,9 @@ +# Фотографии + +Unsplash, локальные копии для иллюстрации блюд; оригинальный вид приготовления может отличаться. + +oats: https://images.unsplash.com/photo-1517673400267-0251440c45dc?auto=format&fit=crop&w=900&q=80 +chicken: https://images.unsplash.com/photo-1532550907401-a500c9a57435?auto=format&fit=crop&w=900&q=80 +salad: https://images.unsplash.com/photo-1512621776951-a57141f2eefd?auto=format&fit=crop&w=900&q=80 + +Лицензия: https://unsplash.com/license diff --git a/assets/chicken.jpg b/assets/chicken.jpg new file mode 100644 index 0000000..0bcc176 Binary files /dev/null and b/assets/chicken.jpg differ diff --git a/assets/oats.jpg b/assets/oats.jpg new file mode 100644 index 0000000..35ec087 Binary files /dev/null and b/assets/oats.jpg differ diff --git a/assets/salad.jpg b/assets/salad.jpg new file mode 100644 index 0000000..a91900f Binary files /dev/null and b/assets/salad.jpg differ diff --git a/docs/glossary.md b/docs/glossary.md index d99e5a2..cb1c92a 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -36,3 +36,7 @@ | Готовые занятия в зале | план тренировок | программа жиросжигания | Четыре общих занятия без персонализации | | Объём упражнения | подходы, повторы | сеты, репы | Количество повторений упражнения | | Сохранённые занятия | журнал тренировок | лог тренировок | Общий список занятий пользователя | +| Каталог блюд | рецепты | — | Фото, состав и приготовление блюда | +| Пищевая ценность | калории, белки, жиры, углеводы | — | Приблизительное значение на порцию | +| Количество еды | порции | — | Количество порций одного блюда | +| Состав блюда | ингредиенты | — | Продукты с массой до приготовления | diff --git a/docs/recipes.md b/docs/recipes.md new file mode 100644 index 0000000..04aeb36 --- /dev/null +++ b/docs/recipes.md @@ -0,0 +1,20 @@ +# Каталог рецептов + +Откройте `/recipes.html`, язык: `?lang=ru`, `?lang=kk` или `?lang=en`. +При отсутствии index.html сервер открывает каталог на `/`. + +Запуск: `npm ci`, `npm start`. Проверки: `npm run lint`, `npm test`. +Проверка браузера: `npx playwright install chromium`, затем `npx playwright test`. + +Фотографии лежат в assets, источники — assets/README.md. Они иллюстративные. +КБЖУ рассчитывается по приблизительным значениям ингредиентов на 100 г +в recipes.data.json; массы сырые, указанная вода добавляется к блюду. +Показатели зависят от производителя продуктов. Количество порций — 1–8. +Пользовательские тексты — recipes.i18n.json и recipes-status.i18n.js. +При изменении сообщения загрузки/ошибки обновляйте оба файла. + +Проверенные видимые тексты: заголовок, вступление, выбор языка, названия блюд, +время, порции и подписи кнопок, КБЖУ, ингредиенты, граммы, шаги приготовления, +пояснение о сыром весе и приблизительных значениях, сообщение отсутствия фото, +ошибка загрузки и повторная попытка, подвал. Сверены с docs/glossary.md; +обращение на «вы», технические идентификаторы и суммы отсутствуют. diff --git a/recipes-core.js b/recipes-core.js new file mode 100644 index 0000000..87980cb --- /dev/null +++ b/recipes-core.js @@ -0,0 +1,12 @@ +(function (root) { + 'use strict'; + function portions(value) { + return Math.min(8, Math.max(1, Math.trunc(Number(value)) || 1)); + } + function nutrition(recipe, foods, count = 1) { + return recipe.ingredients.reduce((sum, [id, grams]) => sum.map((v, i) => v + foods[id][i] * grams * portions(count) / 100), [0, 0, 0, 0]); + } + const api = { portions, nutrition }; + if (typeof module !== 'undefined') module.exports = api; + else root.RecipesCore = api; +})(globalThis); diff --git a/recipes-status.i18n.js b/recipes-status.i18n.js new file mode 100644 index 0000000..dc07d4e --- /dev/null +++ b/recipes-status.i18n.js @@ -0,0 +1,20 @@ +globalThis.RecipeMessages = { + "ru": { + "error": "Не удалось открыть рецепты. Обновите страницу или попробуйте позже.", + "retry": "Попробовать снова", + "title": "Рецепты на каждый день", + "loading": "Загружаем рецепты…" + }, + "kk": { + "error": "Рецепттер ашылмады. Бетті жаңартыңыз немесе кейінірек көріңіз.", + "retry": "Қайталап көру", + "title": "Күнделікті тағам рецептері", + "loading": "Рецепттер жүктелуде…" + }, + "en": { + "error": "Recipes could not be loaded. Refresh the page or try again later.", + "retry": "Try again", + "title": "Recipes for every day", + "loading": "Loading recipes…" + } +}; diff --git a/recipes.css b/recipes.css new file mode 100644 index 0000000..1df51f9 --- /dev/null +++ b/recipes.css @@ -0,0 +1 @@ +:root{font-family:system-ui,-apple-system,sans-serif;color:#243c33;background:#f5f4ed;font-synthesis:none}*{box-sizing:border-box}body{margin:0}main{max-width:1420px;margin:auto;padding:40px 5vw 60px}header{display:flex;justify-content:space-between;gap:24px;align-items:start;margin-bottom:28px}h1{font-family:Georgia,serif;font-size:clamp(2.5rem,5vw,4.4rem);font-weight:400;line-height:1.06;max-width:700px;margin:18px 0}header p{max-width:650px;line-height:1.6}.eyebrow{text-transform:uppercase;letter-spacing:.15em;font-size:.75rem;font-weight:700;color:#52725c}select,button{font:inherit;color:inherit;background:#fff;border:1px solid #c3ccc1;border-radius:10px;min-height:44px;padding:8px 14px}label{display:grid;gap:8px;font-size:.85rem}button{cursor:pointer}button:disabled{opacity:.35;cursor:default}button:focus-visible,select:focus-visible{outline:3px solid #9b632d;outline-offset:3px}.grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:24px;align-items:start}article{background:#fff;border-radius:22px;overflow:hidden;border:1px solid #e0e5da}figure{margin:0;background:#e2e8dc;position:relative;min-height:210px}img{width:100%;aspect-ratio:1.5;object-fit:cover;display:block}.time{position:absolute;left:18px;bottom:16px;border-radius:20px;background:#fff;padding:7px 12px;font-size:.8rem}.content{padding:24px}h2{font-family:Georgia,serif;font-size:1.9rem;font-weight:400;margin:0 0 22px;line-height:1.2}h3{font-size:1.05rem;margin:26px 0 10px}.servings{display:flex;justify-content:space-between;align-items:center;gap:10px;padding-bottom:16px;border-bottom:1px solid #e3e8de}.controls{display:flex;gap:14px;align-items:center}output{min-width:12px;text-align:center;font-weight:700}.nutrition{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:5px;background:#edf3e8;border-radius:12px;padding:14px 8px;margin:8px 0 0}.nutrition div{text-align:center}.nutrition strong{display:block;font-size:1.1rem}.nutrition span{font-size:.65rem;line-height:1.3;display:block;margin-top:5px}.small{font-size:.78rem;line-height:1.6;color:#536658}.ingredients{list-style:none;padding:0;margin:8px 0}.ingredients li{display:flex;justify-content:space-between;gap:16px;padding:9px 0;border-bottom:1px solid #edf0e8;font-size:.9rem}.ingredients b{white-space:nowrap}ol{padding-left:24px;margin:12px 0 0}ol li{font-size:.9rem;line-height:1.6;padding-left:4px;margin-bottom:12px}ol li::marker{color:#537347;font-weight:700}.note{max-width:850px;margin:28px 0;line-height:1.7;color:#536658;font-size:.85rem}footer{border-top:1px solid #d3ddce;padding-top:24px;font-family:Georgia,serif}.photo-error{padding:28px;line-height:1.6;margin:0}.failure{padding:40px;max-width:600px}.total{margin-top:16px}body[data-loaded="true"] main{animation:appear .3s ease-out}@keyframes appear{from{opacity:0}to{opacity:1}}@media(max-width:1050px){.grid{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:650px){main{padding:24px 18px 40px}header{display:block}header label{display:flex;align-items:center;margin-top:20px}.grid{grid-template-columns:1fr}h1{font-size:2.7rem}.content{padding:22px}img{aspect-ratio:1.6}}@media(prefers-reduced-motion:reduce){body[data-loaded="true"] main{animation:none}} diff --git a/recipes.data.json b/recipes.data.json new file mode 100644 index 0000000..8040487 --- /dev/null +++ b/recipes.data.json @@ -0,0 +1,152 @@ +{ + "foods": { + "oats": [ + 370, + 13, + 7, + 62 + ], + "milk": [ + 52, + 3, + 2.5, + 4.7 + ], + "banana": [ + 89, + 1.1, + 0.3, + 22.8 + ], + "chicken": [ + 110, + 23, + 1.5, + 0 + ], + "rice": [ + 350, + 7, + 1, + 78 + ], + "broccoli": [ + 34, + 2.8, + 0.4, + 6.6 + ], + "oil": [ + 900, + 0, + 100, + 0 + ], + "water": [ + 0, + 0, + 0, + 0 + ], + "tomato": [ + 18, + 0.9, + 0.2, + 3.9 + ], + "cucumber": [ + 15, + 0.7, + 0.1, + 3.6 + ], + "feta": [ + 265, + 14, + 21, + 4 + ], + "lettuce": [ + 15, + 1.4, + 0.2, + 2.9 + ] + }, + "recipes": [ + { + "id": "oats", + "minutes": 12, + "ingredients": [ + [ + "oats", + 50 + ], + [ + "milk", + 150 + ], + [ + "banana", + 100 + ], + [ + "water", + 50 + ] + ] + }, + { + "id": "chicken", + "minutes": 30, + "ingredients": [ + [ + "chicken", + 150 + ], + [ + "rice", + 60 + ], + [ + "broccoli", + 150 + ], + [ + "oil", + 5 + ], + [ + "water", + 150 + ] + ] + }, + { + "id": "salad", + "minutes": 10, + "ingredients": [ + [ + "tomato", + 150 + ], + [ + "cucumber", + 150 + ], + [ + "feta", + 60 + ], + [ + "lettuce", + 40 + ], + [ + "oil", + 5 + ] + ] + } + ] +} diff --git a/recipes.html b/recipes.html new file mode 100644 index 0000000..ef476cc --- /dev/null +++ b/recipes.html @@ -0,0 +1,9 @@ + + + + + + + +
+ diff --git a/recipes.i18n.json b/recipes.i18n.json new file mode 100644 index 0000000..ea251bb --- /dev/null +++ b/recipes.i18n.json @@ -0,0 +1,206 @@ +{ + "ru": { + "title": "Рецепты на каждый день", + "intro": "Выберите блюдо, укажите количество порций и готовьте по шагам.", + "eyebrow": "Питание • простые идеи", + "language": "Язык", + "servings": "Порции", + "less": "Меньше порций", + "more": "Больше порций", + "ingredients": "Ингредиенты", + "steps": "Как приготовить", + "perServing": "На одну порцию, примерно", + "total": "На всё блюдо, примерно", + "nutrition": [ + "ккал", + "Белки, г", + "Жиры, г", + "Углеводы, г" + ], + "grams": "г", + "minutes": "мин", + "note": "Вес указан для сырых продуктов. Пищевая ценность приблизительная и зависит от выбранных продуктов. Фото иллюстрируют блюдо.", + "photo": "Фото блюда недоступно. Используйте состав и шаги приготовления.", + "error": "Не удалось открыть рецепты. Обновите страницу или попробуйте позже.", + "retry": "Попробовать снова", + "loading": "Загружаем рецепты…", + "raw": "Вес до приготовления", + "footer": "Простые продукты. Понятные шаги. Ваш ритм.", + "recipes": { + "oats": { + "title": "Овсянка с бананом", + "steps": [ + "Смешайте хлопья, молоко и воду в небольшой кастрюле.", + "Доведите до кипения и варите на слабом огне 5–7 минут, помешивая.", + "Нарежьте банан и добавьте в готовую кашу." + ] + }, + "chicken": { + "title": "Курица с рисом и брокколи", + "steps": [ + "Промойте рис, залейте водой и варите под крышкой около 15–20 минут до мягкости.", + "Нарежьте курицу небольшими кусочками. Смажьте сковороду маслом и готовьте курицу 10–15 минут, переворачивая, до полной готовности (74 °C внутри).", + "Приготовьте брокколи на пару 5–7 минут до мягкости и подайте с курицей и рисом." + ] + }, + "salad": { + "title": "Овощной салат с фетой", + "steps": [ + "Вымойте и обсушите овощи и листья салата.", + "Нарежьте помидор, огурец и фету, порвите листья салата.", + "Соедините ингредиенты, заправьте маслом и аккуратно перемешайте." + ] + } + }, + "foods": { + "oats": "Овсяные хлопья", + "milk": "Молоко 2,5%", + "banana": "Банан без кожуры", + "chicken": "Куриная грудка без кожи", + "rice": "Рис сухой", + "broccoli": "Брокколи", + "oil": "Оливковое масло", + "water": "Вода", + "tomato": "Помидор", + "cucumber": "Огурец", + "feta": "Сыр фета", + "lettuce": "Листья салата" + } + }, + "kk": { + "title": "Күнделікті тағам рецептері", + "intro": "Тағамды таңдап, порция санын көрсетіңіз де, қадамдар бойынша дайындаңыз.", + "eyebrow": "Тамақтану • оңай идеялар", + "language": "Тіл", + "servings": "Порциялар", + "less": "Порцияны азайту", + "more": "Порцияны көбейту", + "ingredients": "Ингредиенттер", + "steps": "Дайындау жолы", + "perServing": "Бір порцияға, шамамен", + "total": "Барлық тағамға, шамамен", + "nutrition": [ + "ккал", + "Ақуыз, г", + "Май, г", + "Көмірсу, г" + ], + "grams": "г", + "minutes": "мин", + "note": "Салмақ шикі өнімдер үшін көрсетілген. Тағамдық құндылық шамамен берілген және таңдалған өнімдерге байланысты. Фотосуреттер тағамды бейнелейді.", + "photo": "Тағам фотосы ашылмады. Құрамы мен дайындау қадамдарын пайдаланыңыз.", + "error": "Рецепттер ашылмады. Бетті жаңартыңыз немесе кейінірек көріңіз.", + "retry": "Қайталап көру", + "loading": "Рецепттер жүктелуде…", + "raw": "Пісіргенге дейінгі салмақ", + "footer": "Қарапайым өнімдер. Түсінікті қадамдар. Өз ырғағыңыз.", + "recipes": { + "oats": { + "title": "Банан қосылған сұлы ботқасы", + "steps": [ + "Үлпектерді, сүтті және суды шағын кәстрөлге салыңыз.", + "Қайнатып, баяу отта 5–7 минут араластырып пісіріңіз.", + "Бананды турап, дайын ботқаға қосыңыз." + ] + }, + "chicken": { + "title": "Күріш пен брокколи қосылған тауық еті", + "steps": [ + "Күрішті жуып, су құйыңыз. Қақпағын жауып, жұмсарғанша 15–20 минут пісіріңіз.", + "Тауық етін шағын бөліктерге кесіңіз. Табаға май жағып, етті аударып отырып 10–15 минут толық піскенше қуырыңыз (ішкі температурасы 74 °C).", + "Брокколиді 5–7 минут буға пісіріп, тауық еті және күрішпен ұсыныңыз." + ] + }, + "salad": { + "title": "Фета қосылған көкөніс салаты", + "steps": [ + "Көкөністер мен салат жапырақтарын жуып, құрғатыңыз.", + "Қызанақ, қияр және фетаны турап, салат жапырақтарын үзіңіз.", + "Барлығын араластырып, май қосыңыз да, абайлап араластырыңыз." + ] + } + }, + "foods": { + "oats": "Сұлы үлпектері", + "milk": "Сүт 2,5%", + "banana": "Қабығы аршылған банан", + "chicken": "Терісіз тауық төс еті", + "rice": "Құрғақ күріш", + "broccoli": "Брокколи", + "oil": "Зәйтүн майы", + "water": "Су", + "tomato": "Қызанақ", + "cucumber": "Қияр", + "feta": "Фета ірімшігі", + "lettuce": "Салат жапырақтары" + } + }, + "en": { + "title": "Recipes for every day", + "intro": "Choose a dish, set your servings and follow the cooking steps.", + "eyebrow": "Nutrition • simple ideas", + "language": "Language", + "servings": "Servings", + "less": "Fewer servings", + "more": "More servings", + "ingredients": "Ingredients", + "steps": "How to cook", + "perServing": "Per serving, approximately", + "total": "Whole dish, approximately", + "nutrition": [ + "kcal", + "Protein, g", + "Fat, g", + "Carbs, g" + ], + "grams": "g", + "minutes": "min", + "note": "Weights are for raw ingredients. Nutrition is approximate and varies with the products you use. Photos illustrate the dish.", + "photo": "The dish photo could not load. Use the ingredients and cooking steps.", + "error": "Recipes could not be loaded. Refresh the page or try again later.", + "retry": "Try again", + "loading": "Loading recipes…", + "raw": "Weight before cooking", + "footer": "Simple ingredients. Clear steps. Your rhythm.", + "recipes": { + "oats": { + "title": "Banana porridge", + "steps": [ + "Combine oats, milk and water in a small saucepan.", + "Bring to a simmer and cook gently for 5–7 minutes, stirring.", + "Slice the banana and add it to the cooked porridge." + ] + }, + "chicken": { + "title": "Chicken, rice & broccoli", + "steps": [ + "Rinse the rice, add the water and simmer covered for about 15–20 minutes until tender.", + "Cut the chicken into small pieces. Oil a pan and cook for 10–15 minutes, turning, until fully cooked (74 °C in the centre).", + "Steam the broccoli for 5–7 minutes until tender and serve with the chicken and rice." + ] + }, + "salad": { + "title": "Vegetable & feta salad", + "steps": [ + "Wash and dry the vegetables and lettuce.", + "Chop the tomato, cucumber and feta, and tear the lettuce.", + "Combine everything, drizzle with oil and toss gently." + ] + } + }, + "foods": { + "oats": "Rolled oats", + "milk": "Milk, 2.5% fat", + "banana": "Peeled banana", + "chicken": "Skinless chicken breast", + "rice": "Dry rice", + "broccoli": "Broccoli", + "oil": "Olive oil", + "water": "Water", + "tomato": "Tomato", + "cucumber": "Cucumber", + "feta": "Feta cheese", + "lettuce": "Lettuce" + } + } +} diff --git a/recipes.js b/recipes.js new file mode 100644 index 0000000..ac9ada8 --- /dev/null +++ b/recipes.js @@ -0,0 +1,102 @@ +/* global RecipesCore, RecipeMessages */ +'use strict'; +const app = document.getElementById('app'); +const names = { ru: 'Русский', kk: 'Қазақша', en: 'English' }; +const requested = new URLSearchParams(location.search).get('lang') || navigator.language.split('-')[0]; +let lang = Object.hasOwn(names, requested) ? requested : 'ru'; +document.documentElement.lang = lang; +document.title = RecipeMessages[lang].title; +app.textContent = RecipeMessages[lang].loading; +let data, translations; +const counts = new Map(); +const e = (tag, text, className) => { + const node = document.createElement(tag); + if (text != null) node.textContent = text; + if (className) node.className = className; + return node; +}; +function nutrients(values, t) { + const box = e('div', null, 'nutrition'); + values.forEach((value, i) => { + const cell = e('div'); + cell.append(e('strong', new Intl.NumberFormat(lang, { maximumFractionDigits: i ? 1 : 0 }).format(value)), e('span', t.nutrition[i])); + box.append(cell); + }); + return box; +} +function card(recipe, t) { + const count = counts.get(recipe.id) || 1; + const text = t.recipes[recipe.id]; + const article = e('article'); article.dataset.recipe = recipe.id; + const figure = e('figure'); + const img = e('img'); img.src = `/assets/${recipe.id}.jpg`; img.alt = text.title; img.width = 900; img.height = 600; + img.addEventListener('error', () => { img.replaceWith(e('p', t.photo, 'photo-error')); }); + figure.append(img, e('span', `${recipe.minutes} ${t.minutes}`, 'time')); + const content = e('div', null, 'content'); + const title = e('h2', text.title); title.id = `title-${recipe.id}`; + article.setAttribute('aria-labelledby', title.id); + const controls = e('div', null, 'controls'); + const minus = e('button', '−'); minus.type = 'button'; minus.setAttribute('aria-label', t.less); minus.disabled = count === 1; + const plus = e('button', '+'); plus.type = 'button'; plus.setAttribute('aria-label', t.more); plus.disabled = count === 8; + const output = e('output', count); output.setAttribute('aria-live', 'polite'); output.setAttribute('aria-label', t.servings); + const change = (delta) => { + counts.set(recipe.id, RecipesCore.portions(count + delta)); + const replacement = card(recipe, translations[lang]); + article.replaceWith(replacement); + const buttons = replacement.querySelectorAll('.controls button'); + const target = buttons[delta < 0 ? 0 : 1]; + (target.disabled ? buttons[delta < 0 ? 1 : 0] : target).focus(); + }; + minus.onclick = () => change(-1); plus.onclick = () => change(1); + controls.append(minus, output, plus); + const servings = e('div', null, 'servings'); servings.append(e('span', t.servings), controls); + const ingredients = e('ul', null, 'ingredients'); + for (const [id, grams] of recipe.ingredients) { + const item = e('li'); item.append(e('span', t.foods[id]), e('b', `${grams * count} ${t.grams}`)); ingredients.append(item); + } + const steps = e('ol'); for (const step of text.steps) steps.append(e('li', step)); + content.append(title, servings, e('p', t.perServing, 'small'), nutrients(RecipesCore.nutrition(recipe, data.foods), t)); + if (count > 1) content.append(e('p', t.total, 'small total'), nutrients(RecipesCore.nutrition(recipe, data.foods, count), t)); + content.append(e('h3', t.ingredients), e('p', t.raw, 'small'), ingredients, e('h3', t.steps), steps); + article.append(figure, content); return article; +} +function render() { + const t = translations[lang]; + document.documentElement.lang = lang; document.title = t.title; + const header = e('header'), intro = e('div'); + intro.append(e('p', t.eyebrow, 'eyebrow'), e('h1', t.title), e('p', t.intro)); + const label = e('label', t.language), select = e('select'); + select.id = 'language'; + for (const [code, name] of Object.entries(names)) { + const option = e('option', name); option.value = code; option.selected = code === lang; select.append(option); + } + select.onchange = () => { + lang = select.value; + const url = new URL(location.href); url.searchParams.set('lang', lang); history.replaceState(null, '', url); + render(); document.getElementById('language').focus(); + }; + label.append(select); header.append(intro, label); + const grid = e('div', null, 'grid'); for (const recipe of data.recipes) grid.append(card(recipe, t)); + app.replaceChildren(header, grid, e('p', t.note, 'note'), e('footer', t.footer)); + app.setAttribute('aria-busy', 'false'); document.body.dataset.loaded = 'true'; +} +async function load() { + app.setAttribute('aria-busy', 'true'); + try { + const responses = await Promise.all(['/recipes.data.json', '/recipes.i18n.json'].map(url => fetch(url))); + if (responses.some(response => !response.ok)) throw new Error('catalog unavailable'); + [data, translations] = await Promise.all(responses.map(response => response.json())); + render(); + } catch { + // Error text lives in the translation resource, including the offline fallback. + const fallback = RecipeMessages; + app.replaceChildren(); + if (fallback) { + const box = e('div', null, 'failure'); box.setAttribute('role', 'alert'); + const retry = e('button', fallback[lang].retry); retry.onclick = load; + box.append(e('p', fallback[lang].error), retry); app.append(box); + } + app.setAttribute('aria-busy', 'false'); + } +} +load(); diff --git a/tests/browser/recipes.spec.js b/tests/browser/recipes.spec.js new file mode 100644 index 0000000..c9ad4a6 --- /dev/null +++ b/tests/browser/recipes.spec.js @@ -0,0 +1,40 @@ +const { test, expect } = require('@playwright/test'); +test('Три рецепта, две порции, границы и перевод без потери выбора', async ({ page }) => { + await page.goto('/recipes.html?lang=ru'); + await expect(page.locator('article')).toHaveCount(3); + const oats = page.locator('[data-recipe=oats]'); + await expect(oats.getByRole('button', { name: 'Меньше порций' })).toBeDisabled(); + await oats.getByRole('button', { name: 'Больше порций' }).click(); + await expect(oats.locator('output')).toHaveText('2'); + await expect(oats.locator('.ingredients li').first()).toContainText('100 г'); + await expect(oats.locator('.nutrition').first().locator('strong').first()).toHaveText('352'); + await expect(oats.locator('.nutrition').nth(1).locator('strong').first()).toHaveText('704'); + for (let i = 0; i < 6; i++) await oats.getByRole('button', { name: 'Больше порций' }).click(); + await expect(oats.getByRole('button', { name: 'Больше порций' })).toBeDisabled(); + for (const [lang, title] of [['kk', 'Күнделікті тағам рецептері'], ['en', 'Recipes for every day'], ['ru', 'Рецепты на каждый день']]) { + await page.locator('select').selectOption(lang); await expect(page.locator('h1')).toHaveText(title); await expect(oats.locator('output')).toHaveText('8'); + } + for (const img of await page.locator('img').all()) expect(await img.evaluate(img => img.naturalWidth)).toBeGreaterThan(0); +}); +test('Фото недоступно: состав и шаги остаются видимыми', async ({ page }) => { + await page.route('**/assets/oats.jpg', route => route.abort()); + await page.goto('/recipes.html?lang=ru'); + const oats = page.locator('[data-recipe=oats]'); + await expect(oats.getByText('Фото блюда недоступно.', { exact: false })).toBeVisible(); + await expect(oats.locator('ol li')).toHaveCount(3); +}); +test('Ошибка загрузки: понятное сообщение и повторная попытка', async ({ page }) => { + await page.route('**/recipes.data.json', route => route.fulfill({ status: 503, body: '' })); + await page.goto('/recipes.html?lang=ru'); + await expect(page.getByRole('alert')).toContainText('Не удалось открыть рецепты. Обновите страницу или попробуйте позже.'); + await page.unroute('**/recipes.data.json'); + await page.getByRole('button', { name: 'Попробовать снова' }).click(); + await expect(page.locator('article')).toHaveCount(3); +}); +test('Узкий экран: тексты видимы, горизонтальной прокрутки нет', async ({ page }) => { + await page.setViewportSize({ width: 375, height: 812 }); + await page.goto('/recipes.html?lang=kk'); + await expect(page.locator('article')).toHaveCount(3); + expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBeTruthy(); + await page.screenshot({ path: '/tmp/tptip-3-mobile.png', fullPage: true }); +}); diff --git a/tests/recipes-server.test.js b/tests/recipes-server.test.js new file mode 100644 index 0000000..3fb39cb --- /dev/null +++ b/tests/recipes-server.test.js @@ -0,0 +1,14 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const { createServer } = require('../server'); +test('Каталог доступен по ссылке, ресурсы локальны, закрытые файлы недоступны', async () => { + const server = createServer(); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const base = `http://127.0.0.1:${server.address().port}`; + try { + for (const path of ['/', '/recipes.html', '/recipes.css', '/recipes.js', '/recipes-core.js', '/recipes.i18n.json', '/recipes.data.json', '/recipes-status.i18n.js', '/assets/oats.jpg', '/assets/chicken.jpg', '/assets/salad.jpg', '/healthz']) { + const res = await fetch(base + path); assert.equal(res.status, 200, path); assert.ok((await res.arrayBuffer()).byteLength > 0); + } + for (const path of ['/.env', '/server.js', '/.peppa/project.json', '/assets/README.md', '/unknown']) assert.equal((await fetch(base + path)).status, 404); + } finally { await new Promise(resolve => server.close(resolve)); } +}); diff --git a/tests/recipes.test.js b/tests/recipes.test.js new file mode 100644 index 0000000..6f29dc0 --- /dev/null +++ b/tests/recipes.test.js @@ -0,0 +1,34 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const data = require('../recipes.data.json'); +const translations = require('../recipes.i18n.json'); +const { portions, nutrition } = require('../recipes-core'); +test('Просмотр рецепта: три полных рецепта на каждом языке с локальными фото', () => { + assert.equal(data.recipes.length, 3); + for (const recipe of data.recipes) { + const image = fs.readFileSync(`assets/${recipe.id}.jpg`); + assert.equal(image.readUInt16BE(), 0xffd8); + assert.ok(image.length > 10000); + for (const lang of ['ru', 'kk', 'en']) { + const t = translations[lang]; + assert.ok(t.recipes[recipe.id].title); + assert.ok(t.recipes[recipe.id].steps.length >= 3); + for (const [id, grams] of recipe.ingredients) { + assert.ok(t.foods[id]); assert.ok(grams > 0); assert.equal(data.foods[id].length, 4); + } + assert.deepEqual(Object.keys(t).sort(), Object.keys(translations.ru).sort()); + } + } +}); +test('Две порции: 100 г хлопьев и удвоенное общее КБЖУ', () => { + const oats = data.recipes[0]; + assert.equal(oats.ingredients[0][1] * portions(2), 100); + const one = nutrition(oats, data.foods); + assert.ok(Math.abs(one[0] - 352) < .01); + assert.deepEqual(nutrition(oats, data.foods, 2), one.map(v => v * 2)); +}); +test('Границы количества порций: от 1 до 8, только целые числа', () => { + for (const v of [-1, 0, '', 'oops', null]) assert.equal(portions(v), 1); + assert.equal(portions(20), 8); assert.equal(portions(2.9), 2); +});