Compare commits

...

3 Commits

Author SHA1 Message Date
116aacb168 TPTIP-19: карточка блюда — отдельные строки, отступ под нижнее меню
All checks were successful
peppa/lint lint: success за 0с
peppa/test test: success за 0с
ci / checks (pull_request) Successful in 5s
deploy / deploy (pull_request) Successful in 13s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 11:46:17 +05:00
27019195a1 Merge pull request 'TPTIP-17: подсказка на пустом главном экране' (#13) from task/tptip-17 into main
All checks were successful
peppa/lint lint: success за 0с
peppa/test test: success за 0с
ci / checks (push) Successful in 6s
deploy / deploy (push) Successful in 18s
2026-11-17 11:45:53 +05:00
b396afdcd4 TPTIP-17: подсказка на пустом главном экране
All checks were successful
peppa/lint lint: success за 0с
peppa/test test: success за 0с
ci / checks (pull_request) Successful in 5s
deploy / deploy (pull_request) Successful in 13s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 11:45:34 +05:00
8 changed files with 175 additions and 5 deletions

View File

@ -17,7 +17,7 @@
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}
html,body{margin:0;background:var(--bg);color:var(--text);font:16px/1.4 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
#app{max-width:640px;margin:0 auto;min-height:100vh;padding:12px 16px calc(84px + env(safe-area-inset-bottom))}
#app{max-width:640px;margin:0 auto;min-height:100vh;padding:12px 16px calc(120px + env(safe-area-inset-bottom))}
h1,h2,h3{margin:0}
h2{font-size:1.15rem}
h3{font-size:1rem}
@ -83,6 +83,9 @@ input:focus,select:focus,textarea:focus,button:focus-visible{outline:2px solid v
.item:first-child{border-top:0}
.item .main{flex:1;min-width:0;cursor:pointer;overflow-wrap:anywhere}
.item .main b{display:block;overflow-wrap:anywhere}
.item .main .dish-row{display:block;margin-top:4px}
.item.dish{flex-wrap:wrap}
.item.dish>button{flex:none;margin-left:auto}
.badge{display:inline-block;border-radius:999px;padding:1px 8px;font-size:.75rem;background:var(--bg);border:1px solid var(--line);color:var(--muted)}
.ok{color:var(--ok)}.bad{color:var(--bad)}
.quick{display:grid;grid-template-columns:repeat(3,1fr);gap:8px}
@ -673,6 +676,7 @@ function viewToday() {
h('div', { class: 'row', style: 'justify-content:center;margin-top:10px' },
t.water > 0 ? h('button', { class: 'chip minus', 'aria-label': 'Убрать 250 мл воды', onclick: removeLastWater }, '−250') : null,
h('button', { class: 'chip on', onclick: () => addWater(250) }, '+250 мл воды')),
t.meals === 0 && t.water === 0 ? h('p', { class: 'small muted', 'data-empty-hint': '', style: 'text-align:center;margin:8px 0 0' }, 'Пока ничего не добавлено, поэтому кольца пустые. Нажмите «+ Еда», «+250 мл воды» или выберите блюдо ниже — кольца заполнятся сами.') : null,
h('p', { class: 'left ' + (left >= 0 ? 'ok' : 'bad') }, leftText)),
h('div', { class: 'quick two' },
h('button', { onclick: () => openMealForm({ date: ui.date }) }, '+ Еда'),
@ -886,12 +890,12 @@ function chooseRecipe(r) {
function recipeView(r, actions) {
const lines = r.ingredients.split('\n').map(x => x.trim()).filter(Boolean);
const steps = (r.steps || '').split('\n').map(x => x.trim()).filter(Boolean);
return h('div', { class: 'item', style: 'align-items:flex-start' },
return h('div', { class: 'item dish', style: 'align-items:flex-start' },
r.photo ? h('img', { src: r.photo, alt: r.title, style: 'width:96px;height:96px;object-fit:cover;border-radius:12px;flex:none' }) : h('div', { style: 'width:96px;height:96px;border-radius:12px;background:var(--bg);display:flex;align-items:center;justify-content:center;font-size:2rem;flex:none' }, '🍲'),
h('div', { class: 'main', onclick: () => { if (db.recipes.includes(r)) openRecipeForm({ entry: r }); } }, h('b', null, r.title),
h('span', { class: 'muted small' }, '⏱ ' + r.time + ' мин'),
r.kcal != null ? h('span', { class: 'small', 'data-nutrition': '' }, (r.grams ? 'Порция ' + fmtInt(r.grams) + ' г · ' : '') + fmtInt(r.kcal) + ' ккал · Б ' + fmt(r.protein || 0) + ' · Ж ' + fmt(r.fat || 0) + ' · У ' + fmt(r.carbs || 0)) : null,
lines.length ? h('div', { class: 'small' }, 'Состав: ' + lines.join(', ')) : null,
h('span', { class: 'muted small dish-row' }, '⏱ ' + r.time + ' мин'),
r.kcal != null ? h('span', { class: 'small dish-row', 'data-nutrition': '' }, (r.grams ? 'Порция ' + fmtInt(r.grams) + ' г · ' : '') + fmtInt(r.kcal) + ' ккал · Б ' + fmt(r.protein || 0) + ' · Ж ' + fmt(r.fat || 0) + ' · У ' + fmt(r.carbs || 0)) : null,
lines.length ? h('div', { class: 'small dish-row' }, 'Состав: ' + lines.join(', ')) : null,
steps.length ? h('div', { class: 'small', 'data-steps': '' }, h('b', null, 'Как приготовить'), h('ol', { style: 'margin:4px 0 0;padding-left:20px' }, ...steps.map(x => h('li', null, x)))) : null),
actions);
}
@ -907,6 +911,7 @@ function recipesCard() {
function suggestionBlock() {
const r = suggestedRecipe(ui.date);
return h('div', null, h('div', { class: 'muted small', style: 'margin:6px 0' }, 'Идея на этот день'),
h('div', { class: 'small muted', 'data-choose-hint': '', style: 'margin-bottom:6px' }, 'Кнопка «Выбрать» добавит блюдо в приём пищи и в кольца за этот день.'),
recipeView(r, h('button', { class: 'primary', onclick: () => chooseRecipe(r) }, 'Выбрать')));
}
/** Выбор рецепта на выбранный день или создание нового. */

View File

@ -0,0 +1 @@
Подсказка — обычный абзац в viewToday, виден при t.meals === 0 и t.water === 0. Тексты на русском, как весь интерфейс приложения.

View File

@ -0,0 +1,6 @@
## Why
У нового пользователя за мастером кольца показывают нули без пояснений.
## What Changes
- Под кольцами на пустом дне — подсказка, что ничего не добавлено и как добавить.
- У идеи блюда — пояснение, что «Выбрать» добавляет блюдо в приём пищи и в кольца.

View File

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

View File

@ -0,0 +1,3 @@
- [x] Подсказка под кольцами на пустом дне
- [x] Пояснение про «Выбрать» у идеи блюда
- [x] Тест сценария

View File

@ -0,0 +1,20 @@
# home-empty-state Specification
## Purpose
TBD - created by archiving change tptip-17-empty-home-hint. Update Purpose after archive.
## Requirements
### Requirement: Подсказка на пустом дне
Главный экран SHALL показывать подсказку рядом с кольцами, пока за день нет еды и воды.
#### Scenario: Новый пользователь
- **GIVEN** день без приёмов пищи и воды
- **WHEN** пользователь открывает главный экран
- **THEN** под кольцами написано, что пока ничего не добавлено и как добавить
- **AND** у блюда сказано, что «Выбрать» добавляет его в приём пищи и в кольца
#### Scenario: После выбора блюда
- **GIVEN** пустой день с подсказкой
- **WHEN** пользователь нажимает «Выбрать»
- **THEN** подсказка пропадает

View File

@ -82,3 +82,21 @@ test('Сценарий: рецепт читается на телефоне —
assert.match(css, /overflow-wrap:anywhere/);
assert.doesNotMatch(source, /text-overflow:\s*ellipsis/);
});
test('Сценарий: на пустом дне рядом с кольцами есть подсказка, после «Выбрать» она исчезает', t => {
const { dom, document } = open(); t.after(() => dom.window.close());
const hint = document.querySelector('[data-empty-hint]');
assert.ok(hint, 'нет подсказки');
assert.match(hint.textContent, /Пока ничего не добавлено/);
assert.match(document.querySelector('[data-choose-hint]').textContent, /«Выбрать» добавит блюдо в приём пищи и в кольца/);
[...document.querySelectorAll('button')].find(b => b.textContent === 'Выбрать').click();
assert.equal(document.querySelector('[data-empty-hint]'), null);
});
test('Сценарий: время, порция и состав в карточке — отдельные строки, меню не закрывает низ', t => {
const { dom, document } = open(); t.after(() => dom.window.close());
const card = [...document.querySelectorAll('.item')].find(i => i.querySelector('[data-nutrition]'));
const rows = card.querySelectorAll('.main .dish-row');
assert.ok(rows.length >= 3, 'время, порция и состав должны быть отдельными строками');
assert.match(source, /#app\{[^}]*padding:12px 16px calc\(1[2-9]\dpx/);
});

103
tests/dish-card.test.js-e Normal file
View File

@ -0,0 +1,103 @@
// Сценарии TPTIP-10: карточка блюда с граммовкой, КБЖУ и рецептом; «Выбрать» пишет приём пищи.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const { JSDOM, VirtualConsole } = require('jsdom');
const plan = require('../gym-plan.i18n.js');
const source = fs.readFileSync('index.html', 'utf8');
const initial = vm.runInNewContext(source.split('/* LOGIC:START */')[1].split('/* LOGIC:END */')[0] + '; defaultData()');
initial.settings.onboarded = true;
function open() {
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 = () => {}; w.localStorage.setItem('tpt.v1', JSON.stringify(initial)); }
});
assert.deepEqual(errors, []);
return { dom, errors, document: dom.window.document };
}
test('Сценарий: карточка блюда показывает фото, граммы, КБЖУ и шаги', t => {
const { dom, document } = open(); t.after(() => dom.window.close());
const card = [...document.querySelectorAll('.item')].find(i => i.querySelector('[data-nutrition]'));
assert.ok(card, 'нет карточки с КБЖУ');
assert.ok(card.querySelector('img'));
assert.match(card.querySelector('[data-nutrition]').textContent, /Порция \d+ г · \d+ ккал · Б .* · Ж .* · У /);
assert.ok(card.querySelectorAll('[data-steps] li').length >= 3);
});
test('Сценарий: «Выбрать» добавляет блюдо в приём пищи с теми же значениями', t => {
const { dom, document, errors } = open(); t.after(() => dom.window.close());
const card = [...document.querySelectorAll('.item')].find(i => i.querySelector('[data-nutrition]'));
const title = card.querySelector('b').textContent;
const kcal = card.querySelector('[data-nutrition]').textContent.match(/(\d+) ккал/)[1];
[...card.querySelectorAll('button')].find(b => b.textContent === 'Выбрать').click();
assert.deepEqual(errors, []);
const saved = JSON.parse(dom.window.localStorage.getItem('tpt.v1'));
const m = saved.meals.find(x => x.name === title);
assert.ok(m);
assert.equal(String(m.kcal), kcal);
assert.equal(m.qty, 1);
assert.match(document.querySelector('#view').textContent, new RegExp(kcal));
});
test('Сценарий: у каждого готового блюда есть фото, вес, КБЖУ и не менее трёх шагов на русском', t => {
const { dom } = open(); t.after(() => dom.window.close());
const dishes = dom.window.eval('BUILTIN_RECIPES');
assert.ok(dishes.length >= 7);
for (const d of dishes) {
assert.ok(d.photo, 'нет фото: ' + d.title);
assert.ok(d.grams > 0 && d.kcal > 0 && d.protein >= 0 && d.fat >= 0 && d.carbs >= 0, 'нет цифр: ' + d.title);
const steps = d.steps.split('\n').filter(Boolean);
assert.ok(steps.length >= 3, 'мало шагов: ' + d.title);
assert.ok(steps.every(x => /[а-яё]/i.test(x)), 'шаг не на русском: ' + d.title);
}
});
test('Сценарий: после «Выбрать» видны вес и КБЖУ блюда, кольца и подтверждение обновились', t => {
const { dom, document, errors } = open(); t.after(() => dom.window.close());
const card = [...document.querySelectorAll('.item')].find(i => i.querySelector('[data-nutrition]'));
const title = card.querySelector('b').textContent;
const n = card.querySelector('[data-nutrition]').textContent.match(/Порция (\d+) г · (\d+) ккал · Б (\S+) · Ж (\S+) · У (\S+)/);
const ringsBefore = document.querySelector('.rings').textContent;
[...card.querySelectorAll('button')].find(b => b.textContent === 'Выбрать').click();
assert.deepEqual(errors, []);
assert.notEqual(document.querySelector('.rings').textContent, ringsBefore);
assert.match(document.querySelector('.rings').textContent, new RegExp(n[2]));
assert.match(document.getElementById('toast').textContent, /добавлено в приём пищи/);
[...document.querySelectorAll('#tabsIn button')].find(x => /Питание/.test(x.textContent)).click();
const row = [...document.querySelectorAll('#view .item')].find(i => i.querySelector('b').textContent === title && /порц\./.test(i.textContent));
assert.ok(row, 'нет записи в приёме пищи');
assert.match(row.textContent, new RegExp('\\(' + n[1] + ' г\\)'));
assert.match(row.textContent, new RegExp(n[2] + ' ккал · Б ' + n[3] + ' · Ж ' + n[4] + ' · У ' + n[5]));
});
test('Сценарий: рецепт читается на телефоне — текст переносится, а не обрезается', () => {
const css = source.match(/\.item \.main\{[^}]*\}/)[0];
assert.match(css, /min-width:0/);
assert.match(css, /overflow-wrap:anywhere/);
assert.doesNotMatch(source, /text-overflow:\s*ellipsis/);
});
<<<<<<< HEAD
test('Сценарий: на пустом дне рядом с кольцами есть подсказка, после «Выбрать» она исчезает', t => {
const { dom, document } = open(); t.after(() => dom.window.close());
const hint = document.querySelector('[data-empty-hint]');
assert.ok(hint, 'нет подсказки');
assert.match(hint.textContent, /Пока ничего не добавлено/);
assert.match(document.querySelector('[data-choose-hint]').textContent, /«Выбрать» добавит блюдо в приём пищи и в кольца/);
[...document.querySelectorAll('button')].find(b => b.textContent === 'Выбрать').click();
assert.equal(document.querySelector('[data-empty-hint]'), null);
=======
test('Сценарий: время, порция и состав в карточке — отдельные строки, меню не закрывает низ', t => {
const { dom, document } = open(); t.after(() => dom.window.close());
const card = [...document.querySelectorAll('.item')].find(i => i.querySelector('[data-nutrition]'));
const rows = card.querySelectorAll('.main .dish-row');
assert.ok(rows.length >= 3, 'время, порция и состав должны быть отдельными строками');
assert.match(source, /#app\{[^}]*padding:12px 16px calc\(1[2-9]\dpx/);
>>>>>>> 576873e (TPTIP-19: карточка блюда — отдельные строки, отступ под нижнее меню)
});