Skip to content

Commit 86e7798

Browse files
Trends Year: carbs and fat as stacked weekly averages
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 3cc45ba commit 86e7798

2 files changed

Lines changed: 36 additions & 16 deletions

File tree

‎CLAUDE.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ Personal calorie and macro tracker, shared with a few friends. Not commercial. M
2828
- `goals` holds one row per user (calories as a ceiling, protein, fluid_ml, creatine_g), own-row RLS. A null goal means off: protein loses its goal bar, and fluids and creatine disappear from the summary (creatine's Trends card also disappears; Fluids' Trends chart stays, without a goal line). With no row the app uses only a calorie ceiling of 2000, everything else off. Standard supplement foods are in `supabase/seed_supplements.sql`.
2929
- `profiles` holds one row per user (birth_year, sex male/female/other, height_cm, weight_kg, units us/metric, activity, aim), own-row RLS; always stored metric. It is written by the Goals sheet's collapsed "Help me choose" helper (`helperCompute()`), which prefills from it. The helper uses Mifflin-St Jeor x activity (1.2/1.375/1.55/1.725), "Other" averages the sex term (-78) and floors (1,500 / 1,200 / 1,350 cal); aims are lose slowly -10% (protein 2.0 g/kg), lose faster -20% (2.2), maintain (1.6), build muscle +10% (2.0); fluids 35 ml/kg; protein and fluids use the weight for a BMI of 25 when the person is heavier. "Fill in my goals" fills and switches on calories, protein and fluids (never creatine) and saves the profile; only "Save goals" saves goals. Under 18 it refuses. Guests keep the profile in the stand-in and it merges on sign-in if the account has none.
3030
- The Trends tab (ruled sections for calories, protein, fluids, carbs and fat, creatine dots and alcohol) reads the `daily_totals` view; charts are inline SVG drawn by `drawTrendChart()` / `drawDotStrip()`, not a library. `renderTrends()` writes each card's shell (`trendCardShell()`), then hands its parts to one renderer per kind, picked by `trendCardKind()` from `TREND_RENDERERS` (`renderGoalCard`, `renderStackCard`, `renderWeightCard`, `renderCreatineCard`, `renderAlcoholByDay`, `renderAlcoholCalendar`); a new card kind is a new renderer there. Bars: amber counts toward or met a goal, crimson is over the calorie limit, short of a floor goal is a pale bar with a dark 3px cap at the value (`--miss` body, `--miss-cap`; the cap carries the contrast, so missed days stay quiet); today is a dashed outline (unfinished) unless already over or met. Alcohol counts a day with nothing logged as 0 drinks (it has no bar or circle, but counts as 0 in averages and totals; the foot says so). On 7 days it is bars by day with a 7-day average line (like the goal charts). On 4 weeks it is a calendar like creatine's (`drawAlcoholCalendar()`): a filled circle with the number on drink days, a pale ring on dry logged days, a tiny dot on unlogged days, and each week's total on the right. A week's total is the drinks actually logged (the current week's so far), shown as "13*" when some past days of it were not logged and "—" when none were. "avg a week" is the mean of the finished weeks' totals on screen (no line). Tapping a day or a week total fills the readout. Creatine is dots: one row on 7 days, a calendar on 4 weeks (whole Monday-to-Sunday weeks around the window, so 4 or 5 rows; padding days count like any other, future days are empty; weeks are Monday-first everywhere, as in the alcohol calendar; both use `calendarDays()`); its header shows days at goal and the current streak (`creatineStreak`, counted back from today or yesterday, regardless of the window).
31-
- Trends has a third range, **Year** (`trendDays === 'year'`, `trendYear` null for the last 52 weeks or a calendar year; `yearWeeks()`, `setTrendNav()`). The default is the last 52 weeks ("Past year"); back goes to the last full calendar year (the weeks whose Monday is in it), then a year at a time down to the year of the first entry or weigh-in (`trendFirstDate`); forward from the latest full year returns to the last 52 weeks. Cards not in `YEAR_CARDS` are hidden on Year. Calories, protein and fluids are one bar per Monday-to-Sunday week (`renderGoalYear()`): the average a day over its logged days, today left out, coloured against today's goal (goals have no history), pale (`.tb-thin`) under `THIN_WEEK_DAYS` (3) logged days, the current week dashed. Weight on Year is one dot per week (the average of that week's real weigh-ins; no weigh-ins, no dot) and a 4-week average line (`weightAvgOn(known, d, 28)` at the week's last day, or its latest weigh-in), chosen because a year of daily dots was too crowded and a 7-day line on weekly dots adds nothing. Its Year tiles are change and pace (a week) along the 4-week line, plus distance to goal on the last 52 weeks only (no "latest": it ignores the window). On desktop (`(hover: hover) and (pointer: fine)`), hovering any Trends bar, dot or week previews it in that card as a tap would (`previewTrendCard()`, which re-renders one card with `renderTrendCard()`); leaving the card restores the pinned selection. Each card's readout is never empty (`setReadout()`): with nothing hovered or tapped it shows the latest item dimmed and without links ("Today", "This week", the latest weigh-in, or the window's last day or week), and it reserves two lines on phones (one on desktop, where every readout fits one line at 900px), so the chart never moves. Week labels are "Oct 12–18" or "This week" (`weekLabel()`). Both use a month axis (`monthAxis()`, chosen by `chartDayAxis()` for more than 31 items). The range label is "Past year" or the year, since dates do not fit beside three tabs on a 375px phone.
31+
- Trends has a third range, **Year** (`trendDays === 'year'`, `trendYear` null for the last 52 weeks or a calendar year; `yearWeeks()`, `setTrendNav()`). The default is the last 52 weeks ("Past year"); back goes to the last full calendar year (the weeks whose Monday is in it), then a year at a time down to the year of the first entry or weigh-in (`trendFirstDate`); forward from the latest full year returns to the last 52 weeks. Cards not in `YEAR_CARDS` are hidden on Year. Carbs and fat are stacked weekly averages (`renderStackYear()`); both share `yearWeekStats()`. Calories, protein and fluids are one bar per Monday-to-Sunday week (`renderGoalYear()`): the average a day over its logged days, today left out, coloured against today's goal (goals have no history), pale (`.tb-thin`) under `THIN_WEEK_DAYS` (3) logged days, the current week dashed. Weight on Year is one dot per week (the average of that week's real weigh-ins; no weigh-ins, no dot) and a 4-week average line (`weightAvgOn(known, d, 28)` at the week's last day, or its latest weigh-in), chosen because a year of daily dots was too crowded and a 7-day line on weekly dots adds nothing. Its Year tiles are change and pace (a week) along the 4-week line, plus distance to goal on the last 52 weeks only (no "latest": it ignores the window). On desktop (`(hover: hover) and (pointer: fine)`), hovering any Trends bar, dot or week previews it in that card as a tap would (`previewTrendCard()`, which re-renders one card with `renderTrendCard()`); leaving the card restores the pinned selection. Each card's readout is never empty (`setReadout()`): with nothing hovered or tapped it shows the latest item dimmed and without links ("Today", "This week", the latest weigh-in, or the window's last day or week), and it reserves two lines on phones (one on desktop, where every readout fits one line at 900px), so the chart never moves. Week labels are "Oct 12–18" or "This week" (`weekLabel()`). Both use a month axis (`monthAxis()`, chosen by `chartDayAxis()` for more than 31 items). The range label is "Past year" or the year, since dates do not fit beside three tabs on a 375px phone.
3232
- `daily_totals` has no rows for days with no entries, so empty days are naturally skipped.
3333
- Accessibility: pinch-zoom stays on (keep inputs at 16px or more so iOS does not zoom on focus); every icon-only button has an `aria-label`; one `:focus-visible` ring for all controls; sheets take focus when they open and hand it back on close (not to text fields); `prefers-reduced-motion` turns transitions off. An axe-core scan of Today, the edit sheet and Trends was clean in both themes (Nov 2026).
3434
- Security lives in RLS, not in the client. Any new table needs RLS enabled and policies written before it is used.

‎js/trends.js‎

Lines changed: 35 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ const fmtMD = d => { const [, mo, da] = d.split('-'); return `${Number(mo)}/${da
4848

4949
const isYear = () => trendDays === 'year';
5050
const thisYear = () => Number(todayStr().slice(0, 4));
51-
const YEAR_CARDS = ['cal', 'wt', 'pro', 'flu'];
51+
const YEAR_CARDS = ['cal', 'wt', 'pro', 'flu', 'cf'];
5252
// A week on the Year view counts fully only with this many logged days; fewer and its bar is pale.
5353
const THIN_WEEK_DAYS = 3;
5454

@@ -240,7 +240,7 @@ function trendCardShell(cfg) {
240240

241241
// Which renderer draws a card. Alcohol is by day on the 7-day view and a calendar on the 4-week view.
242242
function trendCardKind(cfg) {
243-
if (isYear() && !cfg.kind && !cfg.stack) return 'goalYear';
243+
if (isYear() && !cfg.kind) return cfg.stack ? 'stackYear' : 'goalYear';
244244
if (cfg.kind === 'alcohol') return trendDays === 7 ? 'alcDay' : 'alcCal';
245245
return cfg.kind || (cfg.stack ? 'stack' : 'goal');
246246
}
@@ -433,24 +433,29 @@ function renderGoalCard({ cfg, goal, days, today, chart, ro, stats }) {
433433
// Year view of a goal chart: one bar per week, the average a day over its logged days (today left out).
434434
// A week with fewer than THIN_WEEK_DAYS logged days is pale; the current week is a dashed outline.
435435
// Past weeks are judged against today's goal (goals have no history).
436-
function renderGoalYear({ cfg, goal, weeks, today, chart, ro, stats, foot }) {
437-
const div = cfg.div || 1;
438-
const ws = weeks.map(w => {
439-
const vals = [];
440-
let m = 0; // days of the week before today
436+
// Each Year week's tracked days before today: { logged (dates), vals (dayVal of each), m (days before today),
437+
// avg, live (the current week), thin (finished, under THIN_WEEK_DAYS logged) }.
438+
function yearWeekStats(cfg, weeks, today) {
439+
return weeks.map(w => {
440+
const logged = [], vals = [];
441+
let m = 0;
441442
for (let k = 0; k < 7; k++) {
442443
const d = addDays(w, k);
443444
if (d >= today) break;
444445
m++;
445446
const v = dayVal(cfg, d);
446-
if (v !== null) vals.push(v);
447+
if (v !== null) { logged.push(d); vals.push(v); }
447448
}
448-
return { vals, m, avg: mean(vals) };
449-
});
450-
const items = weeks.map((w, i) => {
451449
const live = addDays(w, 6) >= today;
452-
return { id: w, val: ws[i].avg === null ? null : ws[i].avg / div, live, thin: !live && ws[i].vals.length < THIN_WEEK_DAYS };
450+
return { logged, vals, m, avg: mean(vals), live, thin: !live && vals.length < THIN_WEEK_DAYS };
453451
});
452+
}
453+
const thinFoot = items => items.some(i => i.thin && i.val !== null) ? `Pale: fewer than ${THIN_WEEK_DAYS} days logged that week.` : '';
454+
455+
function renderGoalYear({ cfg, goal, weeks, today, chart, ro, stats, foot }) {
456+
const div = cfg.div || 1;
457+
const ws = yearWeekStats(cfg, weeks, today);
458+
const items = weeks.map((w, i) => ({ id: w, val: ws[i].avg === null ? null : ws[i].avg / div, live: ws[i].live, thin: ws[i].thin }));
454459
drawTrendChart(chart, { ...cfg, avg: false }, items, goal ? goal / div : null);
455460
const met = v => cfg.dir === 'ceil' ? v <= goal : v >= goal;
456461
const si = weeks.indexOf(trendSel), pi = si >= 0 ? si : weeks.length - 1;
@@ -462,11 +467,26 @@ function renderGoalYear({ cfg, goal, weeks, today, chart, ro, stats, foot }) {
462467
const since = trendFirstDate && trendFirstDate > weeks[0] ? ` since ${monthYear(trendFirstDate)}` : '';
463468
stats.innerHTML = statTile(avg === null ? '—' : fmtV(cfg, avg), 'avg a day' + since) +
464469
(goal ? statTile(all.length ? Math.round(100 * all.filter(met).length / all.length) + '%' : '—', cfg.tile) : '');
465-
foot.textContent = items.some(i => i.thin && i.val !== null) ? `Pale: fewer than ${THIN_WEEK_DAYS} days logged that week.` : '';
470+
foot.textContent = thinFoot(items);
471+
}
472+
473+
// Year view of carbs and fat: stacked weekly averages a day over the logged days, pale when thinly logged.
474+
function renderStackYear({ cfg, weeks, today, chart, ro, stats, foot }) {
475+
const ws = yearWeekStats(cfg, weeks, today);
476+
const partsOf = s => s.logged.length ? cfg.stack.map(([k]) => mean(s.logged.map(d => trendRows.get(d)[k]))) : null;
477+
const items = weeks.map((w, i) => ({ id: w, val: ws[i].avg, parts: partsOf(ws[i]), live: ws[i].live, thin: ws[i].thin }));
478+
drawTrendChart(chart, cfg, items, null);
479+
const si = weeks.indexOf(trendSel), pi = si >= 0 ? si : weeks.length - 1, it = items[pi], s = ws[pi];
480+
const what = it.parts ? cfg.stack.map(([, , lab], j) => `${lab} ${fmtNum(it.parts[j])} g`).join(' · ') + ` a day · ${s.vals.length}/${s.m} logged`
481+
: s.m ? 'no entries' : 'no full days yet';
482+
setReadout(ro, `<b>${weekLabel(weeks[pi], today)}</b> · ${what}`, si < 0);
483+
const days = ws.flatMap(s => s.logged);
484+
stats.innerHTML = cfg.stack.map(([k, , lab]) => statTile(days.length ? fmtNum(mean(days.map(d => trendRows.get(d)[k]))) + ' g' : '—', `${lab.toLowerCase()}, avg a day`)).join('');
485+
foot.textContent = thinFoot(items);
466486
}
467487

468488
const TREND_RENDERERS = {
469-
goalYear: renderGoalYear,
489+
goalYear: renderGoalYear, stackYear: renderStackYear,
470490
alcDay: renderAlcoholByDay, alcCal: renderAlcoholCalendar, weight: renderWeightCard,
471491
dots: renderCreatineCard, stack: renderStackCard, goal: renderGoalCard,
472492
};
@@ -554,7 +574,7 @@ function drawTrendChart(el, cfg, items, goal) {
554574
it.parts.forEach((pv, j) => {
555575
const ph2 = h * pv / tot;
556576
yy -= ph2;
557-
g += `<rect class="${cfg.stack[j][1]}" opacity="${it.live ? 0.45 : 1}" x="${x}" y="${yy}" width="${bw}" height="${Math.max(0, ph2)}" rx="2"/>`;
577+
g += `<rect class="${cfg.stack[j][1]}" opacity="${it.live ? 0.45 : it.thin ? 0.35 : 1}" x="${x}" y="${yy}" width="${bw}" height="${Math.max(0, ph2)}" rx="2"/>`;
558578
});
559579
if (isSel) g += `<rect class="tb-selring" x="${x}" y="${y(it.val)}" width="${bw}" height="${h}" rx="2"/>`;
560580
return;

0 commit comments

Comments
 (0)