Salud: Today by default, chart panels, and an aura behind the whole app
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s

Three things the screen was missing, plus the launch photo.

**Today.** The period filter started at 30 days, which buried the question a five-minute
cadence exists to answer: what do the numbers say right now? "Today" is now first and the
default, and it means today — the grid drops metrics nobody has measured today (the scale
is not stepped on every morning), and if nothing has come in yet the grid falls back to
everything and says so rather than showing an empty screen. The number on every card was
always the newest reading; what is new is that the card says which day it is and when it
landed ("hoy · hace 12 min"), so the claim can be checked instead of trusted. The screen
also refreshes itself every minute while it is open, which is what makes a five-minute
cadence visible.

The filter and the charts want different windows, and the view keeps them apart: a
sparkline or a trend needs history, so the fetch never asks for less than a week even in
"Today", and anything labelled with a window says which one it is. (The alternative —
fetching one day and drawing nothing — would have made Today the one mode with no charts.)

**Chart panels.** Every tile carries a 52px sparkline, which shows a shape and cannot be
read. The first few metrics in the catalogue's own order now get a full-width panel each:
axes, the window's min / avg / max, and the card's own colour, so a panel and its tile are
recognisably the same metric.

**The aura.** index.html carries the three "Diamond Weave" layers and index.css puts the
base colour on `body` where the blend modes composite against it, with `#app` lifted to
z-index 1 so the absolutely-positioned layers cannot paint over the page (everything modal
was already higher). Dark keeps `screen`; the light theme switches the same layers to
`multiply`, because screened amber over white is amber that has been washed away. The blur
radii follow the spec per breakpoint, and the layers are fixed rather than absolute so
scrolling never repaints two 200px blurs.

