Apple Health (Salud): a per-profile ingest endpoint, and a tab that draws it
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

An iOS automation in Health Auto Export POSTs Apple Health to /api/vitals/ingest,
and the new Salud tab (next to Plan) draws whatever arrived: steps, heart rate,
sleep, weight, oxygen, workouts and every other metric HAE can export, grouped into
cards with a trend, a sparkline and a 7/30/90/365-day range. Nothing on that screen
is an input, and the watch's workouts stay out of the history on purpose — they
carry no sets and no weights, so folding them into progression, PRs and the recovery
model would be inventing data.

The interesting part is duplicates. A five-minute automation re-sends overlapping
windows: with Date Range "Today", appending would count a day of steps again on
every run, and with "Since Last Sync", replacing would throw away everything but the
last five minutes. So the endpoint decides per payload instead. Datapoints that sit
on midnight are HAE's own day grouping, i.e. a *total*, and a day total replaces the
day it names — re-sending the same day all afternoon converges on that day's total.
Anything else is a real sample, identified by its instant plus its numbers and
stored once, which is right for overlapping and disjoint windows alike. Every sync
answers with a receipt (received / duplicates / stored), so a misconfigured
automation is visible rather than silent, and day keys come from the date the phone
wrote — never the server's clock, or every evening's steps would land on tomorrow.

Per profile and private by construction. Each profile mints its own ingest key
(Salud → ⚙), which is write-only: it can add to that one profile's health file and
cannot read a single number back, so a key leaking out of a phone is a nuisance
rather than a disclosure. It is its own credential, so rotating it disconnects a
phone without signing anybody out anywhere. The data lives in
data/vitals-<uid>.json, outside the synced state document, so a year of heart rate
never round-trips through localStorage on every device, and it is bounded on write:
400 days per metric, a 72 h dedupe ledger, the newest 300 workouts.

Two traps that only exist in production, both fixed here and both of which would
have shipped broken. api/Dockerfile copies the modules server.js imports by name,
and vitals.js was not on that list — a container that boots straight into
ERR_MODULE_NOT_FOUND. And the web container's nginx capped every /api body at 5 MB,
which a health export with Summarize Data off exceeds; that one route now gets the
API's own 32 MB while every other path keeps 5 MB, with the shared proxy settings
hoisted to server level so the two locations cannot drift apart.

Coverage: vitals.js (13 tests — overlapping, disjoint, day-grouped, raw, heart rate,
sleep, blood pressure, pruning, timezones), the routes against a real server (4 —
isolation between profiles, a key that cannot read, ten re-sends changing nothing),
the card model (18) and the screen (4). docs/HEALTH.md has the Health Auto Export
settings and the merge table; the five endpoints are in api/openapi.yaml under the
health tag, and website/api.html is rebuilt from it.
This commit is contained in:
dsantillan committed 2026-09-23 10:11:00 -04:00
1 parent 0819d03efb
commit 691e664d3f
22 files changed
+2897 -42

No files matched your search

