Compare commits
4 Commits
8f5be07e67
...
d4b7d78806
| Author | SHA1 | Date | |
|---|---|---|---|
| d4b7d78806 | |||
| cbc89c1038 | |||
| 6713e77330 | |||
| 1338578367 |
5
.dockerignore
Normal file
5
.dockerignore
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
.git
|
||||||
|
node_modules
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
test-results
|
||||||
@ -9,7 +9,7 @@ check="$1"
|
|||||||
cfg=.peppa/project.json
|
cfg=.peppa/project.json
|
||||||
cmd=$(jq -r --arg c "$check" '.checks[$c] // empty' "$cfg" 2>/dev/null)
|
cmd=$(jq -r --arg c "$check" '.checks[$c] // empty' "$cfg" 2>/dev/null)
|
||||||
if [[ -z "$cmd" ]]; then
|
if [[ -z "$cmd" ]]; then
|
||||||
echo "peppa: проверка «$check» не настроена — пропуск"
|
echo "peppa: проверка «${check}» не настроена — пропуск"
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
log=$(mktemp)
|
log=$(mktemp)
|
||||||
|
|||||||
@ -69,8 +69,9 @@ report() { # report <status> [reason]
|
|||||||
}
|
}
|
||||||
|
|
||||||
dc() { # dc <image> <compose args…>
|
dc() { # dc <image> <compose args…>
|
||||||
local img="$1"; shift
|
local img="$1" sentry_env=staging; shift
|
||||||
IMAGE="$img" HOST="$host" ROUTER="$router" APP_PORT="$port" docker compose -p "$project" -f "$compose" "$@"
|
[[ $env_name == prod ]] && sentry_env=prod
|
||||||
|
SENTRY_RELEASE="$sha" SENTRY_ENVIRONMENT="${SENTRY_ENVIRONMENT:-$sentry_env}" IMAGE="$img" HOST="$host" ROUTER="$router" APP_PORT="$port" docker compose -p "$project" -f "$compose" "$@"
|
||||||
}
|
}
|
||||||
|
|
||||||
healthy() {
|
healthy() {
|
||||||
|
|||||||
5
.gitignore
vendored
5
.gitignore
vendored
@ -2,3 +2,8 @@ node_modules/
|
|||||||
.env
|
.env
|
||||||
.env.local
|
.env.local
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
|
||||||
|
node_modules/
|
||||||
|
test-results/
|
||||||
|
playwright-report/
|
||||||
|
generated/
|
||||||
|
|||||||
15
.peppa/memory.md
Normal file
15
.peppa/memory.md
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
# Память проекта
|
||||||
|
|
||||||
|
## Команды
|
||||||
|
- Проверки: bash .gitea/peppa-check.sh install|lint|test; npm ci, npm run lint, npm test. NODE_TEST_CONTEXT снимается в npm test, иначе Node пропускает запуск тестов.
|
||||||
|
- TPTIP-3: npm ci; npm run build; npm start; проверки npm run lint и npm test, браузер npx playwright install chromium && npx playwright test. Каталог /recipes.html, ru/kk/en, локальные фото assets/.
|
||||||
|
|
||||||
|
## Решения
|
||||||
|
- Приложение — index.html, данные в localStorage tpt.v1; чистая логика между LOGIC:START/END тестируется через node:vm, интерфейс — jsdom.
|
||||||
|
- Каталог gym-plan.i18n.js содержит ru/kk/en (?lang= или язык браузера); GymPlan.draft создаёт независимый черновик для openWorkoutForm, сохраняется только обычная запись workouts.
|
||||||
|
- server.js отдаёт файлы по белому списку FILES и /healthz; без index.html на / показывается about.html. Dockerfile использует COPY . . с .dockerignore.
|
||||||
|
- Новый статический файл добавляйте в server.js FILES и sw.js FILES с повышением CACHE для офлайн-режима.
|
||||||
|
- Переводы страницы продукта — about.i18n.json (ru/kk/en).
|
||||||
|
|
||||||
|
## Грабли
|
||||||
|
- На 17.11.2026 origin/main содержал только bootstrap, приложение было в task/tptip-8, сервер — в task/tptip-6; task/tptip-5 включает обе зависимости. При объединении server.js и Dockerfile использована версия TPTIP-6.
|
||||||
@ -1 +1,18 @@
|
|||||||
{"slug":"treker-po-trenirovkam-i-pitaniyu","key":"TPTIP","name":"Трекер по тренировкам и питанию","peppaUrl":"https://peppa.telecom.quest"}
|
{
|
||||||
|
"slug": "treker-po-trenirovkam-i-pitaniyu",
|
||||||
|
"key": "TPTIP",
|
||||||
|
"name": "Трекер по тренировкам и питанию",
|
||||||
|
"peppaUrl": "https://peppa.telecom.quest",
|
||||||
|
"checks": {
|
||||||
|
"install": "npm ci",
|
||||||
|
"lint": "npm run lint",
|
||||||
|
"test": "npm test",
|
||||||
|
"build": "npm run build"
|
||||||
|
},
|
||||||
|
"deploy": {
|
||||||
|
"compose": "deploy/compose.yml",
|
||||||
|
"service": "web",
|
||||||
|
"port": 3000,
|
||||||
|
"health": "/healthz"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
17
Dockerfile
Normal file
17
Dockerfile
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
FROM node:22-bookworm-slim AS build
|
||||||
|
WORKDIR /app
|
||||||
|
COPY package.json package-lock.json ./
|
||||||
|
RUN npm ci
|
||||||
|
COPY telemetry-client.js ./
|
||||||
|
RUN npm run build
|
||||||
|
RUN npm prune --omit=dev
|
||||||
|
|
||||||
|
FROM node:22-bookworm-slim
|
||||||
|
WORKDIR /app
|
||||||
|
ENV NODE_ENV=production PORT=3000
|
||||||
|
COPY --from=build /app/node_modules ./node_modules
|
||||||
|
COPY --from=build /app/generated ./generated
|
||||||
|
COPY server.js recipes.html recipes.css recipes.js recipes-core.js recipes.data.json recipes.i18n.json recipes-status.i18n.js ./
|
||||||
|
COPY assets ./assets
|
||||||
|
EXPOSE 3000
|
||||||
|
CMD ["node", "server.js"]
|
||||||
9
assets/README.md
Normal file
9
assets/README.md
Normal file
@ -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
|
||||||
BIN
assets/chicken.jpg
Normal file
BIN
assets/chicken.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 130 KiB |
BIN
assets/oats.jpg
Normal file
BIN
assets/oats.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 108 KiB |
BIN
assets/salad.jpg
Normal file
BIN
assets/salad.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 139 KiB |
@ -7,6 +7,10 @@ services:
|
|||||||
image: ${IMAGE}
|
image: ${IMAGE}
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
environment:
|
environment:
|
||||||
|
SENTRY_DSN: "${SENTRY_DSN:-}"
|
||||||
|
PUBLIC_SENTRY_DSN: "${PUBLIC_SENTRY_DSN:-}"
|
||||||
|
SENTRY_RELEASE: "${SENTRY_RELEASE:-}"
|
||||||
|
SENTRY_ENVIRONMENT: "${SENTRY_ENVIRONMENT:-dev}"
|
||||||
PORT: "${APP_PORT:-3000}"
|
PORT: "${APP_PORT:-3000}"
|
||||||
networks:
|
networks:
|
||||||
- traefik_default
|
- traefik_default
|
||||||
|
|||||||
@ -32,3 +32,7 @@
|
|||||||
| Вернуть работу | поправить | реджект, вернуть в бэклог, change request | Кнопка «Поправить» |
|
| Вернуть работу | поправить | реджект, вернуть в бэклог, change request | Кнопка «Поправить» |
|
||||||
| Список задач | доска, бэклог | канбан-борд, backlog | «Бэклог» допустим как название колонки |
|
| Список задач | доска, бэклог | канбан-борд, backlog | «Бэклог» допустим как название колонки |
|
||||||
| Ошибки продукта | баги | инциденты, Bugsink, Sentry | Вкладка «Баги» |
|
| Ошибки продукта | баги | инциденты, Bugsink, Sentry | Вкладка «Баги» |
|
||||||
|
| Каталог блюд | рецепты | — | Фото, состав и приготовление блюда |
|
||||||
|
| Пищевая ценность | калории, белки, жиры, углеводы | — | Приблизительное значение на порцию |
|
||||||
|
| Количество еды | порции | — | Количество порций одного блюда |
|
||||||
|
| Состав блюда | ингредиенты | — | Продукты с массой до приготовления |
|
||||||
|
|||||||
25
docs/recipes.md
Normal file
25
docs/recipes.md
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
# Каталог рецептов
|
||||||
|
|
||||||
|
Откройте `/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;
|
||||||
|
обращение на «вы», технические идентификаторы и суммы отсутствуют.
|
||||||
|
|
||||||
|
Мониторинг ошибок: `SENTRY_DSN` для сервера, `PUBLIC_SENTRY_DSN` для браузера,
|
||||||
|
`SENTRY_RELEASE` — SHA версии, `SENTRY_ENVIRONMENT` — dev/staging/prod.
|
||||||
|
Без DSN SDK не инициализируется, sendDefaultPii выключен. Клиентский SDK
|
||||||
|
собирается через `npm run build`; перед npm start выполните эту команду.
|
||||||
7
eslint.config.mjs
Normal file
7
eslint.config.mjs
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
import js from '@eslint/js';
|
||||||
|
import globals from 'globals';
|
||||||
|
export default [
|
||||||
|
{ ignores: ['node_modules/**', 'generated/**'] },
|
||||||
|
js.configs.recommended,
|
||||||
|
{ files: ['**/*.js', '**/*.mjs'], languageOptions: { globals: { ...globals.node, ...globals.browser } } }
|
||||||
|
];
|
||||||
@ -0,0 +1,2 @@
|
|||||||
|
schema: spec-driven
|
||||||
|
created: 2026-11-17
|
||||||
@ -0,0 +1,15 @@
|
|||||||
|
## Context
|
||||||
|
В origin/main только шаблон, TPTIP-6 и TPTIP-8 пока в отдельных ветках. Старого плана TPTIP-3 нет. См. proposal.md.
|
||||||
|
|
||||||
|
## Goals / Non-Goals
|
||||||
|
Независимый каталог /recipes.html, без переноса большого трекера из TPTIP-8.
|
||||||
|
|
||||||
|
## Decisions
|
||||||
|
- Статические HTML/CSS/JS и JSON ru/kk/en: текущий стек без фреймворка.
|
||||||
|
- Три локально сохранённых фото Unsplash с указанием источника в assets/README.md; внешняя сеть при просмотре не нужна. Альтернатива внешних URL делает просмотр зависимым от сети.
|
||||||
|
- Пищевая ценность приблизительная, вычисляется из фиксированных показателей на 100 г ингредиентов. Все веса относятся к сырым продуктам; готовая порция содержит весь рецепт.
|
||||||
|
- Отдельный recipes.html сохраняет пространство index.html для TPTIP-8. Мини-сервер на базе TPTIP-6 использует белый список; если index отсутствует, корень открывает каталог. При объединении с TPTIP-6 сохранить оба списка файлов и fallback.
|
||||||
|
- Node tests и ESLint; команды записываются в checks, для preview требуется Dockerfile и deploy из шаблона Node.
|
||||||
|
|
||||||
|
## Risks / Trade-offs
|
||||||
|
Фото иллюстрируют блюдо и могут отличаться от результата → подпись на странице. Погрешность состава → явная подпись «примерно». Личные загрузки вне задачи. Sentry подключён по общему правилу проекта: DSN только из env, без DSN SDK не запускается; sendDefaultPii=false, release и environment из переменных окружения. Клиентский пакет собирается esbuild локально, внешнего CDN нет.
|
||||||
@ -0,0 +1,20 @@
|
|||||||
|
Задача TPTIP-3 — фото блюд, рецепты, граммовки и КБЖУ.
|
||||||
|
|
||||||
|
## Why
|
||||||
|
Пользователю нужны готовые идеи еды с понятным составом и приготовлением.
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
- Каталог из трёх блюд с локальными фотографиями, ингредиентами и шагами.
|
||||||
|
- КБЖУ на порцию, переключение количества порций и языка ru/kk/en.
|
||||||
|
|
||||||
|
## Capabilities
|
||||||
|
### New Capabilities
|
||||||
|
- `recipes`: просмотр рецептов и пересчёт порций.
|
||||||
|
### Modified Capabilities
|
||||||
|
Нет.
|
||||||
|
|
||||||
|
## Impact
|
||||||
|
Отдельная страница recipes.html, данные переводов, локальные фото и проверки. Главная страница соседней TPTIP-8 не меняется. Вне scope: загрузка личных фото, распознавание продуктов, дневник питания.
|
||||||
|
|
||||||
|
## Вопросы к PM
|
||||||
|
Нет.
|
||||||
@ -0,0 +1,30 @@
|
|||||||
|
## Purpose
|
||||||
|
Каталог помогает выбрать блюдо по фотографии, приготовить его по граммовкам и увидеть приблизительную пищевую ценность порции.
|
||||||
|
|
||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: Полный рецепт
|
||||||
|
Система SHALL показывать минимум три рецепта с локальными фото, граммовками сырых ингредиентов, шагами приготовления и приблизительным КБЖУ на порцию на русском, казахском и английском языках.
|
||||||
|
|
||||||
|
#### Scenario: Просмотр рецепта
|
||||||
|
- **GIVEN** выбран русский язык
|
||||||
|
- **WHEN** пользователь открывает /recipes.html
|
||||||
|
- **THEN** видны три блюда, их фотографии, ингредиенты в граммах, шаги и КБЖУ на одну порцию
|
||||||
|
|
||||||
|
#### Scenario: Фото недоступно
|
||||||
|
- **GIVEN** фотография блюда не загрузилась
|
||||||
|
- **WHEN** пользователь просматривает рецепт
|
||||||
|
- **THEN** видна подпись вместо фото, ингредиенты и шаги доступны
|
||||||
|
|
||||||
|
### Requirement: Пересчёт порций
|
||||||
|
Система SHALL пересчитывать граммовки и общее КБЖУ для целого количества порций от 1 до 8, сохраняя КБЖУ на одну порцию.
|
||||||
|
|
||||||
|
#### Scenario: Две порции
|
||||||
|
- **GIVEN** в одной порции овсянки 50 г хлопьев
|
||||||
|
- **WHEN** пользователь выбирает 2 порции
|
||||||
|
- **THEN** показаны 100 г хлопьев, удвоенное общее КБЖУ и неизменное КБЖУ на порцию
|
||||||
|
|
||||||
|
#### Scenario: Нижняя граница
|
||||||
|
- **GIVEN** выбрана 1 порция
|
||||||
|
- **WHEN** пользователь просматривает управление порциями
|
||||||
|
- **THEN** уменьшение количества порций недоступно
|
||||||
@ -0,0 +1,12 @@
|
|||||||
|
# Tasks
|
||||||
|
|
||||||
|
## 1. Каталог
|
||||||
|
- [x] 1.1 Добавить три рецепта, переводы ru/kk/en и локальные фотографии; проверить полноту данных и пересчёт тестами, записать источники фото.
|
||||||
|
- [x] 1.2 Сделать адаптивную страницу, управление порциями и замену недоступного фото; проверить в браузере, сверить тексты со словарём.
|
||||||
|
|
||||||
|
## 2. Доставка и проверка
|
||||||
|
- [x] 2.1 Подключить выдачу страницы и ресурсов, настроить линтер и проверки; проверить HTTP-маршруты и запрет произвольных файлов тестами.
|
||||||
|
- [x] 2.2 Запустить проверки проекта, проверить страницу на узком экране и выполнить openspec validate.
|
||||||
|
|
||||||
|
## Workflow follow-up
|
||||||
|
- Записать память, архивировать change, открыть PR и передать на ревью.
|
||||||
32
openspec/specs/recipes/spec.md
Normal file
32
openspec/specs/recipes/spec.md
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
# recipes Specification
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
Каталог помогает выбрать блюдо по фотографии, приготовить его по граммовкам и увидеть приблизительную пищевую ценность порции.
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
### Requirement: Полный рецепт
|
||||||
|
Система SHALL показывать минимум три рецепта с локальными фото, граммовками сырых ингредиентов, шагами приготовления и приблизительным КБЖУ на порцию на русском, казахском и английском языках.
|
||||||
|
|
||||||
|
#### Scenario: Просмотр рецепта
|
||||||
|
- **GIVEN** выбран русский язык
|
||||||
|
- **WHEN** пользователь открывает /recipes.html
|
||||||
|
- **THEN** видны три блюда, их фотографии, ингредиенты в граммах, шаги и КБЖУ на одну порцию
|
||||||
|
|
||||||
|
#### Scenario: Фото недоступно
|
||||||
|
- **GIVEN** фотография блюда не загрузилась
|
||||||
|
- **WHEN** пользователь просматривает рецепт
|
||||||
|
- **THEN** видна подпись вместо фото, ингредиенты и шаги доступны
|
||||||
|
|
||||||
|
### Requirement: Пересчёт порций
|
||||||
|
Система SHALL пересчитывать граммовки и общее КБЖУ для целого количества порций от 1 до 8, сохраняя КБЖУ на одну порцию.
|
||||||
|
|
||||||
|
#### Scenario: Две порции
|
||||||
|
- **GIVEN** в одной порции овсянки 50 г хлопьев
|
||||||
|
- **WHEN** пользователь выбирает 2 порции
|
||||||
|
- **THEN** показаны 100 г хлопьев, удвоенное общее КБЖУ и неизменное КБЖУ на порцию
|
||||||
|
|
||||||
|
#### Scenario: Нижняя граница
|
||||||
|
- **GIVEN** выбрана 1 порция
|
||||||
|
- **WHEN** пользователь просматривает управление порциями
|
||||||
|
- **THEN** уменьшение количества порций недоступно
|
||||||
2348
package-lock.json
generated
Normal file
2348
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
21
package.json
Normal file
21
package.json
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
{
|
||||||
|
"name": "tptip-recipes",
|
||||||
|
"private": true,
|
||||||
|
"scripts": {
|
||||||
|
"lint": "eslint .",
|
||||||
|
"test": "node --test tests/*.test.js",
|
||||||
|
"start": "node server.js",
|
||||||
|
"build": "esbuild telemetry-client.js --bundle --minify --outfile=generated/telemetry.js"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@eslint/js": "^9.39.0",
|
||||||
|
"@playwright/test": "^1.56.0",
|
||||||
|
"esbuild": "^0.28.2",
|
||||||
|
"eslint": "^9.39.0",
|
||||||
|
"globals": "^16.5.0"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@sentry/browser": "^11.13.0",
|
||||||
|
"@sentry/node": "^11.13.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
2
playwright.config.js
Normal file
2
playwright.config.js
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
const { defineConfig } = require('@playwright/test');
|
||||||
|
module.exports = defineConfig({ testDir: './tests/browser', use: { baseURL: 'http://127.0.0.1:3093', browserName: 'chromium' }, webServer: { command: 'node server.js', env: { PORT: '3093' }, url: 'http://127.0.0.1:3093/healthz' } });
|
||||||
12
recipes-core.js
Normal file
12
recipes-core.js
Normal file
@ -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);
|
||||||
20
recipes-status.i18n.js
Normal file
20
recipes-status.i18n.js
Normal file
@ -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…"
|
||||||
|
}
|
||||||
|
};
|
||||||
1
recipes.css
Normal file
1
recipes.css
Normal file
@ -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%;height:auto;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}}
|
||||||
152
recipes.data.json
Normal file
152
recipes.data.json
Normal file
@ -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
|
||||||
|
]
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
10
recipes.html
Normal file
10
recipes.html
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title></title><link rel="stylesheet" href="/recipes.css">
|
||||||
|
<script defer src="/recipes-status.i18n.js"></script><script defer src="/recipes-core.js"></script><script defer src="/recipes.js"></script>
|
||||||
|
<script defer src="/telemetry.js"></script>
|
||||||
|
</head>
|
||||||
|
<body><main id="app" aria-busy="true"></main></body>
|
||||||
|
</html>
|
||||||
206
recipes.i18n.json
Normal file
206
recipes.i18n.json
Normal file
@ -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"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
102
recipes.js
Normal file
102
recipes.js
Normal file
@ -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();
|
||||||
57
server.js
Normal file
57
server.js
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
const Sentry = require('@sentry/node');
|
||||||
|
if (process.env.SENTRY_DSN) Sentry.init({ dsn: process.env.SENTRY_DSN, release: process.env.SENTRY_RELEASE, environment: process.env.SENTRY_ENVIRONMENT || 'dev', sendDefaultPii: false });
|
||||||
|
// Мини-сервер стенда (TPTIP-6): слушает $PORT, /healthz → 200, отдаёт файлы приложения по белому списку.
|
||||||
|
// Пока index.html нет, на «/» открывается каталог рецептов.
|
||||||
|
const http = require('node:http');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const path = require('node:path');
|
||||||
|
|
||||||
|
const DIR = process.env.APP_DIR || __dirname;
|
||||||
|
const FILES = {
|
||||||
|
'/': ['index.html', 'text/html; charset=utf-8'],
|
||||||
|
'/index.html': ['index.html', 'text/html; charset=utf-8'],
|
||||||
|
'/manifest.webmanifest': ['manifest.webmanifest', 'application/manifest+json'],
|
||||||
|
'/sw.js': ['sw.js', 'text/javascript; charset=utf-8'],
|
||||||
|
'/icon.svg': ['icon.svg', 'image/svg+xml'],
|
||||||
|
'/recipes.html': ['recipes.html', 'text/html; charset=utf-8'],
|
||||||
|
'/recipes.css': ['recipes.css', 'text/css; charset=utf-8'],
|
||||||
|
'/telemetry.js': ['generated/telemetry.js', 'text/javascript; charset=utf-8'],
|
||||||
|
'/recipes.js': ['recipes.js', 'text/javascript; charset=utf-8'],
|
||||||
|
'/recipes-core.js': ['recipes-core.js', 'text/javascript; charset=utf-8'],
|
||||||
|
'/recipes.data.json': ['recipes.data.json', 'application/json; charset=utf-8'],
|
||||||
|
'/recipes.i18n.json': ['recipes.i18n.json', 'application/json; charset=utf-8'],
|
||||||
|
'/recipes-status.i18n.js': ['recipes-status.i18n.js', 'text/javascript; charset=utf-8'],
|
||||||
|
'/assets/oats.jpg': ['assets/oats.jpg', 'image/jpeg'],
|
||||||
|
'/assets/chicken.jpg': ['assets/chicken.jpg', 'image/jpeg'],
|
||||||
|
'/assets/salad.jpg': ['assets/salad.jpg', 'image/jpeg'],
|
||||||
|
'/about.html': ['about.html', 'text/html; charset=utf-8'],
|
||||||
|
'/about.i18n.json': ['about.i18n.json', 'application/json; charset=utf-8']
|
||||||
|
};
|
||||||
|
const FALLBACK = { '/': ['recipes.html', 'text/html; charset=utf-8'] };
|
||||||
|
|
||||||
|
function send(res, f, fallback) {
|
||||||
|
fs.readFile(path.join(DIR, f[0]), (err, buf) => {
|
||||||
|
if (err && err.code === 'ENOENT' && fallback) return send(res, fallback, null);
|
||||||
|
if (err && err.code === 'ENOENT') { res.writeHead(404); return res.end('not found'); }
|
||||||
|
if (err) { res.writeHead(500); return res.end('error'); }
|
||||||
|
res.writeHead(200, { 'content-type': f[1], 'cache-control': 'no-cache' });
|
||||||
|
res.end(buf);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function createServer() {
|
||||||
|
return http.createServer((req, res) => {
|
||||||
|
const url = (req.url || '/').split('?')[0];
|
||||||
|
if (url === '/healthz') { res.writeHead(200, { 'content-type': 'text/plain' }); return res.end('ok'); }
|
||||||
|
if (url === '/telemetry.json') {
|
||||||
|
res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' });
|
||||||
|
return res.end(JSON.stringify({ dsn: process.env.PUBLIC_SENTRY_DSN || '', release: process.env.SENTRY_RELEASE, environment: process.env.SENTRY_ENVIRONMENT || 'dev' }));
|
||||||
|
}
|
||||||
|
const f = FILES[url];
|
||||||
|
if (!f) { res.writeHead(404); return res.end('not found'); }
|
||||||
|
send(res, f, FALLBACK[url]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (require.main === module) createServer().listen(Number(process.env.PORT) || 3000, '0.0.0.0');
|
||||||
|
module.exports = { createServer };
|
||||||
4
telemetry-client.js
Normal file
4
telemetry-client.js
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
import * as Sentry from '@sentry/browser';
|
||||||
|
fetch('/telemetry.json').then(response => response.json()).then(config => {
|
||||||
|
if (config.dsn) Sentry.init({ ...config, sendDefaultPii: false });
|
||||||
|
}).catch(() => { /* Optional telemetry must not prevent opening recipes. */ });
|
||||||
40
tests/browser/recipes.spec.js
Normal file
40
tests/browser/recipes.spec.js
Normal file
@ -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, animations: 'disabled' });
|
||||||
|
});
|
||||||
34
tests/recipes.test.js
Normal file
34
tests/recipes.test.js
Normal file
@ -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);
|
||||||
|
});
|
||||||
14
tests/server.test.js
Normal file
14
tests/server.test.js
Normal file
@ -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)); }
|
||||||
|
});
|
||||||
Loading…
Reference in New Issue
Block a user