Initial commit of counter
This commit is contained in:
+867
@@ -0,0 +1,867 @@
|
||||
(() => {
|
||||
'use strict';
|
||||
|
||||
const MEALS = [['breakfast', 'Breakfast'], ['lunch', 'Lunch'], ['dinner', 'Dinner'], ['snack', 'Snacks']];
|
||||
const state = {
|
||||
date: localDate(),
|
||||
day: null,
|
||||
meta: { metPresets: [], styles: [] },
|
||||
view: 'today',
|
||||
scanTab: 'scan',
|
||||
product: null,
|
||||
results: [],
|
||||
meal: 'lunch',
|
||||
controls: null,
|
||||
busy: false,
|
||||
};
|
||||
|
||||
const $ = (selector, root = document) => root.querySelector(selector);
|
||||
const $$ = (selector, root = document) => Array.from(root.querySelectorAll(selector));
|
||||
const esc = (value) => String(value ?? '').replace(/[&<>"']/g, (ch) => ({
|
||||
'&': '&', '<': '<', '>': '>', '"': '"', "'": ''',
|
||||
}[ch]));
|
||||
const round = (n) => Math.round(Number(n) || 0);
|
||||
const fmt = (n) => round(n).toLocaleString();
|
||||
|
||||
// ---------------------------------------------------------------- helpers
|
||||
|
||||
function localDate(date = new Date()) {
|
||||
const shifted = new Date(date.getTime() - date.getTimezoneOffset() * 60000);
|
||||
return shifted.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
function shiftDate(iso, days) {
|
||||
const date = new Date(`${iso}T12:00:00`);
|
||||
date.setDate(date.getDate() + days);
|
||||
return localDate(date);
|
||||
}
|
||||
|
||||
function prettyDate(iso) {
|
||||
const today = localDate();
|
||||
if (iso === today) return 'Today';
|
||||
if (iso === shiftDate(today, -1)) return 'Yesterday';
|
||||
if (iso === shiftDate(today, 1)) return 'Tomorrow';
|
||||
return new Date(`${iso}T12:00:00`).toLocaleDateString(undefined, {
|
||||
weekday: 'short', month: 'short', day: 'numeric',
|
||||
});
|
||||
}
|
||||
|
||||
function mealLabel(id) {
|
||||
const match = MEALS.find((meal) => meal[0] === id);
|
||||
return match ? match[1] : 'Snacks';
|
||||
}
|
||||
|
||||
function mealOptions(selected) {
|
||||
return MEALS.map(([id, label]) =>
|
||||
`<option value="${id}"${id === selected ? ' selected' : ''}>${label}</option>`).join('');
|
||||
}
|
||||
|
||||
let toastTimer = null;
|
||||
function toast(message, kind = '') {
|
||||
const el = $('#toast');
|
||||
el.textContent = message;
|
||||
el.className = `toast show ${kind}`.trim();
|
||||
clearTimeout(toastTimer);
|
||||
toastTimer = setTimeout(() => { el.className = 'toast'; }, 2800);
|
||||
}
|
||||
|
||||
async function api(path, options = {}) {
|
||||
const res = await fetch(`/api${path}`, {
|
||||
...options,
|
||||
headers: { 'Content-Type': 'application/json', ...(options.headers || {}) },
|
||||
});
|
||||
let data = {};
|
||||
try {
|
||||
data = await res.json();
|
||||
} catch {
|
||||
/* non-JSON error */
|
||||
}
|
||||
if (!res.ok) throw new Error(data.error || `Request failed (${res.status})`);
|
||||
return data;
|
||||
}
|
||||
|
||||
const post = (path, body = {}) => api(path, { method: 'POST', body: JSON.stringify(body) });
|
||||
const put = (path, body = {}) => api(path, { method: 'PUT', body: JSON.stringify(body) });
|
||||
const del = (path) => api(path, { method: 'DELETE' });
|
||||
|
||||
// -------------------------------------------------------------- rendering
|
||||
|
||||
function renderToday() {
|
||||
const view = $('#view-today');
|
||||
if (!state.day) {
|
||||
view.innerHTML = '<div class="card"><p class="muted">Loading…</p></div>';
|
||||
return;
|
||||
}
|
||||
|
||||
const day = state.day;
|
||||
const totals = day.totals;
|
||||
const targets = day.targets;
|
||||
const remaining = targets.targetKcal - totals.kcal;
|
||||
const over = remaining < 0;
|
||||
const fraction = targets.targetKcal > 0
|
||||
? Math.min(1, Math.max(0, totals.kcal / targets.targetKcal))
|
||||
: 0;
|
||||
const radius = 52;
|
||||
const circumference = 2 * Math.PI * radius;
|
||||
|
||||
view.innerHTML = `
|
||||
${day.profile.onboarded ? '' : '<button class="banner" type="button" data-action="open-profile">Set up your profile — targets are using placeholder numbers.</button>'}
|
||||
<div class="card hero">
|
||||
<div class="hero-ring">
|
||||
<svg class="ring" viewBox="0 0 120 120" aria-hidden="true">
|
||||
<circle class="ring-bg" cx="60" cy="60" r="${radius}"></circle>
|
||||
<circle class="ring-fg${over ? ' over' : ''}" cx="60" cy="60" r="${radius}"
|
||||
stroke-dasharray="${circumference.toFixed(1)}"
|
||||
stroke-dashoffset="${(circumference * (1 - fraction)).toFixed(1)}"></circle>
|
||||
</svg>
|
||||
<div class="hero-center">
|
||||
<span class="hero-num">${fmt(Math.abs(remaining))}</span>
|
||||
<span class="hero-label">${over ? 'kcal over' : 'kcal left'}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="hero-stats">
|
||||
<div><span class="muted">Eaten</span><strong>${fmt(totals.kcal)}</strong></div>
|
||||
<div><span class="muted">Burned</span><strong>${fmt(targets.totalBurnKcal)}</strong></div>
|
||||
<div><span class="muted">Target</span><strong>${fmt(targets.targetKcal)}</strong></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
${macroBar('Protein', totals.protein_g, targets.protein_g, 'protein')}
|
||||
${macroBar('Carbs', totals.carbs_g, targets.carbs_g, 'carbs')}
|
||||
${macroBar('Fat', totals.fat_g, targets.fat_g, 'fat')}
|
||||
<p class="micro muted">Fiber ${round(totals.fiber_g)} g · Sugar ${round(totals.sugar_g)} g · Sodium ${fmt(totals.sodium_mg)} mg</p>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="row between"><h2>Movement</h2><span class="pill">${fmt(targets.stepKcal)} kcal from steps</span></div>
|
||||
<div class="steps-row">
|
||||
<form class="row-form" id="stepsForm" autocomplete="off">
|
||||
<input name="steps" type="number" inputmode="numeric" min="0" max="200000"
|
||||
value="${day.steps || ''}" placeholder="Steps today" aria-label="Steps today">
|
||||
<button class="btn" type="submit">Save</button>
|
||||
</form>
|
||||
<div class="chips">
|
||||
<button class="chip" type="button" data-action="steps-add" data-amount="1000">+1,000</button>
|
||||
<button class="chip" type="button" data-action="steps-add" data-amount="2000">+2,000</button>
|
||||
</div>
|
||||
</div>
|
||||
${exerciseList(day)}
|
||||
<form class="row-form" id="exerciseForm" autocomplete="off">
|
||||
<select name="preset" aria-label="Workout type">${metOptions()}</select>
|
||||
<input name="minutes" type="number" inputmode="numeric" min="1" max="600" placeholder="min" aria-label="Minutes" required>
|
||||
<button class="btn" type="submit">Add</button>
|
||||
</form>
|
||||
<p class="hint">Your burn estimate is your BMR-based baseline plus ${fmt(targets.stepKcal)} kcal of steps and ${fmt(targets.exerciseKcal)} kcal of workouts.</p>
|
||||
</div>
|
||||
|
||||
<div class="meals">${mealSections(day)}</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function macroBar(label, value, target, cls) {
|
||||
const percent = target > 0 ? Math.min(100, (value / target) * 100) : 0;
|
||||
return `<div class="macro ${cls}">
|
||||
<div class="row between"><span>${label}</span><span class="muted">${round(value)} / ${round(target)} g</span></div>
|
||||
<div class="track ${cls}"><span style="width:${percent.toFixed(1)}%"></span></div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function mealSections(day) {
|
||||
return MEALS.map(([id, label]) => {
|
||||
const items = day.entries.filter((entry) => entry.meal === id);
|
||||
const kcal = items.reduce((sum, entry) => sum + entry.kcal, 0);
|
||||
return `<div class="card meal">
|
||||
<div class="row between"><h2>${label}</h2><span class="pill">${fmt(kcal)} kcal</span></div>
|
||||
${items.length
|
||||
? `<ul class="entry-list">${items.map(entryRow).join('')}</ul>`
|
||||
: '<p class="muted empty">Nothing logged yet.</p>'}
|
||||
<button class="btn ghost small" type="button" data-action="goto-scan" data-meal="${id}">+ Add ${label.toLowerCase()}</button>
|
||||
</div>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function entryRow(entry) {
|
||||
return `<li class="entry">
|
||||
<div class="entry-main">
|
||||
<span class="entry-name">${esc(entry.name)}</span>
|
||||
<span class="entry-meta">${entry.grams ? `${round(entry.grams)} g · ` : ''}${round(entry.protein_g)}P / ${round(entry.carbs_g)}C / ${round(entry.fat_g)}F</span>
|
||||
</div>
|
||||
<span class="entry-kcal">${fmt(entry.kcal)}</span>
|
||||
<button class="x" type="button" data-action="del-entry" data-id="${entry.id}" aria-label="Remove ${esc(entry.name)}">×</button>
|
||||
</li>`;
|
||||
}
|
||||
|
||||
function exerciseList(day) {
|
||||
const items = day.activities.filter((activity) => activity.type === 'exercise');
|
||||
if (!items.length) return '';
|
||||
return `<ul class="entry-list">${items.map((activity) => {
|
||||
const origin = activity.source === 'apple_health'
|
||||
? ' · Apple Health'
|
||||
: activity.source === 'shortcut'
|
||||
? ' · Shortcut'
|
||||
: activity.source === 'health-auto-export' ? ' · Health Auto Export' : '';
|
||||
return `<li class="entry">
|
||||
<div class="entry-main">
|
||||
<span class="entry-name">${esc(activity.name)}</span>
|
||||
<span class="entry-meta">${round(activity.minutes)} min · MET ${activity.met}${origin}</span>
|
||||
</div>
|
||||
<span class="entry-kcal">${fmt(activity.kcal)}</span>
|
||||
<button class="x" type="button" data-action="del-activity" data-id="${activity.id}" aria-label="Remove ${esc(activity.name)}">×</button>
|
||||
</li>`;
|
||||
}).join('')}</ul>`;
|
||||
}
|
||||
|
||||
function metOptions() {
|
||||
return (state.meta.metPresets || [])
|
||||
.map((preset) => `<option value="${esc(preset.id)}">${esc(preset.label)}</option>`)
|
||||
.join('');
|
||||
}
|
||||
|
||||
function renderPlan() {
|
||||
const list = $('#planList');
|
||||
if (!list || !state.day) return;
|
||||
|
||||
const plan = state.day.plan;
|
||||
const targets = state.day.targets;
|
||||
$('#planTarget').textContent = `Target for ${prettyDate(state.date).toLowerCase()}: ${fmt(targets.targetKcal)} kcal and ${fmt(targets.protein_g)} g protein.`;
|
||||
|
||||
if (!plan) {
|
||||
list.innerHTML = '<div class="card"><p class="muted" style="margin:0">No plan yet. Pick a style and generate a day of meals that fits your target.</p></div>';
|
||||
return;
|
||||
}
|
||||
|
||||
const totals = plan.totals;
|
||||
list.innerHTML = `
|
||||
<div class="card plan-summary">
|
||||
<div class="row between"><h2>Your plan</h2><span class="pill">${fmt(totals.kcal)} kcal</span></div>
|
||||
<p class="muted">${round(totals.protein_g)}P / ${round(totals.carbs_g)}C / ${round(totals.fat_g)}F · target ${fmt(targets.targetKcal)} kcal</p>
|
||||
<button class="btn ghost small" type="button" data-action="clear-plan">Clear plan</button>
|
||||
</div>
|
||||
${plan.items.map(planCard).join('')}
|
||||
<p class="hint">Ideas from the built-in meal library. Log one to add it to your day, or use the list as a shopping plan.</p>
|
||||
`;
|
||||
}
|
||||
|
||||
function planCard(item) {
|
||||
return `<div class="card meal">
|
||||
<div class="row between"><h3>${esc(item.name)}</h3><span class="pill">${fmt(item.kcal)} kcal</span></div>
|
||||
<p class="muted small">${mealLabel(item.meal)} · ${round(item.protein_g)}P / ${round(item.carbs_g)}C / ${round(item.fat_g)}F${item.prep ? ` · ${item.prep} min` : ''}</p>
|
||||
<p class="ingredients">${esc((item.ingredients || []).join(' · '))}</p>
|
||||
<button class="btn small" type="button" data-action="log-plan" data-id="${item.id}">Log ${mealLabel(item.meal).toLowerCase()}</button>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function renderYouTargets() {
|
||||
const card = $('#targetsCard');
|
||||
if (!card || !state.day) return;
|
||||
|
||||
const targets = state.day.targets;
|
||||
card.innerHTML = `
|
||||
<div class="row between"><h2>Daily targets</h2><span class="pill">${fmt(targets.targetKcal)} kcal</span></div>
|
||||
<dl class="stats">
|
||||
<div><dt>BMR</dt><dd>${fmt(targets.bmrKcal)}</dd></div>
|
||||
<div><dt>Daily living</dt><dd>${fmt(targets.basalKcal)}</dd></div>
|
||||
<div><dt>Steps</dt><dd>${fmt(targets.stepKcal)}</dd></div>
|
||||
<div><dt>Workouts</dt><dd>${fmt(targets.exerciseKcal)}</dd></div>
|
||||
<div><dt>Goal change</dt><dd>${targets.adjustKcal > 0 ? '+' : ''}${fmt(targets.adjustKcal)}</dd></div>
|
||||
<div><dt>Protein</dt><dd>${fmt(targets.protein_g)} g</dd></div>
|
||||
</dl>
|
||||
`;
|
||||
}
|
||||
|
||||
function fillProfileForm() {
|
||||
const form = $('#profileForm');
|
||||
const profile = state.day && state.day.profile;
|
||||
if (!form || !profile) return;
|
||||
|
||||
form.name.value = profile.name || '';
|
||||
form.sex.value = profile.sex === 'female' ? 'female' : 'male';
|
||||
form.age.value = profile.age;
|
||||
form.height_cm.value = profile.height_cm;
|
||||
form.weight_kg.value = profile.weight_kg;
|
||||
form.goal.value = profile.goal;
|
||||
form.rate_kg_week.value = profile.rate_kg_week;
|
||||
form.diet.value = profile.diet;
|
||||
form.protein_target_g.value = profile.protein_target_g ?? '';
|
||||
}
|
||||
|
||||
function renderProduct(product) {
|
||||
const box = $('#scanResult');
|
||||
if (!box) return;
|
||||
|
||||
if (!product) {
|
||||
box.innerHTML = '';
|
||||
return;
|
||||
}
|
||||
|
||||
const per = product.per100g;
|
||||
const grams = product.servingGrams || 100;
|
||||
const kcal = Math.round((per.kcal * grams) / 100);
|
||||
|
||||
box.innerHTML = `<div class="card product">
|
||||
<div class="product-head">
|
||||
${product.image ? `<img class="product-img" src="${esc(product.image)}" alt="" loading="lazy">` : ''}
|
||||
<div>
|
||||
<h3>${esc(product.name)}</h3>
|
||||
<p class="muted small" style="margin:0">${esc(product.brand || product.source || 'Open Food Facts')}${product.servingLabel ? ` · serving ${esc(product.servingLabel)}` : ''}</p>
|
||||
<p class="small" style="margin:6px 0 0">${per.kcal} kcal · ${per.protein_g}P / ${per.carbs_g}C / ${per.fat_g}F per 100 g</p>
|
||||
</div>
|
||||
</div>
|
||||
<form id="logProductForm" autocomplete="off">
|
||||
<div class="row-form">
|
||||
<input name="grams" type="number" inputmode="decimal" min="1" max="5000" step="1" value="${grams}" aria-label="Portion in grams" required>
|
||||
<span class="unit">grams</span>
|
||||
<span class="product-kcal" id="productKcal">${kcal} kcal</span>
|
||||
</div>
|
||||
<div class="chips">
|
||||
${product.servingGrams ? `<button class="chip" type="button" data-action="portion" data-grams="${product.servingGrams}">Serving (${round(product.servingGrams)} g)</button>` : ''}
|
||||
<button class="chip" type="button" data-action="portion" data-grams="100">100 g</button>
|
||||
</div>
|
||||
<div class="row-form">
|
||||
<select name="meal" aria-label="Meal">${mealOptions(state.meal)}</select>
|
||||
<button class="btn primary" type="submit">Add to day</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function updateProductKcal() {
|
||||
const product = state.product;
|
||||
const form = $('#logProductForm');
|
||||
const out = $('#productKcal');
|
||||
if (!product || !form || !out) return;
|
||||
const grams = Number(form.querySelector('[name="grams"]').value) || 0;
|
||||
out.textContent = `${fmt((product.per100g.kcal * grams) / 100)} kcal`;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------- data
|
||||
|
||||
async function loadDay() {
|
||||
const day = await api(`/day/${state.date}`);
|
||||
state.day = day;
|
||||
$('#dateLabel').textContent = prettyDate(state.date);
|
||||
const next = $('[data-action="date-next"]');
|
||||
if (next) next.disabled = state.date >= localDate();
|
||||
|
||||
renderToday();
|
||||
renderPlan();
|
||||
renderYouTargets();
|
||||
if (state.view === 'you') fillProfileForm();
|
||||
if (state.product) renderProduct(state.product);
|
||||
}
|
||||
|
||||
function finishLogging(day, meal) {
|
||||
state.day = day;
|
||||
state.product = null;
|
||||
renderProduct(null);
|
||||
renderToday();
|
||||
renderPlan();
|
||||
renderYouTargets();
|
||||
setView('today');
|
||||
toast(`Added to ${mealLabel(meal).toLowerCase()}`);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------- scan
|
||||
|
||||
function setScanTab(tab) {
|
||||
state.scanTab = tab;
|
||||
$$('[data-scan-tab]').forEach((button) => {
|
||||
button.classList.toggle('is-active', button.dataset.scanTab === tab);
|
||||
button.setAttribute('aria-selected', button.dataset.scanTab === tab ? 'true' : 'false');
|
||||
});
|
||||
['scan', 'search', 'manual'].forEach((name) => {
|
||||
const pane = $(`#scanPane-${name}`);
|
||||
if (pane) pane.hidden = name !== tab;
|
||||
});
|
||||
if (tab !== 'scan') stopCamera();
|
||||
}
|
||||
|
||||
async function lookupBarcode(code) {
|
||||
const box = $('#scanResult');
|
||||
box.innerHTML = '<div class="card"><p class="muted" style="margin:0">Looking up barcode…</p></div>';
|
||||
try {
|
||||
const data = await api(`/foods/barcode/${encodeURIComponent(code)}`);
|
||||
state.product = data.product;
|
||||
renderProduct(state.product);
|
||||
if (navigator.vibrate) navigator.vibrate(50);
|
||||
} catch (err) {
|
||||
state.product = null;
|
||||
box.innerHTML = `<div class="card">
|
||||
<h3>No match</h3>
|
||||
<p class="muted">${esc(err.message)}</p>
|
||||
<p class="hint">Barcode ${esc(code)}</p>
|
||||
<button class="btn ghost small" type="button" data-action="goto-manual">Add it manually</button>
|
||||
</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
async function runSearch(query) {
|
||||
const box = $('#searchResults');
|
||||
box.innerHTML = '<p class="muted pad">Searching Open Food Facts…</p>';
|
||||
|
||||
const data = await api(`/foods/search?q=${encodeURIComponent(query)}`);
|
||||
state.results = data.products || [];
|
||||
|
||||
if (!state.results.length) {
|
||||
box.innerHTML = `<div class="card">
|
||||
<p class="muted" style="margin:0 0 10px">No matches for “${esc(query)}”. Try a shorter name, or add it manually.</p>
|
||||
<button class="btn ghost small" type="button" data-action="goto-manual">Add manually</button>
|
||||
</div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
box.innerHTML = state.results.map((product, index) => `<button class="result" type="button" data-action="pick-product" data-index="${index}">
|
||||
${product.image
|
||||
? `<img src="${esc(product.image)}" alt="" loading="lazy">`
|
||||
: '<span class="result-placeholder"></span>'}
|
||||
<span class="result-main">
|
||||
<strong>${esc(product.name)}</strong>
|
||||
<span class="muted small">${esc(product.brand || '')} · ${product.per100g.kcal} kcal/100 g</span>
|
||||
</span>
|
||||
</button>`).join('');
|
||||
}
|
||||
|
||||
async function startCamera() {
|
||||
if (!window.isSecureContext) {
|
||||
toast('Camera needs HTTPS — take a photo or type the barcode instead', 'error');
|
||||
return;
|
||||
}
|
||||
if (!window.ZXing) {
|
||||
toast('Scanner library did not load', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
const button = $('#startCameraBtn');
|
||||
const box = $('#cameraBox');
|
||||
const video = $('#camera');
|
||||
button.disabled = true;
|
||||
box.hidden = false;
|
||||
|
||||
try {
|
||||
const reader = new ZXing.BrowserMultiFormatReader();
|
||||
state.controls = await reader.decodeFromConstraints(
|
||||
{ audio: false, video: { facingMode: { ideal: 'environment' } } },
|
||||
video,
|
||||
(result) => {
|
||||
if (!result) return;
|
||||
const code = result.getText();
|
||||
stopCamera();
|
||||
lookupBarcode(code);
|
||||
}
|
||||
);
|
||||
$('#cameraHint').textContent = 'Hold the barcode inside the frame.';
|
||||
} catch (err) {
|
||||
box.hidden = true;
|
||||
button.disabled = false;
|
||||
$('#cameraHint').textContent = `Camera unavailable: ${err && err.message ? err.message : 'permission denied'}. Try a photo instead.`;
|
||||
}
|
||||
}
|
||||
|
||||
function stopCamera() {
|
||||
if (state.controls) {
|
||||
try { state.controls.stop(); } catch { /* already stopped */ }
|
||||
state.controls = null;
|
||||
}
|
||||
const box = $('#cameraBox');
|
||||
if (box) box.hidden = true;
|
||||
const button = $('#startCameraBtn');
|
||||
if (button) button.disabled = false;
|
||||
}
|
||||
|
||||
async function onPhoto(event) {
|
||||
const file = event.target.files && event.target.files[0];
|
||||
event.target.value = '';
|
||||
if (!file) return;
|
||||
if (!window.ZXing) {
|
||||
toast('Scanner library did not load', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
const url = URL.createObjectURL(file);
|
||||
try {
|
||||
const reader = new ZXing.BrowserMultiFormatReader();
|
||||
const result = await reader.decodeFromImageUrl(url);
|
||||
await lookupBarcode(result.getText());
|
||||
} catch {
|
||||
toast('No barcode found in that photo — try again closer', 'error');
|
||||
} finally {
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
}
|
||||
|
||||
async function onHealthFile(event) {
|
||||
const file = event.target.files && event.target.files[0];
|
||||
event.target.value = '';
|
||||
if (!file) return;
|
||||
|
||||
const status = $('#importStatus');
|
||||
const setStatus = (message) => { if (status) status.textContent = message; };
|
||||
|
||||
if (!window.HealthImport) {
|
||||
toast('Import script did not load', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
const daysBack = Number($('#importRange').value) || 90;
|
||||
const since = shiftDate(localDate(), -daysBack);
|
||||
setStatus('Reading export…');
|
||||
|
||||
try {
|
||||
const parsed = await window.HealthImport.parseFile(file, {
|
||||
since,
|
||||
onProgress: (fraction) => setStatus(`Reading export… ${Math.round(fraction * 100)}%`),
|
||||
});
|
||||
|
||||
if (!parsed.days.length && !parsed.workouts.length) {
|
||||
setStatus(`No steps or workouts found in the last ${daysBack} days.`);
|
||||
return;
|
||||
}
|
||||
|
||||
setStatus(`Found ${parsed.days.length} step days and ${parsed.workouts.length} workouts. Saving…`);
|
||||
const result = await post('/import/apple-health', parsed);
|
||||
setStatus(`Imported ${result.stepsDays} step days and ${result.workouts} new workouts.`);
|
||||
toast('Apple Health imported');
|
||||
await loadDay();
|
||||
} catch (err) {
|
||||
setStatus(err.message);
|
||||
toast(err.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------- view
|
||||
|
||||
function setView(view) {
|
||||
if (view !== 'scan') stopCamera();
|
||||
state.view = view;
|
||||
|
||||
$$('.view').forEach((section) => {
|
||||
section.hidden = section.id !== `view-${view}`;
|
||||
});
|
||||
$$('.tab').forEach((tab) => {
|
||||
tab.classList.toggle('is-active', tab.dataset.view === view);
|
||||
});
|
||||
|
||||
if (view === 'plan') {
|
||||
renderPlan();
|
||||
const select = $('#planStyle');
|
||||
const profile = state.day && state.day.profile;
|
||||
if (select && profile && !select.value) select.value = profile.diet || 'any';
|
||||
}
|
||||
if (view === 'you') {
|
||||
fillProfileForm();
|
||||
renderYouTargets();
|
||||
}
|
||||
window.scrollTo(0, 0);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------- events
|
||||
|
||||
async function onClick(event) {
|
||||
const tab = event.target.closest('.tab');
|
||||
if (tab) {
|
||||
setView(tab.dataset.view);
|
||||
return;
|
||||
}
|
||||
|
||||
const scanTab = event.target.closest('[data-scan-tab]');
|
||||
if (scanTab) {
|
||||
setScanTab(scanTab.dataset.scanTab);
|
||||
return;
|
||||
}
|
||||
|
||||
const el = event.target.closest('[data-action]');
|
||||
if (!el) return;
|
||||
|
||||
try {
|
||||
switch (el.dataset.action) {
|
||||
case 'date-prev':
|
||||
state.date = shiftDate(state.date, -1);
|
||||
await loadDay();
|
||||
break;
|
||||
case 'date-next':
|
||||
if (state.date >= localDate()) return;
|
||||
state.date = shiftDate(state.date, 1);
|
||||
await loadDay();
|
||||
break;
|
||||
case 'date-today':
|
||||
state.date = localDate();
|
||||
await loadDay();
|
||||
break;
|
||||
case 'open-profile':
|
||||
setView('you');
|
||||
break;
|
||||
case 'goto-scan': {
|
||||
state.meal = el.dataset.meal || 'lunch';
|
||||
state.product = null;
|
||||
renderProduct(null);
|
||||
const manualMeal = $('#manualMeal');
|
||||
if (manualMeal) manualMeal.value = state.meal;
|
||||
setScanTab('scan');
|
||||
setView('scan');
|
||||
break;
|
||||
}
|
||||
case 'goto-manual':
|
||||
setScanTab('manual');
|
||||
break;
|
||||
case 'del-entry': {
|
||||
const data = await del(`/entries/${el.dataset.id}`);
|
||||
state.day = data.day;
|
||||
renderToday();
|
||||
renderPlan();
|
||||
renderYouTargets();
|
||||
toast('Removed');
|
||||
break;
|
||||
}
|
||||
case 'del-activity': {
|
||||
const data = await del(`/activities/${el.dataset.id}`);
|
||||
state.day = data.day;
|
||||
renderToday();
|
||||
renderYouTargets();
|
||||
toast('Removed');
|
||||
break;
|
||||
}
|
||||
case 'steps-add': {
|
||||
const steps = (state.day && state.day.steps ? state.day.steps : 0) + Number(el.dataset.amount);
|
||||
const data = await post('/activities', { date: state.date, type: 'steps', steps });
|
||||
state.day = data.day;
|
||||
renderToday();
|
||||
renderYouTargets();
|
||||
break;
|
||||
}
|
||||
case 'pick-product': {
|
||||
const product = state.results[Number(el.dataset.index)];
|
||||
if (!product) return;
|
||||
state.product = product;
|
||||
setScanTab('scan');
|
||||
renderProduct(product);
|
||||
break;
|
||||
}
|
||||
case 'portion': {
|
||||
const form = $('#logProductForm');
|
||||
const input = form && form.querySelector('[name="grams"]');
|
||||
if (input) {
|
||||
input.value = el.dataset.grams;
|
||||
updateProductKcal();
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'log-plan': {
|
||||
const data = await post(`/plan/items/${el.dataset.id}/log`, {});
|
||||
state.day = data.day;
|
||||
renderToday();
|
||||
renderPlan();
|
||||
renderYouTargets();
|
||||
toast('Meal logged');
|
||||
break;
|
||||
}
|
||||
case 'clear-plan': {
|
||||
const data = await del(`/plan/${state.date}`);
|
||||
state.day = data.day;
|
||||
renderPlan();
|
||||
toast('Plan cleared');
|
||||
break;
|
||||
}
|
||||
case 'stop-camera':
|
||||
stopCamera();
|
||||
break;
|
||||
case 'photo-scan':
|
||||
$('#photoInput').click();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
} catch (err) {
|
||||
toast(err.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function onInput(event) {
|
||||
if (event.target.closest('#logProductForm input[name="grams"]')) updateProductKcal();
|
||||
}
|
||||
|
||||
async function onSubmit(event) {
|
||||
const form = event.target;
|
||||
if (!['stepsForm', 'exerciseForm', 'barcodeForm', 'searchForm', 'manualForm', 'logProductForm', 'profileForm'].includes(form.id)) return;
|
||||
event.preventDefault();
|
||||
if (state.busy) return;
|
||||
|
||||
try {
|
||||
if (form.id === 'stepsForm') {
|
||||
const steps = Math.max(0, Math.round(Number(form.steps.value) || 0));
|
||||
const data = await post('/activities', { date: state.date, type: 'steps', steps });
|
||||
state.day = data.day;
|
||||
renderToday();
|
||||
renderYouTargets();
|
||||
toast('Steps saved');
|
||||
return;
|
||||
}
|
||||
|
||||
if (form.id === 'exerciseForm') {
|
||||
const preset = (state.meta.metPresets || []).find((item) => item.id === form.preset.value);
|
||||
const minutes = Number(form.minutes.value);
|
||||
if (!preset) throw new Error('Pick an activity');
|
||||
if (!(minutes > 0)) throw new Error('Enter the minutes');
|
||||
const data = await post('/activities', {
|
||||
date: state.date, type: 'exercise', name: preset.label, met: preset.met, minutes,
|
||||
});
|
||||
state.day = data.day;
|
||||
renderToday();
|
||||
renderYouTargets();
|
||||
toast('Workout added');
|
||||
return;
|
||||
}
|
||||
|
||||
if (form.id === 'barcodeForm') {
|
||||
const code = form.barcode.value.replace(/\D/g, '');
|
||||
if (code.length < 6) throw new Error('Enter the digits under the barcode');
|
||||
await lookupBarcode(code);
|
||||
return;
|
||||
}
|
||||
|
||||
if (form.id === 'searchForm') {
|
||||
const query = form.q.value.trim();
|
||||
if (query.length < 2) throw new Error('Search needs at least 2 characters');
|
||||
await runSearch(query);
|
||||
return;
|
||||
}
|
||||
|
||||
if (form.id === 'manualForm') {
|
||||
const body = {
|
||||
date: state.date,
|
||||
meal: form.meal.value,
|
||||
name: form.name.value.trim(),
|
||||
kcal: Number(form.kcal.value) || 0,
|
||||
protein_g: Number(form.protein_g.value) || 0,
|
||||
carbs_g: Number(form.carbs_g.value) || 0,
|
||||
fat_g: Number(form.fat_g.value) || 0,
|
||||
};
|
||||
if (!body.name) throw new Error('Give the food a name');
|
||||
if (!(body.kcal > 0)) throw new Error('Enter the calories');
|
||||
const data = await post('/entries', body);
|
||||
form.reset();
|
||||
const mealSelect = $('#manualMeal');
|
||||
if (mealSelect) mealSelect.value = body.meal;
|
||||
finishLogging(data.day, body.meal);
|
||||
return;
|
||||
}
|
||||
|
||||
if (form.id === 'logProductForm') {
|
||||
const product = state.product;
|
||||
if (!product) throw new Error('Pick a product first');
|
||||
const grams = Number(form.grams.value);
|
||||
if (!(grams > 0)) throw new Error('Enter a portion in grams');
|
||||
const meal = form.meal.value;
|
||||
const data = await post('/entries', {
|
||||
date: state.date,
|
||||
meal,
|
||||
name: product.name,
|
||||
brand: product.brand,
|
||||
barcode: product.code,
|
||||
image_url: product.image,
|
||||
grams,
|
||||
per100g: product.per100g,
|
||||
});
|
||||
finishLogging(data.day, meal);
|
||||
return;
|
||||
}
|
||||
|
||||
if (form.id === 'profileForm') {
|
||||
const body = {
|
||||
name: form.name.value,
|
||||
sex: form.sex.value,
|
||||
age: Number(form.age.value),
|
||||
height_cm: Number(form.height_cm.value),
|
||||
weight_kg: Number(form.weight_kg.value),
|
||||
goal: form.goal.value,
|
||||
rate_kg_week: Number(form.rate_kg_week.value) || 0,
|
||||
diet: form.diet.value,
|
||||
protein_target_g: form.protein_target_g.value === '' ? null : Number(form.protein_target_g.value),
|
||||
};
|
||||
const data = await put('/profile', body);
|
||||
state.day.profile = data.profile;
|
||||
await loadDay();
|
||||
toast('Profile saved');
|
||||
}
|
||||
} catch (err) {
|
||||
toast(err.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function generatePlan() {
|
||||
const button = $('#generatePlanBtn');
|
||||
if (state.busy) return;
|
||||
state.busy = true;
|
||||
button.disabled = true;
|
||||
button.textContent = 'Planning…';
|
||||
|
||||
try {
|
||||
const style = $('#planStyle').value || 'any';
|
||||
const data = await post(`/plan/${state.date}`, { style });
|
||||
state.day.plan = data.plan;
|
||||
renderPlan();
|
||||
toast('Plan ready');
|
||||
} catch (err) {
|
||||
toast(err.message, 'error');
|
||||
} finally {
|
||||
state.busy = false;
|
||||
button.disabled = false;
|
||||
button.textContent = 'Generate plan';
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------- init
|
||||
|
||||
function fillMetaOptions() {
|
||||
const styles = state.meta.styles || [];
|
||||
const styleOptions = styles.map((style) => `<option value="${esc(style.id)}">${esc(style.label)}</option>`).join('');
|
||||
|
||||
const planStyle = $('#planStyle');
|
||||
if (planStyle) planStyle.innerHTML = styleOptions;
|
||||
|
||||
const profileDiet = $('#profileDiet');
|
||||
if (profileDiet) profileDiet.innerHTML = styleOptions;
|
||||
|
||||
const manualMeal = $('#manualMeal');
|
||||
if (manualMeal) manualMeal.innerHTML = mealOptions(state.meal);
|
||||
}
|
||||
|
||||
function bind() {
|
||||
document.addEventListener('click', onClick);
|
||||
document.addEventListener('submit', onSubmit);
|
||||
document.addEventListener('input', onInput);
|
||||
$('#photoInput').addEventListener('change', onPhoto);
|
||||
const healthFile = $('#healthFile');
|
||||
if (healthFile) healthFile.addEventListener('change', onHealthFile);
|
||||
$('#startCameraBtn').addEventListener('click', startCamera);
|
||||
$('#generatePlanBtn').addEventListener('click', generatePlan);
|
||||
}
|
||||
|
||||
async function init() {
|
||||
bind();
|
||||
try {
|
||||
state.meta = await api('/meta');
|
||||
} catch (err) {
|
||||
console.warn('Meta unavailable', err);
|
||||
}
|
||||
fillMetaOptions();
|
||||
|
||||
try {
|
||||
await loadDay();
|
||||
} catch (err) {
|
||||
$('#view-today').innerHTML = `<div class="card"><h2>Can't load your day</h2><p class="error">${esc(err.message)}</p></div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
setView('today');
|
||||
|
||||
const hint = $('#cameraHint');
|
||||
if (!window.isSecureContext) {
|
||||
hint.textContent = 'Live camera needs HTTPS or localhost. Taking a photo or typing the barcode works over plain HTTP.';
|
||||
} else {
|
||||
hint.textContent = 'Point the camera at the barcode. If it will not start, take a photo instead.';
|
||||
}
|
||||
}
|
||||
|
||||
init();
|
||||
})();
|
||||
Reference in New Issue
Block a user