Compare commits
6 Commits
254af7b2aa
...
edbbd1177f
| Author | SHA1 | Date | |
|---|---|---|---|
| edbbd1177f | |||
| a89c3b630f | |||
| fb4d103ba0 | |||
| 041aa99fc1 | |||
| abb966d1ed | |||
| 431ccc3b81 |
@ -14,3 +14,7 @@ deploy
|
|||||||
*.md
|
*.md
|
||||||
Dockerfile
|
Dockerfile
|
||||||
.dockerignore
|
.dockerignore
|
||||||
|
|
||||||
|
generated
|
||||||
|
test-results
|
||||||
|
playwright-report
|
||||||
|
|||||||
@ -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/
|
||||||
|
|||||||
@ -7,12 +7,14 @@
|
|||||||
## Решения
|
## Решения
|
||||||
- Приложение — index.html, данные в localStorage tpt.v1; чистая логика между LOGIC:START/END тестируется через node:vm, интерфейс — jsdom.
|
- Приложение — index.html, данные в localStorage tpt.v1; чистая логика между LOGIC:START/END тестируется через node:vm, интерфейс — jsdom.
|
||||||
- Каталог gym-plan.i18n.js содержит ru/kk/en (?lang= или язык браузера); GymPlan.draft создаёт независимый черновик для openWorkoutForm, сохраняется только обычная запись workouts.
|
- Каталог 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 и /healthz. Dockerfile использует COPY . . с .dockerignore.
|
||||||
- Новый статический файл добавляйте в server.js FILES и sw.js FILES с повышением CACHE для офлайн-режима.
|
- Новый статический файл добавляйте в server.js FILES и sw.js FILES с повышением CACHE для офлайн-режима.
|
||||||
- Переводы страницы продукта — about.i18n.json (ru/kk/en).
|
|
||||||
- TPTIP-4: профиль хранится серверно в DATA_DIR/profile.sqlite (SQLite, Node 24+), не в localStorage; NODE_ENV=production требует HTTPS для Secure cookie. При интеграции веток сохраняйте закрытые /api/profile и постоянный том.
|
- TPTIP-4: профиль хранится серверно в DATA_DIR/profile.sqlite (SQLite, Node 24+), не в localStorage; NODE_ENV=production требует HTTPS для Secure cookie. При интеграции веток сохраняйте закрытые /api/profile и постоянный том.
|
||||||
- TPTIP-4 после объединения main: npm start запускает profile-server.mjs; /tracker требует входа и получает нормы серверного профиля. CommonJS server.js сохранён для старых тестов; личные страницы/API исключены из sw.js, localStorage дневника разделён по имени, измерения туда не пишутся.
|
- TPTIP-4 после объединения main: npm start запускает profile-server.mjs; /tracker требует входа и получает нормы серверного профиля. CommonJS server.js сохранён для старых тестов; личные страницы/API исключены из sw.js, localStorage дневника разделён по имени, измерения туда не пишутся.
|
||||||
- TPTIP-10: готовые блюда (BUILTIN_RECIPES в index.html) хранят КБЖУ на порцию, grams и steps; «Выбрать» (chooseRecipe) ставит блюдо на день и пишет meals-запись; тест tests/dish-card.test.js.
|
- TPTIP-10: готовые блюда (BUILTIN_RECIPES в index.html) хранят КБЖУ на порцию, grams и steps; «Выбрать» (chooseRecipe) ставит блюдо на день и пишет meals-запись; тест tests/dish-card.test.js.
|
||||||
|
|
||||||
|
- TPTIP-11: страницы-заглушки about нет (удалена); мастер (startWizard) показывает пустые поля с подсказками, defaultData с 30/175/75 не менять — на нём держатся тесты.
|
||||||
## Грабли
|
## Грабли
|
||||||
- На 17.11.2026 origin/main содержал только bootstrap, приложение было в task/tptip-8, сервер — в task/tptip-6; task/tptip-5 включает обе зависимости. При объединении server.js и Dockerfile использована версия TPTIP-6.
|
- На 17.11.2026 origin/main содержал только bootstrap, приложение было в task/tptip-8, сервер — в task/tptip-6; task/tptip-5 включает обе зависимости. При объединении server.js и Dockerfile использована версия TPTIP-6.
|
||||||
|
|
||||||
|
- TPTIP-3: каталог /recipes.html (ru/kk/en), локальные фото assets; npm run build перед npm start; браузер npx playwright test. Сохранить маршруты recipes и сборку telemetry при объединении server.js/Dockerfile.
|
||||||
|
|||||||
@ -6,7 +6,8 @@
|
|||||||
"checks": {
|
"checks": {
|
||||||
"install": "npm ci",
|
"install": "npm ci",
|
||||||
"lint": "npm run lint",
|
"lint": "npm run lint",
|
||||||
"test": "npm test"
|
"test": "npm test",
|
||||||
|
"build": "npm run build"
|
||||||
},
|
},
|
||||||
"deploy": {
|
"deploy": {
|
||||||
"compose": "deploy/compose.yml",
|
"compose": "deploy/compose.yml",
|
||||||
|
|||||||
12
Dockerfile
12
Dockerfile
@ -1,8 +1,16 @@
|
|||||||
# Образ стенда (TPTIP-6): статическое приложение + мини-сервер server.js (/healthz, $PORT).
|
FROM node:22-bookworm-slim AS build
|
||||||
# COPY . . с .dockerignore — набор файлов приложения меняется от задачи к задаче, а сервер отдаёт только белый список.
|
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
|
FROM node:22-bookworm-slim
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
ENV NODE_ENV=production PORT=3000
|
ENV NODE_ENV=production PORT=3000
|
||||||
|
COPY --from=build /app/node_modules ./node_modules
|
||||||
|
COPY --from=build /app/generated ./generated
|
||||||
COPY . .
|
COPY . .
|
||||||
EXPOSE 3000
|
EXPOSE 3000
|
||||||
USER node
|
USER node
|
||||||
|
|||||||
62
about.html
62
about.html
@ -1,62 +0,0 @@
|
|||||||
<!doctype html>
|
|
||||||
<html lang="ru">
|
|
||||||
<head>
|
|
||||||
<meta charset="utf-8">
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
||||||
<title></title>
|
|
||||||
<style>
|
|
||||||
:root { --bg:#f6f7f9; --card:#fff; --text:#1d2330; --muted:#5b6475; --accent:#2f7d5b; --line:#e3e6eb; }
|
|
||||||
@media (prefers-color-scheme: dark) { :root { --bg:#14171c; --card:#1d2129; --text:#e8ebf0; --muted:#a3abb8; --accent:#5cc092; --line:#2c323c; } }
|
|
||||||
* { box-sizing: border-box; }
|
|
||||||
body { margin:0; background:var(--bg); color:var(--text); font:16px/1.55 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif; }
|
|
||||||
main { max-width:720px; margin:0 auto; padding:32px 16px 48px; }
|
|
||||||
header { display:flex; justify-content:space-between; align-items:flex-start; gap:12px; flex-wrap:wrap; }
|
|
||||||
h1 { font-size:1.75rem; line-height:1.2; margin:0 0 8px; }
|
|
||||||
.lead { color:var(--muted); margin:0 0 16px; }
|
|
||||||
.status { border-left:4px solid var(--accent); background:var(--card); padding:12px 16px; border-radius:8px; margin:0 0 24px; }
|
|
||||||
section { background:var(--card); border:1px solid var(--line); border-radius:12px; padding:16px 20px; margin:0 0 16px; }
|
|
||||||
h2 { font-size:1.125rem; margin:0 0 8px; color:var(--accent); }
|
|
||||||
ul, ol { margin:0; padding-left:1.25rem; }
|
|
||||||
li + li { margin-top:6px; }
|
|
||||||
label { color:var(--muted); font-size:.875rem; }
|
|
||||||
select { font:inherit; padding:4px 8px; border-radius:6px; border:1px solid var(--line); background:var(--card); color:var(--text); }
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<main>
|
|
||||||
<header>
|
|
||||||
<div>
|
|
||||||
<h1 data-t="title"></h1>
|
|
||||||
<p class="lead" data-t="lead"></p>
|
|
||||||
</div>
|
|
||||||
<label><span data-t="lang"></span>
|
|
||||||
<select id="lang"><option value="ru">Русский</option><option value="kk">Қазақша</option><option value="en">English</option></select>
|
|
||||||
</label>
|
|
||||||
</header>
|
|
||||||
<p class="status" data-t="status"></p>
|
|
||||||
<section><h2 data-t="whatTitle"></h2><ul data-list="what"></ul></section>
|
|
||||||
<section><h2 data-t="howTitle"></h2><ol data-list="how"></ol></section>
|
|
||||||
<section><h2 data-t="checkTitle"></h2><ol data-list="check"></ol></section>
|
|
||||||
</main>
|
|
||||||
<script>
|
|
||||||
(async function () {
|
|
||||||
var dict = await fetch('about.i18n.json').then(function (r) { return r.json(); });
|
|
||||||
function pick(code) { return dict[code] ? code : 'ru'; }
|
|
||||||
function render(code) {
|
|
||||||
var t = dict[code];
|
|
||||||
document.documentElement.lang = code;
|
|
||||||
document.title = t.title;
|
|
||||||
document.querySelectorAll('[data-t]').forEach(function (el) { el.textContent = t[el.dataset.t]; });
|
|
||||||
document.querySelectorAll('[data-list]').forEach(function (el) {
|
|
||||||
el.replaceChildren.apply(el, t[el.dataset.list].map(function (s) { var li = document.createElement('li'); li.textContent = s; return li; }));
|
|
||||||
});
|
|
||||||
document.getElementById('lang').value = code;
|
|
||||||
}
|
|
||||||
var q = new URLSearchParams(location.search).get('lang');
|
|
||||||
var code = pick(q || (navigator.language || 'ru').slice(0, 2));
|
|
||||||
render(code);
|
|
||||||
document.getElementById('lang').addEventListener('change', function (e) { render(pick(e.target.value)); });
|
|
||||||
})();
|
|
||||||
</script>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
@ -1,38 +0,0 @@
|
|||||||
{
|
|
||||||
"ru": {
|
|
||||||
"lang": "Язык",
|
|
||||||
"title": "Трекер тренировок и питания",
|
|
||||||
"lead": "Личный дневник тренировок и питания. Работает в браузере на телефоне и компьютере, записи хранятся только на вашем устройстве.",
|
|
||||||
"status": "Сейчас здесь страница продукта. Сам трекер появится по этой ссылке, когда вы примете задачу с приложением.",
|
|
||||||
"whatTitle": "Что это",
|
|
||||||
"what": ["Записывайте тренировки: дата, тип (силовая, кардио, растяжка), упражнения, подходы, повторы, вес, длительность и самочувствие.", "Ведите питание: что съели и сколько калорий, белков, жиров и углеводов.", "Смотрите итоги за день и неделю."],
|
|
||||||
"howTitle": "Как пользоваться",
|
|
||||||
"how": ["Откройте ссылку на телефоне или компьютере.", "Добавьте тренировку или приём пищи кнопкой «Добавить».", "Записи сохраняются сами — их увидите только вы и только на этом устройстве."],
|
|
||||||
"checkTitle": "Как проверить",
|
|
||||||
"check": ["Откройте эту ссылку — страница загружается.", "Добавьте тренировку, обновите страницу — запись на месте.", "Если что-то не так, нажмите «Поправить» у задачи и опишите, что увидели."]
|
|
||||||
},
|
|
||||||
"kk": {
|
|
||||||
"lang": "Тіл",
|
|
||||||
"title": "Жаттығу және тамақтану трекері",
|
|
||||||
"lead": "Жаттығу мен тамақтанудың жеке күнделігі. Телефон мен компьютердегі браузерде жұмыс істейді, жазбалар тек сіздің құрылғыңызда сақталады.",
|
|
||||||
"status": "Қазір мұнда өнім беті тұр. Қосымшасы бар тапсырманы қабылдағаннан кейін трекердің өзі осы сілтеме бойынша ашылады.",
|
|
||||||
"whatTitle": "Бұл не",
|
|
||||||
"what": ["Жаттығуларды жазыңыз: күні, түрі (күш, кардио, созылу), жаттығулар, тәсілдер, қайталау, салмақ, ұзақтығы және көңіл-күй.", "Тамақтануды жүргізіңіз: не жедіңіз, қанша калория, ақуыз, май және көмірсу.", "Күн мен апта қорытындысын көріңіз."],
|
|
||||||
"howTitle": "Қалай пайдалану керек",
|
|
||||||
"how": ["Сілтемені телефонда немесе компьютерде ашыңыз.", "«Қосу» батырмасымен жаттығуды немесе тамақты қосыңыз.", "Жазбалар өздігінен сақталады — оларды тек сіз және тек осы құрылғыда көресіз."],
|
|
||||||
"checkTitle": "Қалай тексеру керек",
|
|
||||||
"check": ["Осы сілтемені ашыңыз — бет жүктеледі.", "Жаттығу қосып, бетті жаңартыңыз — жазба орнында.", "Бірдеңе дұрыс болмаса, тапсырмадағы «Түзету» батырмасын басып, не көргеніңізді жазыңыз."]
|
|
||||||
},
|
|
||||||
"en": {
|
|
||||||
"lang": "Language",
|
|
||||||
"title": "Workout and nutrition tracker",
|
|
||||||
"lead": "A personal workout and nutrition diary. Works in the browser on your phone and computer; entries are stored only on your device.",
|
|
||||||
"status": "This is the product page for now. The tracker itself will open at this link once you accept the task with the app.",
|
|
||||||
"whatTitle": "What it is",
|
|
||||||
"what": ["Log workouts: date, type (strength, cardio, stretching), exercises, sets, reps, weight, duration and how you felt.", "Track meals: what you ate and its calories, protein, fat and carbs.", "See daily and weekly totals."],
|
|
||||||
"howTitle": "How to use it",
|
|
||||||
"how": ["Open the link on your phone or computer.", "Add a workout or a meal with the «Add» button.", "Entries save automatically — only you can see them, and only on this device."],
|
|
||||||
"checkTitle": "How to check it",
|
|
||||||
"check": ["Open this link — the page loads.", "Add a workout and reload the page — the entry is still there.", "If something is wrong, press «Fix» on the task and describe what you saw."]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
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
|
||||||
|
|||||||
@ -36,3 +36,7 @@
|
|||||||
| Готовые занятия в зале | план тренировок | программа жиросжигания | Четыре общих занятия без персонализации |
|
| Готовые занятия в зале | план тренировок | программа жиросжигания | Четыре общих занятия без персонализации |
|
||||||
| Объём упражнения | подходы, повторы | сеты, репы | Количество повторений упражнения |
|
| Объём упражнения | подходы, повторы | сеты, репы | Количество повторений упражнения |
|
||||||
| Сохранённые занятия | журнал тренировок | лог тренировок | Общий список занятий пользователя |
|
| Сохранённые занятия | журнал тренировок | лог тренировок | Общий список занятий пользователя |
|
||||||
|
| Каталог блюд | рецепты | — | Фото, состав и приготовление блюда |
|
||||||
|
| Пищевая ценность | калории, белки, жиры, углеводы | — | Приблизительное значение на порцию |
|
||||||
|
| Количество еды | порции | — | Количество порций одного блюда |
|
||||||
|
| Состав блюда | ингредиенты | — | Продукты с массой до приготовления |
|
||||||
|
|||||||
25
docs/recipes.md
Normal file
25
docs/recipes.md
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
# Каталог рецептов
|
||||||
|
|
||||||
|
Откройте `/recipes.html`, язык: `?lang=ru`, `?lang=kk` или `?lang=en`.
|
||||||
|
Каталог открывается из карточки рецептов на главной. Корень `/` сохраняет существующий трекер.
|
||||||
|
|
||||||
|
Запуск: `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 выполните эту команду.
|
||||||
@ -1,6 +1,7 @@
|
|||||||
import js from '@eslint/js';
|
import js from '@eslint/js';
|
||||||
import globals from 'globals';
|
import globals from 'globals';
|
||||||
export default [
|
export default [
|
||||||
|
{ ignores: ['node_modules/**', 'generated/**', 'test-results/**'] },
|
||||||
js.configs.recommended,
|
js.configs.recommended,
|
||||||
{ files: ['**/*.{js,mjs}'], languageOptions: { globals: { ...globals.browser, ...globals.node, ...globals.serviceworker } } }
|
{ files: ['**/*.{js,mjs}'], languageOptions: { globals: { ...globals.browser, ...globals.node, ...globals.serviceworker } } }
|
||||||
];
|
];
|
||||||
|
|||||||
18
index.html
18
index.html
@ -125,6 +125,7 @@ input:focus,select:focus,textarea:focus,button:focus-visible{outline:2px solid v
|
|||||||
<div id="toast" role="status"></div>
|
<div id="toast" role="status"></div>
|
||||||
|
|
||||||
<script src="gym-plan.i18n.js"></script>
|
<script src="gym-plan.i18n.js"></script>
|
||||||
|
<script src="recipes-status.i18n.js"></script>
|
||||||
<script>
|
<script>
|
||||||
/* =====================================================================
|
/* =====================================================================
|
||||||
СЛОЙ ДАННЫХ (чистые функции, без DOM) — проверяется tests/logic.test.js
|
СЛОЙ ДАННЫХ (чистые функции, без DOM) — проверяется tests/logic.test.js
|
||||||
@ -900,6 +901,7 @@ function recipesCard() {
|
|||||||
return h('div', { class: 'card' },
|
return h('div', { class: 'card' },
|
||||||
h('div', { class: 'row between' }, h('h3', null, 'Рецепты на день'),
|
h('div', { class: 'row between' }, h('h3', null, 'Рецепты на день'),
|
||||||
h('button', { onclick: openRecipePicker }, '+ Рецепт')),
|
h('button', { onclick: openRecipePicker }, '+ Рецепт')),
|
||||||
|
globalThis.RecipeMessages ? h('a', { href: '/recipes.html?lang=ru' }, globalThis.RecipeMessages.ru.title) : null,
|
||||||
planned.length ? planned.map(({ p, r }) => recipeView(r, h('button', { class: 'ghost icon', 'aria-label': 'Убрать рецепт из дня', onclick: () => { db.plan = db.plan.filter(x => x.id !== p.id); save(); render(); } }, '✕')))
|
planned.length ? planned.map(({ p, r }) => recipeView(r, h('button', { class: 'ghost icon', 'aria-label': 'Убрать рецепт из дня', onclick: () => { db.plan = db.plan.filter(x => x.id !== p.id); save(); render(); } }, '✕')))
|
||||||
: suggestionBlock());
|
: suggestionBlock());
|
||||||
}
|
}
|
||||||
@ -1132,11 +1134,12 @@ function viewStats() {
|
|||||||
НАСТРОЙКИ, МАСТЕР, ЭКСПОРТ / ИМПОРТ
|
НАСТРОЙКИ, МАСТЕР, ЭКСПОРТ / ИМПОРТ
|
||||||
===================================================================== */
|
===================================================================== */
|
||||||
/** Поля калькулятора нормы. */
|
/** Поля калькулятора нормы. */
|
||||||
function calcFields(pr) {
|
function calcFields(pr, hints) {
|
||||||
|
hints = hints || {};
|
||||||
const sex = selectField('Пол', [['m', 'Мужской'], ['f', 'Женский']], pr.sex);
|
const sex = selectField('Пол', [['m', 'Мужской'], ['f', 'Женский']], pr.sex);
|
||||||
const age = numField('Возраст, лет', { value: pr.age, required: true, int: true, min: 10, max: 100 });
|
const age = numField('Возраст, лет', { value: pr.age, placeholder: hints.age, required: true, int: true, min: 10, max: 100 });
|
||||||
const height = numField('Рост, см', { value: pr.height, required: true, min: 100, max: 250 });
|
const height = numField('Рост, см', { value: pr.height, placeholder: hints.height, required: true, min: 100, max: 250 });
|
||||||
const weight = numField('Вес, кг', { value: pr.weight, required: true, min: 25, max: 400 });
|
const weight = numField('Вес, кг', { value: pr.weight, placeholder: hints.weight, required: true, min: 25, max: 400 });
|
||||||
const act = selectField('Активность', ACTIVITY, pr.activity);
|
const act = selectField('Активность', ACTIVITY, pr.activity);
|
||||||
return {
|
return {
|
||||||
el: h('div', null, h('div', { class: 'grid2' }, sex, age), h('div', { class: 'grid2' }, height, weight), act),
|
el: h('div', null, h('div', { class: 'grid2' }, sex, age), h('div', { class: 'grid2' }, height, weight), act),
|
||||||
@ -1257,7 +1260,9 @@ function onImport(ev) {
|
|||||||
/** Мастер первого запуска: шаг 1 — цель и данные, шаг 2 — нормы. */
|
/** Мастер первого запуска: шаг 1 — цель и данные, шаг 2 — нормы. */
|
||||||
function startWizard() {
|
function startWizard() {
|
||||||
let goal = db.settings.goal;
|
let goal = db.settings.goal;
|
||||||
const calc = calcFields(db.settings.profile);
|
// Чужие числа по умолчанию не подставляем: поля пустые, в них только подсказка.
|
||||||
|
const calc = calcFields(Object.assign({}, db.settings.profile, { age: null, height: null, weight: null }),
|
||||||
|
{ age: 'например, 30', height: 'например, 175', weight: 'например, 75' });
|
||||||
const body = h('div');
|
const body = h('div');
|
||||||
let close;
|
let close;
|
||||||
const step1 = () => body.replaceChildren(
|
const step1 = () => body.replaceChildren(
|
||||||
@ -1266,7 +1271,8 @@ function startWizard() {
|
|||||||
h('div', { class: 'foot' }, h('button', { class: 'primary', onclick: () => { const p = calc.read(); if (!p) return; db.settings.goal = goal; db.settings.profile = p; step2(p); } }, 'Далее')));
|
h('div', { class: 'foot' }, h('button', { class: 'primary', onclick: () => { const p = calc.read(); if (!p) return; db.settings.goal = goal; db.settings.profile = p; step2(p); } }, 'Далее')));
|
||||||
const step2 = p => {
|
const step2 = p => {
|
||||||
const norms = normFields(Object.assign({}, db.settings, suggestNorms(goal, p)));
|
const norms = normFields(Object.assign({}, db.settings, suggestNorms(goal, p)));
|
||||||
body.replaceChildren(h('p', { class: 'muted' }, 'Шаг 2 из 2. Проверьте нормы — их можно поменять.'), norms.el,
|
body.replaceChildren(h('p', { class: 'muted' }, 'Шаг 2 из 2. Мы посчитали ваши дневные нормы по введённым данным.'),
|
||||||
|
h('p', { class: 'small muted', 'data-norms-hint': '' }, 'Если нужно, поправьте любое число вручную — затем нажмите «Готово».'), norms.el,
|
||||||
h('div', { class: 'foot' }, h('button', { onclick: step1 }, 'Назад'), h('button', { class: 'primary', onclick: () => { const n = norms.read(); if (!n) return; Object.assign(db.settings, n, { onboarded: true }); save(); close(); render(); toast('Готово! Можно записывать день.'); } }, 'Готово')));
|
h('div', { class: 'foot' }, h('button', { onclick: step1 }, 'Назад'), h('button', { class: 'primary', onclick: () => { const n = norms.read(); if (!n) return; Object.assign(db.settings, n, { onboarded: true }); save(); close(); render(); toast('Готово! Можно записывать день.'); } }, 'Готово')));
|
||||||
};
|
};
|
||||||
step1();
|
step1();
|
||||||
|
|||||||
@ -0,0 +1,4 @@
|
|||||||
|
## Решения
|
||||||
|
- Сервер без FALLBACK: нет index.html — 404, заглушек нет.
|
||||||
|
- calcFields получает необязательные подсказки; мастер обнуляет возраст/рост/вес только в окне, defaultData не меняется (нужен существующим тестам и настройкам).
|
||||||
|
- Кэш service worker поднят до tpt-v4-wizard.
|
||||||
@ -0,0 +1,8 @@
|
|||||||
|
## Why
|
||||||
|
На приёмке по ссылке мог открыться английский текст-заглушка, а мастер первого запуска подставлял чужие числа (30 лет, 175 см, 75 кг).
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
- Страница-заглушка (about.html, about.i18n.json) удалена; сервер отдаёт только трекер.
|
||||||
|
- Мастер: поля данных пустые, числа — только подсказки.
|
||||||
|
- Шаг 2 объясняет, что нормы посчитаны и их можно поправить.
|
||||||
|
- Окно мастера после «Готово» не возвращается (проверено тестом).
|
||||||
@ -0,0 +1,22 @@
|
|||||||
|
## REMOVED Requirements
|
||||||
|
|
||||||
|
### Requirement: Страница продукта на трёх языках
|
||||||
|
**Reason**: страница-заглушка убрана, пользователь видит только трекер.
|
||||||
|
|
||||||
|
### Requirement: Продукт открывается по ссылке
|
||||||
|
**Reason**: заменено требованием «Трекер открывается по ссылке» без страницы-заглушки.
|
||||||
|
|
||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: Трекер открывается по ссылке
|
||||||
|
Главная страница SHALL показывать приложение; страницы-заглушки с описанием нет.
|
||||||
|
|
||||||
|
#### Scenario: Приложение есть
|
||||||
|
- **GIVEN** в образе есть `index.html`
|
||||||
|
- **WHEN** пользователь открывает `/`
|
||||||
|
- **THEN** открывается трекер
|
||||||
|
|
||||||
|
#### Scenario: Страницы описания нет
|
||||||
|
- **GIVEN** сервер запущен
|
||||||
|
- **WHEN** пользователь открывает `/about.html`
|
||||||
|
- **THEN** ответ — 404
|
||||||
@ -0,0 +1,20 @@
|
|||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: Мастер первого запуска без чужих чисел
|
||||||
|
Поля возраста, роста и веса в мастере SHALL быть пустыми с подсказкой; на втором шаге SHALL быть сказано, что нормы посчитаны и их можно поправить; после «Готово» мастер SHALL не открываться снова.
|
||||||
|
|
||||||
|
#### Scenario: Первый шаг
|
||||||
|
- **GIVEN** приложение открыто впервые
|
||||||
|
- **WHEN** появляется мастер
|
||||||
|
- **THEN** поля возраста, роста и веса пустые, в них видны подсказки «например, 30», «например, 175», «например, 75»
|
||||||
|
|
||||||
|
#### Scenario: Второй шаг и завершение
|
||||||
|
- **GIVEN** на первом шаге введены возраст 40, рост 170, вес 65
|
||||||
|
- **WHEN** пользователь нажимает «Далее»
|
||||||
|
- **THEN** видно «Мы посчитали ваши дневные нормы» и подсказку, что их можно поправить
|
||||||
|
- **AND** после «Готово» и перезагрузки мастер не появляется
|
||||||
|
|
||||||
|
#### Scenario: Пустые поля
|
||||||
|
- **GIVEN** мастер открыт, поля пусты
|
||||||
|
- **WHEN** пользователь нажимает «Далее»
|
||||||
|
- **THEN** остаётся первый шаг, у полей показана ошибка
|
||||||
@ -0,0 +1,4 @@
|
|||||||
|
- [x] 1. Убрать страницу-заглушку и её маршруты
|
||||||
|
- [x] 2. Пустые поля мастера с подсказками
|
||||||
|
- [x] 3. Пояснение на шаге 2
|
||||||
|
- [x] 4. Тесты и проверки
|
||||||
@ -12,4 +12,7 @@
|
|||||||
- Node tests и ESLint; команды записываются в checks, для preview требуется Dockerfile и deploy из шаблона Node.
|
- Node tests и ESLint; команды записываются в checks, для preview требуется Dockerfile и deploy из шаблона Node.
|
||||||
|
|
||||||
## Risks / Trade-offs
|
## Risks / Trade-offs
|
||||||
Фото иллюстрируют блюдо и могут отличаться от результата → подпись на странице. Погрешность состава → явная подпись «примерно». Личные загрузки и Sentry не добавляются: нет нового backend поведения, отдельная инфраструктура вне задачи.
|
Фото иллюстрируют блюдо и могут отличаться от результата → подпись на странице. Погрешность состава → явная подпись «примерно». Личные загрузки вне задачи. Sentry подключён по общему правилу проекта: DSN только из env, без DSN SDK не запускается; sendDefaultPii=false, release и environment из переменных окружения. Клиентский пакет собирается esbuild локально, внешнего CDN нет.
|
||||||
|
|
||||||
|
## Интеграция после обновления main
|
||||||
|
TPTIP-5 вошла в main во время проверки. При rebase сохранены index.html, gym-plan, прежние тесты сервера, fallback about.html, ESLint 10 и jsdom. Добавлены ссылка из карточки рецептов, маршруты каталога и ресурсы service worker, версия кэша повышена. Docker сохраняет COPY . . с исключениями и USER node, дополняя сборкой SDK.
|
||||||
@ -1,12 +1,12 @@
|
|||||||
# Tasks
|
# Tasks
|
||||||
|
|
||||||
## 1. Каталог
|
## 1. Каталог
|
||||||
- [ ] 1.1 Добавить три рецепта, переводы ru/kk/en и локальные фотографии; проверить полноту данных и пересчёт тестами, записать источники фото.
|
- [x] 1.1 Добавить три рецепта, переводы ru/kk/en и локальные фотографии; проверить полноту данных и пересчёт тестами, записать источники фото.
|
||||||
- [ ] 1.2 Сделать адаптивную страницу, управление порциями и замену недоступного фото; проверить в браузере, сверить тексты со словарём.
|
- [x] 1.2 Сделать адаптивную страницу, управление порциями и замену недоступного фото; проверить в браузере, сверить тексты со словарём.
|
||||||
|
|
||||||
## 2. Доставка и проверка
|
## 2. Доставка и проверка
|
||||||
- [ ] 2.1 Подключить выдачу страницы и ресурсов, настроить линтер и проверки; проверить HTTP-маршруты и запрет произвольных файлов тестами.
|
- [x] 2.1 Подключить выдачу страницы и ресурсов, настроить линтер и проверки; проверить HTTP-маршруты и запрет произвольных файлов тестами.
|
||||||
- [ ] 2.2 Запустить проверки проекта, проверить страницу на узком экране и выполнить openspec validate.
|
- [x] 2.2 Запустить проверки проекта, проверить страницу на узком экране и выполнить openspec validate.
|
||||||
|
|
||||||
## Workflow follow-up
|
## Workflow follow-up
|
||||||
- Записать память, архивировать change, открыть PR и передать на ревью.
|
- Записать память, архивировать change, открыть PR и передать на ревью.
|
||||||
@ -18,34 +18,15 @@ TBD - created by archiving change tptip-6-open-by-link. Update Purpose after arc
|
|||||||
- **WHEN** приходит запрос `GET /.peppa/project.json`
|
- **WHEN** приходит запрос `GET /.peppa/project.json`
|
||||||
- **THEN** ответ — 404
|
- **THEN** ответ — 404
|
||||||
|
|
||||||
### Requirement: Продукт открывается по ссылке
|
### Requirement: Трекер открывается по ссылке
|
||||||
Главная страница SHALL показывать приложение, а если его файла нет — страницу продукта с описанием,
|
Главная страница SHALL показывать приложение; страницы-заглушки с описанием нет.
|
||||||
инструкцией и способом проверки.
|
|
||||||
|
|
||||||
#### Scenario: Приложение есть
|
#### Scenario: Приложение есть
|
||||||
- **GIVEN** в образе есть `index.html`
|
- **GIVEN** в образе есть `index.html`
|
||||||
- **WHEN** пользователь открывает `/`
|
- **WHEN** пользователь открывает `/`
|
||||||
- **THEN** открывается трекер
|
- **THEN** открывается трекер
|
||||||
|
|
||||||
#### Scenario: Приложения ещё нет
|
#### Scenario: Страницы описания нет
|
||||||
- **GIVEN** в образе нет `index.html`
|
- **GIVEN** сервер запущен
|
||||||
- **WHEN** пользователь открывает `/`
|
- **WHEN** пользователь открывает `/about.html`
|
||||||
- **THEN** открывается страница продукта с разделами «Что это», «Как пользоваться», «Как проверить»
|
- **THEN** ответ — 404
|
||||||
|
|
||||||
### Requirement: Страница продукта на трёх языках
|
|
||||||
Страница продукта SHALL брать тексты из файла переводов (ru, kk, en), по умолчанию — русский.
|
|
||||||
|
|
||||||
#### Scenario Outline: Выбор языка
|
|
||||||
- **GIVEN** страница продукта открыта по адресу `/about.html?lang=<lang>`
|
|
||||||
- **WHEN** страница загрузилась
|
|
||||||
- **THEN** заголовок — «<title>»
|
|
||||||
|
|
||||||
| lang | title |
|
|
||||||
|---|---|
|
|
||||||
| ru | Трекер тренировок и питания |
|
|
||||||
| en | Workout and nutrition tracker |
|
|
||||||
|
|
||||||
#### Scenario: Неизвестный язык
|
|
||||||
- **GIVEN** страница продукта открыта по адресу `/about.html?lang=xx`
|
|
||||||
- **WHEN** страница загрузилась
|
|
||||||
- **THEN** тексты показаны на русском
|
|
||||||
|
|||||||
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** уменьшение количества порций недоступно
|
||||||
@ -218,3 +218,22 @@ TBD - created by archiving change tptip-8-fitness-tracker. Update Purpose after
|
|||||||
- **GIVEN** свой рецепт без значений КБЖУ
|
- **GIVEN** свой рецепт без значений КБЖУ
|
||||||
- **WHEN** пользователь нажимает «Выбрать»
|
- **WHEN** пользователь нажимает «Выбрать»
|
||||||
- **THEN** рецепт ставится на день, запись о еде не создаётся
|
- **THEN** рецепт ставится на день, запись о еде не создаётся
|
||||||
|
|
||||||
|
### Requirement: Мастер первого запуска без чужих чисел
|
||||||
|
Поля возраста, роста и веса в мастере SHALL быть пустыми с подсказкой; на втором шаге SHALL быть сказано, что нормы посчитаны и их можно поправить; после «Готово» мастер SHALL не открываться снова.
|
||||||
|
|
||||||
|
#### Scenario: Первый шаг
|
||||||
|
- **GIVEN** приложение открыто впервые
|
||||||
|
- **WHEN** появляется мастер
|
||||||
|
- **THEN** поля возраста, роста и веса пустые, в них видны подсказки «например, 30», «например, 175», «например, 75»
|
||||||
|
|
||||||
|
#### Scenario: Второй шаг и завершение
|
||||||
|
- **GIVEN** на первом шаге введены возраст 40, рост 170, вес 65
|
||||||
|
- **WHEN** пользователь нажимает «Далее»
|
||||||
|
- **THEN** видно «Мы посчитали ваши дневные нормы» и подсказку, что их можно поправить
|
||||||
|
- **AND** после «Готово» и перезагрузки мастер не появляется
|
||||||
|
|
||||||
|
#### Scenario: Пустые поля
|
||||||
|
- **GIVEN** мастер открыт, поля пусты
|
||||||
|
- **WHEN** пользователь нажимает «Далее»
|
||||||
|
- **THEN** остаётся первый шаг, у полей показана ошибка
|
||||||
|
|||||||
1189
package-lock.json
generated
1189
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
12
package.json
12
package.json
@ -5,12 +5,20 @@
|
|||||||
"type": "commonjs",
|
"type": "commonjs",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"lint": "eslint .",
|
"lint": "eslint .",
|
||||||
"test": "env -u NODE_TEST_CONTEXT node --test tests/*.test.js"
|
"test": "env -u NODE_TEST_CONTEXT node --test tests/*.test.js",
|
||||||
|
"start": "node server.js",
|
||||||
|
"build": "esbuild telemetry-client.js --bundle --minify --outfile=generated/telemetry.js"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^10.0.1",
|
"@eslint/js": "^10.0.1",
|
||||||
"eslint": "^10.15.0",
|
"eslint": "^10.15.0",
|
||||||
"globals": "^17.14.0",
|
"globals": "^17.14.0",
|
||||||
"jsdom": "^31.0.1"
|
"jsdom": "^31.0.1",
|
||||||
|
"@playwright/test": "^1.56.0",
|
||||||
|
"esbuild": "^0.28.2"
|
||||||
|
},
|
||||||
|
"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();
|
||||||
28
server.js
28
server.js
@ -1,5 +1,8 @@
|
|||||||
|
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, отдаёт файлы приложения по белому списку.
|
// Мини-сервер стенда (TPTIP-6): слушает $PORT, /healthz → 200, отдаёт файлы приложения по белому списку.
|
||||||
// Пока index.html нет, на «/» отдаётся страница продукта about.html.
|
// По ссылке открывается трекер; каталог рецептов доступен на /recipes.html.
|
||||||
|
|
||||||
const http = require('node:http');
|
const http = require('node:http');
|
||||||
const fs = require('node:fs');
|
const fs = require('node:fs');
|
||||||
const path = require('node:path');
|
const path = require('node:path');
|
||||||
@ -12,14 +15,21 @@ const FILES = {
|
|||||||
'/manifest.webmanifest': ['manifest.webmanifest', 'application/manifest+json'],
|
'/manifest.webmanifest': ['manifest.webmanifest', 'application/manifest+json'],
|
||||||
'/sw.js': ['sw.js', 'text/javascript; charset=utf-8'],
|
'/sw.js': ['sw.js', 'text/javascript; charset=utf-8'],
|
||||||
'/icon.svg': ['icon.svg', 'image/svg+xml'],
|
'/icon.svg': ['icon.svg', 'image/svg+xml'],
|
||||||
'/about.html': ['about.html', 'text/html; charset=utf-8'],
|
'/recipes.html': ['recipes.html', 'text/html; charset=utf-8'],
|
||||||
'/about.i18n.json': ['about.i18n.json', 'application/json; 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']
|
||||||
};
|
};
|
||||||
const FALLBACK = { '/': ['about.html', 'text/html; charset=utf-8'] };
|
|
||||||
|
|
||||||
function send(res, f, fallback) {
|
function send(res, f) {
|
||||||
fs.readFile(path.join(DIR, f[0]), (err, buf) => {
|
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 && err.code === 'ENOENT') { res.writeHead(404); return res.end('not found'); }
|
||||||
if (err) { res.writeHead(500); return res.end('error'); }
|
if (err) { res.writeHead(500); return res.end('error'); }
|
||||||
res.writeHead(200, { 'content-type': f[1], 'cache-control': 'no-cache' });
|
res.writeHead(200, { 'content-type': f[1], 'cache-control': 'no-cache' });
|
||||||
@ -31,9 +41,13 @@ function createServer() {
|
|||||||
return http.createServer((req, res) => {
|
return http.createServer((req, res) => {
|
||||||
const url = (req.url || '/').split('?')[0];
|
const url = (req.url || '/').split('?')[0];
|
||||||
if (url === '/healthz') { res.writeHead(200, { 'content-type': 'text/plain' }); return res.end('ok'); }
|
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];
|
const f = FILES[url];
|
||||||
if (!f) { res.writeHead(404); return res.end('not found'); }
|
if (!f) { res.writeHead(404); return res.end('not found'); }
|
||||||
send(res, f, FALLBACK[url]);
|
send(res, f);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
4
sw.js
4
sw.js
@ -1,6 +1,6 @@
|
|||||||
// Сервис-воркер: приложение открывается без интернета (сначала сеть, при отсутствии — копия из кэша).
|
// Сервис-воркер: приложение открывается без интернета (сначала сеть, при отсутствии — копия из кэша).
|
||||||
const CACHE = 'tpt-v3-dish-card';
|
const CACHE = 'tpt-v5-wizard-recipes';
|
||||||
const FILES = ['./', 'index.html', 'gym-plan.i18n.js', 'manifest.webmanifest', 'icon.svg'];
|
const FILES = ['./', 'index.html', 'gym-plan.i18n.js', 'manifest.webmanifest', 'icon.svg', 'recipes.html', 'recipes.css', 'recipes.js', 'recipes-core.js', 'recipes-status.i18n.js', 'recipes.data.json', 'recipes.i18n.json', 'telemetry.js', 'assets/oats.jpg', 'assets/chicken.jpg', 'assets/salad.jpg'];
|
||||||
self.addEventListener('install', e => { e.waitUntil(caches.open(CACHE).then(c => c.addAll(FILES)).then(() => self.skipWaiting())); });
|
self.addEventListener('install', e => { e.waitUntil(caches.open(CACHE).then(c => c.addAll(FILES)).then(() => self.skipWaiting())); });
|
||||||
self.addEventListener('activate', e => {
|
self.addEventListener('activate', e => {
|
||||||
e.waitUntil(caches.keys().then(ks => Promise.all(ks.filter(k => k !== CACHE).map(k => caches.delete(k)))).then(() => self.clients.claim()));
|
e.waitUntil(caches.keys().then(ks => Promise.all(ks.filter(k => k !== CACHE).map(k => caches.delete(k)))).then(() => self.clients.claim()));
|
||||||
|
|||||||
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. */ });
|
||||||
48
tests/browser/recipes.spec.js
Normal file
48
tests/browser/recipes.spec.js
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
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' });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Переход из трекера в каталог рецептов', async ({ page }) => {
|
||||||
|
await page.addInitScript(() => localStorage.setItem('tpt.v1', JSON.stringify({ v: 1, settings: { onboarded: true } })));
|
||||||
|
await page.goto('/');
|
||||||
|
await page.getByRole('link', { name: 'Рецепты на каждый день' }).first().click();
|
||||||
|
await expect(page.locator('article')).toHaveCount(3);
|
||||||
|
await expect(page).toHaveURL(/recipes.html/);
|
||||||
|
});
|
||||||
14
tests/recipes-server.test.js
Normal file
14
tests/recipes-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)); }
|
||||||
|
});
|
||||||
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);
|
||||||
|
});
|
||||||
@ -1,4 +1,4 @@
|
|||||||
// Сценарии спеки deploy (TPTIP-6): сервер стенда и страница продукта.
|
// Сценарии спеки deploy (TPTIP-6): сервер стенда и отсутствие страницы-заглушки.
|
||||||
const test = require('node:test');
|
const test = require('node:test');
|
||||||
const assert = require('node:assert');
|
const assert = require('node:assert');
|
||||||
const fs = require('node:fs');
|
const fs = require('node:fs');
|
||||||
@ -22,8 +22,6 @@ function tmpDir(files) {
|
|||||||
return d;
|
return d;
|
||||||
}
|
}
|
||||||
|
|
||||||
const about = fs.readFileSync(path.join(ROOT, 'about.html'), 'utf8');
|
|
||||||
|
|
||||||
test('Сервер жив: GET /healthz → 200 «ok»', () => withServer(ROOT, async (base) => {
|
test('Сервер жив: GET /healthz → 200 «ok»', () => withServer(ROOT, async (base) => {
|
||||||
const r = await fetch(base + '/healthz');
|
const r = await fetch(base + '/healthz');
|
||||||
assert.strictEqual(r.status, 200);
|
assert.strictEqual(r.status, 200);
|
||||||
@ -36,28 +34,13 @@ test('Неизвестный адрес: служебные файлы не от
|
|||||||
}
|
}
|
||||||
}));
|
}));
|
||||||
|
|
||||||
test('Приложение есть: «/» отдаёт index.html', () => withServer(tmpDir({ 'index.html': '<title>Трекер</title>', 'about.html': about }), async (base) => {
|
test('Приложение есть: «/» отдаёт index.html', () => withServer(tmpDir({ 'index.html': '<title>Трекер</title>' }), async (base) => {
|
||||||
const r = await fetch(base + '/');
|
const r = await fetch(base + '/');
|
||||||
assert.strictEqual(r.status, 200);
|
assert.strictEqual(r.status, 200);
|
||||||
assert.match(await r.text(), /<title>Трекер<\/title>/);
|
assert.match(await r.text(), /<title>Трекер<\/title>/);
|
||||||
}));
|
}));
|
||||||
|
|
||||||
test('Приложения ещё нет: «/» отдаёт страницу продукта', () => withServer(tmpDir({ 'about.html': about }), async (base) => {
|
test('Страницы-заглушки нет: «/» без приложения не отдаёт английский текст', () => withServer(tmpDir({}), async (base) => {
|
||||||
const r = await fetch(base + '/');
|
assert.strictEqual((await fetch(base + '/')).status, 404);
|
||||||
assert.strictEqual(r.status, 200);
|
assert.strictEqual((await fetch(base + '/about.html')).status, 404);
|
||||||
assert.match(r.headers.get('content-type'), /text\/html/);
|
|
||||||
assert.match(await r.text(), /data-list="check"/);
|
|
||||||
}));
|
}));
|
||||||
|
|
||||||
test('Страница продукта на трёх языках: все ключи есть в ru, kk, en', () => {
|
|
||||||
const dict = JSON.parse(fs.readFileSync(path.join(ROOT, 'about.i18n.json'), 'utf8'));
|
|
||||||
assert.deepStrictEqual(Object.keys(dict).sort(), ['en', 'kk', 'ru']);
|
|
||||||
const keys = new Set([...about.matchAll(/data-(?:t|list)="([^"]+)"/g)].map((m) => m[1]));
|
|
||||||
for (const code of ['ru', 'kk', 'en']) for (const k of keys) assert.ok(dict[code][k], `${code}.${k}`);
|
|
||||||
assert.strictEqual(dict.ru.title, 'Трекер тренировок и питания');
|
|
||||||
assert.strictEqual(dict.en.title, 'Workout and nutrition tracker');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('Неизвестный язык: страница выбирает русский', () => {
|
|
||||||
assert.match(about, /dict\[code\] \? code : 'ru'/);
|
|
||||||
});
|
|
||||||
|
|||||||
51
tests/wizard.test.js
Normal file
51
tests/wizard.test.js
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
// Сценарии TPTIP-11: мастер первого запуска без чужих чисел, с понятным вторым шагом.
|
||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const { JSDOM, VirtualConsole } = require('jsdom');
|
||||||
|
const plan = require('../gym-plan.i18n.js');
|
||||||
|
const source = fs.readFileSync('index.html', 'utf8');
|
||||||
|
|
||||||
|
function open(saved) {
|
||||||
|
const errors = [];
|
||||||
|
const vc = new VirtualConsole();
|
||||||
|
vc.on('jsdomError', e => errors.push(e));
|
||||||
|
const dom = new JSDOM(source.replace('<script src="gym-plan.i18n.js"></script>', ''), {
|
||||||
|
url: 'http://localhost/', runScripts: 'dangerously', virtualConsole: vc,
|
||||||
|
beforeParse(w) { w.GymPlan = plan; w.scrollTo = () => {}; if (saved) w.localStorage.setItem('tpt.v1', saved); }
|
||||||
|
});
|
||||||
|
assert.deepEqual(errors, []);
|
||||||
|
return { dom, document: dom.window.document };
|
||||||
|
}
|
||||||
|
const btn = (d, t) => [...d.querySelectorAll('button')].find(b => b.textContent === t);
|
||||||
|
const inputs = d => [...d.querySelectorAll('.sheet input')];
|
||||||
|
|
||||||
|
test('Сценарий: на первом шаге поля пустые, числа только в подсказках', t => {
|
||||||
|
const { dom, document } = open(); t.after(() => dom.window.close());
|
||||||
|
const [age, height, weight] = inputs(document);
|
||||||
|
for (const i of [age, height, weight]) assert.equal(i.value, '');
|
||||||
|
assert.match(age.placeholder, /30/);
|
||||||
|
btn(document, 'Далее').click();
|
||||||
|
assert.match(document.querySelector('.sheet').textContent, /Шаг 1 из 2/);
|
||||||
|
assert.equal(inputs(document).length, 3, 'пустые поля не пускают дальше');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Сценарий: на втором шаге нормы посчитаны и правятся вручную; окно больше не появляется', t => {
|
||||||
|
const { dom, document } = open(); t.after(() => dom.window.close());
|
||||||
|
const [age, height, weight] = inputs(document);
|
||||||
|
age.value = '40'; height.value = '170'; weight.value = '65';
|
||||||
|
btn(document, 'Далее').click();
|
||||||
|
const sheet = document.querySelector('.sheet');
|
||||||
|
assert.match(sheet.textContent, /Шаг 2 из 2\. Мы посчитали/);
|
||||||
|
assert.ok(sheet.querySelector('[data-norms-hint]'));
|
||||||
|
const kcal = inputs(document)[0];
|
||||||
|
assert.ok(Number(kcal.value) > 1000);
|
||||||
|
kcal.value = '1800';
|
||||||
|
btn(document, 'Готово').click();
|
||||||
|
const saved = dom.window.localStorage.getItem('tpt.v1');
|
||||||
|
assert.equal(JSON.parse(saved).settings.kcal, 1800);
|
||||||
|
assert.equal(JSON.parse(saved).settings.onboarded, true);
|
||||||
|
assert.equal(document.querySelector('.sheet'), null);
|
||||||
|
const again = open(saved); t.after(() => again.dom.window.close());
|
||||||
|
assert.equal(again.document.querySelector('.sheet'), null);
|
||||||
|
});
|
||||||
Loading…
Reference in New Issue
Block a user