+5
View File
@@ -30,6 +30,7 @@ import Plan from './views/Plan.jsx'
import RoutineEdit from './views/RoutineEdit.jsx'
import Workout from './views/Workout.jsx'
import Stats from './views/Stats.jsx'
import Health from './views/Health.jsx'
import History from './views/History.jsx'
import Library from './views/Library.jsx'
import Muscles from './views/Muscles.jsx'
@@ -159,6 +160,10 @@ function Shell() {
<Route path="/plan/r/:id" element={<RoutineEdit />} />
<Route path="/workout" element={<Workout />} />
<Route path="/stats" element={<Stats />} />
{/* Apple Health metrics the iPhone posts in (api/vitals.js). Read-only, and
per profile: the route is reachable by guest mode too, where it explains how to
connect rather than pretending there is data. */}
<Route path="/health" element={<Health />} />
<Route path="/history" element={<History />} />
<Route path="/library" element={<Library />} />
<Route path="/muscles" element={<Muscles />} />
+3 -1
View File
@@ -14,7 +14,6 @@ export default function TabBar({ onStart }) {
if (!user && !isGuest) return null
const cur = loc.pathname.split('/')[1] || 'home'
const on = k => cur === k || (cur === 'history' && k === 'stats') || (cur === 'settings' && k === 'home') || (cur === 'muscles' && k === 'library')
const startWorkout = () => {
if (!S.active) {
// A weekday can hold several routines; start the combined session if any of them has
@@ -33,6 +32,9 @@ export default function TabBar({ onStart }) {
<nav id="tabbar">
<Tab k="home" icon="house" to="/home" label={t('Home')} />
<Tab k="plan" icon="calendar" to="/plan" label={t('Plan')} />
{/* Apple Health. Next to Plan because both answer "what am I doing about my body", and
second in the bar (not last) because it is a place you go on purpose, not a drawer. */}
<Tab k="health" icon="heart" to="/health" label={t('Health')} />
{/* On the workout screen itself there is nothing to resume, so the button reads as the
tab it is and stays lit (#29); anywhere else it brings you back to the exercise you
were on — the marker is kept in S.active.cur and never moves on its own (#21). */}
+29
View File
@@ -1252,6 +1252,35 @@ body.chips-dragging *{cursor:inherit}
.tile .v{font-size:26px;font-weight:600;letter-spacing:-.026em;margin-top:5px;line-height:1.1}
.tile.tappable:active{background:var(--surface-2)}
/* --- Salud (Apple Health cards) --------------------------------------------
A health card is a tile with three more things in it: a unit, a trend arrow and a four-point
sparkline. The sparkline is what makes the grid readable at a glance — a bare "12,481" says
nothing about whether that is a good week — so it gets its own fixed-height box rather than
being allowed to stretch the card when a metric has only one day of data. */
.vh-card{width:100%;text-align:left;display:block;font:inherit;color:inherit;padding-bottom:10px}
.vh-unit{margin-left:4px;font-size:14px;font-weight:500;color:var(--label-2);letter-spacing:0}
.vh-trend{
float:right;display:inline-flex;align-items:center;gap:1px;
font-size:13px;font-weight:500;letter-spacing:0;
}
.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}
.vh-sheet-top{margin:2px 0 12px}
.vh-chart{padding:6px 4px 2px;margin-bottom:4px}
/* The endpoint and the header are long single tokens: wrap them instead of letting the row
scroll the whole sheet sideways. */
.vh-code{
flex:1;min-width:0;display:block;word-break:break-all;
font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px;line-height:1.45;
background:var(--surface-2);color:var(--label);border-radius:var(--r-sm);padding:7px 9px;
}
.vh-err{display:flex;flex-direction:column;align-items:flex-start;gap:4px;color:var(--orange)}
.vh-err .icn{font-size:16px}
.vh-empty{text-align:left}
.vh-empty .ico{font-size:30px;color:var(--acc);display:flex;justify-content:center;margin:4px 0 10px}
/* --- PR badge --- */
.pr{
display:inline-flex;align-items:center;gap:4px;
+10 -1
View File
@@ -26,6 +26,14 @@ const LABELS = {
'auth.pair.create': 'Created a pairing code',
'auth.pair.ok': 'Paired a phone',
'auth.pair.fail': 'Pairing failed',
// Apple Health (Salud): a phone syncing on its own, and the credential it uses. Filed under
// auth.* because that is what they are — a device coming online, and a key minted or retired
// for it — and because the first segment of an event name is also its filter category.
'auth.health.ingest': 'Apple Health sync failed',
'auth.health.ingest.first': 'Started syncing Apple Health',
'auth.health.key.create': 'Created a health ingest key',
'auth.health.key.rotate': 'Replaced the health ingest key',
'auth.health.clear': 'Deleted their health data',
'admin.user.disable': 'Disabled an account',
'admin.user.enable': 'Re-enabled an account',
'admin.user.delete': 'Deleted an account',
@@ -49,7 +57,8 @@ const REASONS = {
'invite-invalid': 'the invite code was used or revoked in the meantime',
'invite-rejected': 'wrong or already-used invite code',
'code-invalid': 'wrong or expired pairing code',
'user-unavailable': 'the profile behind the pairing code is disabled or gone'
'user-unavailable': 'the profile behind the pairing code is disabled or gone',
'bad-payload': 'the body was not a Health Auto Export JSON export'
}
export const auditReason = msg => REASONS[msg] || (msg ? String(msg) : '')
+355
View File
@@ -0,0 +1,355 @@
/* vitals-view.js — turn the stored health aggregates into the cards the Salud view renders.
*
* Everything here is a pure function of the document `GET /api/vitals` returns, which is why it
* is a lib and not inline in the view: the mapping from "what HAE calls a metric" to "what the
* card says" is the part that has to be right for a hundred metrics, and it is much easier to
* test than to click through.
*
* The server stores numbers per *field* without interpreting them (`f: { Avg: {min,sum,max,last} }`),
* on purpose: heart rate arrives as Min/Avg/Max, blood pressure as systolic/diastolic, sleep as
* asleep/inBed/core/deep/rem, and a metric that did not exist when this file was written arrives
* as whatever HAE decided to call it. The catalogue below is the only place that says which of
* 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'
/** 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']
const GROUP_LABEL = {
activity: 'Activity', heart: 'Heart', body: 'Body', sleep: 'Sleep', vitals: 'Vitals', other: 'Other'
}
const spec = (label, group, o = {}) => ({
label,
group,
// `field` is a candidate list because the same logical metric is spelled differently by HAE's
// own settings: an aggregated night is `asleep` (hours), a segmented one is `qty` per segment.
fields: [].concat(o.field || 'qty'),
agg: o.agg || 'sum',
unit: o.unit || '',
icon: o.icon || 'dot',
dec: o.dec == null ? 0 : o.dec,
better: o.better || null // 'down' for resting heart rate, 'up' for VO2 max, null = neutral
})
/* The catalogue. Names are HAE's snake_case metric keys as they appear in the JSON export
("Metric Name Format: All metric names use snake_case"). Unknown names are still shown —
humanized, in 'Other' — so an export of everything stays useful the day it arrives. */
export const METRICS = {
// — activity —
step_count: spec('Steps', 'activity', { unit: 'steps', icon: 'figureRun' }),
distance_walking_running: spec('Distance', 'activity', { unit: 'km', dec: 2, icon: 'figureRun' }),
walking_running_distance: spec('Distance', 'activity', { unit: 'km', dec: 2, icon: 'figureRun' }),
flights_climbed: spec('Flights climbed', 'activity', { unit: 'flights', icon: 'arrowUp' }),
apple_exercise_time: spec('Exercise time', 'activity', { unit: 'min', icon: 'timer' }),
apple_stand_time: spec('Stand time', 'activity', { unit: 'min', icon: 'clock' }),
apple_stand_hour: spec('Stand hours', 'activity', { unit: 'h', icon: 'clock' }),
active_energy: spec('Active energy', 'activity', { unit: 'kcal', icon: 'flame', better: 'up' }),
basal_energy_burned: spec('Resting energy', 'activity', { unit: 'kcal', icon: 'flame' }),
physical_effort: spec('Physical effort', 'activity', { unit: '', dec: 1, agg: 'avg', icon: 'bolt' }),
time_in_daylight: spec('Time in daylight', 'activity', { unit: 'min', icon: 'sun' }),
mindful_minutes: spec('Mindful minutes', 'activity', { unit: 'min', icon: 'moon' }),
// — heart —
heart_rate: spec('Heart rate', 'heart', { field: 'Avg', agg: 'avg', unit: 'bpm', icon: 'heart' }),
resting_heart_rate: spec('Resting heart rate', 'heart', { agg: 'avg', unit: 'bpm', icon: 'heart', better: 'down' }),
walking_heart_rate_average: spec('Walking heart rate', 'heart', { agg: 'avg', unit: 'bpm', icon: 'heart', better: 'down' }),
heart_rate_variability: spec('Heart rate variability', 'heart', { agg: 'avg', unit: 'ms', icon: 'bolt', better: 'up' }),
heart_rate_recovery_one_minute: spec('Heart rate recovery', 'heart', { agg: 'avg', unit: 'bpm', icon: 'reset', better: 'up' }),
vo2_max: spec('VO₂ max', 'heart', { dec: 1, icon: 'rocket', better: 'up' }),
cardio_recovery: spec('Cardio recovery', 'heart', { agg: 'avg', unit: 'bpm', icon: 'reset', better: 'up' }),
atrial_fibrillation_burden: spec('AFib burden', 'heart', { agg: 'avg', unit: '%', dec: 1, icon: 'warning', better: 'down' }),
// — body —
weight_body_mass: spec('Weight', 'body', { agg: 'last', unit: 'kg', dec: 1, icon: 'scale' }),
body_mass_index: spec('BMI', 'body', { agg: 'last', dec: 1, icon: 'scale' }),
body_fat_percentage: spec('Body fat', 'body', { agg: 'last', unit: '%', dec: 1, icon: 'scale', better: 'down' }),
lean_body_mass: spec('Lean mass', 'body', { agg: 'last', unit: 'kg', dec: 1, icon: 'arm' }),
waist_circumference: spec('Waist', 'body', { agg: 'last', unit: 'cm', dec: 1, icon: 'scale', better: 'down' }),
height: spec('Height', 'body', { agg: 'last', unit: 'cm', icon: 'person' }),
basal_body_temperature: spec('Basal temperature', 'body', { agg: 'last', unit: '°C', dec: 2, icon: 'flame' }),
apple_sleeping_wrist_temperature: spec('Wrist temperature', 'body', { agg: 'last', unit: '°C', dec: 2, icon: 'flame' }),
// — sleep — (`asleep` when HAE aggregates the night, `qty` when it sends the segments)
sleep_analysis: spec('Sleep', 'sleep', { field: ['asleep', 'qty'], unit: 'h', dec: 1, icon: 'moon' }),
sleep_rem: spec('REM sleep', 'sleep', { agg: 'last', unit: 'h', dec: 1, icon: 'moon' }),
sleep_core: spec('Core sleep', 'sleep', { agg: 'last', unit: 'h', dec: 1, icon: 'moon' }),
sleep_deep: spec('Deep sleep', 'sleep', { agg: 'last', unit: 'h', dec: 1, icon: 'moon' }),
// — vitals —
oxygen_saturation: spec('Blood oxygen', 'vitals', { agg: 'avg', unit: '%', dec: 0, icon: 'target', better: 'up' }),
respiratory_rate: spec('Respiratory rate', 'vitals', { agg: 'avg', unit: 'breaths/min', dec: 1, icon: 'bolt' }),
blood_pressure_systolic: spec('Blood pressure', 'vitals', { agg: 'last', unit: 'mmHg', icon: 'heart', better: 'down' }),
blood_pressure_diastolic: spec('Blood pressure (diastolic)', 'vitals', { agg: 'last', unit: 'mmHg', icon: 'heart', better: 'down' }),
body_temperature: spec('Body temperature', 'vitals', { agg: 'last', unit: '°C', dec: 2, icon: 'flame' }),
blood_glucose: spec('Blood glucose', 'vitals', { agg: 'last', unit: 'mg/dL', icon: 'target' }),
water: spec('Water', 'vitals', { unit: 'L', dec: 2, icon: 'download', better: 'up' }),
dietary_water: spec('Water', 'vitals', { unit: 'L', dec: 2, icon: 'download', better: 'up' }),
uv_exposure: spec('UV exposure', 'vitals', { dec: 1, icon: 'sun' }),
environmental_audio_exposure: spec('Ambient sound', 'vitals', { agg: 'avg', unit: 'dB', icon: 'bolt' }),
headphone_audio_exposure: spec('Headphone level', 'vitals', { agg: 'avg', unit: 'dB', icon: 'bolt', better: 'down' }),
walking_steadiness: spec('Walking steadiness', 'vitals', { agg: 'last', unit: '%', icon: 'figureRun', better: 'up' }),
walking_speed: spec('Walking speed', 'vitals', { agg: 'avg', unit: 'km/h', dec: 1, icon: 'figureRun', better: 'up' }),
walking_step_length: spec('Step length', 'vitals', { agg: 'avg', unit: 'cm', dec: 1, icon: 'figureRun' }),
walking_asymmetry_percentage: spec('Walking asymmetry', 'vitals', { agg: 'avg', unit: '%', dec: 1, icon: 'figureRun', better: 'down' }),
walking_double_support_percentage: spec('Double support', 'vitals', { agg: 'avg', unit: '%', dec: 1, icon: 'figureRun' }),
stair_speed_up: spec('Stair speed up', 'vitals', { agg: 'avg', icon: 'arrowUp' }),
stair_speed_down: spec('Stair speed down', 'vitals', { agg: 'avg', icon: 'arrowDown' })
}
const AGG = {
sum: f => f.sum,
avg: f => f.avg,
last: f => f.last,
min: f => f.min,
max: f => f.max
}
/** "walking_steadiness" → "Walking steadiness", for a metric the catalogue has never heard of. */
export function humanize(name) {
const s = String(name || '').replace(/_/g, ' ').trim()
return s ? s[0].toUpperCase() + s.slice(1) : ''
}
/** The catalogue entry for a metric name, with an honest fallback for anything unknown. */
export function specOf(name) {
if (METRICS[name]) return METRICS[name]
return { label: humanize(name), group: 'other', fields: null, agg: null, unit: '', icon: 'dot', dec: 1, better: null, unknown: true }
}
/**
* One day's number for one metric.
*
* A known metric uses its catalogue rule. An unknown one shows the field with the most samples
* that day — the number the watch actually measured most often — falling back to whichever field
* is there, so nothing is hidden just because nobody wrote a rule for it.
*/
export function valueOfDay(day, s) {
const f = (day && day.f) || {}
const keys = Object.keys(f)
if (!keys.length) return null
if (s.fields) {
const field = s.fields.find(k => f[k] && (AGG[s.agg] || AGG.sum)(f[k]) != null)
if (field) return (AGG[s.agg] || AGG.sum)(f[field])
}
if (s.unknown) {
const best = keys.slice().sort((a, b) => (f[b].n || 0) - (f[a].n || 0))[0]
return f[best].avg ?? f[best].last ?? f[best].sum ?? null
}
return null
}
/** How many days of samples a metric's series covers, for the "n days" captions. */
const pointsOf = series => series.reduce((n, p) => n + (p.n || 0), 0)
/**
* Every metric that has data, as a card.
*
* `delta` compares the newest day with the mean of the other days in the window, not with the day
* before it: one bad morning is not a trend, and a single-day comparison makes the arrow flip
* every time somebody sleeps badly. `trendDays` says how many days went into that mean, so the
* view can stay quiet on a card built from one day.
*/
export function metricCards(data, { days = 90 } = {}) {
const metrics = (data && data.metrics) || {}
const cards = []
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 }))
.filter(p => p.v != null && Number.isFinite(p.v))
if (!series.length) continue
const latest = series[series.length - 1]
const prior = series.slice(0, -1)
const mean = prior.length ? prior.reduce((a, p) => a + p.v, 0) / prior.length : null
cards.push({
name,
label: s.unknown ? s.label : t(s.label),
group: s.group,
unit: s.unit || (m && m.units) || '',
icon: s.icon,
dec: s.dec,
better: s.better,
unknown: !!s.unknown,
value: latest.v,
day: latest.day,
delta: mean != null && mean !== 0 ? (latest.v - mean) / Math.abs(mean) : null,
avg: mean,
trendDays: prior.length,
series,
total: series.reduce((a, p) => a + p.v, 0),
samples: pointsOf(series),
sources: (m && m.sources) || [],
days: series.length,
requestedDays: days
})
}
return 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) => {
const ga = GROUP_ORDER.indexOf(a.group), gb = GROUP_ORDER.indexOf(b.group)
if (ga !== gb) return ga - gb
const ra = rank.has(a.name) ? rank.get(a.name) : 1e6
const rb = rank.has(b.name) ? rank.get(b.name) : 1e6
if (ra !== rb) return ra - rb
return a.label.localeCompare(b.label)
})
}
/** Cards bucketed for rendering: only the groups that actually have something in them. */
export function groupedCards(cards) {
return GROUP_ORDER
.map(group => ({ group, label: t(GROUP_LABEL[group]), cards: cards.filter(c => c.group === group) }))
.filter(g => g.cards.length)
}
/** Which way the arrow should point, or null when the metric has no better direction. */
export function trendOf(card) {
if (!card || card.delta == null || card.trendDays < 1 || Math.abs(card.delta) < 0.005) return null
const dir = card.delta > 0 ? 'up' : 'down'
const good = card.better ? (card.better === dir ? 'good' : 'bad') : 'flat'
return { dir, good, pct: Math.abs(card.delta) }
}
/** A card's series shaped for LineChart: one point per day, x = that day's noon. */
export function chartPoints(card) {
return (card?.series || []).map(p => ({ t: Date.parse(p.day + 'T12:00:00'), y: p.v, d: p.day }))
}
/* ---------- units and numbers ---------- */
// HAE's unit strings are compact and sometimes need a human spelling. Values are never converted:
// what the watch measured is what is shown, so a card can never disagree with the Health app.
const UNIT_LABEL = {
count: '', 'count/min': 'bpm', bpm: 'bpm', hr: 'h', min: 'min', kcal: 'kcal', kJ: 'kJ',
kg: 'kg', lb: 'lb', km: 'km', mi: 'mi', m: 'm', cm: 'cm', '%': '%', degC: '°C', degF: '°F',
mmHg: 'mmHg', ms: 'ms', L: 'L', mL: 'mL', 'mg/dL': 'mg/dL', dB: 'dB', flights: 'flights'
}
export const unitLabel = u => (u && UNIT_LABEL[u] != null ? UNIT_LABEL[u] : (u || ''))
/** Numbers are formatted for reading, with the metric's own precision — not the weight setting. */
export function fmtValue(v, dec = 0) {
if (v == null || !Number.isFinite(v)) return '—'
const p = Math.pow(10, dec)
const n = Math.round(v * p) / p
return n.toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: dec })
}
/** A day's worth of gap since the last sample, for "last sync" captions. */
export function agoLabel(ts, now = Date.now()) {
if (!ts) return ''
const mins = Math.round((now - ts) / 60000)
if (mins < 2) return t('just now')
if (mins < 60) return t('{0} min ago', mins)
const hours = Math.round(mins / 60)
if (hours < 24) return t('{0} h ago', hours)
return t('{0} d ago', Math.round(hours / 24))
}
/* ---------- the fields behind a card ---------- */
const FIELD_LABEL = {
qty: 'Value', Avg: 'Average', Min: 'Minimum', Max: 'Maximum', sum: 'Total',
asleep: 'Asleep', inBed: 'In bed', awake: 'Awake',
// The sleep stages borrow the metric labels rather than a bare 'Core'/'REM': those keys already
// mean something else in the catalogue (the core muscle group), and a translation key cannot
// mean two things in two screens.
core: 'Core sleep', deep: 'Deep sleep', rem: 'REM sleep',
systolic: 'Systolic', diastolic: 'Diastolic', value: 'Value'
}
const fieldLabel = k => (FIELD_LABEL[k] ? t(FIELD_LABEL[k]) : humanize(k))
/**
* The detail rows for a card's newest day: every field the metric actually carried, with its
* aggregate for that day. This is what makes an unrecognised metric legible — the sheet shows the
* numbers HAE sent under the names HAE used, instead of a card that says "Other: 91".
*/
export function detailRows(card, day, m) {
const stored = ((m && m.days) || []).find(d => d.day === (day || card.day))
if (!stored) return []
const s = specOf(card.name)
const primary = s.fields ? s.fields.find(k => stored.f[k]) : null
return Object.entries(stored.f).map(([k, f]) => ({
key: k,
label: fieldLabel(k),
// The aggregate is per field: a counter's day is its total, a rate's is its average.
value: k === primary || s.unknown
? ((AGG[s.agg] || AGG.sum)(f) ?? f.last)
: f.avg,
agg: k === primary || s.unknown ? (s.agg || 'sum') : 'avg',
min: f.min, max: f.max, n: f.n,
unit: card.unit
}))
}
/* ---------- workouts ---------- */
// HAE names the activity the way Apple does, in Title Case and sometimes with a long tail.
export const workoutIcon = name => {
const n = String(name || '').toLowerCase()
if (/strength|weight|functional|core|hiit|cross/.test(n)) return 'dumbbell'
if (/run|walk|hik|sprint/.test(n)) return 'figureRun'
if (/cycl|bike|spin/.test(n)) return 'bike'
if (/swim/.test(n)) return 'swim'
if (/yoga|pilates|flexib|stretch|cooldown|mind/.test(n)) return 'stretch'
if (/box|kick|martial/.test(n)) return 'boxing'
if (/row|elliptical|stair|ski/.test(n)) return 'machine'
return 'bolt'
}
/**
* The read-only list of what the watch recorded, newest first.
*
* These are deliberately NOT the app's own sessions: they carry no sets, no weights and no reps,
* so folding them into the workout history would put entries into volume, PRs and the recovery
* model that nothing in them can support. They are shown here, next to the metrics they came with.
*/
export function workoutRows(data, { limit = 25 } = {}) {
return ((data && data.workouts) || []).slice(0, limit).map(w => {
const f = w.fields || {}
const energy = f.activeEnergy?.qty ?? f.totalEnergy?.qty ?? null
const units = f.activeEnergy?.units || f.totalEnergy?.units || 'kcal'
const dist = f.distance?.qty ?? null
const distUnits = f.distance?.units || 'km'
return {
key: `${w.name}|${w.start}`,
name: w.name,
icon: workoutIcon(w.name),
day: w.day,
date: fmtDate(w.day),
dur: w.durMin ? fmtDur(w.durMin * 60000) : '',
energy: energy != null ? `${fmtValue(energy, 0)} ${unitLabel(units)}` : '',
distance: dist != null ? `${fmtValue(dist, 2)} ${unitLabel(distUnits)}` : '',
avgHr: w.avgHr != null ? `${fmtValue(w.avgHr, 0)} bpm` : '',
maxHr: w.maxHr != null ? `${fmtValue(w.maxHr, 0)} bpm` : ''
}
})
}
/* ---------- whole-document helpers ---------- */
export const hasVitals = data => !!data && Object.keys(data.metrics || {}).length > 0
/** Which days in the window have anything at all — the strip at the top of the view. */
export function activeDays(data) {
const set = new Set()
for (const m of Object.values((data && data.metrics) || {})) for (const d of m.days || []) set.add(d.day)
return [...set].sort()
}
/**
* The ingest URL to paste into Health Auto Export. Absolute, because the phone is not the page:
* `appBase()` alone would be a path on a device that has never heard of this host.
*/
export function ingestUrl(loc = typeof location !== 'undefined' ? location : null) {
if (!loc) return '/api/vitals/ingest'
const path = (loc.pathname || '/')
const base = path.slice(0, path.lastIndexOf('/') + 1) || '/'
return `${loc.origin || ''}${base}api/vitals/ingest`.replace(/([^:]\/)\/+/g, '$1')
}
+206
View File
@@ -0,0 +1,206 @@
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
} from './vitals-view.js'
/* The mapping from HAE's metric names to what a card shows. Worth testing because it is the one
place that decides which number out of Min/Avg/Max a human sees, and because an export of
"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 bucket = v => ({ n: 1, sum: v, min: v, max: v, last: v, avg: v })
const doc = {
updatedAt: Date.parse('2026-05-04T10:00:00Z'),
last: { ts: Date.parse('2026-05-04T10:00:00Z'), metrics: 3, points: 3, duplicates: 0, workouts: 1 },
metrics: {
step_count: {
units: 'count', sources: ['Apple Watch'],
days: [day('2026-05-01', { qty: bucket(5000) }), day('2026-05-02', { qty: bucket(7000) }), day('2026-05-03', { qty: bucket(12000) })]
},
heart_rate: {
units: 'bpm',
days: [day('2026-05-03', {
Min: { n: 288, sum: 16000, min: 52, max: 62, last: 58, avg: 55.6 },
Avg: { n: 288, sum: 20000, min: 55, max: 96, last: 72, avg: 69.4 },
Max: { n: 288, sum: 26000, min: 80, max: 140, last: 120, avg: 90.3 }
})]
},
weight_body_mass: { units: 'kg', days: [day('2026-05-03', { qty: bucket(80.4) })] },
sleep_analysis: { units: 'hr', days: [day('2026-05-03', { asleep: bucket(7.4), deep: bucket(1.2) })] },
resting_heart_rate: { units: 'bpm', days: [day('2026-05-02', { qty: bucket(58) }), day('2026-05-03', { qty: bucket(52) })] },
some_new_metric: {
units: '%',
days: [day('2026-05-03', { qty: bucket(91), confidence: { n: 3, sum: 1.5, min: 0.4, max: 0.6, last: 0.5, avg: 0.5 } })]
}
},
workouts: [
{ name: 'Functional Strength Training', day: '2026-05-03', start: 1, end: 2, durMin: 45, avgHr: 128.4, maxHr: 172, fields: { activeEnergy: { qty: 320, units: 'kcal' }, distance: { qty: 3.25, units: 'km' } } },
{ name: 'Outdoor Walk', day: '2026-05-02', start: 0, end: 1, durMin: 30, avgHr: null, maxHr: null, fields: {} }
]
}
const card = (data, name) => metricCards(data).find(c => c.name === name)
describe('metricCards', () => {
it('reads the number its catalogue entry names, not the first one in the object', () => {
expect(card(doc, 'heart_rate').value).toBe(69.4) // the day's average, not Min or Max
expect(card(doc, 'heart_rate').unit).toBe('bpm')
expect(card(doc, 'step_count').value).toBe(12000) // the day's total
expect(card(doc, 'weight_body_mass').value).toBe(80.4) // the last reading
expect(card(doc, 'sleep_analysis').value).toBe(7.4) // hours asleep, not the deep stage
expect(card(doc, 'resting_heart_rate').value).toBe(52)
})
it('lands a segmented sleep payload on the same card as an aggregated one', () => {
// `asleep` for an aggregated night, `qty` per segment when HAE summarisation is off.
const segmented = { metrics: { sleep_analysis: { units: 'hr', days: [day('2026-05-03', { qty: { n: 6, sum: 7.1, min: 0.4, max: 2, last: 1.1, avg: 1.18 } })] } } }
expect(card(segmented, 'sleep_analysis').value).toBe(7.1)
})
it('humanizes an unknown metric, puts it in Other, and shows the field with the most samples', () => {
const c = card(doc, 'some_new_metric')
expect(c.label).toBe('Some new metric')
expect(c.group).toBe('other')
expect(c.value).toBe(0.5) // three samples of `confidence` beat one of `qty`
expect(c.unknown).toBe(true)
expect(c.name in METRICS).toBe(false)
expect(specOf('nope_not_a_metric').group).toBe('other')
expect(humanize('walking_steadiness')).toBe('Walking steadiness')
expect(humanize('')).toBe('')
})
it('does not render a card of dashes when the field a metric needs never appeared', () => {
const odd = { metrics: { blood_pressure_systolic: { units: 'mmHg', days: [day('2026-05-03', { diastolic: bucket(82) })] } } }
expect(valueOfDay(odd.metrics.blood_pressure_systolic.days[0], specOf('blood_pressure_systolic'))).toBeNull()
expect(metricCards(odd)).toEqual([])
expect(hasVitals({ metrics: {} })).toBe(false)
expect(hasVitals(doc)).toBe(true)
expect(hasVitals(null)).toBe(false)
})
it('is ordered by group, catalogue metrics before unknowns, and stable', () => {
const cards = metricCards(doc)
expect(cards.map(c => c.group)).toEqual(['activity', 'heart', 'heart', 'body', 'sleep', 'other'])
expect(groupedCards(cards).map(g => g.group)).toEqual(['activity', 'heart', 'body', 'sleep', 'other'])
expect(groupedCards(cards).map(g => g.cards.length)).toEqual([1, 2, 1, 1, 1])
expect(cards.filter(c => c.group === 'heart').map(c => c.name)).toEqual(['heart_rate', 'resting_heart_rate'])
expect(sortCards([{ name: 'b', label: 'B', group: 'other' }, { name: 'a', label: 'A', group: 'other' }]).map(c => c.label)).toEqual(['A', 'B'])
})
it('carries the days, samples and sources a card caption needs', () => {
const steps = card(doc, 'step_count')
expect(steps.days).toBe(3)
expect(steps.samples).toBe(3)
expect(steps.total).toBe(24000)
expect(steps.sources).toEqual(['Apple Watch'])
expect(steps.day).toBe('2026-05-03')
expect(steps.requestedDays).toBe(90)
})
})
describe('trendOf', () => {
it('compares the newest day with the average of the window', () => {
const steps = card(doc, 'step_count')
expect(steps.delta).toBeCloseTo(1, 10) // 12000 against a 6000 mean
expect(steps.trendDays).toBe(2)
expect(trendOf(steps)).toEqual({ dir: 'up', good: 'flat', pct: 1 }) // steps have no better way
})
it('knows which direction is the good one', () => {
expect(trendOf(card(doc, 'resting_heart_rate'))).toMatchObject({ dir: 'down', good: 'good' })
})
it('stays quiet with one day of data, or with a change under half a percent', () => {
const weight = card(doc, 'weight_body_mass')
expect(weight.delta).toBeNull()
expect(weight.trendDays).toBe(0)
expect(trendOf(weight)).toBeNull()
const flat = metricCards({ metrics: { step_count: { units: 'count', days: [day('2026-05-01', { qty: bucket(10000) }), day('2026-05-02', { qty: bucket(10020) })] } } })[0]
expect(trendOf(flat)).toBeNull()
})
})
describe('chartPoints', () => {
it('is one point per day at noon, which is what LineChart wants', () => {
const pts = chartPoints(card(doc, 'step_count'))
expect(pts.map(p => p.d)).toEqual(['2026-05-01', '2026-05-02', '2026-05-03'])
expect(pts.map(p => p.y)).toEqual([5000, 7000, 12000])
expect(pts[0].t).toBe(Date.parse('2026-05-01T12:00:00'))
expect(chartPoints(null)).toEqual([])
})
})
describe('detailRows', () => {
it('shows every field HAE sent, under the name HAE used', () => {
const rows = detailRows(card(doc, 'heart_rate'), undefined, doc.metrics.heart_rate)
expect(rows.map(r => r.key)).toEqual(['Min', 'Avg', 'Max'])
expect(rows.map(r => r.label)).toEqual(['Minimum', 'Average', 'Maximum'])
expect(rows.map(r => r.value)).toEqual([55.6, 69.4, 90.3])
expect(rows[1]).toMatchObject({ min: 55, max: 96, n: 288 })
expect(detailRows(card(doc, 'heart_rate'), undefined, { days: [] })).toEqual([])
})
it('labels a field nobody has a rule for from its own name', () => {
const rows = detailRows(card(doc, 'some_new_metric'), undefined, doc.metrics.some_new_metric)
expect(rows.map(r => r.label)).toEqual(['Value', 'Confidence'])
})
})
describe('workoutRows', () => {
it('carries duration, energy, distance and heart rate, with an icon per activity', () => {
const rows = workoutRows(doc)
expect(rows.length).toBe(2)
expect(rows[0]).toMatchObject({ name: 'Functional Strength Training', icon: 'dumbbell', dur: '45 min', energy: '320 kcal', distance: '3.25 km', avgHr: '128 bpm' })
expect(rows[1]).toMatchObject({ icon: 'figureRun', energy: '', avgHr: '' })
expect(workoutRows(doc, { limit: 1 }).length).toBe(1)
})
it('picks an icon from the activity name', () => {
expect(workoutIcon('Pool Swim')).toBe('swim')
expect(workoutIcon('Indoor Cycling')).toBe('bike')
expect(workoutIcon('Yoga')).toBe('stretch')
expect(workoutIcon('Outdoor Run')).toBe('figureRun')
expect(workoutIcon(undefined)).toBe('bolt')
})
})
describe('days, units and captions', () => {
it('lists every day that has anything, once, oldest first', () => {
expect(activeDays(doc)).toEqual(['2026-05-01', '2026-05-02', '2026-05-03'])
expect(activeDays(null)).toEqual([])
})
it('spells units for a human and keeps the metric\'s own precision', () => {
expect(unitLabel('count')).toBe('')
expect(unitLabel('count/min')).toBe('bpm')
expect(unitLabel('degC')).toBe('°C')
expect(unitLabel('somethingElse')).toBe('somethingElse')
expect(fmtValue(12000)).toBe((12000).toLocaleString(undefined, { maximumFractionDigits: 0 }))
expect(fmtValue(80.44, 1)).toBe('80.4')
expect(fmtValue(7.35, 1)).toBe('7.4')
expect(fmtValue(69.44, 0)).toBe('69')
expect(fmtValue(null)).toBe('—')
expect(fmtValue(NaN)).toBe('—')
})
it('reads the "last sync" caption like a person wrote it', () => {
const now = Date.parse('2026-05-04T10:00:00Z')
expect(agoLabel(now - 30000, now)).toBe('just now')
expect(agoLabel(now - 12 * 60000, now)).toBe('12 min ago')
expect(agoLabel(now - 5 * 3600000, now)).toBe('5 h ago')
expect(agoLabel(now - 3 * 86400000, now)).toBe('3 d ago')
expect(agoLabel(0, now)).toBe('')
})
it('builds an absolute ingest URL that survives a subpath deployment', () => {
expect(ingestUrl({ origin: 'https://gym.example.com', pathname: '/' })).toBe('https://gym.example.com/api/vitals/ingest')
expect(ingestUrl({ origin: 'https://example.com', pathname: '/gym/' })).toBe('https://example.com/gym/api/vitals/ingest')
// A deep link is index.html, never a directory: the base is everything up to the last slash.
expect(ingestUrl({ origin: 'https://example.com', pathname: '/gym/index.html' })).toBe('https://example.com/gym/api/vitals/ingest')
expect(ingestUrl({ origin: 'http://localhost:5173', pathname: '/health' })).toBe('http://localhost:5173/api/vitals/ingest')
})
})
+140
View File
@@ -1273,4 +1273,144 @@ export default {
'Try again': 'Reintentar',
'Start over': 'Empezar de nuevo',
'“{0}” added to your plan': '«{0}» añadida a tu plan',
/* ---------------------------------------------------------------- Salud --
Apple Health (Health Auto Export → /api/vitals/ingest). The metric, group and field labels
below are translated at render time from lib/vitals-view.js, where they live in a catalogue
rather than inside a t() call — a source-string scanner cannot see them, so this block is the
only place they exist and it has to be kept in step with METRICS by hand. */
// groups
'Activity': 'Actividad',
'Heart': 'Corazón',
'Body': 'Cuerpo',
'Sleep': 'Sueño',
'Vitals': 'Vitales',
// 'Other' already exists above (the muscle-balance "Other" group) and means the same thing.
// metrics
'Steps': 'Pasos',
'Distance': 'Distancia',
'Flights climbed': 'Pisos subidos',
'Exercise time': 'Tiempo de ejercicio',
'Stand time': 'Tiempo de pie',
'Stand hours': 'Horas de pie',
'Active energy': 'Energía activa',
'Resting energy': 'Energía en reposo',
'Physical effort': 'Esfuerzo físico',
'Time in daylight': 'Tiempo a la luz del día',
'Mindful minutes': 'Minutos de atención plena',
'Heart rate': 'Frecuencia cardíaca',
'Resting heart rate': 'Frecuencia en reposo',
'Walking heart rate': 'Frecuencia al caminar',
'Heart rate variability': 'Variabilidad cardíaca',
'Heart rate recovery': 'Recuperación cardíaca',
'VO₂ max': 'VO₂ máx',
'Cardio recovery': 'Recuperación cardiovascular',
'AFib burden': 'Carga de fibrilación auricular',
'Weight': 'Peso',
'BMI': 'IMC',
'Body fat': 'Grasa corporal',
'Lean mass': 'Masa magra',
'Waist': 'Cintura',
'Height': 'Altura',
'Basal temperature': 'Temperatura basal',
'Wrist temperature': 'Temperatura de muñeca',
'REM sleep': 'Sueño REM',
'Core sleep': 'Sueño central',
'Deep sleep': 'Sueño profundo',
'Blood oxygen': 'Oxígeno en sangre',
'Respiratory rate': 'Frecuencia respiratoria',
'Blood pressure': 'Presión arterial',
'Blood pressure (diastolic)': 'Presión arterial (diastólica)',
'Body temperature': 'Temperatura corporal',
'Blood glucose': 'Glucosa en sangre',
'Water': 'Agua',
'UV exposure': 'Exposición UV',
'Ambient sound': 'Ruido ambiental',
'Headphone level': 'Nivel de auriculares',
'Walking steadiness': 'Estabilidad al caminar',
'Walking speed': 'Velocidad al caminar',
'Step length': 'Longitud de zancada',
'Walking asymmetry': 'Asimetría al caminar',
'Double support': 'Apoyo doble',
'Stair speed up': 'Velocidad al subir escaleras',
'Stair speed down': 'Velocidad al bajar escaleras',
// the fields inside a metric's detail sheet
'Value': 'Valor',
'Average': 'Media',
'Minimum': 'Mínimo',
'Maximum': 'Máximo',
'Total': 'Total',
'Asleep': 'Dormido',
'In bed': 'En cama',
'Awake': 'Despierto',
// The sleep stages are named through their metric keys instead of bare 'Core'/'Deep'/'REM':
// 'Core' already means the core muscle group elsewhere in this file, and one key cannot mean
// two different things in two screens.
'Deep': 'Profundo',
'REM': 'REM',
'Systolic': 'Sistólica',
'Diastolic': 'Diastólica',
// the screen
'Health': 'Salud',
'From Apple Health on your iPhone': 'Desde Apple Health en tu iPhone',
'Last sync {0}': 'Última sincronización {0}',
'last sync {0}': 'última sincronización {0}',
'just now': 'hace un momento',
'{0} min ago': 'hace {0} min',
'{0} h ago': 'hace {0} h',
'{0} d ago': 'hace {0} d',
'Refresh': 'Actualizar',
'{0} metrics': '{0} métricas',
'Nothing in this range — try a wider one.': 'No hay nada en este rango: prueba con uno más amplio.',
'Workouts from your iPhone': 'Entrenamientos de tu iPhone',
'{0} avg': '{0} de media',
'Read-only on purpose: these carry no sets or weights, so they stay out of your progression, your PRs and the recovery model.': 'Solo lectura a propósito: no traen series ni pesos, así que quedan fuera de tu progresión, tus PRs y el modelo de recuperación.',
'vs your average': 'frente a tu media',
'What the watch sent': 'Lo que envió el reloj',
'{0} samples': '{0} muestras',
'{0} days with data in this range': '{0} días con datos en este rango',
// setup
'Connect Apple Health': 'Conectar Apple Health',
'{0} copied': '{0} copiado',
'Key': 'Clave',
'URL': 'URL',
'Close': 'Cerrar',
'Create an ingest key': 'Crear una clave de ingesta',
'1. The endpoint': '1. El endpoint',
'2. The header': '2. El encabezado',
'3. In Health Auto Export': '3. En Health Auto Export',
'Automation type': 'Tipo de automatización',
'REST API': 'REST API',
'Export format': 'Formato de exportación',
'Export version': 'Versión de exportación',
'Summarize data': 'Resumir datos',
'Time grouping': 'Agrupación temporal',
'Days': 'Días',
'Date range': 'Rango de fechas',
'Previous 7 Days': 'Últimos 7 días',
'Health Auto Export runs an automation on your iPhone and posts to this profile. The key below only works for your account, and only for this: it can add health data and cannot read anything back.': 'Health Auto Export ejecuta una automatización en tu iPhone y envía los datos a este perfil. La clave de aquí abajo solo funciona para tu cuenta y solo para esto: puede añadir datos de salud y no puede leer nada.',
'Grouping by days is what makes a five-minute cadence safe: each sync carries the day\'s total and replaces the previous one, so nothing is ever counted twice. Raw samples work too — they are de-duplicated instead.': 'Agrupar por días es lo que hace segura una cadencia de cinco minutos: cada envío trae el total del día y reemplaza al anterior, así que nada se cuenta dos veces. Las muestras crudas también funcionan: esas se deduplican.',
'Pick a cadence that suits you — every 5 minutes, hourly, or once a day all land the same way.': 'Elige la cadencia que te sirva: cada 5 minutos, cada hora o una vez al día llegan igual de bien.',
'Manage': 'Gestionar',
'Replace the key': 'Reemplazar la clave',
'The old one stops working immediately': 'La anterior deja de funcionar al instante',
'Delete the health data': 'Borrar los datos de salud',
'Keeps your workouts and your key': 'Conserva tus entrenamientos y tu clave',
'Replace the ingest key?': '¿Reemplazar la clave de ingesta?',
'Your iPhone stops syncing until you paste the new key into Health Auto Export. Nothing already stored is lost.': 'Tu iPhone deja de sincronizar hasta que pegues la nueva clave en Health Auto Export. No se pierde nada de lo ya guardado.',
// 'Replace' already exists above, with the same meaning.
'Delete the health data?': '¿Borrar los datos de salud?',
'Every metric and workout that came from your iPhone is removed for good. Your KuentaGYM workouts, your passes and your key are untouched.': 'Se eliminan para siempre todas las métricas y los entrenamientos que vinieron de tu iPhone. Tus entrenamientos de KuentaGYM, tus passkeys y tu clave quedan intactos.',
// empty state and toasts
'No health data yet': 'Todavía no hay datos de salud',
'Nothing here comes from this app: it comes from your iPhone. Set up the automation once and every metric you choose in Health Auto Export shows up on this screen — steps, heart rate, sleep, weight, oxygen, workouts and the rest.': 'Nada de esto lo genera esta app: viene de tu iPhone. Configura la automatización una vez y cada métrica que elijas en Health Auto Export aparecerá en esta pantalla: pasos, frecuencia cardíaca, sueño, peso, oxígeno, entrenamientos y lo demás.',
'Ingest key created': 'Clave de ingesta creada',
'New key created': 'Nueva clave creada',
'Health data deleted': 'Datos de salud borrados',
// the Settings row and the guest-mode explanation
'Apple Health (live sync)': 'Apple Health (sincronización en vivo)',
'Your iPhone posts steps, sleep, heart rate and the rest to your profile': 'Tu iPhone envía pasos, sueño, frecuencia cardíaca y lo demás a tu perfil',
'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',
}
+276
View File
@@ -0,0 +1,276 @@
/* Salud — what the watch recorded, as read-only cards.
*
* The data does not come from this app: an iOS automation (Health Auto Export) POSTs Apple Health
* to /api/vitals/ingest, per profile, and this screen draws whatever arrived. Two consequences
* shape everything below.
*
* Nothing here is an input. There is no editing, no goal to set, no weight to log — a card shows
* what the phone said and nothing else, because the moment this screen could write, it would be a
* second source of truth for the same numbers (and the body-weight log already lives in Stats).
*
* It renders what it is given. The catalogue in lib/vitals-view.js gives the ~50 metrics people
* actually track a label, a unit and the aggregate worth showing; anything else still becomes a
* card under Other, labelled from its own HAE name. So "export everything" is a usable screen on
* day one, and the next metric Apple ships does not need a code change to show up.
*/
import { useCallback, useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { api } from '../lib/api.js'
import { t } from '../lib/i18n.js'
import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
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 {
groupedCards, metricCards, trendOf, chartPoints, workoutRows, hasVitals,
fmtValue, unitLabel, agoLabel, ingestUrl, detailRows
} from '../lib/vitals-view.js'
const RANGES = [
{ value: 7, label: '7d' },
{ value: 30, label: '30d' },
{ value: 90, label: '90d' },
{ value: 365, label: '1a' }
]
/** A trend arrow: green when it moved the way the metric is supposed to move. */
function Trend({ card }) {
const tr = trendOf(card)
if (!tr) return null
const color = tr.good === 'good' ? 'var(--green)' : tr.good === 'bad' ? 'var(--orange)' : 'var(--label-3)'
return <span className="vh-trend" style={{ color }}>
<Icon name={tr.dir === 'up' ? 'arrowUp' : 'arrowDown'} />
{Math.round(tr.pct * 100)}%
</span>
}
/** One card. Everything is a button: the detail sheet is where the chart and the fields live. */
function MetricCard({ card, onOpen }) {
return <button className="tile tappable vh-card" onClick={() => onOpen(card)}>
<div className="l"><Icon name={card.icon} />{card.label}</div>
<div className="v">
{fmtValue(card.value, card.dec)}
{unitLabel(card.unit) ? <span className="vh-unit">{unitLabel(card.unit)}</span> : null}
<Trend card={card} />
</div>
{card.series.length > 1
? <div className="vh-spark"><LineChart points={chartPoints(card)} h={36} axes={false} /></div>
: <div className="vh-spark-ph" />}
</button>
}
/* ---------- the two sheets ---------- */
/**
* The detail sheet: the full chart, then every field HAE sent for the newest day. The second half
* is what makes an unknown metric legible — the numbers under the names HAE used, rather than a
* card that says "91" and nothing about what 91 was.
*/
function MetricSheet({ card, metric, close }) {
const rows = detailRows(card, undefined, metric)
const tr = trendOf(card)
return <>
<h3>{card.label}</h3>
<div className="vh-sheet-top">
<div className="stat-v" style={{ fontSize: 34 }}>
{fmtValue(card.value, card.dec)}
{unitLabel(card.unit) ? <span className="vh-unit">{unitLabel(card.unit)}</span> : null}
</div>
<div className="small dim">
{card.day}
{tr ? ` · ${tr.dir === 'up' ? '+' : '−'}${Math.round(tr.pct * 100)}% ${t('vs your average')}` : ''}
</div>
</div>
<div className="card vh-chart"><LineChart points={chartPoints(card)} h={160} unit={unitLabel(card.unit)} /></div>
{rows.length > 0 && <>
<h4 className="sec">{t('What the watch sent')}</h4>
<div className="list">{rows.map(r => <Row key={r.key} title={r.label}
subtitle={r.n > 1 ? t('{0} samples', r.n) : null}
value={fmtValue(r.value, r.value != null && Math.abs(r.value) < 100 ? 1 : 0) + (unitLabel(r.unit) ? ' ' + unitLabel(r.unit) : '')} />)}</div>
</>}
<div className="small dim" style={{ marginTop: 12 }}>
{t('{0} days with data in this range', card.days)}
{card.sources.length ? ' · ' + card.sources.join(', ') : ''}
</div>
<div style={{ height: 12 }} />
<Button onClick={close}>{t('Close')}</Button>
</>
}
/** Setup: the URL, the header, the settings in Health Auto Export that keep the numbers exact. */
function SetupSheet({ data, onKey, onRotate, onDelete, close }) {
const toast = useUI(s => s.toast)
const url = ingestUrl()
const copy = (text, label) => { navigator.clipboard?.writeText(text).catch(() => {}); toast(t('{0} copied', label)) }
return <>
<h3>{t('Connect Apple Health')}</h3>
<div className="small dim" style={{ lineHeight: 1.5, marginBottom: 14 }}>
{t('Health Auto Export runs an automation on your iPhone and posts to this profile. The key below only works for your account, and only for this: it can add health data and cannot read anything back.')}
</div>
<h4 className="sec">{t('1. The endpoint')}</h4>
<div className="cfgrow"><code className="vh-code">{url}</code>
<button className="iconbtn" onClick={() => copy(url, t('URL'))} aria-label={t('Copy')}><Icon name="clipboard" /></button></div>
<h4 className="sec">{t('2. The header')}</h4>
{data?.key
? <div className="cfgrow"><code className="vh-code">Authorization: Bearer {data.key}</code>
<button className="iconbtn" onClick={() => copy('Bearer ' + data.key, t('Key'))} aria-label={t('Copy')}><Icon name="clipboard" /></button></div>
: <Button variant="primary" icon="key" onClick={onKey}>{t('Create an ingest key')}</Button>}
<h4 className="sec">{t('3. In Health Auto Export')}</h4>
<div className="list">
<Row icon="upload" title={t('Automation type')} value={t('REST API')} />
<Row icon="calendar" title={t('Export format')} value="JSON" />
<Row icon="list" title={t('Export version')} value="2" />
<Row icon="check" title={t('Summarize data')} value={t('On')} />
<Row icon="clock" title={t('Time grouping')} value={t('Days')} />
<Row icon="history" title={t('Date range')} value={t('Previous 7 Days')} />
</div>
<div className="small dim" style={{ marginTop: 10, lineHeight: 1.5 }}>
{t('Grouping by days is what makes a five-minute cadence safe: each sync carries the day\'s total and replaces the previous one, so nothing is ever counted twice. Raw samples work too — they are de-duplicated instead.')}
</div>
<div className="small dim" style={{ marginTop: 8, lineHeight: 1.5 }}>
{t('Pick a cadence that suits you — every 5 minutes, hourly, or once a day all land the same way.')}
</div>
{data?.key && <>
<h4 className="sec">{t('Manage')}</h4>
<div className="list">
<Row icon="reset" title={t('Replace the key')} subtitle={t('The old one stops working immediately')} accessory="chevron" onClick={onRotate} />
<Row icon="trash" iconTint="var(--red)" title={t('Delete the health data')} subtitle={t('Keeps your workouts and your key')} onClick={onDelete} />
</div>
</>}
<div style={{ height: 12 }} />
<Button onClick={close}>{t('Close')}</Button>
</>
}
function Empty({ onSetup }) {
return <div className="card vh-empty">
<div className="ico"><Icon name="heart" /></div>
<h4 className="sec" style={{ marginTop: 6 }}>{t('No health data yet')}</h4>
<div className="small dim" style={{ lineHeight: 1.55, marginBottom: 14 }}>
{t('Nothing here comes from this app: it comes from your iPhone. Set up the automation once and every metric you choose in Health Auto Export shows up on this screen — steps, heart rate, sleep, weight, oxygen, workouts and the rest.')}
</div>
<Button variant="primary" icon="link" onClick={onSetup}>{t('Connect Apple Health')}</Button>
</div>
}
/* ---------- the view ---------- */
export default function Health() {
const nav = useNavigate()
const openSheet = useUI(s => s.openSheet)
const toast = useUI(s => s.toast)
const isGuest = useStore(s => s.isGuest())
const [data, setData] = useState(null)
const [err, setErr] = useState('')
const [days, setDays] = useState(30)
const [loading, setLoading] = useState(true)
const load = useCallback(() => {
setLoading(true)
api('/api/vitals?days=' + days)
.then(d => { setData(d); setErr('') })
.catch(e => setErr(e.message))
.finally(() => setLoading(false))
}, [days])
useEffect(() => { if (!isGuest) load() }, [load, isGuest])
const key = () => api('/api/vitals/key', { method: 'POST' })
.then(r => { setData(d => ({ ...d, key: r.key })); toast(t('Ingest key created')) })
.catch(e => toast(e.message))
const rotate = () => confirmSheet({
title: t('Replace the ingest key?'),
message: t('Your iPhone stops syncing until you paste the new key into Health Auto Export. Nothing already stored is lost.'),
confirmText: t('Replace'), danger: true,
onConfirm: () => api('/api/vitals/key/rotate', { method: 'POST' })
.then(r => { setData(d => ({ ...d, key: r.key })); toast(t('New key created')) })
.catch(e => toast(e.message))
})
const wipe = () => confirmSheet({
title: t('Delete the health data?'),
message: t('Every metric and workout that came from your iPhone is removed for good. Your KuentaGYM workouts, your passes and your key are untouched.'),
confirmText: t('Delete'), danger: true,
onConfirm: () => api('/api/vitals', { method: 'DELETE' })
.then(() => { load(); toast(t('Health data deleted')) })
.catch(e => toast(e.message))
})
const setup = () => openSheet(close => <SetupSheet data={data} onKey={key} onRotate={rotate} onDelete={wipe} close={close} />)
const openMetric = card => openSheet(close => <MetricSheet card={card} metric={data.metrics[card.name]} close={close} />)
/* Guest mode keeps everything in this browser and never talks to a server, so there is nothing
for a phone to post to. Saying so once is friendlier than a 401 the visitor cannot act on. */
if (isGuest) return <>
<div className="hdr"><div><h1>{t('Health')}</h1><div className="sub">{t('From Apple Health on your iPhone')}</div></div></div>
<div className="card vh-empty">
<div className="ico"><Icon name="heart" /></div>
<h4 className="sec" style={{ marginTop: 6 }}>{t('Apple Health needs a profile')}</h4>
<div className="small dim" style={{ lineHeight: 1.55, marginBottom: 14 }}>
{t('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.')}
</div>
<Button variant="primary" icon="person" onClick={() => nav('/settings')}>{t('Create a profile')}</Button>
</div>
</>
const cards = hasVitals(data) ? metricCards(data, { days }) : []
const groups = groupedCards(cards)
const workouts = workoutRows(data, { limit: 20 })
const last = data?.last?.ts
return <>
<div className="hdr">
<div style={{ flex: 1 }}>
<h1>{t('Health')}</h1>
<div className="sub">
{last ? t('Last sync {0}', agoLabel(last)) : t('From Apple Health on your iPhone')}
</div>
</div>
<button className="iconbtn" onClick={setup} aria-label={t('Connect Apple Health')}><Icon name="gear" /></button>
<button className="iconbtn" onClick={load} aria-label={t('Refresh')}><Icon name="reset" /></button>
</div>
{err && <div className="card vh-err"><Icon name="warning" /> {err}<div style={{ height: 8 }} />
<Button size="sm" onClick={load}>{t('Try again')}</Button></div>}
{!err && loading && !data && <div className="empty"><div className="ico"><Icon name="heart" /></div>{t('Loading…')}</div>}
{!err && data && !hasVitals(data) && <Empty onSetup={setup} />}
{!err && hasVitals(data) && <>
<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)) : ''}
</div>
{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>
</div>)}
{cards.length === 0 && <div className="small dim" style={{ margin: '0 2px 12px' }}>
{t('Nothing in this range — try a wider one.')}
</div>}
{workouts.length > 0 && <>
<h4 className="sec">{t('Workouts from your iPhone')}</h4>
<div className="list">
{workouts.map(w => <Row key={w.key} icon={w.icon} title={w.name}
subtitle={[w.date, w.dur, w.energy, w.distance].filter(Boolean).join(' · ')}
value={w.avgHr ? t('{0} avg', w.avgHr) : null} />)}
</div>
<div className="small dim" style={{ margin: '8px 2px 0', lineHeight: 1.5 }}>
{t('Read-only on purpose: these carry no sets or weights, so they stay out of your progression, your PRs and the recovery model.')}
</div>
</>}
<div style={{ height: 16 }} />
</>}
</>
}
+112
View File
@@ -0,0 +1,112 @@
// @vitest-environment happy-dom
/* Salud has one job: draw whatever the phone sent, and explain itself when nothing has arrived.
A render test rather than a click-through because the screen is almost entirely a function of
the document — the metric catalogue decides the label, the unit and which number is shown, and
the failures worth catching (a card that crashes on a metric nobody wrote a rule for, an empty
profile that renders as a blank screen instead of instead of the setup steps) are exactly the
ones a hand-test with the author's own data never reaches. */
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useStore } from '../store/useStore.js'
const api = vi.fn()
vi.mock('../lib/api.js', () => ({ api: (...args) => api(...args) }))
vi.mock('react-router-dom', () => ({ useNavigate: () => vi.fn() }))
vi.mock('../sheets.jsx', () => ({ confirmSheet: vi.fn() }))
const { default: Health } = await import('./Health.jsx')
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 })
const VITALS = {
ok: true,
days: 30,
key: 'kghealth_TESTKEY',
updatedAt: Date.parse('2026-09-03T22:00:00Z'),
last: { ts: Date.parse('2026-09-03T22:00:00Z'), metrics: 4, points: 9, duplicates: 288, workouts: 1 },
metrics: {
step_count: { units: 'count', sources: ['Apple Watch'], days: [day('2026-09-01', { qty: bucket(9000) }), day('2026-09-02', { qty: bucket(11000) }), day('2026-09-03', { qty: bucket(12481) })] },
heart_rate: { units: 'bpm', sources: ['Apple Watch'], days: [day('2026-09-03', { Avg: { n: 288, sum: 20000, min: 54, max: 96, last: 72, avg: 69.4 } })] },
sleep_analysis: { units: 'hr', sources: ['Apple Watch'], days: [day('2026-09-03', { asleep: bucket(7.4), deep: bucket(1.2) })] },
walking_steadiness: { units: '%', sources: ['iPhone'], days: [day('2026-09-03', { qty: bucket(91) })] },
// A metric the catalogue has never heard of: it must still become a card, in Other, under a
// humanised name — "export everything" is the point of the feature.
some_metric_from_the_future: { units: 'ms', sources: ['Apple Watch'], days: [day('2026-09-03', { qty: { n: 4, sum: 480, min: 100, max: 140, last: 130, avg: 120 } })] }
},
workouts: [
{ name: 'Functional Strength Training', day: '2026-09-03', start: 1, end: 2, durMin: 50, avgHr: 134.5, maxHr: 168, fields: { activeEnergy: { qty: 318, units: 'kcal' } } }
]
}
let host, root
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host)
api.mockReset()
localStorage.removeItem('gym_guest')
useStore.setState({ user: { id: 'u1', name: 'Test' } })
})
afterEach(() => { act(() => root.unmount()); host.remove() })
const mount = async () => {
await act(async () => { root.render(<Health />) })
await act(async () => {}) // let the fetch's promise settle
}
const text = () => host.textContent
const cards = () => [...host.querySelectorAll('.vh-card')]
describe('Salud', () => {
it('draws one card per metric, grouped, with the number the catalogue says to show', async () => {
api.mockResolvedValue(VITALS)
await mount()
expect(cards().length).toBe(5)
const labels = cards().map(c => c.querySelector('.l').textContent)
expect(labels).toEqual(['Steps', 'Heart rate', 'Sleep', 'Walking steadiness', 'Some metric from the future'])
// Steps show the day's total, heart rate the day's average, sleep hours asleep. The unknown
// metric falls back to the field with the most samples (its average), rather than a dash.
expect(cards()[0].querySelector('.v').textContent).toContain('12,481')
expect(cards()[1].querySelector('.v').textContent).toContain('69')
expect(cards()[1].querySelector('.v').textContent).toContain('bpm')
expect(cards()[2].querySelector('.v').textContent).toContain('7.4')
expect(cards()[3].querySelector('.v').textContent).toContain('91')
expect(cards()[4].querySelector('.v').textContent).toContain('120')
// Group headings, the range control, and the read-only workout list.
expect(text()).toContain('Activity')
expect(text()).toContain('Heart')
expect(text()).toContain('Vitals')
expect(text()).toContain('Other')
expect(text()).toContain('Workouts from your iPhone')
expect(text()).toContain('Functional Strength Training')
expect(text()).toContain('50 min')
expect(text()).toContain('318 kcal')
expect(api).toHaveBeenCalledWith('/api/vitals?days=30')
})
it('offers the setup steps instead of a blank screen when nothing has arrived', async () => {
api.mockResolvedValue({ ok: true, days: 30, key: null, updatedAt: 0, last: null, metrics: {}, workouts: [] })
await mount()
expect(cards().length).toBe(0)
expect(text()).toContain('No health data yet')
expect(text()).toContain('Connect Apple Health')
})
it('says a guest needs a profile rather than showing a 401 it cannot act on', async () => {
localStorage.setItem('gym_guest', '1')
useStore.setState({ user: null })
await mount()
expect(text()).toContain('Apple Health needs a profile')
expect(api).not.toHaveBeenCalled()
})
it('shows the error with a retry instead of pretending there is no data', async () => {
api.mockRejectedValue(new Error('HTTP 500'))
await mount()
expect(text()).toContain('HTTP 500')
expect(text()).toContain('Try again')
expect(text()).not.toContain('No health data yet')
})
})
+5
View File
@@ -383,6 +383,11 @@ export default function Settings() {
{/* ---------- data: fill it, bring things over, back it up, wipe it ---------- */}
<Section title={t('Data')}>
{/* Above the file imports on purpose: this one keeps working after today, while the rows
below it are one-shot reads of an export. */}
<Row icon="heart" iconTint="var(--red)" title={t('Apple Health (live sync)')}
subtitle={t('Your iPhone posts steps, sleep, heart rate and the rest to your profile')}
accessory="chevron" onClick={() => nav('/health')} />
<Row icon="sparkles" iconTint="var(--acc)" title={t('Load starter plan')} accessory="chevron" onClick={starterPlanSheet} />
<Row icon="shuffle" iconTint="var(--teal)" title={t('Import from another app')}
subtitle={t('FitNotes, Strong, Hevy — or body weight from Apple Health')}