@ -4,6 +4,9 @@
< 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 >
/* ===== Темы: светлая по умолчанию, тёмная по системе или вручную ===== */
@ -70,7 +73,10 @@ input:focus,select:focus,textarea:focus,button:focus-visible{outline:2px solid v
.ring .over .val{stroke:var(--bad)}
.bar{height:10px;border-radius:6px;background:var(--line);overflow:hidden}
.bar>i{display:block;height:100%;border-radius:6px}
@media (max-width:380px){.rings{gap:3px}.ring .c{font-size:.68rem}.ring .c small{display:none}}
@media (max-width:380px){.rings{gap:3px}.ring .c{font-size:.7rem}.ring .c small{font-size:.56rem}}
.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)}
@ -137,9 +143,11 @@ function defaultData() {
settings: {
goal: 'maintain', kcal: 2000, protein: 120, fat: 65, carbs: 230, water: 2000, workoutsPerWeek: 3,
profile: { sex: 'm', age: 30, height: 175, weight: 75, activity: 1.375 },
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: []
foods: [], meals: [], water: [], workouts: [], exercises: [], body: [], recipes: [], plan: [], daily: [], shopDone: []
};
}
@ -245,7 +253,10 @@ function periodStats(data, end, days) {
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,
@ -317,13 +328,91 @@ function normalizeImport(obj, keepOnboarded) {
const base = defaultData();
const out = { v: 1, settings: Object.assign(base.settings, obj.settings) };
out.settings.onboarded = keepOnboarded ? !!obj.settings.onboarded : true;
out.settings.profile = Object.assign(base.settings.profile, obj.settings.profile || {});
for (const k of ['foods', 'meals', 'water', 'workouts', 'exercises', 'body', 'recipes', 'plan']) {
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 */
/* =====================================================================
@ -377,6 +466,8 @@ function svg(tag, props, ...kids) {
}
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()]; }
@ -489,8 +580,8 @@ function ring(label, fact, target, unit, color) {
svg('svg', { viewBox: '0 0 100 100', 'aria-hidden': 'true' },
svg('circle', { class: 'bg', cx: 50, cy: 50, r: R, fill: 'none', 'stroke-width': 10 }),
svg('circle', { class: 'val', cx: 50, cy: 50, r: R, fill: 'none', 'stroke-width': 10, stroke: color, 'stroke-dasharray': (pct * C) + ' ' + C })),
h('div', { class: 'c' }, fmtInt(fact), h('small', null, '/ ' + fmtInt(target) ))),
h('div', { class: 't' }, label, h('div', { class: 'muted small' }, unit) ));
h('div', { class: 'c' }, fmtInt(fact), h('small', null, 'из ' + fmtInt(target) + ' ' + unit ))),
h('div', { class: 't' }, label));
}
/** Линейный график по точкам [{x:'ГГГГ-М М -ДД', y}]. */
function lineChart(points, unit) {
@ -559,30 +650,51 @@ function dateNav() {
ЭКРАН «СЕГОДНЯ»
===================================================================== */
function viewToday() {
const s = db.settings, t = dayTotals(db, ui.date), left = s.kcal - t.kcal;
const water = h('div', { class: 'row between' },
h('span', null, '💧 Вода: ', h('b', null, t.water), ' / ' + s.water + ' мл'),
h('button', { class: 'ghost', onclick: () => removeLastWater(), disabled: t.water === 0 }, '− 250'));
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' }, 'Тренировки не было. План на неделю можно задать в «Настройках».');
return h('div', null, dateNav(),
h('div', { class: 'card' },
h('div', { class: 'rings' },
ring('Ккал', t.kcal, s.kcal, 'ккал', 'var(--kcal)'), ring('Белки', t.protein, s.protein, 'г ', 'var(--prot)'),
ring('Жиры', t.fat, s.fat, 'г ', 'var(--fat)'), ring('Углев.', t.carbs, s.carbs, 'г ', 'var(--carb)'), ring('Вода', t.water, s.water, 'мл', 'var(--water)')),
h('p', { class: left >= 0 ? 'ok' : 'bad', style: 'text-align:center;margin:10px 0 0' },
t.meals === 0 ? 'Еда за этот день пока не записана' : left >= 0 ? 'Осталось ' + fmtInt(left) + ' ккал' : 'Выше нормы на ' + fmtInt(-left) + ' ккал')),
h('div', { class: 'quick' },
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 мл воды')),
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('button', { onclick: () => addWater(250) }, '+ Вода 250 мл')),
h('div', { class: 'card' }, water),
recipesCard(),
h('div', { class: 'card' }, h('h3', null, 'Тренировка'),
t.workouts.length ? t.workouts.map(w => h('div', { class: 'item' }, h('div', { class: 'main', onclick: () => openWorkoutForm({ entry: w }) },
h('b', null, '✅ ' + typeName(WORKOUT_TYPES, w.type)), h('span', { class: 'muted small' }, workoutSummary(w))))) :
h('div', { class: 'empty' }, 'Тренировки в этот день не было')),
h('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 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 + ' мл воды');
}
@ -608,12 +720,42 @@ function viewFood() {
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' }, 'Пока пусто'));
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, 'г '))),
recipesCard(), sections);
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);
@ -784,7 +926,7 @@ function viewWorkouts() {
h('div', { class: 'chips' }, [['all', 'В с е '], ...WORKOUT_TYPES].map(([k, n]) => h('button', { class: 'chip' + (ui.wFilter === k ? ' on' : ''), onclick: () => { ui.wFilter = k; render(); } }, n))),
h('div', { class: 'card' }, list.length ? list.map(w => h('div', { class: 'item' },
h('div', { class: 'main', onclick: () => openWorkoutForm({ entry: w }) },
h('b', null, longDate(w.date) + ' · ' + typeName(WORKOUT_TYPES, w.type)),
h('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),
@ -804,13 +946,14 @@ function repeatLast() {
function openWorkoutForm(o) {
const e = o.entry, isNew = !e;
const date = dateField('Дата', e ? e.date : o.date);
const type = selectField('Тип', WORKOUT_TYPES, e ? e.type : 'strength', () => { drawType(); });
const guess = o.planned ? (/кардио|б е г |вело|плав/i.test(o.planned) ? 'cardio' : /растяж|йога|стретч/i.test(o.planned) ? 'stretch' : 'strength') : 'strength';
const type = selectField('Тип', WORKOUT_TYPES, e ? e.type : guess, () => { drawType(); });
const dur = numField('Длительность, мин', { value: e ? e.duration : '', required: true, min: 1, max: 1440, int: true });
let feel = e ? e.feel : 3;
const feelBox = h('div', { class: 'chips' });
const drawFeel = () => feelBox.replaceChildren(...[1, 2, 3, 4, 5].map(n => h('button', { class: 'chip' + (feel === n ? ' on' : ''), type: 'button', onclick: () => { feel = n; drawFeel(); } }, String(n))));
drawFeel();
const note = h('textarea', { rows: 2, maxlength: 300, placeholder: 'Необязательно' }, e ? e.note : '');
const note = h('textarea', { rows: 2, maxlength: 300, placeholder: 'Необязательно' }, e ? e.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');
@ -868,7 +1011,9 @@ function openWorkoutForm(o) {
if (tp === 'strength') rec.exercises = cleaned;
if (e) { for (const k of ['distance', 'pulse', 'exercises']) delete e[k]; Object.assign(e, rec); } else db.workouts.push(rec);
for (const ex of cleaned) if (!db.exercises.some(n => n.toLowerCase() === ex.name.toLowerCase())) db.exercises.push(ex.name);
ui.date = d; save(); close(); render(); toast('Сохранено');
ui.date = d; save(); close(); render();
const recs = workoutRecords(db, rec);
toast(recs.length ? '🏆 Новый рекорд! ' + recs.map(r => r.name + ' — ' + fmt(r.weight) + ' кг').join(', ') : 'Сохранено');
}, del)));
}
@ -880,25 +1025,36 @@ function viewBody() {
return h('div', null,
h('button', { class: 'primary', style: 'width:100%;margin-top:4px', onclick: () => openBodyForm({}) }, '+ В е с или замеры'),
h('div', { class: 'card' }, h('h3', null, 'В е с , кг'), lineChart(weightSeries(db), 'кг')),
h('div', { class: 'card' }, h('h3', null, 'История'), list.length ? list.map(b => h('div', { class: 'item' },
h('div', { class: '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 close = openSheet(e ? 'Запись о теле' : 'Новая запись о теле', h('div', null, date, w, h('div', { class: 'grid2' }, waist, hips), chest, err, formFoot(() => {
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)) { err.textContent = 'Заполните хотя бы одно значение'; 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 };
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)));
@ -920,10 +1076,15 @@ function viewStats() {
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.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' }, 'Добавьте силовую тренировку, чтобы увидеть график')));
}
@ -990,6 +1151,7 @@ function viewSettings() {
h('div', { class: 'card' }, h('h3', null, 'Нормы в день'), norms.el,
h('button', { class: 'primary', style: 'width:100%', onclick: () => { const n = norms.read(), p = calc.read(); if (!n || !p) return; Object.assign(s, n, { goal, profile: p }); save(); render(); toast('Настройки сохранены'); } }, 'Сохранить')),
h('div', { class: 'card' }, themeSel),
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: питание'),
@ -999,6 +1161,42 @@ function viewSettings() {
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);
@ -1036,7 +1234,27 @@ function startWizard() {
close = openSheet('Добро пожаловать', body, { locked: 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 >