**The launch screen.** assets/splash.jpg is a 3862×5786 photograph from a camera, so
nothing ships it raw: build-app-icons.mjs now derives public/splash.webp (1170px wide, 62 KB
— WebP because it is a photo) for the boot screen and resources/splash.jpg (2732×2732,
fitted on the aura's base colour rather than cropped, so a portrait composition survives)
for @capacitor/assets. The 12 MB original is gitignored: the derived files are committed,
so a clone still builds, and the script says what is missing when regeneration is asked for
without it.
This commit is contained in:
dsantillan committed 2026-09-23 11:32:51 -04:00
1 parent 3b7c9011c4
commit c3c1c2836c
15 files changed
+374 -27

No files matched your search

+6 -5
View File
@@ -55,7 +55,7 @@ function applyPrefs(theme, accent) {
de.dataset.theme = resolveTheme(theme)
de.dataset.accent = ACCENTS[accent] ? accent : 'lime'
const meta = document.querySelector('meta[name="theme-color"]')
if (meta) meta.content = de.dataset.theme === 'light' ? '#f2f2f7' : '#000000'
if (meta) meta.content = de.dataset.theme === 'light' ? '#f2f2f7' : '#100e0b' // matches the aura's base (index.css)
}
function Shell() {
@@ -136,10 +136,11 @@ function Shell() {
const authed = user || isGuest
if (!ready && !authed) return (
<div id="app">
{/* The mark, dimmed, as the boot placeholder — the same image the login screen shows, so
the app never flashes a different logo on its way in. */}
<div style={{ paddingTop: '44vh', display: 'flex', justifyContent: 'center' }}>
<img className="brand boot" src="logo.png" alt="" />
{/* The launch screen: the photo, then the app's own mark on it (see .boot-splash in
index.css). Fixed to the viewport, so #app's own padding does not matter here. */}
<div className="boot-splash">
<img className="boot-photo" src="splash.webp" alt="" />
<img className="boot-logo" src="logo.png" alt="KuentaGYM" />
</div>
</div>
)
+70 -1
View File
@@ -164,7 +164,57 @@ button,.chip,.tile,.item,.wday,.cal-d,.swatch,.hm-c,.lrow,.seg button,.stp butto
#app{
padding:calc(var(--sat) + 8px) var(--pad) calc(88px + var(--sab));
max-width:560px;margin:0 auto;
/* Above the aura (index.html): its layers are absolutely positioned and would otherwise paint
over the page, since a positioned box paints above static content no matter where it sits in
the DOM. Everything modal already sits higher — #modal-root is 100, the tab bar 50. */
position:relative;z-index:1;
}
/* ================= Aura background ("Diamond Weave") =======================================
The base colour goes on BODY, never on the container: the two blurred layers use
mix-blend-mode, and a blend composites against what is painted behind the element — the page
background. Put the colour on the container and they blend with that instead, which is what
turns this effect into a flat brown smear.
Dark theme: `screen` over the warm near-black below, which is what the gradient was tuned for.
Light theme: the same layers with `multiply`, because `screen` over a white surface washes the
colour away completely (the spec's own note). Nothing else changes — same geometry, same hues.
`position: fixed` rather than absolute so scrolling never repaints two 200px blurs, and
`will-change: transform` keeps each blurred layer on its own GPU texture. */
:root[data-theme="dark"] body{background-color:#100e0b}
.aura{position:fixed;inset:0;z-index:0;overflow:hidden;pointer-events:none}
.aura-layer-1,.aura-layer-2,.aura-layer-3{position:absolute;inset:0;pointer-events:none;transform:translateZ(0);will-change:transform}
.aura-layer-1{
mix-blend-mode:normal;
background:
repeating-linear-gradient(45deg,transparent,transparent 30px,rgba(245,158,11,.08) 30px,rgba(245,158,11,.08) 31px),
repeating-linear-gradient(-45deg,transparent,transparent 30px,rgba(245,158,11,.08) 30px,rgba(245,158,11,.08) 31px);
}
.aura-layer-2{
mix-blend-mode:screen;filter:blur(200px);
background:radial-gradient(circle at 50% 50%,rgba(245,158,11,.5) 0%,transparent 45%);
}
.aura-layer-3{
mix-blend-mode:screen;filter:blur(125px);
background:radial-gradient(circle at 20% 80%,rgba(217,119,6,.3) 0%,transparent 35%);
}
/* Wider screens get the desktop blur radii from the spec; phones keep the smaller ones, which are
cheaper and read the same at that size. */
@media (min-width:700px){
.aura-layer-2{filter:blur(260px)}
.aura-layer-3{filter:blur(180px)}
}
/* Light theme: multiply, so the amber darkens the pale background instead of being screened into
nothing. Same layers, same colours, opposite blend. */
:root[data-theme="light"] .aura-layer-2,
:root[data-theme="light"] .aura-layer-3{mix-blend-mode:multiply}
/* The launch screen, while the profile is being read. The photo fills the viewport and the app's
own mark sits on it, over a soft darkening so the logo never fights a busy part of the image.
public/splash.webp is derived from assets/splash.jpg by scripts/build-app-icons.mjs. */
.boot-splash{position:fixed;inset:0;z-index:1;display:grid;place-items:center;overflow:hidden}
.boot-splash img.boot-photo{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}
.boot-splash::after{content:'';position:absolute;inset:0;background:radial-gradient(circle at 50% 45%,transparent 30%,rgba(16,14,11,.55) 100%)}
.boot-splash img.boot-logo{position:relative;width:104px;height:auto;filter:drop-shadow(0 8px 24px rgba(0,0,0,.45))}
/* Keep the last workout controls clear of the mobile overlays without adding a second
screenful of blank scroll space. The stacked rest timer needs the larger reserve. */
body.resting #app{padding-bottom:calc(206px + var(--sab))}
@@ -396,7 +446,6 @@ h4.sec{
is the transparent PNG (public/logo.png, generated by scripts/build-app-icons.mjs), so it sits
on whatever background the screen already has rather than carrying a plate of its own. */
.brand{display:block;width:88px;height:auto;margin:0 auto}
.brand.boot{width:56px;opacity:.85}
/* NOTE on every backdrop-filter pair in this file: the -webkit- line comes first and the
standard property last, which is the order a prefixed/standard pair wants — whichever is
@@ -1290,6 +1339,26 @@ body.chips-dragging *{cursor:inherit}
.vh-trend .icn{font-size:13px;--icon-stroke:2.2}
.vh-spark{margin:2px -6px -4px;height:36px;overflow:hidden}
.vh-spark-ph{height:36px}
/* Which day the number is from, and when it landed. Dim and small on purpose: it is the footnote
to a 26px number, not a second number. `.vh-ago` brings its own separator so the two can be
written as siblings without the view threading punctuation through a translation. */
.vh-when{margin-top:3px;font-size:11px;color:var(--label-3);letter-spacing:0}
.vh-when .vh-ago::before{content:' · '}
/* --- the chart panels -----------------------------------------------------
Full-width panels for the few metrics people open this screen for. Same `--tint` contract as
the tiles, so a panel and its card are recognisably the same metric. */
.vh-charts{display:flex;flex-direction:column;gap:10px;margin-bottom:14px}
.vh-tchart{--tint:var(--grey);width:100%;text-align:left;display:block;font:inherit;color:inherit;
padding:12px 10px 6px;background:color-mix(in srgb,var(--tint) 6%,var(--surface))}
.vh-tchart:active{background:color-mix(in srgb,var(--tint) 12%,var(--surface-2))}
.vh-tchart-hd{display:flex;align-items:baseline;justify-content:space-between;gap:10px;padding:0 2px;margin-bottom:2px}
.vh-tchart-t{display:flex;align-items:center;gap:5px;font-size:14px;font-weight:500;color:var(--label-2)}
.vh-tchart-t .icn{font-size:15px;color:var(--tint)}
.vh-tchart-v{font-size:22px;font-weight:600;letter-spacing:-.022em;color:var(--tint);font-variant-numeric:tabular-nums}
.vh-tchart-v i{margin-left:3px;font-size:12px;font-weight:500;font-style:normal;color:var(--label-2)}
.vh-tchart-ft{display:flex;gap:12px;padding:0 2px;margin-top:1px;font-size:11.5px;color:var(--label-3);font-variant-numeric:tabular-nums}
.vh-window{font-weight:400;color:var(--label-3);text-transform:none;letter-spacing:0}
.vh-sheet-top{margin:2px 0 12px}
.vh-chart{padding:6px 4px 2px;margin-bottom:4px}
+44 -4
View File
@@ -12,7 +12,7 @@
* those numbers a human wants to see first — so adding a metric is a line here, and losing none.
*/
import { t } from './i18n-core.js'
import { fmtDur, fmtDate } from './format.js'
import { fmtDur, fmtDate, isoOf } from './format.js'
/** Group order on the screen. Anything not in the catalogue lands in 'other', at the end. */
export const GROUP_ORDER = ['activity', 'heart', 'body', 'sleep', 'vitals', 'other']
@@ -176,7 +176,7 @@ export function metricCards(data, { days = 90 } = {}) {
for (const [name, m] of Object.entries(metrics)) {
const s = specOf(name)
const series = ((m && m.days) || [])
.map(d => ({ day: d.day, v: valueOfDay(d, s), n: d.n || 0 }))
.map(d => ({ day: d.day, v: valueOfDay(d, s), n: d.n || 0, lastTs: d.lastTs || null }))
.filter(p => p.v != null && Number.isFinite(p.v))
if (!series.length) continue
const latest = series[series.length - 1]
@@ -194,6 +194,9 @@ export function metricCards(data, { days = 90 } = {}) {
unknown: !!s.unknown,
value: latest.v,
day: latest.day,
// When the newest reading actually landed. The phone pushes every few minutes, so this is
// what makes "today's number" verifiable rather than a claim: a card can say "hace 12 min".
lastTs: latest.lastTs,
delta: mean != null && mean !== 0 ? (latest.v - mean) / Math.abs(mean) : null,
avg: mean,
trendDays: prior.length,
@@ -208,8 +211,7 @@ export function metricCards(data, { days = 90 } = {}) {
return sortCards(cards)
}
/** Catalogue order first (Activity, Heart, Body…), then the unknowns alphabetically. Stable. */
export function sortCards(cards) {
/** Catalogue order first (Activity, Heart, Body…), then the unknowns alphabetically. Stable. */export function sortCards(cards) {
const rank = new Map()
Object.keys(METRICS).forEach((k, i) => rank.set(k, i))
return cards.slice().sort((a, b) => {
@@ -242,6 +244,44 @@ export function chartPoints(card) {
return (card?.series || []).map(p => ({ t: Date.parse(p.day + 'T12:00:00'), y: p.v, d: p.day }))
}
/**
* The newest day a card has, as a caption: "today", "yesterday", or the date.
*
* A card's number is always the newest reading, and with a five-minute cadence that is usually
* today's — but not always: nobody weighs themselves at 3 a.m., so a weight card can legitimately
* be showing yesterday. Saying which day it is costs four characters and stops the screen from
* quietly implying that every number is live.
*/
export function dayLabel(day, now = new Date()) {
if (!day) return ''
if (day === isoOf(now)) return t('today')
const y = new Date(now)
y.setDate(y.getDate() - 1)
if (day === isoOf(y)) return t('yesterday')
return fmtDate(day)
}
/**
* The cards worth a full-width chart: the catalogue's own order (steps, heart rate, sleep…),
* only the ones the window has enough days to draw. A chart of a single point is a dot, so those
* are left to the grid's own card rather than given a panel that looks broken.
*/
export function trendCards(cards, { limit = 4, minDays = 2 } = {}) {
return cards.filter(c => c.series.length >= minDays).slice(0, limit)
}
/** min / max / average over a card's window, for the caption under a chart. */
export function seriesStats(card) {
const vs = (card?.series || []).map(p => p.v).filter(v => Number.isFinite(v))
if (!vs.length) return null
return {
min: Math.min(...vs),
max: Math.max(...vs),
avg: vs.reduce((a, b) => a + b, 0) / vs.length,
days: vs.length
}
}
/* ---------- units and numbers ---------- */
// HAE's unit strings are compact and sometimes need a human spelling. Values are never converted:
+34 -2
View File
@@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest'
import {
METRICS, specOf, humanize, valueOfDay, metricCards, sortCards, groupedCards, trendOf,
chartPoints, workoutRows, hasVitals, activeDays, ingestUrl, unitLabel, fmtValue, agoLabel,
detailRows, workoutIcon, GROUP_ORDER, tintOf
detailRows, workoutIcon, GROUP_ORDER, tintOf, dayLabel, trendCards, seriesStats
} from './vitals-view.js'
/* The mapping from HAE's metric names to what a card shows. Worth testing because it is the one
@@ -10,7 +10,7 @@ import {
"everything" is guaranteed to contain metrics nobody has written a rule for yet. */
/** A stored day bucket the way the server writes one. */
const day = (d, f, n = 1) => ({ day: d, n, f })
const day = (d, f, n = 1) => ({ day: d, n, f, lastTs: Date.parse(d + 'T09:00:00Z') })
const bucket = v => ({ n: 1, sum: v, min: v, max: v, last: v, avg: v })
const doc = {
@@ -166,6 +166,38 @@ describe('detailRows', () => {
})
})
describe('dayLabel / trendCards / seriesStats', () => {
const now = new Date('2026-05-03T09:00:00')
it('names the newest day in words when it is recent', () => {
expect(dayLabel('2026-05-03', now)).toBe('today')
expect(dayLabel('2026-05-02', now)).toBe('yesterday')
// Anything older gets a real date rather than a vague "3 days ago": a weight card showing
// last week's reading should look like last week's reading.
expect(dayLabel('2026-04-28', now)).not.toBe('today')
expect(dayLabel('2026-04-28', now)).toMatch(/28/)
expect(dayLabel(undefined, now)).toBe('')
})
it('picks the cards a full-width chart is worth, in catalogue order', () => {
const cards = metricCards(doc)
const picked = trendCards(cards, { limit: 3 })
// In this fixture only two metrics have two days or more; heart_rate and weight_body_mass
// carry a single day each, and a one-point chart is a dot nobody can read.
expect(picked.map(c => c.name)).toEqual(['step_count', 'resting_heart_rate'])
expect(trendCards(cards, { limit: 20 }).every(c => c.series.length >= 2)).toBe(true)
// A card with a single day is left out: a one-point chart is a dot.
expect(trendCards([{ name: 'x', series: [{ day: '2026-05-03', v: 1 }] }])).toEqual([])
})
it('summarises a window for the caption under a chart', () => {
expect(seriesStats(card(doc, 'step_count'))).toMatchObject({ min: 5000, max: 12000, days: 3 })
expect(seriesStats(card(doc, 'step_count')).avg).toBe(8000)
expect(seriesStats({ series: [] })).toBeNull()
expect(card(doc, 'step_count').lastTs).toBeTruthy()
})
})
describe('workoutRows', () => {
it('carries duration, energy, distance and heart rate, with an icon per activity', () => {
const rows = workoutRows(doc)
+12
View File
@@ -1416,4 +1416,16 @@ export default {
'Apple Health needs a profile': 'Apple Health necesita un perfil',
'Guest mode lives entirely in this browser, and your iPhone can only post to a profile on a server. Create one, then connect Apple Health from here — it takes a minute and nothing you logged as a guest is lost.': 'El modo invitado vive enteramente en este navegador, y tu iPhone solo puede enviar datos a un perfil en un servidor. Crea uno y luego conecta Apple Health desde aquí: toma un minuto y no se pierde nada de lo que registraste como invitado.',
'Create a profile': 'Crear un perfil',
// el filtro de periodo, las gráficas y el rótulo de frescura
'Today': 'Hoy',
'today': 'hoy',
'yesterday': 'ayer',
'Trends': 'Tendencias',
'the last {0} days': 'últimos {0} días',
'the last year': 'último año',
'updated {0}': 'actualizado {0}',
'Nothing has come in today yet — this is the latest reading of each metric.': 'Todavía no llegó nada de hoy: esto es la última lectura de cada métrica.',
'low {0}': 'mín {0}',
'avg {0}': 'media {0}',
'high {0}': 'máx {0}',
}
+95 -11
View File
@@ -23,16 +23,22 @@ import { confirmSheet } from '../sheets.jsx'
import { Button, Row, Segmented } from '../components/ui.jsx'
import Icon from '../components/Icon.jsx'
import LineChart from '../components/LineChart.jsx'
import { todayISO } from '../lib/format.js'
import {
groupedCards, metricCards, trendOf, chartPoints, workoutRows, hasVitals,
fmtValue, unitLabel, agoLabel, ingestUrl, detailRows
fmtValue, unitLabel, agoLabel, ingestUrl, detailRows, dayLabel, trendCards, seriesStats
} from '../lib/vitals-view.js'
/* The period filter, "Today" first and by default: a card's headline is always the newest
reading, and "is that right now?" is the question a five-minute cadence exists to answer. The
`key` is translated at render time (a module-level t() would freeze the language at import);
day counts read the same in every language. */
const RANGES = [
{ value: 7, label: '7d' },
{ value: 30, label: '30d' },
{ value: 90, label: '90d' },
{ value: 365, label: '1a' }
{ value: 1, key: 'Today' },
{ value: 7, label: '7 d' },
{ value: 30, label: '30 d' },
{ value: 90, label: '90 d' },
{ value: 365, label: '1 a' }
]
/** A trend arrow: green when it moved the way the metric is supposed to move. */
@@ -61,9 +67,50 @@ function MetricCard({ card, onOpen }) {
{card.series.length > 1
? <div className="vh-spark"><LineChart points={chartPoints(card)} h={36} axes={false} color={card.tint} /></div>
: <div className="vh-spark-ph" />}
{/* Which day this number is from, and when it landed. Nobody weighs themselves at 3 a.m., so
a card can legitimately be showing yesterday — saying so costs four characters and stops
the screen from implying that every number is live. */}
<div className="vh-when">
{dayLabel(card.day)}
{card.lastTs ? <span className="vh-ago">{agoLabel(card.lastTs)}</span> : null}
</div>
</button>
}
/**
* The charts. Every card in the grid carries a sparkline, which is enough to see a shape and not
* enough to read one — so the first few metrics in the catalogue's own order (steps, heart rate,
* sleep…, the ones people open this screen for) get a panel: axes, the window's own min/max/avg,
* and the card's colour, so a panel and its tile are recognisably the same thing.
*/
function TrendSection({ cards, windowLabel, onOpen }) {
const picked = trendCards(cards, { limit: 4 })
if (!picked.length) return null
return <>
<h4 className="sec">{t('Trends')}<span className="vh-window"> · {windowLabel}</span></h4>
<div className="vh-charts">
{picked.map(c => {
const st = seriesStats(c)
return <button key={c.name} className="card vh-tchart" style={{ '--tint': c.tint }} onClick={() => onOpen(c)}>
<div className="vh-tchart-hd">
<span className="vh-tchart-t"><Icon name={c.icon} />{c.label}</span>
<span className="vh-tchart-v">
{fmtValue(c.value, c.dec)}
{unitLabel(c.unit) ? <i>{unitLabel(c.unit)}</i> : null}
</span>
</div>
<LineChart points={chartPoints(c)} h={104} unit={unitLabel(c.unit)} color={c.tint} />
{st && <div className="vh-tchart-ft">
<span>{t('low {0}', fmtValue(st.min, c.dec))}</span>
<span>{t('avg {0}', fmtValue(st.avg, c.dec))}</span>
<span>{t('high {0}', fmtValue(st.max, c.dec))}</span>
</div>}
</button>
})}
</div>
</>
}
/* ---------- the two sheets ---------- */
/**
@@ -187,17 +234,34 @@ export default function Health() {
const isGuest = useStore(s => s.isGuest())
const [data, setData] = useState(null)
const [err, setErr] = useState('')
const [days, setDays] = useState(30)
const [days, setDays] = useState(1)
const [loading, setLoading] = useState(true)
/* Two different windows, and the screen keeps them apart on purpose.
*
* The headline on every card is the *newest reading* — with the phone pushing every few minutes,
* that is the moment, and it is what "Today" selects. A trend, though, cannot be computed from a
* single day, so the fetch never asks for less than a week: "Today" filters which cards are worth
* showing, and the sparklines and the chart panels draw those seven days of context. Anything
* labelled with a window says which one it is. */
const chartDays = days === 1 ? 7 : days
const load = useCallback(() => {
setLoading(true)
api('/api/vitals?days=' + days)
api('/api/vitals?days=' + chartDays)
.then(d => { setData(d); setErr('') })
.catch(e => setErr(e.message))
.finally(() => setLoading(false))
}, [days])
}, [chartDays])
useEffect(() => { if (!isGuest) load() }, [load, isGuest])
// The phone posts every few minutes; a minute is often enough for the screen to feel live, and
// it costs one small request. It never shows the loading state: `loading` is only rendered when
// there is no data yet, so a refresh in the background is invisible.
useEffect(() => {
if (isGuest) return
const id = setInterval(load, 60000)
return () => clearInterval(id)
}, [load, isGuest])
// Both of these resolve with the key so the setup sheet can show it the instant it exists — the
// sheet cannot read it off this screen's state (see the note in SetupSheet).
@@ -240,10 +304,20 @@ export default function Health() {
</div>
</>
const cards = hasVitals(data) ? metricCards(data, { days }) : []
const all = hasVitals(data) ? metricCards(data, { days: chartDays }) : []
// "Today" means today: a metric nobody measured yet (weight, on a day you skipped the scale) is
// not a number you are looking for at that moment. If nothing at all has come in today — first
// open of the morning, before the first sync — the grid falls back to everything rather than
// showing an empty screen, and says so.
const todayISO_ = todayISO()
const fresh = all.filter(c => c.day === todayISO_)
const cards = days === 1 && fresh.length ? fresh : all
const fellBack = days === 1 && !fresh.length && all.length > 0
const groups = groupedCards(cards)
const workouts = workoutRows(data, { limit: 20 })
const last = data?.last?.ts
const windowLabel = chartDays >= 365 ? t('the last year') : t('the last {0} days', chartDays)
const ranges = RANGES.map(r => ({ value: r.value, label: r.key ? t(r.key) : r.label }))
return <>
<div className="hdr">
@@ -265,11 +339,21 @@ export default function Health() {
{!err && data && !hasVitals(data) && <Empty onSetup={setup} />}
{!err && hasVitals(data) && <>
<Segmented options={RANGES} value={days} onChange={setDays} className="seg-range" />
<Segmented options={ranges} value={days} onChange={setDays} className="seg-range" />
<div className="small dim" style={{ margin: '8px 2px 12px' }}>
{t('{0} metrics', cards.length)}{data.last ? ' · ' + t('last sync {0}', agoLabel(data.last.ts)) : ''}
{/* The numbers below are always the newest reading, and with the phone pushing every few
minutes that is the moment. Saying when it landed is what makes the claim checkable
instead of something you have to trust. */}
{t('{0} metrics', cards.length)}
{last ? ' · ' + t('updated {0}', agoLabel(last)) : ''}
</div>
{fellBack && <div className="small dim" style={{ margin: '0 2px 12px', lineHeight: 1.5 }}>
{t('Nothing has come in today yet — this is the latest reading of each metric.')}
</div>}
<TrendSection cards={all} windowLabel={windowLabel} onOpen={openMetric} />
{groups.map(g => <div key={g.group}>
<h4 className="sec">{g.label}</h4>
<div className="tiles">{g.cards.map(c => <MetricCard key={c.name} card={c} onOpen={openMetric} />)}</div>
+35 -1
View File
@@ -17,6 +17,7 @@ vi.mock('../sheets.jsx', () => ({ confirmSheet: vi.fn() }))
const { default: Health } = await import('./Health.jsx')
const { default: Modals } = await import('../components/Modals.jsx')
const { todayISO } = await import('../lib/format.js')
const bucket = v => ({ n: 1, sum: v, min: v, max: v, last: v, avg: v })
const day = (d, f, n = 1) => ({ day: d, n, f })
@@ -84,7 +85,9 @@ describe('Salud', () => {
expect(text()).toContain('Functional Strength Training')
expect(text()).toContain('50 min')
expect(text()).toContain('318 kcal')
expect(api).toHaveBeenCalledWith('/api/vitals?days=30')
// "Today" is the default, and it still fetches a week: the headline number is the newest
// reading, but a trend needs history — see the note in the view.
expect(api).toHaveBeenCalledWith('/api/vitals?days=7')
})
it('paints each card with its family colour, which is what makes the grid scannable', async () => {
@@ -122,6 +125,37 @@ describe('Salud', () => {
})
})
describe('the Today filter', () => {
const docWithDays = days => ({
ok: true, days: 7, key: null, updatedAt: Date.now(), last: { ts: Date.now(), metrics: 2, points: 2, duplicates: 0, workouts: 0 },
metrics: days, workouts: []
})
const bucket = v => ({ n: 1, sum: v, min: v, max: v, last: v, avg: v })
const day = (d, f) => ({ day: d, n: 1, f, lastTs: Date.now() - 12 * 60000 })
it('shows only what came in today, and counts it', async () => {
const today = todayISO()
api.mockResolvedValue(docWithDays({
step_count: { units: 'count', days: [day(today, { qty: bucket(900) })] },
weight_body_mass: { units: 'kg', days: [day('2026-01-02', { qty: bucket(80) })] } // older
}))
await mount()
expect(cards().map(c => c.querySelector('.l').textContent)).toEqual(['Steps'])
// ...and the card says which day, plus how fresh it is — the whole point of the filter.
expect(text()).toContain('today')
expect(text()).toMatch(/12 min ago/)
})
it('falls back to everything, and says so, when today has nothing yet', async () => {
api.mockResolvedValue(docWithDays({
weight_body_mass: { units: 'kg', days: [day('2026-01-02', { qty: bucket(80) })] }
}))
await mount()
expect(cards().length).toBe(1)
expect(text()).toContain('Nothing has come in today yet')
})
})
/* The setup sheet is rendered from an element captured when it was opened (useUI.openSheet keeps
the JSX), so anything it reads off the screen's state is frozen at that moment. The first
version keyed the whole "2. The header" block off the screen's `key`, which meant clicking