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
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:
1 parent
3b7c9011c4
commit
c3c1c2836c
15 files changed
+374
-27
No files matched your search
@@ -21,3 +21,9 @@ node_modules
|
||||
junit.xml
|
||||
coverage/
|
||||
frontend/bundle-size.json
|
||||
|
||||
# The launch-screen photograph, 12 MB straight off a camera. The two versions the app ships are
|
||||
# derived from it by frontend/scripts/build-app-icons.mjs and ARE committed (public/splash.webp for
|
||||
# the web, resources/splash.jpg for the native shells), so a clone builds and runs without it — only
|
||||
# regenerating the splash needs the original, which the script says out loud when it is missing.
|
||||
assets/splash.jpg
|
||||
@@ -94,6 +94,10 @@ would catch is a change nothing checks here.
|
||||
Settings, Admin, Login, RoutineEdit), routed by `react-router-dom` from `App.jsx`.
|
||||
- **`components/`** — shared UI (charts, modals, timers); `instr/` holds per-language exercise
|
||||
instruction text; `locales/` is the i18n string catalogue (`lib/i18n.js` / `i18n-core.js`).
|
||||
- **The aura and the splash** — `index.html` carries three decorative layers (the "Diamond Weave"
|
||||
gradient) that blend against the `body` background, so the base colour lives on `body` in
|
||||
`index.css` and `#app` sits above them at `z-index: 1`. The launch photo is derived from
|
||||
`assets/splash.jpg` by `frontend/scripts/build-app-icons.mjs` (which also writes every icon).
|
||||
- Mobile: `@capacitor/*` wraps the same web build into native shells under `frontend/android` and
|
||||
`frontend/ios` (see `docs/MOBILE.md`); `mobile.js` in `lib/` gates native-only behavior (file
|
||||
persistence, local notifications, wake lock) behind a `MOBILE` flag.
|
||||
|
||||
@@ -82,6 +82,12 @@ That writes `resources/icon.png` plus the three the web app serves: `public/icon
|
||||
and favicon) and `public/logo.png` (transparent, for the tab bar's Start button, the login screen
|
||||
and the boot placeholder). Change `ICON_BG` in that script to re-skin all of them at once.
|
||||
|
||||
The launch screen comes from the same place: `assets/splash.jpg` (the photograph, deliberately
|
||||
not committed — 12 MB off a camera) is what `scripts/build-app-icons.mjs` turns into
|
||||
`public/splash.webp` for the web boot screen and `resources/splash.jpg` (2732×2732, on the aura's
|
||||
base colour, fitted rather than cropped) for `@capacitor/assets`. Drop a replacement at that path
|
||||
and the script regenerates both; without it, it says so and skips them.
|
||||
|
||||
Then generate the platform assets from it:
|
||||
|
||||
```sh
|
||||
|
||||
@@ -18,6 +18,20 @@
|
||||
<link rel="icon" type="image/png" href="icon-180.png">
|
||||
</head>
|
||||
<body>
|
||||
<!-- "Diamond Weave" aura — the atmosphere behind every screen.
|
||||
Three stacked layers, two of them blurred and composited with mix-blend-mode against the BODY
|
||||
background, which is why this container must never carry a background-color of its own: the
|
||||
layers would blend against that instead of the page and the effect washes out. The base colour
|
||||
lives on body in index.css (warm near-black in the dark theme; the usual light background in
|
||||
the light theme, where the layers switch to `multiply` for the same reason).
|
||||
It lives here rather than in React so it exists before the app boots — the splash has
|
||||
something to sit on — and costs no render. Every layer is decorative: aria-hidden here, and
|
||||
pointer-events:none in the CSS so it can never eat a tap. -->
|
||||
<div class="aura" aria-hidden="true">
|
||||
<div class="aura-layer-1"></div>
|
||||
<div class="aura-layer-2"></div>
|
||||
<div class="aura-layer-3"></div>
|
||||
</div>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.jsx"></script>
|
||||
</body>
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
"scope": "./",
|
||||
"display": "standalone",
|
||||
"orientation": "portrait",
|
||||
"background_color": "#0c0e12",
|
||||
"theme_color": "#0c0e12",
|
||||
"background_color": "#100e0b",
|
||||
"theme_color": "#100e0b",
|
||||
"icons": [
|
||||
{ "src": "icon-180.png", "sizes": "180x180", "type": "image/png", "purpose": "any" },
|
||||
{ "src": "icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any maskable" }
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 62 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 637 KiB |
@@ -20,16 +20,25 @@
|
||||
* and the icon reads as one piece at 180 px. Change ICON_BG to re-skin all of them at once.
|
||||
*/
|
||||
import sharp from 'sharp'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
// sharp takes paths, not file: URLs — hence fileURLToPath here and in icon() below.
|
||||
const SRC = fileURLToPath(new URL('../../assets/logoym.png', import.meta.url))
|
||||
/** The launch photo. 3862×5786 and 12 MB straight off a camera — every version the app ships is
|
||||
* derived here, because none of them can be that file. */
|
||||
const SPLASH_SRC = fileURLToPath(new URL('../../assets/splash.jpg', import.meta.url))
|
||||
// The photograph itself is NOT committed: it is 12 MB straight off a camera, and the two versions
|
||||
// the app uses are a fraction of that (see the bottom of this file). Keep the original next to the
|
||||
// repo, or drop a replacement at the same path, and this regenerates from it.
|
||||
const splashMissing = !existsSync(SPLASH_SRC)
|
||||
const PUB = new URL('../public/', import.meta.url)
|
||||
const RES = new URL('../resources/', import.meta.url)
|
||||
|
||||
/** The emblem's own dominant colour (sampled from the source), used to fill the icon squares. */
|
||||
const ICON_BG = '#031808'
|
||||
/** Behind the native splash, the aura's own base colour (index.css) so the two never disagree. */
|
||||
const SPLASH_BG = '#100e0b'
|
||||
/** Fraction of the canvas the emblem occupies. The maskable safe circle is 80% of the square, and
|
||||
* the emblem's own corners are transparent, so slightly past it costs nothing and gains size. */
|
||||
const ICON_FIT = 0.88
|
||||
@@ -72,3 +81,39 @@ console.log(` public/logo.png transparent ${(mark.length / 1024).toFixed(1)}
|
||||
// The Capacitor source icon for the native shells (docs/MOBILE.md: `npx @capacitor/assets
|
||||
// generate` reads resources/). Kept opaque and 1024 wide, which is what that tool wants.
|
||||
await icon(1024, new URL('icon.png', RES))
|
||||
|
||||
/* ---------------------------------------------------------------- the launch screen --
|
||||
*
|
||||
* assets/splash.jpg is a photograph — 3862×5786, 12 MB — so nothing ships it as it is. Two
|
||||
* versions come out of it:
|
||||
*
|
||||
* public/splash.webp what the web app shows while the profile loads (`.boot-splash` in
|
||||
* index.css). Phone-width and WebP, because it is a photograph: the same
|
||||
* frame as a JPEG at matching quality is several times the bytes.
|
||||
* resources/splash.png the @capacitor/assets source for the native shells. That tool wants a
|
||||
* square, so the photo is fitted inside 2732×2732 on the dark base colour
|
||||
* rather than cropped — a portrait photograph cropped to a square loses
|
||||
* the composition somebody chose.
|
||||
*/
|
||||
const SPLASH_W = 1170 // covers a 390pt phone at 3× without shipping a poster
|
||||
if (!splashMissing) {
|
||||
await sharp(SPLASH_SRC)
|
||||
.resize(SPLASH_W, null, { fit: 'inside', withoutEnlargement: true })
|
||||
.webp({ quality: 78, effort: 5 })
|
||||
.toFile(fileURLToPath(new URL('splash.webp', PUB)))
|
||||
const splashOut = readFileSync(fileURLToPath(new URL('splash.webp', PUB)))
|
||||
console.log(` public/splash.webp launch screen ${(splashOut.length / 1024).toFixed(0)} KB`)
|
||||
}
|
||||
|
||||
if (splashMissing) {
|
||||
console.log(' assets/splash.jpg is not here — skipping the launch screen (it is not committed)')
|
||||
} else {
|
||||
const splashInner = await sharp(SPLASH_SRC).resize(2732, 2732, { fit: 'inside' }).toBuffer()
|
||||
// JPEG, not PNG: this is a photograph, and as a PNG it came out at 10.6 MB for no visible gain.
|
||||
await sharp({ create: { width: 2732, height: 2732, channels: 3, background: SPLASH_BG } })
|
||||
.composite([{ input: splashInner, gravity: 'centre' }])
|
||||
.jpeg({ quality: 86, chromaSubsampling: '4:4:4' })
|
||||
.toFile(fileURLToPath(new URL('splash.jpg', RES)))
|
||||
const nativeOut = readFileSync(fileURLToPath(new URL('splash.jpg', RES)))
|
||||
console.log(` resources/splash.jpg native source 2732x2732 bg ${SPLASH_BG} ${(nativeOut.length / 1024 / 1024).toFixed(1)} MB`)
|
||||
}
|
||||
@@ -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
@@ -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}
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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}',
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user