treker-po-trenirovkam-i-pit.../index.html

1426 lines
108 KiB
HTML
Raw Permalink 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">
<meta name="theme-color" content="#2f7de1">
<link rel="manifest" href="manifest.webmanifest">
<link rel="icon" href="icon.svg" type="image/svg+xml">
<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(120px + 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}
.link-btn{display:flex;align-items:center;justify-content:center;gap:6px;margin:10px 0 4px;text-decoration:none;font-weight:600;color:var(--accent);border-color:var(--accent)}
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 .req{color:var(--bad);font-size:.8rem}
.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,minmax(0,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;line-height:1.2;overflow-wrap:anywhere}.ring .t small{font-size:.62rem}.ring .t .amt{display:block;font-size:.74rem;font-weight:600;white-space:nowrap}
.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:2px}.ring .c{font-size:.72rem}.ring .t{font-size:.7rem;letter-spacing:-.01em}.ring .t .amt{font-size:.64rem}.ring .t small{font-size:.54rem}}
@media (max-width:340px){.rings{margin:0 -10px}.ring .t{font-size:.62rem}.ring .t .amt{font-size:.58rem}.ring .t small{font-size:.48rem}}
.left{text-align:center;font-weight:700;font-size:1.05rem;margin:12px 0 0}
.quick.two{grid-template-columns:1fr 1fr}
.chip.minus{border-color:var(--water);color:var(--water);font-weight:700}
/* списки */
.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;overflow-wrap:anywhere}
.item .main b{display:block;overflow-wrap:anywhere}
.item.dish{display:grid;grid-template-columns:96px minmax(0,1fr);gap:8px 12px;align-items:start}
.item.dish .dish-row{display:block;margin-top:4px}
.item.dish .dish-body{grid-column:1/-1;cursor:pointer;overflow-wrap:break-word}
.item.dish .recipe-steps{margin:6px 0 0;padding-left:22px;overflow-wrap:anywhere}.item.dish .recipe-steps[hidden]{display:none}
.item.dish .dish-actions{grid-column:1/-1;display:flex;justify-content:flex-end}
.rings-cap{text-align:center;margin:0 0 6px}
.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}
@media (max-width:699px){
.welcome-sheet{max-height:100dvh;padding:12px 12px calc(12px + env(safe-area-inset-bottom))}
.welcome-sheet p{margin:6px 0}
.welcome-sheet .field{margin:4px 0}
.welcome-sheet .foot{margin-top:8px}
.welcome-sheet .chip{padding:8px 10px}
.welcome-sheet .grid2{gap:0 8px}
.welcome-sheet .field .req{display:block}
}
.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}
.recipe-photo,.recipe-photo-placeholder{width:96px;height:96px;border-radius:12px;object-fit:cover}.recipe-photo-placeholder{background:var(--bg);display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;gap:6px}.recipe-photo-placeholder>span:first-child{font-size:2rem}[data-ingredients] ul{margin:8px 0;padding-left:20px}
</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 src="gym-plan.i18n.js"></script>
<script src="recipes-status.i18n.js"></script>
<script>
/* =====================================================================
СЛОЙ ДАННЫХ (чистые функции, без DOM) — проверяется tests/logic.test.js
===================================================================== */
/* LOGIC:START */
const STORAGE_KEY = typeof window !== 'undefined' && window.TPTProfile ? 'tpt.user.' + window.TPTProfile.username : '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: null, age: null, height: null, weight: null, activity: null },
plan: ['', '', '', '', '', '', ''], // план тренировок по дням недели, индекс = Date.getDay() (0 — воскресенье)
reminders: { on: false, water: true, waterEvery: 2, dinner: true, dinnerTime: '20:00', workout: true, workoutTime: '18:00' },
theme: 'auto', onboarded: false
},
foods: [], meals: [], water: [], workouts: [], exercises: [], body: [], recipes: [], plan: [], daily: [], shopDone: []
};
}
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);
const dl = data.daily.filter(x => x.date >= start && x.date <= end);
const avg = key => { const v = dl.filter(x => x[key] != null).map(x => x[key]); return v.length ? round1(v.reduce((a, b) => a + b, 0) / v.length) : null; };
return {
avgSteps: avg('steps') == null ? null : Math.round(avg('steps')), avgSleep: avg('sleep'),
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;
const dflt = defaultData().settings;
out.settings.profile = Object.assign(dflt.profile, obj.settings.profile || {});
out.settings.reminders = Object.assign(dflt.reminders, obj.settings.reminders || {});
out.settings.plan = Array.isArray(obj.settings.plan) && obj.settings.plan.length === 7 ? obj.settings.plan.map(String) : dflt.plan;
for (const k of ['foods', 'meals', 'water', 'workouts', 'exercises', 'body', 'recipes', 'plan', 'daily', 'shopDone']) {
if (obj[k] != null && !Array.isArray(obj[k])) throw new Error('Файл повреждён: раздел «' + k + '» записан неверно.');
out[k] = obj[k] || [];
}
return out;
}
/** Понедельник недели, в которую входит дата. */
function weekStart(k) { return addDays(k, -((parseKey(k).getDay() + 6) % 7)); }
/** Рекорды, поставленные в тренировке: вес выше любого из прошлых дней (при наличии истории). */
function workoutRecords(data, w) {
const out = [], same = (a, b) => a.toLowerCase() === b.toLowerCase();
for (const e of (w.exercises || [])) {
const mx = Math.max(0, ...e.sets.map(s => s.weight));
let prior = 0, had = false;
for (const o of data.workouts) {
if (o.id === w.id || o.date >= w.date) continue;
for (const x of (o.exercises || [])) if (same(x.name, e.name)) { had = true; prior = Math.max(prior, ...x.sets.map(s => s.weight)); }
}
if (had && mx > prior) out.push({ name: e.name, weight: mx, prev: prior });
}
return out;
}
/** Личные рекорды: максимальный вес по каждому упражнению и дата, когда он взят впервые. */
function personalBests(data) {
const best = new Map();
for (const w of data.workouts.slice().sort((a, b) => a.date < b.date ? -1 : 1)) {
for (const e of (w.exercises || [])) {
const mx = Math.max(0, ...e.sets.map(s => s.weight)), k = e.name.toLowerCase(), cur = best.get(k);
if (mx > 0 && (!cur || mx > cur.weight)) best.set(k, { name: e.name, weight: mx, date: w.date });
}
}
return [...best.values()].sort((a, b) => a.name.localeCompare(b.name, 'ru'));
}
/** Список покупок: строки состава «Продукт — 50 г» суммируются по продукту и единице. */
function shoppingList(recipes) {
const map = new Map();
for (const r of recipes) for (const raw of r.ingredients.split('\n')) {
const line = raw.trim();
if (!line) continue;
const m = line.match(/^(.+?)\s*[—–-]\s*(\d+(?:[.,]\d+)?)\s*(.*)$/);
let name = line, qty = null, unit = '';
if (m) { name = m[1].trim(); qty = Number(m[2].replace(',', '.')); unit = m[3].replace(/\(.*?\)/g, '').trim(); }
const key = name.toLowerCase() + '|' + unit.toLowerCase(), cur = map.get(key);
if (cur) { if (qty != null && cur.qty != null) cur.qty = round1(cur.qty + qty); } else map.set(key, { key, name, qty, unit });
}
return [...map.values()].sort((a, b) => a.name.localeCompare(b.name, 'ru'));
}
/** Копии записей еды из одного дня в другой (весь день или один приём пищи). */
function copyMeals(data, from, to, type) {
return data.meals.filter(m => m.date === from && (!type || m.type === type)).map(m => ({ ...m, id: uid(), date: to }));
}
/** Сколько дней назад было последнее фото прогресса (null — фото ещё не было). */
function daysSincePhoto(data, today) {
const ph = data.body.filter(b => b.photo).map(b => b.date).sort();
return ph.length ? Math.round((parseKey(today) - parseKey(ph[ph.length - 1])) / 86400000) : null;
}
/** Какие напоминания пора показать сейчас; fired — что уже показано {вид: ключ}. */
function dueReminders(data, now, fired) {
const r = data.settings.reminders || {};
if (!r.on) return [];
const date = dateKey(now), min = now.getHours() * 60 + now.getMinutes(), t = dayTotals(data, date), out = [];
const toMin = x => { const [hh, mm] = String(x || '').split(':').map(Number); return hh * 60 + (mm || 0); };
if (r.water && min >= 540 && min <= 1260 && t.water < data.settings.water) {
const key = date + '#' + Math.floor((min - 540) / (Math.max(1, r.waterEvery || 2) * 60));
if (fired.water !== key) out.push({ kind: 'water', key, text: 'Пора попить воды: выпито ' + t.water + ' из ' + data.settings.water + ' мл' });
}
if (r.dinner && min >= toMin(r.dinnerTime) && !data.meals.some(m => m.date === date && m.type === 'dinner') && fired.dinner !== date) {
out.push({ kind: 'dinner', key: date, text: 'Не забудьте записать ужин' });
}
const plan = (data.settings.plan || [])[now.getDay()];
if (r.workout && plan && min >= toMin(r.workoutTime) && !t.workouts.length && fired.workout !== date) {
out.push({ kind: 'workout', key: date, text: 'Тренировка по плану: ' + plan });
}
return out;
}
/* LOGIC:END */
/* =====================================================================
ХРАНЕНИЕ
===================================================================== */
let db = load();
function applyPrivateProfile() {
if (!window.TPTProfile) return;
const personal = window.TPTProfile;
delete db.settings.normsPending;
db.settings.profile = { ...personal.profile, sex: personal.profile.sex === 'male' ? 'm' : 'f' };
db.settings.goal = personal.profile.goal;
Object.assign(db.settings, suggestNorms(db.settings.goal, db.settings.profile), { onboarded: true });
db.settings.kcal = personal.nutrition.calories;
db.settings.protein = personal.nutrition.protein;
}
applyPrivateProfile();
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() {
applyPrivateProfile();
try { localStorage.setItem(STORAGE_KEY, JSON.stringify(window.TPTProfile ? { ...db, settings: { ...db.settings, profile: defaultData().settings.profile } } : 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));
/** Число с пробелом между тысячами: 1 850. */
const fmtK = n => Math.round(n).toLocaleString('ru-RU');
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: opts.welcome ? 'sheet welcome-sheet' : '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;
}
/** Понятная ошибка простыми словами с допустимым диапазоном. */
function wizardError(o, raw, err) {
if (err === 'Заполните это поле') return 'Заполните это поле';
return 'Укажите ' + o.what + (o.hint ? ' ' + o.hint.charAt(0).toLowerCase() + o.hint.slice(1) : '') + '.';
}
/** Ставит курсор в первое поле с ошибкой. */
function focusFirstError(root) {
const bad = root.querySelector('.field.bad input');
if (bad) bad.focus();
}
/** Числовое поле: 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;
if (o.what && o.required) {
el.querySelector('.lbl').append(h('span', { class: 'req' }, o.reqText || ' · обязательно'));
input.setAttribute('aria-required', 'true');
input.addEventListener('blur', () => el.read());
input.addEventListener('input', () => { if (el.classList.contains('bad')) el.read(); });
}
el.read = () => {
const r = parseNum(input.value, o);
if (!r.ok && o.what) r.error = wizardError(o, input.value, r.error);
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;
const gen = { 'килокалории': 'килокалорий', 'граммы': 'граммов', 'миллилитры': 'миллилитров' }[unit] || unit;
return h('div', { class: 'ring', role: 'img', 'aria-label': label + ': съедено ' + fmtInt(fact) + ' из ' + fmtInt(target) + ' ' + gen },
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' }, Math.round((target > 0 ? fact / target : 0) * 100) + ' %')),
h('div', { class: 't' }, h('b', null, label), h('span', { class: 'amt', 'data-amount': '' }, fmtInt(fact) + ' из ' + fmtInt(target)),
h('small', { class: 'muted', style: 'display:block' }, 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 gymLang = GymPlan.language(new URLSearchParams(location.search).get('lang') || 'ru');
const gymText = GymPlan.text(gymLang);
const ui = { tab: new URLSearchParams(location.search).get('plan') === '1' ? 'gymPlan' : '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 = { gymPlan: viewGymPlan, 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, leftP = Math.round(s.protein - t.protein);
const planName = (s.plan || [])[parseKey(ui.date).getDay()] || '';
const proteinPart = leftP > 0 ? fmtK(leftP) + ' г белка' : 'белок выполнен';
const leftText = left >= 0 ? 'Осталось: ' + fmtK(left) + ' ккал · ' + proteinPart : 'Выше нормы на ' + fmtK(-left) + ' ккал · ' + proteinPart;
const trainingBody = 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)))))
: planName
? h('div', { class: 'row between' }, h('b', null, (ui.date === todayKey() ? 'Сегодня по плану: ' : 'По плану: ') + planName),
h('button', { class: 'primary', onclick: () => openWorkoutForm({ date: ui.date, planned: planName }) }, 'Записать'))
: h('div', { class: 'empty' }, 'Тренировки не было. План на неделю можно задать в «Настройках».');
if (t.meals > 0 || t.water > 0 || t.workouts.length) { if (!db.settings.hintDone) { db.settings.hintDone = true; save(); } }
const hintDone = !!db.settings.hintDone;
const openPlan = () => { ui.tab = 'gymPlan'; render(); window.scrollTo(0, 0); };
const goSettings = () => { ui.tab = 'settings'; render(); window.scrollTo(0, 0); };
return h('div', null, dateNav(),
h('div', { class: 'card' }, h('button', { class: 'primary', style: 'width:100%', 'data-plan-open': '', 'aria-describedby': 'planWhat', onclick: openPlan }, planHome.button),
h('p', { id: 'planWhat', class: 'small muted', 'data-plan-what': '', style: 'margin:8px 0 0' }, planHome.what),
window.TPTProfile ? h('a', { href: '/?lang=' + gymLang + '#daily-menu', 'data-menu-open': '' }, window.TPTMenuText) : null,
db.workouts.length ? null : h('p', { class: 'small muted', 'data-plan-start': '', style: 'margin:4px 0 0' }, h('button', { class: 'link-btn', style: 'text-align:left', onclick: openPlan }, planHome.start))),
s.normsPending ? h('div', { class: 'card', 'data-norms-pending': '' }, h('b', null, 'Дневные нормы пока не рассчитаны'),
h('p', { class: 'small muted', style: 'margin:6px 0 8px' }, 'Сейчас показаны примерные цифры. Укажите возраст, рост и вес в «Настройках» — и нормы станут вашими.'),
h('button', { class: 'primary', 'data-norms-open': '', onclick: goSettings }, 'Открыть «Настройки»')) : null,
h('div', { class: 'card' },
h('p', { class: 'small muted rings-cap', 'data-rings-caption': '' }, 'Съедено из дневной нормы'),
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('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 мл воды')),
!hintDone && t.meals === 0 && t.water === 0 && !t.workouts.length ? h('p', { class: 'small muted', 'data-empty-hint': '', style: 'text-align:center;margin:8px 0 0' }, 'Пока ничего не добавлено. Чтобы кольца заполнились, выберите блюдо в «Питании» или добавьте тренировку. Как только вы что-нибудь добавите, эта подсказка исчезнет.') : null,
h('p', { class: 'left ' + (left >= 0 ? 'ok' : 'bad') }, leftText)),
h('div', { class: 'quick two' },
h('button', { onclick: () => openMealForm({ date: ui.date }) }, '+ Еда'),
h('button', { onclick: () => openWorkoutForm({ date: ui.date }) }, '+ Тренировка')),
h('div', { class: 'card' }, h('h3', null, 'Тренировка'), trainingBody,
t.workouts.length && planName ? h('div', { class: 'small muted' }, 'По плану на этот день: ' + planName) : null),
recipesCard(), dailyCard(),
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 viewGymPlan() {
return h('div', { lang: gymLang },
h('button', { onclick: () => { ui.tab = 'today'; render(); } }, gymText.back),
h('div', { class: 'card' }, h('h2', null, gymText.title), h('p', null, gymText.intro), h('p', { class: 'small muted' }, gymText.hint)),
...GymPlan.days(gymLang).map(day => h('section', { class: 'card' },
h('h3', null, day.name), h('b', null, gymText.duration),
h('p', null, gymText.warmup), h('p', null, gymText.strength),
h('ul', null, ...day.exercises.map(ex => h('li', null,
ex.name, h('div', { class: 'small muted' }, gymText.dose.replace('{reps}', ex.reps))))),
h('p', null, day.cardio), h('p', null, gymText.stretch),
h('button', { class: 'primary', onclick: () => openWorkoutForm({ date: ui.date, draft: GymPlan.draft(day.id, gymLang) }) }, gymText.record))));
}
/** Шаги и сон за день: два простых поля, сохраняются при выходе из поля. */
function dailyCard() {
const rec = db.daily.find(x => x.date === ui.date);
const steps = h('input', { type: 'text', inputmode: 'numeric', placeholder: '0', 'aria-label': 'Шаги', value: rec && rec.steps != null ? rec.steps : '' });
const sleep = h('input', { type: 'text', inputmode: 'decimal', placeholder: '0', 'aria-label': 'Сон, часы', value: rec && rec.sleep != null ? String(rec.sleep).replace('.', ',') : '' });
const commit = () => {
const a = parseNum(steps.value, { int: true, min: 0, max: 200000 }), b = parseNum(sleep.value, { min: 0, max: 24 });
if (!a.ok || !b.ok) return toast('Шаги — целое число, сон — часы от 0 до 24. Поправьте значение.');
db.daily = db.daily.filter(x => x.date !== ui.date);
if (a.value != null || b.value != null) db.daily.push({ id: uid(), date: ui.date, steps: a.value, sleep: b.value });
save(); toast('Сохранено');
};
steps.addEventListener('change', commit); sleep.addEventListener('change', commit);
return h('div', { class: 'card' }, h('h3', null, 'Шаги и сон'),
h('div', { class: 'grid2', style: 'margin-top:6px' }, field('Шаги', steps), field('Сон, часов', sleep)));
}
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' }, 'Пока пусто'), copyButton(key, name)]);
});
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, 'г')),
repeatDayButton()),
sections, recipesCard(), shoppingCard());
}
/** «Скопировать вчерашний завтрак»: кнопка видна, если приём пуст, а в прошлый день он был. */
function copyButton(type, name) {
const prev = addDays(ui.date, -1);
if (!db.meals.some(m => m.date === prev && m.type === type)) return null;
const label = ui.date === todayKey() ? 'Скопировать вчерашний ' + name.toLowerCase() : 'Скопировать ' + name.toLowerCase() + ' за ' + longDate(prev);
return h('button', { style: 'width:100%', onclick: () => { db.meals.push(...copyMeals(db, prev, ui.date, type)); save(); render(); toast('Скопировано'); } }, '📋 ' + label);
}
/** «Повторить день»: копирует всю еду предыдущего дня. */
function repeatDayButton() {
const prev = addDays(ui.date, -1), n = db.meals.filter(m => m.date === prev).length;
if (!n) return null;
const doCopy = () => { db.meals.push(...copyMeals(db, prev, ui.date)); save(); render(); toast('День повторён: ' + n + ' записей'); };
return h('button', { style: 'width:100%;margin-top:10px', onclick: () => db.meals.some(m => m.date === ui.date)
? confirmBox('За этот день уже есть записи. Добавить к ним еду за ' + longDate(prev) + '?', 'Добавить', doCopy) : doCopy() }, '🔁 Повторить день (' + longDate(prev) + ')');
}
/** Список покупок из рецептов, выбранных на неделю (пн–вс). */
function shoppingCard() {
const ws = weekStart(ui.date), days = [...Array(7)].map((_, i) => addDays(ws, i));
const recs = db.plan.filter(x => days.includes(x.date)).map(x => db.recipes.find(r => r.id === x.recipeId)).filter(Boolean);
const list = shoppingList(recs), line = i => i.name + (i.qty != null ? ' — ' + fmt(i.qty) + (i.unit ? ' ' + i.unit : '') : '');
const done = k => db.shopDone.includes(ws + '|' + k);
return h('div', { class: 'card' }, h('h3', null, 'Список покупок на неделю'),
h('div', { class: 'muted small' }, longDate(ws) + ' — ' + longDate(days[6])),
list.length ? [list.map(i => h('label', { class: 'item' }, h('input', { type: 'checkbox', style: 'width:auto;min-height:0', checked: done(i.key),
onchange: ev => { db.shopDone = db.shopDone.filter(k => k !== ws + '|' + i.key); if (ev.target.checked) db.shopDone.push(ws + '|' + i.key); save(); render(); } }),
h('span', { class: 'grow', style: done(i.key) ? 'text-decoration:line-through;opacity:.6' : '' }, line(i)))),
h('button', { style: 'margin-top:8px', onclick: () => { const txt = list.map(line).join('\n'); (navigator.clipboard ? navigator.clipboard.writeText(txt) : Promise.reject()).then(() => toast('Список скопирован'), () => toast('Не удалось скопировать. Выделите список вручную.')); } }, 'Скопировать список')]
: h('div', { class: 'empty' }, 'Выберите рецепты на дни этой недели — список продуктов соберётся сам'));
}
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' ? ' г' : ' порц.') + (m.grams ? ' (' + fmtInt(m.grams * m.qty) + ' г)' : '') + ' · ' + 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, grams: 340, kcal: 375, protein: 14, fat: 10, carbs: 57, ingredients: 'Овсяные хлопья — 50 г\nМолоко — 200 мл\nМалина или черника — 80 г\nМёд — 1 ч. л.', steps: 'Вскипятите молоко в небольшой кастрюле.\nВсыпьте хлопья и варите 5–7 минут, помешивая.\nПереложите кашу в тарелку.\nДобавьте ягоды и мёд.', photo: dishArt('🥣', '#ffd9a8', '#f4a261') },
{ id: 'b2', title: 'Омлет с овощами', time: 10, grams: 330, kcal: 315, protein: 20, fat: 22, carbs: 6, ingredients: 'Яйца — 3 шт.\nПомидор — 1 шт.\nБолгарский перец — ½ шт.\nМасло оливковое — 1 ч. л.', steps: 'Нарежьте помидор и перец мелкими кубиками.\nОбжарьте овощи на масле 2–3 минуты.\nВзбейте яйца с щепоткой соли и залейте овощи.\nГотовьте под крышкой на слабом огне 4–5 минут.', photo: dishArt('🍳', '#fff1a8', '#f6c453') },
{ id: 'b3', title: 'Куриная грудка с гречкой', time: 30, grams: 260, kcal: 420, protein: 42, fat: 5, carbs: 52, ingredients: 'Куриная грудка — 150 г\nГречка — 70 г (сухая)\nЛук — ½ шт.\nСпеции, соль', steps: 'Промойте гречку, залейте двойным объёмом воды и варите 15 минут под крышкой.\nНарежьте грудку кусочками и посыпьте специями.\nОбжарьте мясо с луком 8–10 минут до готовности.\nПодавайте мясо с гречкой.', photo: dishArt('🍗', '#f9c9a0', '#e07a5f') },
{ id: 'b4', title: 'Творог с фруктами', time: 5, grams: 315, kcal: 435, protein: 32, fat: 19, carbs: 34, ingredients: 'Творог 5 % — 180 г\nБанан — 1 шт.\nГрецкие орехи — 15 г', steps: 'Выложите творог в миску.\nНарежьте банан кружочками.\nИзмельчите орехи ножом.\nСмешайте всё или выложите слоями.', photo: dishArt('🍓', '#ffd1dc', '#ef6f8b') },
{ id: 'b5', title: 'Лосось с рисом и брокколи', time: 35, grams: 400, kcal: 600, protein: 39, fat: 20, carbs: 66, ingredients: 'Филе лосося — 150 г\nРис — 70 г (сухой)\nБрокколи — 150 г\nЛимон — ¼ шт.', steps: 'Отварите рис до готовности, около 15 минут.\nРазберите брокколи на соцветия и варите на пару 5 минут.\nПосолите лосось и запекайте при 200 °C 12–15 минут.\nПодавайте рыбу с рисом и брокколи, сбрызните лимоном.', photo: dishArt('🐟', '#bfe3f2', '#4a90b8') },
{ id: 'b6', title: 'Греческий салат', time: 10, grams: 425, kcal: 415, protein: 12, fat: 35, carbs: 13, ingredients: 'Огурец — 1 шт.\nПомидоры — 2 шт.\nСыр фета — 60 г\nМаслины — 30 г\nМасло оливковое — 1 ст. л.', steps: 'Нарежьте огурец и помидоры крупными кусочками.\nДобавьте маслины.\nСверху положите фету кубиками.\nПолейте маслом и слегка посолите.', photo: dishArt('🥗', '#d4ecc0', '#6aa84f') },
{ id: 'b7', title: 'Чечевичный суп', time: 40, grams: 330, kcal: 430, protein: 24, fat: 2, carbs: 79, ingredients: 'Красная чечевица — 80 г\nМорковь — 1 шт.\nЛук — 1 шт.\nКартофель — 1 шт.\nСпеции, зелень', steps: 'Нарежьте лук, морковь и картофель кубиками.\nЗалейте овощи и промытую чечевицу 600 мл воды.\nВарите 25 минут на слабом огне.\nДобавьте специи и зелень, по желанию взбейте блендером.', photo: dishArt('🍲', '#ffe0b5', '#d98b3a') }
];
const recipeDetails = GymPlan.text('ru').recipeDetails;
const recipesHome = GymPlan.text('ru').recipesHome;
const planHome = GymPlan.text('ru').planHome;
const legacyRecipeIngredients = BUILTIN_RECIPES.map(r => r.ingredients);
const recipePhotos = { b1: '/assets/oats.jpg', b3: '/assets/chicken.jpg', b6: '/assets/salad.jpg' };
BUILTIN_RECIPES.forEach((r, i) => {
r.ingredients = recipeDetails.ingredients[i];
if (recipePhotos[r.id]) r.photo = recipePhotos[r.id];
});
for (const r of db.recipes) {
const i = BUILTIN_RECIPES.findIndex(b => b.id === r.id);
if (i < 0) continue;
if (r.ingredients === legacyRecipeIngredients[i]) r.ingredients = BUILTIN_RECIPES[i].ingredients;
if (!r.photo || r.photo.startsWith('data:image/svg+xml;utf8,')) r.photo = BUILTIN_RECIPES[i].photo;
}
/** Ранее сохранённым копиям готовых блюд дописываем граммовку, КБЖУ и шаги. */
for (const r of db.recipes) {
const b = BUILTIN_RECIPES.find(x => x.id === r.id);
if (b && r.kcal == null && !r.steps) Object.assign(r, { grams: b.grams, kcal: b.kcal, protein: b.protein, fat: b.fat, carbs: b.carbs, steps: b.steps });
}
/** Подсказка рецепта на день: по номеру дня, чтобы каждый день был свой. */
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 chooseRecipe(r, confirmed) {
if (!confirmed && db.plan.some(x => x.date === ui.date && x.recipeId === r.id)) {
return confirmBox('«' + r.title + '» уже добавлено на этот день. Добавить ещё одну порцию?', 'Добавить ещё', () => chooseRecipe(r, true));
}
db.plan.push({ id: uid(), date: ui.date, recipeId: adoptRecipe(r) });
if (r.kcal != null) db.meals.push({ id: uid(), date: ui.date, type: defaultMealType(), name: r.title, mode: 'portion', qty: 1, ...(r.grams ? { grams: r.grams } : {}), kcal: r.kcal, protein: r.protein || 0, fat: r.fat || 0, carbs: r.carbs || 0 });
save(); render(); toast(r.kcal != null ? r.title + ' добавлен в приём пищи' : 'Рецепт добавлен на день');
}
/** Рецепт по шагам: раскрывается и закрывается кнопкой; без шагов — подсказка. */
function recipeToggle(steps) {
if (!steps.length) return h('div', { class: 'small muted', 'data-no-recipe': '', style: 'margin-top:6px' }, 'Рецепт для этого блюда пока не добавлен.');
const list = h('ol', { class: 'recipe-steps', 'data-steps': '', hidden: '' }, ...steps.map(x => h('li', null, x)));
const btn = h('button', { type: 'button', class: 'ghost', 'data-recipe-toggle': '', 'aria-expanded': 'false', style: 'margin-top:6px' }, 'Показать рецепт');
btn.addEventListener('click', ev => {
ev.stopPropagation();
const open = list.hidden;
list.hidden = !open;
btn.setAttribute('aria-expanded', String(open));
btn.textContent = open ? 'Скрыть рецепт' : 'Показать рецепт';
});
list.addEventListener('click', ev => ev.stopPropagation());
return h('div', null, btn, list);
}
function recipePhoto(r) {
const placeholder = () => h('div', { class: 'recipe-photo-placeholder', 'data-photo-placeholder': '' },
h('span', { 'aria-hidden': 'true' }, '🍲'), h('span', { class: 'small' }, recipeDetails.photoMissing));
if (!r.photo || r.photo.startsWith('data:image/svg+xml;utf8,')) return placeholder();
const img = h('img', { src: r.photo, alt: r.title, class: 'recipe-photo' });
img.addEventListener('error', () => img.replaceWith(placeholder()), { once: true });
return img;
}
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);
const edit = () => { if (db.recipes.includes(r)) openRecipeForm({ entry: r }); };
return h('div', { class: 'item dish' },
recipePhoto(r),
h('div', { class: 'main', onclick: edit }, h('b', null, r.title),
h('div', { class: 'muted small dish-row', 'data-time': '' }, '⏱ ' + r.time + ' мин'),
r.kcal != null ? h('div', { 'data-nutrition': '' },
h('div', { class: 'small muted', 'data-per-serving': '' }, recipeDetails.perServing),
r.grams ? h('div', { class: 'small dish-row', 'data-portion': '' }, 'Порция ' + fmtInt(r.grams) + ' г') : null,
h('div', { class: 'small dish-row', 'data-macros': '' }, fmtInt(r.kcal) + ' ккал · Б ' + fmt(r.protein || 0) + ' · Ж ' + fmt(r.fat || 0) + ' · У ' + fmt(r.carbs || 0))) : null),
h('div', { class: 'dish-body', onclick: edit },
lines.length ? h('div', { class: 'small', 'data-ingredients': '' }, h('div', null, recipeDetails.ingredientsTitle), h('ul', null, ...lines.map(line => h('li', null, line)))) : null,
recipeToggle(steps)),
actions ? h('div', { class: 'dish-actions' }, actions) : null);
}
/** Карточка «Рецепты на день» для выбранной даты. */
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', { 'aria-describedby': 'recipes-add-hint', 'data-add-recipe': '', onclick: openRecipePicker }, '+ Рецепт')),
h('div', { class: 'small muted', id: 'recipes-add-hint', 'data-add-hint': '' }, recipesHome.addHint),
h('a', { class: 'btn link-btn', href: '/recipes.html?lang=ru', 'aria-label': recipesHome.catalogLabel, 'data-recipes-catalog': '' }, '📖 ' + recipesHome.catalog + ' →'),
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(); } }, '✕')))
: [h('div', { class: 'small', 'data-recipes-empty': '', role: 'note' }, recipesHome.empty), suggestionBlock()]);
}
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) }, 'Выбрать')));
}
/** Выбор рецепта на выбранный день или создание нового. */
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: () => { close(); chooseRecipe(r); } }, 'Выбрать'))));
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 stepsBox = h('textarea', { rows: 4, maxlength: 2000, placeholder: 'По одному шагу в строке' }, e && e.steps ? e.steps : '');
const nv = k => e && e[k] != null ? e[k] : '';
const grams = numField('Вес порции, г', { value: nv('grams'), min: 1, max: 5000 });
const nk = numField('Ккал на порцию', { value: nv('kcal'), min: 0, max: 10000 });
const np = numField('Белки, г', { value: nv('protein'), min: 0, max: 1000 });
const nf = numField('Жиры, г', { value: nv('fat'), min: 0, max: 1000 });
const nc = numField('Углеводы, г', { value: nv('carbs'), min: 0, max: 1000 });
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, field('Как приготовить', stepsBox), grams, h('div', { class: 'grid4' }, nk, np, nf, nc),
formFoot(() => {
const t = title.read(), tm = time.read(), nr = [grams, nk, np, nf, nc].map(x => x.read());
if (t == null || tm == null || nr.some(x => x == 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, steps: stepsBox.value.trim(), grams: nr[0].v, kcal: nr[1].v, protein: nr[2].v, fat: nr[3].v, carbs: nr[4].v };
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), workoutRecords(db, w).length ? h('span', { class: 'badge', style: 'margin-left:6px' }, '🏆 Новый рекорд!') : null),
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 draft = o.draft;
const date = dateField('Дата', e ? e.date : o.date);
const guess = o.planned ? (/кардио|бег|вело|плав/i.test(o.planned) ? 'cardio' : /растяж|йога|стретч/i.test(o.planned) ? 'stretch' : 'strength') : 'strength';
const type = selectField('Тип', WORKOUT_TYPES, e ? e.type : draft ? draft.type : guess, () => { drawType(); });
const dur = numField('Длительность, мин', { value: e ? e.duration : draft ? draft.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 : draft ? draft.note : (o.planned ? 'По плану: ' + o.planned : ''));
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 = draft ? JSON.parse(JSON.stringify(draft.exercises)) : 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; if (draft) { ui.tab = 'workouts'; ui.wFilter = 'all'; } save(); close(); render();
const recs = workoutRecords(db, rec);
toast(recs.length ? '🏆 Новый рекорд! ' + recs.map(r => r.name + ' — ' + fmt(r.weight) + ' кг').join(', ') : 'Сохранено');
}, 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 small' }, '📷 ', daysSincePhoto(db, todayKey()) == null ? 'Фото прогресса помогает увидеть изменения. Делайте новое раз в 2–4 недели.'
: daysSincePhoto(db, todayKey()) >= 14 ? 'Последнее фото было ' + daysSincePhoto(db, todayKey()) + ' дн. назад — пора сделать новое.' : 'Последнее фото — ' + daysSincePhoto(db, todayKey()) + ' дн. назад. Следующее лучше через 2–4 недели.'),
h('div', { class: 'card' }, h('h3', null, 'История'), list.length ? list.map(b => h('div', { class: 'item' }, b.photo ? h('img', { src: b.photo, alt: 'Фото прогресса', style: 'width:56px;height:56px;object-fit:cover;border-radius:10px;flex:none' }) : null,
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;
let photo = e ? e.photo || '' : '';
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 prev = h('div');
const drawPhoto = () => prev.replaceChildren(photo ? h('img', { src: photo, alt: 'Фото прогресса', style: 'width:100%;max-height:240px;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, date, w, h('div', { class: 'grid2' }, waist, hips), chest, field('Фото прогресса', file), prev, 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) && !photo) { 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, photo };
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('div', { class: 'stat' }, h('span', { class: 'muted small' }, 'Шаги в день'), h('b', null, st.avgSteps == null ? '—' : fmtK(st.avgSteps))),
h('div', { class: 'stat' }, h('span', { class: 'muted small' }, 'Сон, часов'), h('b', null, fmt(st.avgSleep)))),
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, '🏆 Личные рекорды'), personalBests(db).length
? personalBests(db).map(r => h('div', { class: 'item' }, h('div', { class: 'main' }, h('b', null, r.name), h('span', { class: 'muted small' }, longDate(r.date))), h('b', null, fmt(r.weight) + ' кг')))
: h('div', { class: 'empty' }, 'Рекорды появятся после силовых тренировок')),
h('div', { class: 'card' }, h('h3', null, 'Рабочий вес по упражнению'),
exSel ? [exSel, lineChart(exerciseSeries(db, ui.statEx), 'кг')] : h('div', { class: 'empty' }, 'Добавьте силовую тренировку, чтобы увидеть график')));
}
/* =====================================================================
НАСТРОЙКИ, МАСТЕР, ЭКСПОРТ / ИМПОРТ
===================================================================== */
/** Поля калькулятора нормы. */
function calcFields(pr, hints) {
hints = hints || {};
const sex = selectField('Пол', [['m', 'Мужской'], ['f', 'Женский']], pr.sex);
const age = numField('Возраст, лет', { value: pr.age, placeholder: hints.age, required: true, int: true, min: 10, max: 100, reqText: ' · нужно для расчёта норм', what: 'возраст', hint: 'От 10 до 100 лет' });
const height = numField('Рост, см', { value: pr.height, placeholder: hints.height, required: true, min: 100, max: 250, reqText: ' · нужно для расчёта норм', what: 'рост', hint: 'От 100 до 250 см' });
const weight = numField('Вес, кг', { value: pr.weight, placeholder: hints.weight, required: true, min: 25, max: 400, reqText: ' · нужно для расчёта норм', what: 'вес', hint: 'От 25 до 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, what: 'калории в день', hint: 'От 500 до 10000 ккал' }),
protein: numField('Белки, г', { value: s.protein, required: true, min: 0, max: 1000, what: 'белки', hint: 'От 0 до 1000 г' }),
fat: numField('Жиры, г', { value: s.fat, required: true, min: 0, max: 1000, what: 'жиры', hint: 'От 0 до 1000 г' }),
carbs: numField('Углеводы, г', { value: s.carbs, required: true, min: 0, max: 2000, what: 'углеводы', hint: 'От 0 до 2000 г' }),
water: numField('Вода, мл', { value: s.water, required: true, int: true, min: 0, max: 10000, what: 'норму воды', hint: 'От 0 до 10000 мл' }),
workoutsPerWeek: numField('Тренировок в неделю', { value: s.workoutsPerWeek, required: true, int: true, min: 0, max: 21, what: 'число тренировок', hint: 'От 0 до 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 = {};
let ok = true;
for (const k of Object.keys(f)) { const r = f[k].read(); if (!r) ok = false; else out[k] = r.v; }
return ok ? out : null;
}
};
}
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 = s.normsPending ? calcFields(Object.assign({}, s.profile, { age: null, height: null, weight: null }), { age: 'например, 30', height: 'например, 175', weight: 'например, 75' }) : 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,
...(window.TPTProfile ? [h('div', { class: 'card' }, h('a', { href: '/?lang=' + (new URLSearchParams(location.search).get('lang') || 'ru') }, window.TPTProfileText))] : [
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 p = calc.read(); if (!p) { focusFirstError($('view')); return; } if (s.normsPending) norms.fill(suggestNorms(goal, p)); const n = norms.read(); if (!n) return; Object.assign(s, n, { goal, profile: p }); delete s.normsPending; save(); render(); toast('Настройки сохранены'); } }, 'Сохранить'))
]),
h('div', { class: 'card' }, themeSel),
planCard(), remindersCard(), installCard(),
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); }));
}
const DAYS_SHORT = [['Понедельник', 1], ['Вторник', 2], ['Среда', 3], ['Четверг', 4], ['Пятница', 5], ['Суббота', 6], ['Воскресенье', 0]];
/** План тренировок по дням недели. */
function planCard() {
return h('div', { class: 'card' }, h('h3', null, 'План тренировок на неделю'),
h('p', { class: 'small muted' }, 'Например: понедельник — ноги, среда — спина, пятница — кардио. Пустое поле — день отдыха.'),
DAYS_SHORT.map(([name, idx]) => h('label', { class: 'item' }, h('span', { style: 'width:120px;flex:none' }, name),
h('input', { type: 'text', maxlength: 40, value: db.settings.plan[idx], placeholder: 'Отдых', 'aria-label': name, onchange: ev => { db.settings.plan[idx] = ev.target.value.trim(); save(); toast('План сохранён'); } }))));
}
/** Напоминания: работают, пока приложение открыто или установлено на телефон. */
function remindersCard() {
const r = db.settings.reminders, upd = () => { save(); checkReminders(); };
const chk = (label, key) => h('label', { class: 'row', style: 'margin:8px 0' }, h('input', { type: 'checkbox', style: 'width:auto;min-height:0', checked: !!r[key], onchange: ev => { r[key] = ev.target.checked; upd(); } }), label);
const time = (label, key) => h('label', { class: 'field' }, h('span', { class: 'lbl' }, label), h('input', { type: 'time', value: r[key], onchange: ev => { if (ev.target.value) { r[key] = ev.target.value; upd(); } } }));
const on = h('input', { type: 'checkbox', style: 'width:auto;min-height:0', checked: !!r.on, onchange: async ev => {
if (ev.target.checked) {
if (typeof Notification === 'undefined') { ev.target.checked = false; return toast('Этот браузер не умеет показывать напоминания.'); }
const perm = Notification.permission === 'granted' ? 'granted' : await Notification.requestPermission();
if (perm !== 'granted') { ev.target.checked = false; return toast('Разрешите уведомления в настройках браузера, чтобы получать напоминания.'); }
}
r.on = ev.target.checked; upd(); render();
} });
return h('div', { class: 'card' }, h('h3', null, 'Напоминания'),
h('label', { class: 'row', style: 'margin:8px 0' }, on, 'Включить напоминания'),
r.on ? h('div', null, chk('Попить воды (с 9:00 до 21:00)', 'water'),
selectField('Как часто пить', [[1, 'Каждый час'], [2, 'Каждые 2 часа'], [3, 'Каждые 3 часа']], r.waterEvery, ev => { r.waterEvery = Number(ev.target.value); upd(); }),
chk('Записать ужин', 'dinner'), time('Во сколько напомнить про ужин', 'dinnerTime'),
chk('Тренировка по плану', 'workout'), time('Во сколько напомнить про тренировку', 'workoutTime')) : null,
h('p', { class: 'small muted' }, 'Напоминания приходят, пока приложение открыто или установлено на телефоне. Закрытое приложение без сервера напомнить не может.'));
}
let installEvent = null;
window.addEventListener('beforeinstallprompt', ev => { ev.preventDefault(); installEvent = ev; if (ui.tab === 'settings') render(); });
function installCard() {
return h('div', { class: 'card' }, h('h3', null, 'Установка на телефон'),
installEvent ? h('button', { class: 'primary', onclick: () => { installEvent.prompt(); installEvent = null; render(); } }, 'Установить приложение')
: h('p', { class: 'small muted' }, 'В Chrome: меню ⋮ → «Установить приложение». В Safari на iPhone: «Поделиться» → «На экран “Домой”». После установки приложение открывается без адресной строки и работает без интернета.'));
}
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() {
if (window.TPTProfile) { applyPrivateProfile(); render(); return; }
let goal = db.settings.goal;
// Чужие числа по умолчанию не подставляем: поля пустые, в них только подсказка.
const calc = calcFields(Object.assign({}, db.settings.profile, { age: null, height: null, weight: null }),
{ age: 'например, 30', height: 'например, 175', weight: 'например, 75' });
const body = h('div');
let close;
const skipBtn = () => h('button', { 'data-skip': '', onclick: () => { db.settings.onboarded = true; db.settings.normsPending = true; save(); close(); render(); toast('Можно смотреть приложение. Данные для норм укажите позже в «Настройки».'); } }, 'Пропустить');
const goalHint = h('p', { class: 'small muted', 'data-goal-note': '' });
const goalNote = () => { goalHint.textContent = GymPlan.text('ru').welcomeGoal.replace('{goal}', GOALS.find(g => g[0] === goal)[1]); };
goalNote();
const step1 = () => body.replaceChildren(
h('p', { class: 'muted', 'data-why': '', 'data-calc-why': '' }, 'Шаг 1 из 2. По возрасту, росту и весу считаются ваши дневные нормы. Не хотите вводить их сейчас — нажмите «Пропустить»: данные можно указать позже в «Настройки».'),
goalChips(() => goal, k => { goal = k; goalNote(); }), goalHint, h('div', { style: 'height:8px' }), calc.el,
h('div', { class: 'foot' }, skipBtn(), h('button', { class: 'primary', onclick: () => { const p = calc.read(); if (!p) { focusFirstError(body); 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. Мы посчитали ваши дневные нормы по введённым данным.'),
h('p', { class: 'small muted', 'data-norms-hint': '' }, 'Если нужно, поправьте любое число вручную — затем нажмите «Готово».'), norms.el,
h('div', { class: 'foot' }, h('button', { onclick: step1 }, 'Назад'), skipBtn(), h('button', { class: 'primary', onclick: () => { const n = norms.read(); if (!n) { focusFirstError(body); return; } Object.assign(db.settings, n, { onboarded: true }); delete db.settings.normsPending; save(); close(); render(); toast('Готово! Можно записывать день.'); } }, 'Готово')));
};
step1();
close = openSheet('Добро пожаловать', body, { locked: true, welcome: true });
}
/** Проверка напоминаний раз в 30 секунд; «показано» хранится отдельно от данных. */
let swReg = null;
function checkReminders() {
if (!db.settings.reminders.on || typeof Notification === 'undefined' || Notification.permission !== 'granted') return;
let fired = {};
try { fired = JSON.parse(localStorage.getItem('tpt.fired') || '{}'); } catch (e) { fired = {}; }
const due = dueReminders(db, new Date(), fired);
for (const r of due) {
fired[r.kind] = r.key;
const opts = { body: r.text, icon: 'icon.svg', tag: 'tpt-' + r.kind };
try { if (swReg && swReg.showNotification) swReg.showNotification('Трекер', opts); else new Notification('Трекер', opts); } catch (e) { /* уведомления недоступны */ }
}
if (due.length) { try { localStorage.setItem('tpt.fired', JSON.stringify(fired)); } catch (e) { /* не страшно */ } }
}
setInterval(checkReminders, 30000);
if ('serviceWorker' in navigator && /^https?:$/.test(location.protocol)) {
navigator.serviceWorker.register('/sw.js').then(r => { swReg = r; }).catch(() => { /* без офлайн-режима */ });
}
render();
checkReminders();
if (!db.settings.onboarded) startWizard();
</script>
</body>
</html>