treker-po-trenirovkam-i-pit.../index.html
Peppa e469b984d7
All checks were successful
peppa/test test: success за 0с
ci / checks (pull_request) Successful in 3s
deploy / deploy (pull_request) Successful in 26s
TPTIP-8: готовые рецепты с иллюстрациями и идея на каждый день
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 15:36:00 +05:00

1044 lines
71 KiB
HTML
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="color-scheme" content="light dark">
<title>Трекер тренировок и питания</title>
<style>
/* ===== Темы: светлая по умолчанию, тёмная по системе или вручную ===== */
:root{--bg:#f3f5f8;--card:#fff;--text:#1b2430;--muted:#657080;--line:#e2e7ee;--accent:#2f7de1;--on-accent:#fff;
--ok:#238a56;--bad:#d03d35;--kcal:#f08a24;--prot:#d9453d;--fat:#d9a400;--carb:#2f7de1;--water:#1d9fc4;--shadow:0 1px 3px rgba(20,30,50,.08)}
@media (prefers-color-scheme:dark){:root:not([data-theme=light]){--bg:#10141a;--card:#1a2029;--text:#e8edf3;--muted:#98a3b2;--line:#2b3441;--accent:#5b9cf0;--on-accent:#0b1220;--ok:#46c47f;--bad:#f06a62;--shadow:none}}
:root[data-theme=dark]{--bg:#10141a;--card:#1a2029;--text:#e8edf3;--muted:#98a3b2;--line:#2b3441;--accent:#5b9cf0;--on-accent:#0b1220;--ok:#46c47f;--bad:#f06a62;--shadow:none}
*{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))}
h1,h2,h3{margin:0}
h2{font-size:1.15rem}
h3{font-size:1rem}
.muted{color:var(--muted)}
.small{font-size:.85rem}
.card{background:var(--card);border:1px solid var(--line);border-radius:14px;padding:14px;margin:12px 0;box-shadow:var(--shadow)}
.row{display:flex;align-items:center;gap:8px}
.row.between{justify-content:space-between}
.row.wrap{flex-wrap:wrap}
.grow{flex:1;min-width:0}
.stack>*+*{margin-top:10px}
/* кнопки и поля */
button,.btn{font:inherit;border:1px solid var(--line);background:var(--card);color:var(--text);border-radius:12px;padding:10px 14px;min-height:44px;cursor:pointer}
button.primary{background:var(--accent);color:var(--on-accent);border-color:var(--accent);font-weight:600}
button.danger{color:var(--bad);border-color:var(--bad)}
button.ghost{border-color:transparent;background:transparent}
button.icon{min-width:44px;padding:8px}
button:disabled{opacity:.5}
.chips{display:flex;gap:8px;flex-wrap:wrap}
.chip{border-radius:999px;padding:8px 14px;min-height:40px}
.chip.on{background:var(--accent);color:var(--on-accent);border-color:var(--accent)}
input,select,textarea{font:inherit;color:var(--text);background:var(--bg);border:1px solid var(--line);border-radius:10px;padding:10px 12px;width:100%;min-height:44px}
input:focus,select:focus,textarea:focus,button:focus-visible{outline:2px solid var(--accent);outline-offset:1px}
.field{display:block;margin:10px 0}
.field .lbl{display:block;font-size:.85rem;color:var(--muted);margin-bottom:4px}
.field .err{color:var(--bad);font-size:.85rem;min-height:0}
.field.bad input,.field.bad select,.field.bad textarea{border-color:var(--bad)}
.grid2{display:grid;grid-template-columns:1fr 1fr;gap:0 10px}
.grid4{display:grid;grid-template-columns:repeat(4,1fr);gap:0 8px}
/* нижнее меню */
#tabs{position:fixed;left:0;right:0;bottom:0;background:var(--card);border-top:1px solid var(--line);display:flex;justify-content:center;padding-bottom:env(safe-area-inset-bottom);z-index:5}
#tabs .in{display:flex;width:100%;max-width:640px}
#tabs button{flex:1;border:0;border-radius:0;background:transparent;font-size:.72rem;padding:6px 2px;color:var(--muted);display:flex;flex-direction:column;align-items:center;gap:2px;min-height:58px}
#tabs button .ic{font-size:1.35rem;line-height:1}
#tabs button.on{color:var(--accent);font-weight:600}
/* дата */
.datenav{display:flex;align-items:center;justify-content:space-between;gap:8px}
.datenav .d{flex:1;text-align:center;font-weight:600}
.datenav .d small{display:block;font-weight:400;color:var(--muted)}
/* кольца и полосы */
.rings{display:grid;grid-template-columns:repeat(5,1fr);gap:6px;text-align:center}
.ring{position:relative}
.ring svg{width:100%;height:auto;display:block;transform:rotate(-90deg)}
.ring .bg{stroke:var(--line)}
.ring .val{stroke-linecap:round;transition:stroke-dasharray .3s}
.ring .c{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;font-size:.8rem;font-weight:700;line-height:1.1}
.ring .c small{font-weight:400;color:var(--muted);font-size:.66rem}
.ring .t{font-size:.78rem;margin-top:2px}
.ring .over .val{stroke:var(--bad)}
.bar{height:10px;border-radius:6px;background:var(--line);overflow:hidden}
.bar>i{display:block;height:100%;border-radius:6px}
@media (max-width:380px){.rings{gap:3px}.ring .c{font-size:.68rem}.ring .c small{display:none}}
/* списки */
.item{display:flex;align-items:center;gap:8px;padding:10px 0;border-top:1px solid var(--line)}
.item:first-child{border-top:0}
.item .main{flex:1;min-width:0;cursor:pointer}
.item .main b{display:block;overflow-wrap:anywhere}
.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}
.quick button{padding:12px 4px;font-weight:600;font-size:.9rem}
.empty{color:var(--muted);text-align:center;padding:14px 0}
/* окна */
#overlay{position:fixed;inset:0;background:rgba(0,0,0,.45);display:none;align-items:flex-end;justify-content:center;z-index:20}
#overlay.on{display:flex}
.sheet{background:var(--card);width:100%;max-width:640px;max-height:92vh;overflow:auto;border-radius:18px 18px 0 0;padding:16px 16px calc(16px + env(safe-area-inset-bottom))}
@media (min-width:700px){#overlay{align-items:center}.sheet{border-radius:18px;max-height:88vh}}
.sheet .head{display:flex;justify-content:space-between;align-items:center;margin-bottom:6px}
.sheet .foot{display:flex;gap:8px;margin-top:14px}
.sheet .foot button{flex:1}
.suggest{position:relative}
.suggest .list{position:absolute;left:0;right:0;top:100%;z-index:3;background:var(--card);border:1px solid var(--line);border-radius:10px;max-height:220px;overflow:auto;box-shadow:0 6px 18px rgba(0,0,0,.18)}
.suggest .list div{padding:10px 12px;border-top:1px solid var(--line);cursor:pointer}
.suggest .list div:first-child{border-top:0}
#toast{position:fixed;left:50%;bottom:calc(76px + env(safe-area-inset-bottom));transform:translateX(-50%);background:var(--text);color:var(--bg);padding:10px 16px;border-radius:12px;z-index:30;display:none;max-width:90vw}
/* графики */
.chart{width:100%;height:auto;display:block}
.chart text{fill:var(--muted);font-size:10px}
.chart .axis{stroke:var(--line)}
.chart .ln{fill:none;stroke:var(--accent);stroke-width:2.5;stroke-linejoin:round}
.chart .dot{fill:var(--accent)}
.chart .bar{fill:var(--kcal)}
.chart .tgt{stroke:var(--muted);stroke-dasharray:4 3}
.stats{display:grid;grid-template-columns:1fr 1fr;gap:10px}
.stat{background:var(--bg);border-radius:12px;padding:10px}
.stat b{display:block;font-size:1.25rem}
.exrow{border:1px solid var(--line);border-radius:12px;padding:10px;margin:10px 0}
.setrow{display:grid;grid-template-columns:28px 1fr 1fr 44px;gap:6px;align-items:center;margin:6px 0}
</style>
</head>
<body>
<div id="app"><main id="view"></main></div>
<nav id="tabs"><div class="in" id="tabsIn"></div></nav>
<div id="overlay"></div>
<div id="toast" role="status"></div>
<script>
/* =====================================================================
СЛОЙ ДАННЫХ (чистые функции, без DOM) — проверяется tests/logic.test.js
===================================================================== */
/* LOGIC:START */
const STORAGE_KEY = 'tpt.v1';
const MEAL_TYPES = [['breakfast', 'Завтрак'], ['lunch', 'Обед'], ['dinner', 'Ужин'], ['snack', 'Перекус']];
const WORKOUT_TYPES = [['strength', 'Силовая'], ['cardio', 'Кардио'], ['stretch', 'Растяжка'], ['other', 'Другое']];
const GOALS = [['lose', 'Похудение'], ['maintain', 'Поддержание'], ['gain', 'Набор']];
const ACTIVITY = [[1.2, 'Сидячий образ жизни'], [1.375, 'Лёгкая (1–3 тренировки в неделю)'],
[1.55, 'Средняя (3–5 тренировок)'], [1.725, 'Высокая (6–7 тренировок)'], [1.9, 'Очень высокая']];
/** Пустая база данных с настройками по умолчанию. */
function defaultData() {
return {
v: 1,
settings: {
goal: 'maintain', kcal: 2000, protein: 120, fat: 65, carbs: 230, water: 2000, workoutsPerWeek: 3,
profile: { sex: 'm', age: 30, height: 175, weight: 75, activity: 1.375 },
theme: 'auto', onboarded: false
},
foods: [], meals: [], water: [], workouts: [], exercises: [], body: [], recipes: [], plan: []
};
}
let _uid = 0;
function uid() { return Date.now().toString(36) + (_uid++).toString(36) + Math.random().toString(36).slice(2, 6); }
const pad2 = n => String(n).padStart(2, '0');
/** Дата → ключ «ГГГГ-ММ-ДД» в местном часовом поясе. */
function dateKey(d) { return d.getFullYear() + '-' + pad2(d.getMonth() + 1) + '-' + pad2(d.getDate()); }
function parseKey(k) { const [y, m, d] = k.split('-').map(Number); return new Date(y, m - 1, d, 12); }
function addDays(k, n) { const d = parseKey(k); d.setDate(d.getDate() + n); return dateKey(d); }
function round1(n) { return Math.round(n * 10) / 10; }
/**
* Разбор числа: принимает точку и запятую.
* opts: {min, max, int, required}. Возвращает {ok, value, error}.
*/
function parseNum(str, opts) {
opts = opts || {};
const s = String(str == null ? '' : str).trim().replace(/\s/g, '').replace(',', '.');
if (s === '') return opts.required ? { ok: false, error: 'Заполните это поле' } : { ok: true, value: null };
if (!/^-?\d+(\.\d+)?$/.test(s)) return { ok: false, error: 'Введите число, например 12,5' };
const v = Number(s);
if (opts.int && !Number.isInteger(v)) return { ok: false, error: 'Нужно целое число' };
if (opts.min != null && v < opts.min) return { ok: false, error: 'Не меньше ' + opts.min };
if (opts.max != null && v > opts.max) return { ok: false, error: 'Не больше ' + opts.max };
return { ok: true, value: v };
}
/** Итоги одной записи еды: base — значения на 100 г или на порцию, qty — граммы или порции. */
function mealTotals(m) {
const k = m.mode === 'per100' ? m.qty / 100 : m.qty;
return { kcal: round1(m.kcal * k), protein: round1(m.protein * k), fat: round1(m.fat * k), carbs: round1(m.carbs * k) };
}
/** Итоги дня: еда, вода, тренировки. */
function dayTotals(data, date) {
const t = { kcal: 0, protein: 0, fat: 0, carbs: 0, water: 0, meals: 0 };
for (const m of data.meals) {
if (m.date !== date) continue;
const x = mealTotals(m);
t.kcal += x.kcal; t.protein += x.protein; t.fat += x.fat; t.carbs += x.carbs; t.meals++;
}
for (const w of data.water) if (w.date === date) t.water += w.ml;
for (const k of ['kcal', 'protein', 'fat', 'carbs']) t[k] = round1(t[k]);
t.workouts = data.workouts.filter(w => w.date === date);
return t;
}
/** Норма по Миффлину–Сан Жеору: BMR × активность. */
function mifflin(p) {
const bmr = 10 * p.weight + 6.25 * p.height - 5 * p.age + (p.sex === 'm' ? 5 : -161);
return { bmr: Math.round(bmr), tdee: Math.round(bmr * p.activity) };
}
/** Предлагаемые нормы под цель: ккал, Б/Ж/У. */
function suggestNorms(goal, p) {
const { tdee } = mifflin(p);
const kcal = Math.round(tdee * (goal === 'lose' ? 0.85 : goal === 'gain' ? 1.1 : 1));
const protein = Math.round(p.weight * (goal === 'lose' ? 2.0 : 1.8));
const fat = Math.round(kcal * 0.25 / 9);
const carbs = Math.max(0, Math.round((kcal - protein * 4 - fat * 9) / 4));
return { kcal, protein, fat, carbs, water: Math.round(p.weight * 30 / 50) * 50 };
}
/** День «с нормой»: еда записана и ккал в пределах ±10 % от цели. */
function dayOk(data, date) {
const t = dayTotals(data, date), g = data.settings.kcal;
return t.meals > 0 && Math.abs(t.kcal - g) <= g * 0.1;
}
/** Серия дней подряд с нормой; если сегодня ещё не засчитан — считаем от вчера. */
function streak(data, today) {
let d = dayOk(data, today) ? today : addDays(today, -1), n = 0;
while (dayOk(data, d) && n < 3650) { n++; d = addDays(d, -1); }
return n;
}
/** Ряд веса по возрастанию дат. */
function weightSeries(data) {
return data.body.filter(b => b.weight != null).map(b => ({ x: b.date, y: b.weight })).sort((a, b) => a.x < b.x ? -1 : a.x > b.x ? 1 : 0);
}
/** Рабочий вес по упражнению: максимум по подходам за каждую тренировку. */
function exerciseSeries(data, name) {
const by = {};
for (const w of data.workouts) for (const e of (w.exercises || [])) {
if (e.name.toLowerCase() !== name.toLowerCase()) continue;
const mx = Math.max(0, ...e.sets.map(s => s.weight));
by[w.date] = Math.max(by[w.date] || 0, mx);
}
return Object.keys(by).sort().map(x => ({ x, y: by[x] }));
}
/** Статистика за период из `days` дней, заканчивающийся датой `end`. */
function periodStats(data, end, days) {
const list = [];
let kc = 0, pr = 0, logged = 0;
for (let i = days - 1; i >= 0; i--) {
const d = addDays(end, -i), t = dayTotals(data, d);
list.push({ date: d, kcal: t.kcal });
if (t.meals > 0) { logged++; kc += t.kcal; pr += t.protein; }
}
const start = addDays(end, -(days - 1));
const workouts = data.workouts.filter(w => w.date >= start && w.date <= end).length;
const ws = weightSeries(data).filter(p => p.x >= start && p.x <= end);
return {
days: list, loggedDays: logged,
avgKcal: logged ? Math.round(kc / logged) : null,
avgProtein: logged ? Math.round(pr / logged) : null,
workouts, workoutTarget: round1(data.settings.workoutsPerWeek * days / 7),
weightChange: ws.length >= 2 ? round1(ws[ws.length - 1].y - ws[0].y) : null
};
}
/** Описание тренировки одной строкой. */
function workoutSummary(w) {
const fmt = n => String(round1(n)).replace('.', ',');
const parts = [];
if (w.type === 'strength') {
const ex = w.exercises || [];
const sets = ex.reduce((a, e) => a + e.sets.length, 0);
const vol = ex.reduce((a, e) => a + e.sets.reduce((b, s) => b + s.reps * s.weight, 0), 0);
parts.push(ex.length + ' упр.', sets + ' подх.');
if (vol > 0) parts.push('объём ' + Math.round(vol) + ' кг');
}
if (w.type === 'cardio') {
if (w.distance != null) parts.push(fmt(w.distance) + ' км');
if (w.pulse != null) parts.push('пульс ' + w.pulse);
}
parts.push(w.duration + ' мин');
return parts.join(' · ');
}
/** CSV для Excel (разделитель «;», десятичная запятая). */
function toCsv(rows) {
const cell = v => {
if (v == null) return '';
let s = typeof v === 'number' ? String(v).replace('.', ',') : String(v);
if (/[;"\n\r]/.test(s)) s = '"' + s.replace(/"/g, '""') + '"';
return s;
};
return '' + rows.map(r => r.map(cell).join(';')).join('\r\n');
}
function mealsCsv(data) {
const names = Object.fromEntries(MEAL_TYPES);
const rows = [['Дата', 'Приём', 'Продукт', 'Режим', 'Количество', 'Ккал', 'Белки', 'Жиры', 'Углеводы']];
for (const m of data.meals.slice().sort((a, b) => a.date < b.date ? -1 : 1)) {
const t = mealTotals(m);
rows.push([m.date, names[m.type], m.name, m.mode === 'per100' ? 'граммы' : 'порции', m.qty, t.kcal, t.protein, t.fat, t.carbs]);
}
return toCsv(rows);
}
function workoutsCsv(data) {
const names = Object.fromEntries(WORKOUT_TYPES);
const rows = [['Дата', 'Тип', 'Минуты', 'Самочувствие', 'Упражнение', 'Подход', 'Повторы', 'Вес, кг', 'Дистанция, км', 'Пульс', 'Заметка']];
for (const w of data.workouts.slice().sort((a, b) => a.date < b.date ? -1 : 1)) {
const base = [w.date, names[w.type], w.duration, w.feel];
if (w.type === 'strength' && w.exercises && w.exercises.length) {
for (const e of w.exercises) e.sets.forEach((s, i) => rows.push([...base, e.name, i + 1, s.reps, s.weight, null, null, w.note]));
} else rows.push([...base, null, null, null, null, w.distance, w.pulse, w.note]);
}
return toCsv(rows);
}
function bodyCsv(data) {
const rows = [['Дата', 'Вес, кг', 'Талия, см', 'Бёдра, см', 'Грудь, см']];
for (const b of data.body.slice().sort((a, c) => a.date < c.date ? -1 : 1)) rows.push([b.date, b.weight, b.waist, b.hips, b.chest]);
return toCsv(rows);
}
/** Проверка и нормализация импортируемого JSON. Бросает Error с понятным текстом. */
function normalizeImport(obj, keepOnboarded) {
if (!obj || typeof obj !== 'object' || obj.v !== 1 || typeof obj.settings !== 'object') {
throw new Error('Это не резервная копия трекера.');
}
const base = defaultData();
const out = { v: 1, settings: Object.assign(base.settings, obj.settings) };
out.settings.onboarded = keepOnboarded ? !!obj.settings.onboarded : true;
out.settings.profile = Object.assign(base.settings.profile, obj.settings.profile || {});
for (const k of ['foods', 'meals', 'water', 'workouts', 'exercises', 'body', 'recipes', 'plan']) {
if (obj[k] != null && !Array.isArray(obj[k])) throw new Error('Файл повреждён: раздел «' + k + '» записан неверно.');
out[k] = obj[k] || [];
}
return out;
}
/* LOGIC:END */
/* =====================================================================
ХРАНЕНИЕ
===================================================================== */
let db = load();
function load() {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (raw) return normalizeImport(JSON.parse(raw), true);
} catch (e) { /* повреждённые данные — начинаем заново */ }
return defaultData();
}
let saveFailed = false;
function save() {
try { localStorage.setItem(STORAGE_KEY, JSON.stringify(db)); saveFailed = false; }
catch (e) { if (!saveFailed) toast('Не удалось сохранить: память браузера недоступна или заполнена.'); saveFailed = true; }
}
/* =====================================================================
ОТОБРАЖЕНИЕ: помощники DOM
===================================================================== */
const $ = id => document.getElementById(id);
const SVGNS = 'http://www.w3.org/2000/svg';
/** Создать элемент: h('div', {class:'x', onclick:fn}, ...дети). */
function h(tag, props, ...kids) {
const el = document.createElement(tag);
for (const [k, v] of Object.entries(props || {})) {
if (k === 'class') el.className = v;
else if (k.startsWith('on')) el.addEventListener(k.slice(2), v);
else if (k === 'value') el.value = v;
else if (v === true) el.setAttribute(k, '');
else if (v !== false && v != null) el.setAttribute(k, v);
}
put(el, kids);
return el;
}
function put(el, kids) {
for (const k of kids.flat(Infinity)) {
if (k == null || k === false) continue;
el.append(k.nodeType ? k : document.createTextNode(String(k)));
}
}
function svg(tag, props, ...kids) {
const el = document.createElementNS(SVGNS, tag);
for (const [k, v] of Object.entries(props || {})) el.setAttribute(k, v);
put(el, kids);
return el;
}
const fmt = n => n == null ? '—' : String(round1(n)).replace('.', ',');
const fmtInt = n => n == null ? '—' : String(Math.round(n));
const MONTHS = ['января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'];
const WEEKDAYS = ['воскресенье', 'понедельник', 'вторник', 'среда', 'четверг', 'пятница', 'суббота'];
function longDate(k) { const d = parseKey(k); return d.getDate() + ' ' + MONTHS[d.getMonth()]; }
function shortDate(k) { return k.slice(8) + '.' + k.slice(5, 7); }
function typeName(list, key) { return (list.find(x => x[0] === key) || [, key])[1]; }
let toastTimer;
function toast(msg) {
const t = $('toast'); t.textContent = msg; t.style.display = 'block';
clearTimeout(toastTimer); toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2600);
}
/** Модальное окно (снизу на телефоне). Возвращает функцию закрытия. */
function openSheet(title, body, opts) {
opts = opts || {};
const ov = $('overlay');
const sheet = h('div', { class: 'sheet', role: 'dialog', 'aria-label': title });
const close = () => { ov.classList.remove('on'); ov.replaceChildren(); document.removeEventListener('keydown', onKey); };
const onKey = e => { if (e.key === 'Escape' && !opts.locked) close(); };
sheet.append(h('div', { class: 'head' }, h('h2', null, title),
opts.locked ? null : h('button', { class: 'ghost icon', 'aria-label': 'Закрыть', onclick: close }, '✕')), body);
ov.replaceChildren(sheet);
ov.onclick = e => { if (e.target === ov && !opts.locked) close(); };
ov.classList.add('on');
document.addEventListener('keydown', onKey);
return close;
}
/** Подтверждение (особенно для удаления). */
function confirmBox(text, okLabel, onYes) {
const close = openSheet('Подтвердите', h('div', null,
h('p', null, text),
h('div', { class: 'foot' },
h('button', { onclick: () => close() }, 'Отмена'),
h('button', { class: 'danger', onclick: () => { close(); onYes(); } }, okLabel || 'Удалить'))));
}
/* ---- поля форм с валидацией ---- */
function field(label, input, hint) {
const err = h('div', { class: 'err' });
const el = h('label', { class: 'field' }, h('span', { class: 'lbl' }, label), input, err, hint ? h('div', { class: 'small muted' }, hint) : null);
el.setErr = m => { err.textContent = m || ''; el.classList.toggle('bad', !!m); return !m; };
return el;
}
/** Числовое поле: read() → значение или null; при ошибке ставит err и возвращает undefined. */
function numField(label, o) {
const input = h('input', { type: 'text', inputmode: o.int ? 'numeric' : 'decimal', autocomplete: 'off', value: o.value == null ? '' : String(o.value).replace('.', ','), placeholder: o.placeholder || '' });
const el = field(label, input, o.hint);
el.input = input;
el.read = () => {
const r = parseNum(input.value, o);
el.setErr(r.ok ? '' : r.error);
return r.ok ? { v: r.value } : null;
};
return el;
}
function selectField(label, options, value, onchange) {
const sel = h('select', { onchange }, options.map(([v, t]) => h('option', { value: v, selected: String(v) === String(value) }, t)));
const el = field(label, sel);
el.input = sel;
return el;
}
function dateField(label, value) {
const input = h('input', { type: 'date', value });
const el = field(label, input);
el.read = () => {
const ok = /^\d{4}-\d{2}-\d{2}$/.test(input.value);
el.setErr(ok ? '' : 'Укажите дату');
return ok ? input.value : null;
};
return el;
}
function textField(label, o) {
const input = h('input', { type: 'text', value: o.value || '', maxlength: o.max || 80, autocomplete: 'off', placeholder: o.placeholder || '' });
const el = field(label, input);
el.input = input;
el.read = () => {
const v = input.value.trim();
el.setErr(o.required && !v ? 'Заполните это поле' : '');
return o.required && !v ? null : v;
};
return el;
}
/** Подсказки при вводе (справочник продуктов/упражнений). */
function attachSuggest(input, getItems, onPick) {
const list = h('div', { class: 'list', hidden: true });
const wrap = h('div', { class: 'suggest' });
input.parentNode && input.parentNode.insertBefore(wrap, input);
wrap.append(input, list);
const show = () => {
const q = input.value.trim().toLowerCase();
const items = getItems().filter(x => !q || x.name.toLowerCase().includes(q)).slice(0, 6);
list.replaceChildren(...items.map(x => h('div', { onpointerdown: e => { e.preventDefault(); list.hidden = true; onPick(x); } }, x.name, x.hint ? h('span', { class: 'muted small' }, ' · ' + x.hint) : null)));
list.hidden = !items.length;
};
input.addEventListener('input', show);
input.addEventListener('focus', show);
input.addEventListener('blur', () => { list.hidden = true; });
return wrap;
}
function formFoot(onSave, extra) {
return h('div', { class: 'foot' }, extra || null, h('button', { class: 'primary', onclick: onSave }, 'Сохранить'));
}
/* ---- SVG-графики ---- */
function ring(label, fact, target, unit, color) {
const R = 40, C = 2 * Math.PI * R, pct = target > 0 ? Math.min(fact / target, 1) : 0, over = target > 0 && fact > target * 1.05;
return h('div', { class: 'ring' },
h('div', { class: over ? 'over' : '', style: 'position:relative' },
svg('svg', { viewBox: '0 0 100 100', 'aria-hidden': 'true' },
svg('circle', { class: 'bg', cx: 50, cy: 50, r: R, fill: 'none', 'stroke-width': 10 }),
svg('circle', { class: 'val', cx: 50, cy: 50, r: R, fill: 'none', 'stroke-width': 10, stroke: color, 'stroke-dasharray': (pct * C) + ' ' + C })),
h('div', { class: 'c' }, fmtInt(fact), h('small', null, '/ ' + fmtInt(target)))),
h('div', { class: 't' }, label, h('div', { class: 'muted small' }, unit)));
}
/** Линейный график по точкам [{x:'ГГГГ-ММ-ДД', y}]. */
function lineChart(points, unit) {
const W = 340, H = 170, L = 34, R = 10, T = 12, B = 22;
if (points.length < 2) return h('div', { class: 'empty' }, points.length ? 'Добавьте ещё одну запись, чтобы появился график.' : 'Пока нет данных для графика.');
const t0 = parseKey(points[0].x).getTime(), t1 = parseKey(points[points.length - 1].x).getTime();
let lo = Math.min(...points.map(p => p.y)), hi = Math.max(...points.map(p => p.y));
if (hi === lo) { hi += 1; lo -= 1; }
const pad = (hi - lo) * 0.1; lo -= pad; hi += pad;
const X = p => L + (t1 === t0 ? 0 : (parseKey(p.x).getTime() - t0) / (t1 - t0)) * (W - L - R);
const Y = p => T + (1 - (p.y - lo) / (hi - lo)) * (H - T - B);
const s = svg('svg', { class: 'chart', viewBox: `0 0 ${W} ${H}`, role: 'img', 'aria-label': 'График, ' + unit });
s.append(svg('line', { class: 'axis', x1: L, y1: H - B, x2: W - R, y2: H - B }), svg('line', { class: 'axis', x1: L, y1: T, x2: L, y2: H - B }),
svg('text', { x: 2, y: T + 4 }, fmt(hi)), svg('text', { x: 2, y: H - B }, fmt(lo)),
svg('text', { x: L, y: H - 6 }, shortDate(points[0].x)), svg('text', { x: W - R, y: H - 6, 'text-anchor': 'end' }, shortDate(points[points.length - 1].x)),
svg('polyline', { class: 'ln', points: points.map(p => X(p) + ',' + Y(p)).join(' ') }));
for (const p of points) s.append(svg('circle', { class: 'dot', cx: X(p), cy: Y(p), r: 3 }, svg('title', null, shortDate(p.x) + ': ' + fmt(p.y) + ' ' + unit)));
return s;
}
/** Столбцы по дням с линией цели. */
function barChart(days, target) {
const W = 340, H = 170, L = 34, R = 6, T = 12, B = 22;
const max = Math.max(target || 0, ...days.map(d => d.kcal), 1) * 1.1;
const bw = (W - L - R) / days.length;
const Y = v => T + (1 - v / max) * (H - T - B);
const s = svg('svg', { class: 'chart', viewBox: `0 0 ${W} ${H}`, role: 'img', 'aria-label': 'Калории по дням' });
s.append(svg('line', { class: 'axis', x1: L, y1: H - B, x2: W - R, y2: H - B }), svg('text', { x: 2, y: T + 4 }, fmtInt(max)), svg('text', { x: 2, y: H - B }, '0'));
days.forEach((d, i) => {
if (d.kcal > 0) s.append(svg('rect', { class: 'bar', x: L + i * bw + bw * 0.12, y: Y(d.kcal), width: bw * 0.76, height: H - B - Y(d.kcal), rx: 2 }, svg('title', null, shortDate(d.date) + ': ' + fmtInt(d.kcal) + ' ккал')));
const every = days.length > 14 ? 5 : 1;
if (i % every === 0 || i === days.length - 1) s.append(svg('text', { x: L + i * bw + bw / 2, y: H - 6, 'text-anchor': 'middle' }, days.length > 14 ? d.date.slice(8) : shortDate(d.date)));
});
if (target) s.append(svg('line', { class: 'tgt', x1: L, y1: Y(target), x2: W - R, y2: Y(target) }));
return s;
}
/* =====================================================================
СОСТОЯНИЕ ЭКРАНА И НАВИГАЦИЯ
===================================================================== */
const todayKey = () => dateKey(new Date());
const ui = { tab: 'today', date: todayKey(), wFilter: 'all', period: 'week', statEx: '' };
const TABS = [['today', '🏠', 'Главная'], ['food', '🍽️', 'Питание'], ['workouts', '🏋️', 'Тренировки'], ['body', '⚖️', 'Тело'], ['stats', '📊', 'Статистика'], ['settings', '⚙️', 'Настройки']];
function applyTheme() {
if (db.settings.theme === 'auto') document.documentElement.removeAttribute('data-theme');
else document.documentElement.setAttribute('data-theme', db.settings.theme);
}
function render() {
applyTheme();
$('tabsIn').replaceChildren(...TABS.map(([k, ic, t]) => h('button', { class: ui.tab === k ? 'on' : '', 'aria-current': ui.tab === k ? 'page' : null, onclick: () => { ui.tab = k; render(); window.scrollTo(0, 0); } }, h('span', { class: 'ic' }, ic), t)));
const views = { today: viewToday, food: viewFood, workouts: viewWorkouts, body: viewBody, stats: viewStats, settings: viewSettings };
$('view').replaceChildren(views[ui.tab]());
}
function dateNav() {
const t = todayKey(), isToday = ui.date === t;
const d = parseKey(ui.date);
const go = n => { ui.date = addDays(ui.date, n); render(); };
const pick = h('input', { type: 'date', value: ui.date, 'aria-label': 'Выбрать дату', style: 'position:absolute;opacity:0;inset:0;width:100%;height:100%', onchange: e => { if (e.target.value) { ui.date = e.target.value; render(); } } });
return h('div', { class: 'datenav' },
h('button', { class: 'icon', 'aria-label': 'Предыдущий день', onclick: () => go(-1) }, '‹'),
h('div', { class: 'd', style: 'position:relative' }, longDate(ui.date) + ' ' + d.getFullYear(), h('small', null, isToday ? 'сегодня, ' + WEEKDAYS[d.getDay()] : WEEKDAYS[d.getDay()]), pick),
h('button', { class: 'icon', 'aria-label': 'Следующий день', onclick: () => go(1) }, '›'));
}
/* =====================================================================
ЭКРАН «СЕГОДНЯ»
===================================================================== */
function viewToday() {
const s = db.settings, t = dayTotals(db, ui.date), left = s.kcal - t.kcal;
const water = h('div', { class: 'row between' },
h('span', null, '💧 Вода: ', h('b', null, t.water), ' / ' + s.water + ' мл'),
h('button', { class: 'ghost', onclick: () => removeLastWater(), disabled: t.water === 0 }, '− 250'));
return h('div', null, dateNav(),
h('div', { class: 'card' },
h('div', { class: 'rings' },
ring('Ккал', t.kcal, s.kcal, 'ккал', 'var(--kcal)'), ring('Белки', t.protein, s.protein, 'г', 'var(--prot)'),
ring('Жиры', t.fat, s.fat, 'г', 'var(--fat)'), ring('Углев.', t.carbs, s.carbs, 'г', 'var(--carb)'), ring('Вода', t.water, s.water, 'мл', 'var(--water)')),
h('p', { class: left >= 0 ? 'ok' : 'bad', style: 'text-align:center;margin:10px 0 0' },
t.meals === 0 ? 'Еда за этот день пока не записана' : left >= 0 ? 'Осталось ' + fmtInt(left) + ' ккал' : 'Выше нормы на ' + fmtInt(-left) + ' ккал')),
h('div', { class: 'quick' },
h('button', { onclick: () => openMealForm({ date: ui.date }) }, '+ Еда'),
h('button', { onclick: () => openWorkoutForm({ date: ui.date }) }, '+ Тренировка'),
h('button', { onclick: () => addWater(250) }, '+ Вода 250 мл')),
h('div', { class: 'card' }, water),
recipesCard(),
h('div', { class: 'card' }, h('h3', null, 'Тренировка'),
t.workouts.length ? t.workouts.map(w => h('div', { class: 'item' }, h('div', { class: 'main', onclick: () => openWorkoutForm({ entry: w }) },
h('b', null, '✅ ' + typeName(WORKOUT_TYPES, w.type)), h('span', { class: 'muted small' }, workoutSummary(w))))) :
h('div', { class: 'empty' }, 'Тренировки в этот день не было')),
h('div', { class: 'card' }, h('div', { class: 'row between' }, h('h3', null, 'Серия'), h('b', null, streak(db, todayKey()) + ' дн.')),
h('div', { class: 'small muted' }, 'Дней подряд, когда калории в пределах ±10 % от нормы')));
}
function addWater(ml) {
db.water.push({ id: uid(), date: ui.date, ml }); save(); render(); toast('Добавлено: ' + ml + ' мл воды');
}
function removeLastWater() {
const i = db.water.map(w => w.date).lastIndexOf(ui.date);
if (i >= 0) { db.water.splice(i, 1); save(); render(); }
}
/* =====================================================================
ПИТАНИЕ
===================================================================== */
function defaultMealType() {
const hr = new Date().getHours();
return hr < 11 ? 'breakfast' : hr < 16 ? 'lunch' : hr < 21 ? 'dinner' : 'snack';
}
function viewFood() {
const s = db.settings, t = dayTotals(db, ui.date);
const dev = (name, fact, goal, unit) => h('div', { class: 'stat' }, h('span', { class: 'muted small' }, name), h('b', null, fmt(fact)),
h('span', { class: 'small ' + (fact > goal * 1.05 ? 'bad' : 'muted') }, 'цель ' + fmtInt(goal) + ' · ' + (fact - goal >= 0 ? '+' : '−') + fmtInt(Math.abs(fact - goal)) + ' ' + unit));
const sections = MEAL_TYPES.map(([key, name]) => {
const items = db.meals.filter(m => m.date === ui.date && m.type === key);
const sum = items.reduce((a, m) => a + mealTotals(m).kcal, 0);
return h('div', { class: 'card' },
h('div', { class: 'row between' }, h('h3', null, name), h('span', { class: 'muted small' }, items.length ? fmtInt(sum) + ' ккал' : ''),
h('button', { onclick: () => openMealForm({ date: ui.date, type: key }) }, '+ Добавить')),
items.length ? items.map(mealRow) : h('div', { class: 'empty' }, 'Пока пусто'));
});
return h('div', null, dateNav(),
h('div', { class: 'card' }, h('h3', null, 'Итог дня'), h('div', { class: 'stats', style: 'margin-top:8px' },
dev('Ккал', t.kcal, s.kcal, 'ккал'), dev('Белки, г', t.protein, s.protein, 'г'), dev('Жиры, г', t.fat, s.fat, 'г'), dev('Углеводы, г', t.carbs, s.carbs, 'г'))),
recipesCard(), sections);
}
function mealRow(m) {
const t = mealTotals(m);
return h('div', { class: 'item' },
h('div', { class: 'main', onclick: () => openMealForm({ entry: m }) }, h('b', null, m.name),
h('span', { class: 'muted small' }, fmt(m.qty) + (m.mode === 'per100' ? ' г' : ' порц.') + ' · ' + fmtInt(t.kcal) + ' ккал · Б ' + fmt(t.protein) + ' · Ж ' + fmt(t.fat) + ' · У ' + fmt(t.carbs))),
h('button', { class: 'ghost icon', 'aria-label': 'Удалить ' + m.name, onclick: () => confirmBox('Удалить «' + m.name + '»?', 'Удалить', () => { db.meals = db.meals.filter(x => x.id !== m.id); save(); render(); }) }, '🗑'));
}
function openMealForm(o) {
const e = o.entry, isNew = !e;
const type = selectField('Приём пищи', MEAL_TYPES, e ? e.type : (o.type || defaultMealType()));
const date = dateField('Дата', e ? e.date : o.date);
const name = textField('Продукт или блюдо', { value: e ? e.name : '', required: true, placeholder: 'Начните вводить — найдём в справочнике' });
const mode = selectField('Значения указаны', [['per100', 'на 100 г'], ['portion', 'на порцию']], e ? e.mode : 'per100', () => { upd(); });
const qtyLbl = h('span');
const qty = numField('Граммы', { value: e ? e.qty : '', required: true, min: 0.1, max: 100000 });
const kcal = numField('Ккал', { value: e ? e.kcal : '', required: true, min: 0, max: 10000 });
const p = numField('Белки, г', { value: e ? e.protein : '', min: 0, max: 1000 });
const f = numField('Жиры, г', { value: e ? e.fat : '', min: 0, max: 1000 });
const c = numField('Углеводы, г', { value: e ? e.carbs : '', min: 0, max: 1000 });
const preview = h('div', { class: 'card small' });
const save2 = h('input', { type: 'checkbox', checked: isNew, style: 'width:auto;min-height:0' });
function upd() {
qty.querySelector('.lbl').textContent = mode.input.value === 'per100' ? 'Сколько, граммы' : 'Сколько порций';
const n = x => { const r = parseNum(x.input.value); return r.ok && r.value != null ? r.value : 0; };
const t = mealTotals({ mode: mode.input.value, qty: n(qty), kcal: n(kcal), protein: n(p), fat: n(f), carbs: n(c) });
preview.textContent = 'Итого: ' + fmtInt(t.kcal) + ' ккал · Б ' + fmt(t.protein) + ' · Ж ' + fmt(t.fat) + ' · У ' + fmt(t.carbs);
}
const body = h('div', null, type, date, name, mode, qty, h('div', { class: 'grid4' }, kcal, p, f, c), preview,
h('label', { class: 'row small' }, save2, 'Сохранить в справочник продуктов'));
attachSuggest(name.input, () => db.foods.map(x => ({ ...x, hint: fmtInt(x.kcal) + ' ккал ' + (x.mode === 'per100' ? 'на 100 г' : 'на порцию') })), x => {
name.input.value = x.name; mode.input.value = x.mode;
kcal.input.value = String(x.kcal).replace('.', ','); p.input.value = String(x.protein).replace('.', ','); f.input.value = String(x.fat).replace('.', ','); c.input.value = String(x.carbs).replace('.', ',');
if (x.mode === 'portion' && !qty.input.value) qty.input.value = '1';
upd(); qty.input.focus();
});
body.addEventListener('input', upd);
upd();
const close = openSheet(isNew ? 'Новая запись о еде' : 'Запись о еде', h('div', null, body, formFoot(() => {
const vals = [date.read(), name.read(), qty.read(), kcal.read(), p.read(), f.read(), c.read()];
if (vals.some(v => v == null)) return;
const rec = {
id: e ? e.id : uid(), date: vals[0], type: type.input.value, name: vals[1], mode: mode.input.value, qty: vals[2].v,
kcal: vals[3].v, protein: vals[4].v || 0, fat: vals[5].v || 0, carbs: vals[6].v || 0
};
if (e) Object.assign(e, rec); else db.meals.push(rec);
if (save2.checked) {
const food = { id: uid(), name: rec.name, mode: rec.mode, kcal: rec.kcal, protein: rec.protein, fat: rec.fat, carbs: rec.carbs };
const ex = db.foods.find(x => x.name.toLowerCase() === food.name.toLowerCase());
if (ex) Object.assign(ex, food, { id: ex.id }); else db.foods.push(food);
}
ui.date = rec.date; save(); close(); render(); toast('Сохранено');
})));
setTimeout(() => name.input.focus(), 50);
}
/* =====================================================================
РЕЦЕПТЫ: фото, время приготовления, состав; привязка к дню
===================================================================== */
/** Уменьшает фото до 640 px и сжимает в JPEG, чтобы поместиться в localStorage. */
function resizePhoto(file) {
return new Promise((resolve, reject) => {
const img = new Image(), url = URL.createObjectURL(file);
img.onload = () => {
const k = Math.min(1, 640 / Math.max(img.width, img.height)), c = document.createElement('canvas');
c.width = Math.round(img.width * k); c.height = Math.round(img.height * k);
c.getContext('2d').drawImage(img, 0, 0, c.width, c.height);
URL.revokeObjectURL(url); resolve(c.toDataURL('image/jpeg', 0.7));
};
img.onerror = () => { URL.revokeObjectURL(url); reject(new Error('bad image')); };
img.src = url;
});
}
/** Картинка-иллюстрация блюда (SVG) для встроенных рецептов. */
function dishArt(emoji, c1, c2) {
const svgText = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200"><defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="${c1}"/><stop offset="1" stop-color="${c2}"/></linearGradient></defs><rect width="200" height="200" fill="url(#g)"/><circle cx="100" cy="108" r="74" fill="#fff" opacity=".35"/><text x="100" y="132" font-size="84" text-anchor="middle">${emoji}</text></svg>`;
return 'data:image/svg+xml;utf8,' + encodeURIComponent(svgText);
}
/** Готовые рецепты: по одному на каждый день недели, подсказка выбирается по дате. */
const BUILTIN_RECIPES = [
{ id: 'b1', title: 'Овсянка с ягодами', time: 15, ingredients: 'Овсяные хлопья — 50 г\nМолоко — 200 мл\nМалина или черника — 80 г\nМёд — 1 ч. л.', photo: dishArt('🥣', '#ffd9a8', '#f4a261') },
{ id: 'b2', title: 'Омлет с овощами', time: 10, ingredients: 'Яйца — 3 шт.\nПомидор — 1 шт.\nБолгарский перец — ½ шт.\nМасло оливковое — 1 ч. л.', photo: dishArt('🍳', '#fff1a8', '#f6c453') },
{ id: 'b3', title: 'Куриная грудка с гречкой', time: 30, ingredients: 'Куриная грудка — 150 г\nГречка — 70 г (сухая)\nЛук — ½ шт.\nСпеции, соль', photo: dishArt('🍗', '#f9c9a0', '#e07a5f') },
{ id: 'b4', title: 'Творог с фруктами', time: 5, ingredients: 'Творог 5 % — 180 г\nБанан — 1 шт.\nГрецкие орехи — 15 г', photo: dishArt('🍓', '#ffd1dc', '#ef6f8b') },
{ id: 'b5', title: 'Лосось с рисом и брокколи', time: 35, ingredients: 'Филе лосося — 150 г\nРис — 70 г (сухой)\nБрокколи — 150 г\nЛимон — ¼ шт.', photo: dishArt('🐟', '#bfe3f2', '#4a90b8') },
{ id: 'b6', title: 'Греческий салат', time: 10, ingredients: 'Огурец — 1 шт.\nПомидоры — 2 шт.\nСыр фета — 60 г\nМаслины — 30 г\nМасло оливковое — 1 ст. л.', photo: dishArt('🥗', '#d4ecc0', '#6aa84f') },
{ id: 'b7', title: 'Чечевичный суп', time: 40, ingredients: 'Красная чечевица — 80 г\nМорковь — 1 шт.\nЛук — 1 шт.\nКартофель — 1 шт.\nСпеции, зелень', photo: dishArt('🍲', '#ffe0b5', '#d98b3a') }
];
/** Подсказка рецепта на день: по номеру дня, чтобы каждый день был свой. */
function suggestedRecipe(date) {
return BUILTIN_RECIPES[Math.floor(parseKey(date).getTime() / 86400000) % BUILTIN_RECIPES.length];
}
/** Копирует встроенный рецепт в данные пользователя (один раз) и возвращает его id. */
function adoptRecipe(r) {
if (!db.recipes.some(x => x.id === r.id)) db.recipes.push({ ...r });
return r.id;
}
function recipeView(r, actions) {
const lines = r.ingredients.split('\n').map(x => x.trim()).filter(Boolean);
return h('div', { class: 'item', 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 + ' мин'),
lines.length ? h('div', { class: 'small' }, 'Состав: ' + lines.join(', ')) : null),
actions);
}
/** Карточка «Рецепты на день» для выбранной даты. */
function recipesCard() {
const planned = db.plan.filter(x => x.date === ui.date).map(x => ({ p: x, r: db.recipes.find(r => r.id === x.recipeId) })).filter(x => x.r);
return h('div', { class: 'card' },
h('div', { class: 'row between' }, h('h3', null, 'Рецепты на день'),
h('button', { onclick: openRecipePicker }, '+ Рецепт')),
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());
}
function suggestionBlock() {
const r = suggestedRecipe(ui.date);
return h('div', null, h('div', { class: 'muted small', style: 'margin:6px 0' }, 'Идея на этот день'),
recipeView(r, h('button', { class: 'primary', onclick: () => { db.plan.push({ id: uid(), date: ui.date, recipeId: adoptRecipe(r) }); save(); render(); toast('Рецепт добавлен на день'); } }, 'Выбрать')));
}
/** Выбор рецепта на выбранный день или создание нового. */
function openRecipePicker() {
const body = h('div');
const close = openSheet('Рецепт на ' + longDate(ui.date), body);
const draw = () => body.replaceChildren(
h('button', { class: 'primary', style: 'width:100%', onclick: () => { close(); openRecipeForm({ addToDay: true }); } }, '+ Новый рецепт'),
...[...db.recipes, ...BUILTIN_RECIPES.filter(b => !db.recipes.some(r => r.id === b.id))].map(r => recipeView(r, h('button', { onclick: () => { db.plan.push({ id: uid(), date: ui.date, recipeId: adoptRecipe(r) }); save(); close(); render(); toast('Рецепт добавлен на день'); } }, 'Выбрать'))));
draw();
}
function openRecipeForm(o) {
const e = o.entry;
let photo = e ? e.photo : '';
const title = textField('Название блюда', { value: e ? e.title : '', required: true, max: 80 });
const time = numField('Время приготовления, мин', { value: e ? e.time : '', required: true, int: true, min: 1, max: 1440 });
const ing = h('textarea', { rows: 5, maxlength: 1500, placeholder: 'По одному продукту в строке, например:\nОвсяные хлопья — 50 г\nМолоко — 200 мл' }, e ? e.ingredients : '');
const ingField = field('Состав продуктов', ing);
const prev = h('div');
const drawPhoto = () => prev.replaceChildren(photo ? h('img', { src: photo, alt: 'Фото блюда', style: 'width:100%;max-height:220px;object-fit:cover;border-radius:12px;margin-bottom:8px' }) : null,
photo ? h('button', { type: 'button', onclick: () => { photo = ''; drawPhoto(); } }, 'Убрать фото') : null);
drawPhoto();
const file = h('input', { type: 'file', accept: 'image/*', onchange: async () => {
if (!file.files[0]) return;
try { photo = await resizePhoto(file.files[0]); drawPhoto(); } catch (x) { toast('Не удалось открыть фото. Выберите другое изображение.'); }
} });
const close = openSheet(e ? 'Рецепт' : 'Новый рецепт', h('div', null, title, field('Фото', file), prev, time, ingField,
formFoot(() => {
const t = title.read(), tm = time.read();
if (t == null || tm == null) return;
const ingText = ing.value.trim();
ingField.setErr(ingText ? '' : 'Укажите состав продуктов');
if (!ingText) return;
const rec = { id: e ? e.id : uid(), title: t, time: tm.v, ingredients: ingText, photo };
if (e) Object.assign(e, rec); else { db.recipes.push(rec); if (o.addToDay) db.plan.push({ id: uid(), date: ui.date, recipeId: rec.id }); }
save(); close(); render(); toast('Рецепт сохранён');
}, e ? h('button', { class: 'danger', onclick: () => { close(); confirmBox('Удалить рецепт «' + e.title + '»? Он пропадёт и из всех дней.', 'Удалить', () => { db.recipes = db.recipes.filter(r => r.id !== e.id); db.plan = db.plan.filter(x => x.recipeId !== e.id); save(); render(); }); } }, 'Удалить') : null)));
}
/* =====================================================================
ТРЕНИРОВКИ
===================================================================== */
function viewWorkouts() {
const list = db.workouts.filter(w => ui.wFilter === 'all' || w.type === ui.wFilter).sort((a, b) => a.date < b.date ? 1 : a.date > b.date ? -1 : 0);
return h('div', null,
h('div', { class: 'row wrap', style: 'margin:4px 0 8px' },
h('button', { class: 'primary grow', onclick: () => openWorkoutForm({ date: ui.date }) }, '+ Тренировка'),
h('button', { class: 'grow', onclick: repeatLast, disabled: !db.workouts.length }, '↻ Повторить прошлую')),
h('div', { class: 'chips' }, [['all', 'Все'], ...WORKOUT_TYPES].map(([k, n]) => h('button', { class: 'chip' + (ui.wFilter === k ? ' on' : ''), onclick: () => { ui.wFilter = k; render(); } }, n))),
h('div', { class: 'card' }, list.length ? list.map(w => h('div', { class: 'item' },
h('div', { class: 'main', onclick: () => openWorkoutForm({ entry: w }) },
h('b', null, longDate(w.date) + ' · ' + typeName(WORKOUT_TYPES, w.type)),
h('span', { class: 'muted small' }, workoutSummary(w) + ' · самочувствие ' + w.feel + '/5'),
w.type === 'strength' && w.exercises.length ? h('div', { class: 'small muted' }, w.exercises.map(e => e.name + ' ' + e.sets.map(s => s.reps + '×' + fmt(s.weight)).join(', ')).join(' | ')) : null,
w.note ? h('div', { class: 'small' }, '📝 ' + w.note) : null),
h('button', { class: 'ghost icon', 'aria-label': 'Удалить тренировку', onclick: () => delWorkout(w) }, '🗑'))) :
h('div', { class: 'empty' }, db.workouts.length ? 'Нет тренировок такого типа' : 'Пока нет ни одной тренировки')));
}
function delWorkout(w) {
confirmBox('Удалить тренировку от ' + longDate(w.date) + '?', 'Удалить', () => { db.workouts = db.workouts.filter(x => x.id !== w.id); save(); render(); });
}
/** Копия последней тренировки (по выбранному фильтру типа) на выбранный день. */
function repeatLast() {
const src = db.workouts.filter(w => ui.wFilter === 'all' || w.type === ui.wFilter).sort((a, b) => a.date < b.date ? 1 : -1)[0];
if (!src) return toast('Нет подходящей тренировки для повтора');
const copy = JSON.parse(JSON.stringify(src)); copy.id = uid(); copy.date = ui.date;
db.workouts.push(copy); save(); render(); toast('Тренировка повторена на ' + longDate(ui.date));
}
function openWorkoutForm(o) {
const e = o.entry, isNew = !e;
const date = dateField('Дата', e ? e.date : o.date);
const type = selectField('Тип', WORKOUT_TYPES, e ? e.type : 'strength', () => { drawType(); });
const dur = numField('Длительность, мин', { value: e ? e.duration : '', required: true, min: 1, max: 1440, int: true });
let feel = e ? e.feel : 3;
const feelBox = h('div', { class: 'chips' });
const drawFeel = () => feelBox.replaceChildren(...[1, 2, 3, 4, 5].map(n => h('button', { class: 'chip' + (feel === n ? ' on' : ''), type: 'button', onclick: () => { feel = n; drawFeel(); } }, String(n))));
drawFeel();
const note = h('textarea', { rows: 2, maxlength: 300, placeholder: 'Необязательно' }, e ? e.note : '');
const dist = numField('Дистанция, км', { value: e ? e.distance : '', min: 0, max: 1000 });
const pulse = numField('Пульс (средний)', { value: e ? e.pulse : '', min: 30, max: 250, int: true });
const exBox = h('div'), typeBox = h('div');
const exs = e && e.exercises ? JSON.parse(JSON.stringify(e.exercises)).map(x => ({ name: x.name, sets: x.sets.map(s => ({ reps: String(s.reps), weight: String(s.weight).replace('.', ',') })) })) : [];
const exErr = h('div', { class: 'err' });
function drawEx() {
exBox.replaceChildren(...exs.map((ex, i) => {
const nameIn = h('input', { type: 'text', value: ex.name, placeholder: 'Название упражнения', maxlength: 60, oninput: () => { ex.name = nameIn.value; } });
const sets = h('div');
const drawSets = () => sets.replaceChildren(...ex.sets.map((s, j) => h('div', { class: 'setrow' }, h('span', { class: 'muted' }, (j + 1) + '.'),
h('input', { type: 'text', inputmode: 'numeric', placeholder: 'повторы', value: s.reps, 'aria-label': 'Повторы', oninput: ev => { s.reps = ev.target.value; } }),
h('input', { type: 'text', inputmode: 'decimal', placeholder: 'вес, кг', value: s.weight, 'aria-label': 'Вес, кг', oninput: ev => { s.weight = ev.target.value; } }),
h('button', { class: 'ghost icon', type: 'button', 'aria-label': 'Убрать подход', onclick: () => { ex.sets.splice(j, 1); drawSets(); } }, '✕'))));
drawSets();
const card = h('div', { class: 'exrow' }, h('div', { class: 'row' }, h('div', { class: 'grow' }, nameIn),
h('button', { class: 'ghost icon', type: 'button', 'aria-label': 'Убрать упражнение', onclick: () => { exs.splice(i, 1); drawEx(); } }, '🗑')), sets,
h('button', { type: 'button', onclick: () => { const l = ex.sets[ex.sets.length - 1]; ex.sets.push(l ? { ...l } : { reps: '', weight: '' }); drawSets(); } }, '+ Подход'));
attachSuggest(nameIn, () => db.exercises.map(n => ({ name: n })), x => { nameIn.value = x.name; ex.name = x.name; });
return card;
}));
}
function drawType() {
const tp = type.input.value;
typeBox.replaceChildren();
if (tp === 'strength') { if (!exs.length) exs.push({ name: '', sets: [{ reps: '', weight: '' }] }); drawEx(); typeBox.append(h('h3', null, 'Упражнения'), exBox, exErr, h('button', { type: 'button', onclick: () => { exs.push({ name: '', sets: [{ reps: '', weight: '' }] }); drawEx(); } }, '+ Упражнение')); }
if (tp === 'cardio') typeBox.append(h('div', { class: 'grid2' }, dist, pulse));
}
drawType();
const body = h('div', null, date, type, dur, field('Самочувствие, 1–5', feelBox), typeBox, field('Заметка', note));
const del = isNew ? null : h('button', { class: 'danger', onclick: () => { close(); delWorkout(e); } }, 'Удалить');
const close = openSheet(isNew ? 'Новая тренировка' : 'Тренировка', h('div', null, body, formFoot(() => {
const d = date.read(), du = dur.read(), tp = type.input.value;
let ok = d != null && du != null, extra = {};
if (tp === 'cardio') { const a = dist.read(), b = pulse.read(); ok = ok && a && b; extra = { distance: a && a.v, pulse: b && b.v }; }
let cleaned = [];
if (tp === 'strength') {
exErr.textContent = '';
for (const ex of exs) {
if (!ex.name.trim() && ex.sets.every(s => !s.reps && !s.weight)) continue;
if (!ex.name.trim()) { exErr.textContent = 'Укажите название упражнения'; ok = false; break; }
const sets = [];
for (const s of ex.sets) {
const r = parseNum(s.reps, { required: true, int: true, min: 1, max: 1000 }), w = parseNum(s.weight || '0', { min: 0, max: 1000 });
if (!r.ok || !w.ok) { exErr.textContent = 'Проверьте подходы «' + ex.name + '»: повторы — целое число, вес — число'; ok = false; break; }
sets.push({ reps: r.value, weight: w.value });
}
if (!ok) break;
if (!sets.length) { exErr.textContent = 'У упражнения «' + ex.name + '» нет подходов'; ok = false; break; }
cleaned.push({ name: ex.name.trim(), sets });
}
if (ok && !cleaned.length) { exErr.textContent = 'Добавьте хотя бы одно упражнение'; ok = false; }
}
if (!ok) return;
const rec = { id: e ? e.id : uid(), date: d, type: tp, duration: du.v, feel, note: note.value.trim(), ...extra };
if (tp === 'strength') rec.exercises = cleaned;
if (e) { for (const k of ['distance', 'pulse', 'exercises']) delete e[k]; Object.assign(e, rec); } else db.workouts.push(rec);
for (const ex of cleaned) if (!db.exercises.some(n => n.toLowerCase() === ex.name.toLowerCase())) db.exercises.push(ex.name);
ui.date = d; save(); close(); render(); toast('Сохранено');
}, del)));
}
/* =====================================================================
ТЕЛО
===================================================================== */
function viewBody() {
const list = db.body.slice().sort((a, b) => a.date < b.date ? 1 : -1);
return h('div', null,
h('button', { class: 'primary', style: 'width:100%;margin-top:4px', onclick: () => openBodyForm({}) }, '+ Вес или замеры'),
h('div', { class: 'card' }, h('h3', null, 'Вес, кг'), lineChart(weightSeries(db), 'кг')),
h('div', { class: 'card' }, h('h3', null, 'История'), list.length ? list.map(b => h('div', { class: 'item' },
h('div', { class: 'main', onclick: () => openBodyForm({ entry: b }) }, h('b', null, longDate(b.date) + ' ' + b.date.slice(0, 4)),
h('span', { class: 'muted small' }, [b.weight != null && 'вес ' + fmt(b.weight) + ' кг', b.waist != null && 'талия ' + fmt(b.waist), b.hips != null && 'бёдра ' + fmt(b.hips), b.chest != null && 'грудь ' + fmt(b.chest)].filter(Boolean).join(' · '))),
h('button', { class: 'ghost icon', 'aria-label': 'Удалить запись', onclick: () => confirmBox('Удалить запись от ' + longDate(b.date) + '?', 'Удалить', () => { db.body = db.body.filter(x => x.id !== b.id); save(); render(); }) }, '🗑'))) : h('div', { class: 'empty' }, 'Пока нет записей')));
}
function openBodyForm(o) {
const e = o.entry;
const date = dateField('Дата', e ? e.date : todayKey());
const w = numField('Вес, кг', { value: e ? e.weight : '', min: 20, max: 500 });
const waist = numField('Талия, см', { value: e ? e.waist : '', min: 20, max: 300 });
const hips = numField('Бёдра, см', { value: e ? e.hips : '', min: 20, max: 300 });
const chest = numField('Грудь, см', { value: e ? e.chest : '', min: 20, max: 300 });
const err = h('div', { class: 'err' });
const close = openSheet(e ? 'Запись о теле' : 'Новая запись о теле', h('div', null, date, w, h('div', { class: 'grid2' }, waist, hips), chest, err, formFoot(() => {
const d = date.read(), r = [w, waist, hips, chest].map(x => x.read());
if (d == null || r.some(x => x == null)) return;
if (r.every(x => x.v == null)) { err.textContent = 'Заполните хотя бы одно значение'; return; }
err.textContent = '';
const rec = { id: e ? e.id : uid(), date: d, weight: r[0].v, waist: r[1].v, hips: r[2].v, chest: r[3].v };
if (e) Object.assign(e, rec); else db.body.push(rec);
save(); close(); render(); toast('Сохранено');
}, e ? h('button', { class: 'danger', onclick: () => { close(); confirmBox('Удалить запись?', 'Удалить', () => { db.body = db.body.filter(x => x.id !== e.id); save(); render(); }); } }, 'Удалить') : null)));
}
/* =====================================================================
СТАТИСТИКА
===================================================================== */
function viewStats() {
const days = ui.period === 'week' ? 7 : 30, end = todayKey(), st = periodStats(db, end, days);
const names = [...new Set(db.workouts.flatMap(w => (w.exercises || []).map(x => x.name)))].sort();
if (!ui.statEx || !names.includes(ui.statEx)) ui.statEx = names[0] || '';
const exSel = names.length ? h('select', { 'aria-label': 'Упражнение', onchange: ev => { ui.statEx = ev.target.value; render(); } }, names.map(n => h('option', { value: n, selected: n === ui.statEx }, n))) : null;
return h('div', null,
h('div', { class: 'chips', style: 'margin:4px 0 8px' }, [['week', 'Неделя'], ['month', 'Месяц']].map(([k, n]) => h('button', { class: 'chip' + (ui.period === k ? ' on' : ''), onclick: () => { ui.period = k; render(); } }, n))),
h('div', { class: 'card' }, h('div', { class: 'stats' },
h('div', { class: 'stat' }, h('span', { class: 'muted small' }, 'Ккал в день (среднее)'), h('b', null, fmtInt(st.avgKcal)), h('span', { class: 'small muted' }, 'цель ' + db.settings.kcal)),
h('div', { class: 'stat' }, h('span', { class: 'muted small' }, 'Белок в день, г'), h('b', null, fmtInt(st.avgProtein)), h('span', { class: 'small muted' }, 'цель ' + db.settings.protein)),
h('div', { class: 'stat' }, h('span', { class: 'muted small' }, 'Тренировки'), h('b', null, st.workouts + ' из ' + fmt(st.workoutTarget)), h('span', { class: 'small muted' }, 'цель на период')),
h('div', { class: 'stat' }, h('span', { class: 'muted small' }, 'Изменение веса'), h('b', null, st.weightChange == null ? '—' : (st.weightChange > 0 ? '+' : '') + fmt(st.weightChange) + ' кг'), h('span', { class: 'small muted' }, st.weightChange == null ? 'нужно 2 записи' : 'за период')),
h('div', { class: 'stat' }, h('span', { class: 'muted small' }, 'Серия дней с нормой'), h('b', null, streak(db, end) + ' дн.')),
h('div', { class: 'stat' }, h('span', { class: 'muted small' }, 'Дней с записью еды'), h('b', null, st.loggedDays + ' из ' + days))),
h('p', { class: 'small muted' }, 'Среднее считается по дням, когда еда записана.')),
h('div', { class: 'card' }, h('h3', null, 'Калории по дням'), barChart(st.days, db.settings.kcal)),
h('div', { class: 'card' }, h('h3', null, 'Вес, кг'), lineChart(weightSeries(db).filter(p => p.x >= st.days[0].date), 'кг')),
h('div', { class: 'card' }, h('h3', null, 'Рабочий вес по упражнению'),
exSel ? [exSel, lineChart(exerciseSeries(db, ui.statEx), 'кг')] : h('div', { class: 'empty' }, 'Добавьте силовую тренировку, чтобы увидеть график')));
}
/* =====================================================================
НАСТРОЙКИ, МАСТЕР, ЭКСПОРТ / ИМПОРТ
===================================================================== */
/** Поля калькулятора нормы. */
function calcFields(pr) {
const sex = selectField('Пол', [['m', 'Мужской'], ['f', 'Женский']], pr.sex);
const age = numField('Возраст, лет', { value: pr.age, required: true, int: true, min: 10, max: 100 });
const height = numField('Рост, см', { value: pr.height, required: true, min: 100, max: 250 });
const weight = numField('Вес, кг', { value: pr.weight, required: true, min: 25, max: 400 });
const act = selectField('Активность', ACTIVITY, pr.activity);
return {
el: h('div', null, h('div', { class: 'grid2' }, sex, age), h('div', { class: 'grid2' }, height, weight), act),
read() {
const r = [age.read(), height.read(), weight.read()];
if (r.some(x => x == null)) return null;
return { sex: sex.input.value, age: r[0].v, height: r[1].v, weight: r[2].v, activity: Number(act.input.value) };
}
};
}
/** Поля норм. */
function normFields(s) {
const f = {
kcal: numField('Ккал в день', { value: s.kcal, required: true, int: true, min: 500, max: 10000 }),
protein: numField('Белки, г', { value: s.protein, required: true, min: 0, max: 1000 }),
fat: numField('Жиры, г', { value: s.fat, required: true, min: 0, max: 1000 }),
carbs: numField('Углеводы, г', { value: s.carbs, required: true, min: 0, max: 2000 }),
water: numField('Вода, мл', { value: s.water, required: true, int: true, min: 0, max: 10000 }),
workoutsPerWeek: numField('Тренировок в неделю', { value: s.workoutsPerWeek, required: true, int: true, min: 0, max: 21 })
};
return {
el: h('div', null, f.kcal, h('div', { class: 'grid2' }, f.protein, f.fat), h('div', { class: 'grid2' }, f.carbs, f.water), f.workoutsPerWeek),
fill(n) { for (const k of ['kcal', 'protein', 'fat', 'carbs', 'water']) f[k].input.value = String(n[k]); },
read() {
const out = {};
for (const k of Object.keys(f)) { const r = f[k].read(); if (!r) return null; out[k] = r.v; }
return out;
}
};
}
function goalChips(get, set) {
const box = h('div', { class: 'chips' });
const draw = () => box.replaceChildren(...GOALS.map(([k, n]) => h('button', { type: 'button', class: 'chip' + (get() === k ? ' on' : ''), onclick: () => { set(k); draw(); } }, n)));
draw();
return box;
}
function viewSettings() {
const s = db.settings;
let goal = s.goal;
const calc = calcFields(s.profile), norms = normFields(s);
const calcNote = h('div', { class: 'small muted' });
const themeSel = selectField('Тема', [['auto', 'Как в системе'], ['light', 'Светлая'], ['dark', 'Тёмная']], s.theme, ev => { s.theme = ev.target.value; save(); applyTheme(); });
const fileIn = h('input', { type: 'file', accept: 'application/json,.json', hidden: true, onchange: onImport });
const catalog = (title, items, del) => h('div', { class: 'card' }, h('h3', null, title),
items.length ? items.map(x => h('div', { class: 'item' }, h('div', { class: 'main' }, x.label), h('button', { class: 'ghost icon', 'aria-label': 'Удалить ' + x.label, onclick: () => confirmBox('Убрать «' + x.label + '» из справочника? Записи в дневнике останутся.', 'Убрать', () => { del(x); save(); render(); }) }, '🗑'))) : h('div', { class: 'empty' }, 'Справочник пуст'));
return h('div', null,
h('div', { class: 'card' }, h('h3', null, 'Цель'), h('div', { style: 'margin-top:8px' }, goalChips(() => goal, k => { goal = k; }))),
h('div', { class: 'card' }, h('h3', null, 'Калькулятор нормы'), h('p', { class: 'small muted' }, 'Формула Миффлина–Сан Жеора. Результат можно поправить вручную ниже.'), calc.el,
h('button', { onclick: () => { const p = calc.read(); if (!p) return; const n = suggestNorms(goal, p); norms.fill(n); calcNote.textContent = 'Базовый обмен ' + mifflin(p).bmr + ' ккал, с активностью ' + mifflin(p).tdee + ' ккал. Нормы подставлены ниже — нажмите «Сохранить».'; } }, 'Рассчитать'), calcNote),
h('div', { class: 'card' }, h('h3', null, 'Нормы в день'), norms.el,
h('button', { class: 'primary', style: 'width:100%', onclick: () => { const n = norms.read(), p = calc.read(); if (!n || !p) return; Object.assign(s, n, { goal, profile: p }); save(); render(); toast('Настройки сохранены'); } }, 'Сохранить')),
h('div', { class: 'card' }, themeSel),
h('div', { class: 'card stack' }, h('h3', null, 'Данные'),
h('div', { class: 'row wrap' }, h('button', { class: 'grow', onclick: exportJson }, 'Экспорт JSON'), h('button', { class: 'grow', onclick: () => fileIn.click() }, 'Импорт JSON'), fileIn),
h('div', { class: 'row wrap' }, h('button', { class: 'grow', onclick: () => download('pitanie.csv', mealsCsv(db), 'text/csv') }, 'CSV: питание'),
h('button', { class: 'grow', onclick: () => download('trenirovki.csv', workoutsCsv(db), 'text/csv') }, 'CSV: тренировки'),
h('button', { class: 'grow', onclick: () => download('telo.csv', bodyCsv(db), 'text/csv') }, 'CSV: тело')),
h('button', { class: 'danger', onclick: () => confirmBox('Удалить все записи и настройки? Это нельзя отменить — сначала сделайте экспорт.', 'Очистить всё', () => { db = defaultData(); save(); ui.date = todayKey(); render(); startWizard(); }) }, 'Очистить все данные')),
catalog('Справочник продуктов', db.foods.map(x => ({ id: x.id, label: x.name })), x => { db.foods = db.foods.filter(f => f.id !== x.id); }),
catalog('Справочник упражнений', db.exercises.map(n => ({ label: n })), x => { db.exercises = db.exercises.filter(n => n !== x.label); }));
}
function download(name, text, mime) {
const a = h('a', { href: URL.createObjectURL(new Blob([text], { type: mime + ';charset=utf-8' })), download: name });
document.body.append(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(a.href), 1000);
}
function exportJson() { download('tracker-' + todayKey() + '.json', JSON.stringify(db, null, 2), 'application/json'); toast('Файл сохранён'); }
function onImport(ev) {
const file = ev.target.files[0]; ev.target.value = '';
if (!file) return;
const rd = new FileReader();
rd.onload = () => {
let data;
try { data = normalizeImport(JSON.parse(rd.result)); } catch (e) { return toast(e instanceof SyntaxError ? 'Файл не читается. Выберите копию, сохранённую в этом приложении.' : e.message + ' Выберите другой файл.'); }
confirmBox('Заменить все текущие данные данными из файла «' + file.name + '»?', 'Заменить', () => { db = data; save(); render(); toast('Данные загружены'); });
};
rd.onerror = () => toast('Не удалось прочитать файл. Попробуйте ещё раз.');
rd.readAsText(file);
}
/** Мастер первого запуска: шаг 1 — цель и данные, шаг 2 — нормы. */
function startWizard() {
let goal = db.settings.goal;
const calc = calcFields(db.settings.profile);
const body = h('div');
let close;
const step1 = () => body.replaceChildren(
h('p', { class: 'muted' }, 'Шаг 1 из 2. Выберите цель и укажите данные — мы посчитаем дневные нормы.'),
goalChips(() => goal, k => { goal = k; }), h('div', { style: 'height:8px' }), calc.el,
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 norms = normFields(Object.assign({}, db.settings, suggestNorms(goal, p)));
body.replaceChildren(h('p', { class: 'muted' }, 'Шаг 2 из 2. Проверьте нормы — их можно поменять.'), 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('Готово! Можно записывать день.'); } }, 'Готово')));
};
step1();
close = openSheet('Добро пожаловать', body, { locked: true });
}
render();
if (!db.settings.onboarded) startWizard();
</script>
</body>
</html>