5 Commits

Author SHA1 Message Date
marcus
6b0b93ea4b Add Jarvis Today dashboard, habit cards and chat placeholder 2026-11-25 00:06:58 -08:00
marcus
694e180855 New app icon: live heartbeat trace
Some checks failed
Build & Release APK / build (push) Has been cancelled
Replaces the outlined-ECG-over-a-heart icon with a bold heartbeat trace in
the dashboard's blue → violet → pink gradient. It fades in from the left
and ends in a glowing "now" dot, like the live point on a chart, over the
app's near-black with a violet glow. The Android foreground is sized to the
66dp safe circle, the themed (monochrome) glyph is solid and a little
smaller, and the adaptive background is now the gradient.

assets/icon-src/make.py (resvg + magick) regenerates every size from one
definition; glyph.svg is replaced by foreground/background/splash.svg.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:45:47 -08:00
marcus
65bf540ea0 Replace Basic-auth login with an API token set in Settings
Some checks failed
Build & Release APK / build (push) Has been cancelled
The app no longer shows a login screen. It opens straight to the Today
screen, which shows nothing until a bearer API token is saved in the new
Settings screen. The token is verified against health-meta.json before it
is stored in the keychain, and can be removed from the same screen.

Server side: health-auth accepts Authorization: Bearer <HEALTH_APP_TOKEN>
(read + write for the Fitbit sync, but not admin-only /life/* paths).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-19 23:07:00 -08:00
81632a4275 Fix: Fitbit screen showed no data after a successful sync
All checks were successful
Build & Release APK / build (push) Successful in 2m4s
load() caches by endpoint for the session, so the post-sync refresh
re-served the pre-sync (empty) summary. Sync now invalidates the
fitbit cache keys — the watermark before reading, summary+latest after
uploading — so the refetch actually hits the server.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-08 00:03:17 -07:00
c48212bfff Fitbit Air: Health Connect sync + vitals dashboard
All checks were successful
Build & Release APK / build (push) Successful in 2m5s
- react-native-health-connect (config plugin, minSdk 26, 11 read perms)
- sync-on-open + manual sync: incremental via server watermark, chunked
  POST to /api/health/v1/fitbit/sync (HR, resting HR, HRV, SpO2, resp
  rate, steps/distance/kcal/floors dailies, staged sleep sessions)
- Fitbit screen: steps/RHR/HRV/SpO2 tiles + daily charts + sleep list +
  per-stream record counts (answers the which-types-does-Google-Health-
  share question empirically)
- Sleep tab now merges Fitbit Air nights (wins over older sources)
- Today screen Fitbit card

Server side (deployed separately on VPS): hc_samples/hc_daily/hc_sleep
tables + sync/latest/summary endpoints in health-api; Caddy routes POST
/api/health/v1/fitbit/* behind the same basic_auth.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-07 22:25:07 -07:00
34 changed files with 2130 additions and 407 deletions

View File

@@ -4,7 +4,7 @@ Cross-platform (iOS + Android) Expo app — native front end for the private
health dashboard at **https://health.rehbock.xyz**.
The app is a pure client: all data lives on the server and is fetched live over
HTTPS with HTTP Basic auth. Nothing is stored on the device except the auth
HTTPS with a bearer API token. Nothing is stored on the device except the auth
token (in the platform keychain via `expo-secure-store`).
## Screens
@@ -30,7 +30,10 @@ npm install
npx expo start # scan the QR with Expo Go (iOS or Android)
```
Log in with the same Basic-auth credentials as the website.
There is no login screen. Open **Settings** (⚙️ on the Today screen) and paste the API token;
without one the app has no data. The server accepts it via `HEALTH_APP_TOKEN` in
`health-auth` (`~/personal/health-auth/.env` on the VPS, passed through `docker-compose.yml`).
Rotate it by changing that value and running `docker compose up -d`.
## Android release APK

View File

@@ -6,7 +6,7 @@
"orientation": "portrait",
"icon": "./assets/images/icon.png",
"scheme": "healthapp",
"userInterfaceStyle": "dark",
"userInterfaceStyle": "automatic",
"backgroundColor": "#0d0d0f",
"ios": {
"icon": "./assets/images/icon.png",
@@ -15,6 +15,19 @@
},
"android": {
"package": "xyz.rehbock.health",
"permissions": [
"android.permission.health.READ_HEART_RATE",
"android.permission.health.READ_RESTING_HEART_RATE",
"android.permission.health.READ_HEART_RATE_VARIABILITY",
"android.permission.health.READ_OXYGEN_SATURATION",
"android.permission.health.READ_SLEEP",
"android.permission.health.READ_STEPS",
"android.permission.health.READ_RESPIRATORY_RATE",
"android.permission.health.READ_DISTANCE",
"android.permission.health.READ_ACTIVE_CALORIES_BURNED",
"android.permission.health.READ_TOTAL_CALORIES_BURNED",
"android.permission.health.READ_FLOORS_CLIMBED"
],
"adaptiveIcon": {
"backgroundColor": "#0d0d0f",
"foregroundImage": "./assets/images/android-icon-foreground.png",
@@ -30,6 +43,15 @@
"plugins": [
"expo-router",
"expo-secure-store",
"react-native-health-connect",
[
"expo-build-properties",
{
"android": {
"minSdkVersion": 26
}
}
],
"./plugins/with-release-signing.js",
[
"expo-splash-screen",
@@ -38,7 +60,8 @@
"image": "./assets/images/splash-icon.png",
"imageWidth": 76
}
]
],
"expo-dev-client"
],
"experiments": {
"typedRoutes": true,

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024"><defs><radialGradient id="hb" cx="50%" cy="44%" r="72%"><stop offset="0" stop-color="#1d1a33"/><stop offset="1" stop-color="#0b0b0e"/></radialGradient></defs><rect width="1024" height="1024" fill="url(#hb)"/></svg>

After

Width:  |  Height:  |  Size: 306 B

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024"><defs><linearGradient id="pl" gradientUnits="userSpaceOnUse" x1="205.1" y1="0" x2="711.9" y2="0"><stop offset="0" stop-color="#3fc8f2"/><stop offset="0.5" stop-color="#7c6cf7"/><stop offset="1" stop-color="#f06bc0"/></linearGradient><linearGradient id="fadeg" gradientUnits="userSpaceOnUse" x1="205.1" y1="0" x2="329.0" y2="0"><stop offset="0" stop-color="#fff" stop-opacity="0.05"/><stop offset="1" stop-color="#fff"/></linearGradient><mask id="fm" maskUnits="userSpaceOnUse" x="0" y="0" width="1024" height="1024"><rect width="1024" height="1024" fill="url(#fadeg)"/></mask><filter id="bl" x="-50%" y="-50%" width="200%" height="200%"><feGaussianBlur stdDeviation="32.5"/></filter><filter id="bl2" x="-100%" y="-100%" width="300%" height="300%"><feGaussianBlur stdDeviation="53.2"/></filter><radialGradient id="dot"><stop offset="0" stop-color="#ffffff"/><stop offset="0.55" stop-color="#ffe6f4"/><stop offset="1" stop-color="#f06bc0"/></radialGradient></defs><g mask="url(#fm)" filter="url(#bl)" opacity="0.75"><path d="M205.1 530.9 L329.0 530.9 L368.4 490.7 L402.2 530.9 L430.3 530.9 L481.0 294.4 L537.3 724.9 L582.4 483.6 L610.6 530.9 L711.9 530.9" fill="none" stroke="url(#pl)" stroke-width="59.1" stroke-linecap="round" stroke-linejoin="round"/></g><circle cx="711.9" cy="530.9" r="112.4" fill="#f06bc0" opacity="0.55" filter="url(#bl2)"/><g mask="url(#fm)"><path d="M205.1 530.9 L329.0 530.9 L368.4 490.7 L402.2 530.9 L430.3 530.9 L481.0 294.4 L537.3 724.9 L582.4 483.6 L610.6 530.9 L711.9 530.9" fill="none" stroke="url(#pl)" stroke-width="59.1" stroke-linecap="round" stroke-linejoin="round"/></g><circle cx="711.9" cy="530.9" r="79.8" fill="none" stroke="#f06bc0" stroke-opacity="0.35" stroke-width="13.0"/><circle cx="711.9" cy="530.9" r="54.4" fill="url(#dot)"/></svg>

After

Width:  |  Height:  |  Size: 1.8 KiB

View File

@@ -1,25 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024">
<defs>
<linearGradient id="heart" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#8a86ff"/>
<stop offset="100%" stop-color="#5b57d6"/>
</linearGradient>
</defs>
<!-- glyph only, transparent bg, scaled into the adaptive-icon safe zone -->
<g transform="translate(512 512) scale(0.62) translate(-512 -512)">
<path d="M512 812
C 402 726, 232 616, 210 462
C 196 360, 268 268, 372 268
C 436 268, 486 304, 512 356
C 538 304, 588 268, 652 268
C 756 268, 828 360, 814 462
C 792 616, 622 726, 512 812 Z"
fill="url(#heart)"/>
<polyline points="60,520 330,520 385,520 425,414 478,626 528,368 576,556 608,520 964,520"
fill="none" stroke="#0d0d0f" stroke-width="58"
stroke-linecap="round" stroke-linejoin="round"/>
<polyline points="60,520 330,520 385,520 425,414 478,626 528,368 576,556 608,520 964,520"
fill="none" stroke="#ffffff" stroke-width="26"
stroke-linecap="round" stroke-linejoin="round"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 1.1 KiB

View File

@@ -1,32 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024">
<defs>
<radialGradient id="bg" cx="50%" cy="38%" r="75%">
<stop offset="0%" stop-color="#1e1e26"/>
<stop offset="100%" stop-color="#0d0d0f"/>
</radialGradient>
<linearGradient id="heart" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#8a86ff"/>
<stop offset="100%" stop-color="#5b57d6"/>
</linearGradient>
</defs>
<rect width="1024" height="1024" fill="url(#bg)"/>
<!-- heart -->
<path d="M512 812
C 402 726, 232 616, 210 462
C 196 360, 268 268, 372 268
C 436 268, 486 304, 512 356
C 538 304, 588 268, 652 268
C 756 268, 828 360, 814 462
C 792 616, 622 726, 512 812 Z"
fill="url(#heart)"/>
<!-- ECG pulse across the heart -->
<polyline points="120,520 330,520 385,520 425,414 478,626 528,368 576,556 608,520 904,520"
fill="none" stroke="#0d0d0f" stroke-width="58"
stroke-linecap="round" stroke-linejoin="round"/>
<polyline points="120,520 330,520 385,520 425,414 478,626 528,368 576,556 608,520 904,520"
fill="none" stroke="#ffffff" stroke-width="26"
stroke-linecap="round" stroke-linejoin="round"/>
</svg>
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024"><defs><radialGradient id="hb" cx="50%" cy="44%" r="72%"><stop offset="0" stop-color="#1d1a33"/><stop offset="1" stop-color="#0b0b0e"/></radialGradient><linearGradient id="pl" gradientUnits="userSpaceOnUse" x1="122.9" y1="0" x2="823.3" y2="0"><stop offset="0" stop-color="#3fc8f2"/><stop offset="0.5" stop-color="#7c6cf7"/><stop offset="1" stop-color="#f06bc0"/></linearGradient><linearGradient id="fadeg" gradientUnits="userSpaceOnUse" x1="122.9" y1="0" x2="294.1" y2="0"><stop offset="0" stop-color="#fff" stop-opacity="0.05"/><stop offset="1" stop-color="#fff"/></linearGradient><mask id="fm" maskUnits="userSpaceOnUse" x="0" y="0" width="1024" height="1024"><rect width="1024" height="1024" fill="url(#fadeg)"/></mask><filter id="bl" x="-50%" y="-50%" width="200%" height="200%"><feGaussianBlur stdDeviation="44.9"/></filter><filter id="bl2" x="-100%" y="-100%" width="300%" height="300%"><feGaussianBlur stdDeviation="73.5"/></filter><radialGradient id="dot"><stop offset="0" stop-color="#ffffff"/><stop offset="0.55" stop-color="#ffe6f4"/><stop offset="1" stop-color="#f06bc0"/></radialGradient></defs><rect width="1024" height="1024" fill="url(#hb)"/><g mask="url(#fm)" filter="url(#bl)" opacity="0.75"><path d="M122.9 538.1 L294.1 538.1 L348.6 482.6 L395.3 538.1 L434.2 538.1 L504.2 211.3 L582.0 806.2 L644.3 472.8 L683.2 538.1 L823.3 538.1" fill="none" stroke="url(#pl)" stroke-width="81.7" stroke-linecap="round" stroke-linejoin="round"/></g><circle cx="823.3" cy="538.1" r="155.3" fill="#f06bc0" opacity="0.55" filter="url(#bl2)"/><g mask="url(#fm)"><path d="M122.9 538.1 L294.1 538.1 L348.6 482.6 L395.3 538.1 L434.2 538.1 L504.2 211.3 L582.0 806.2 L644.3 472.8 L683.2 538.1 L823.3 538.1" fill="none" stroke="url(#pl)" stroke-width="81.7" stroke-linecap="round" stroke-linejoin="round"/></g><circle cx="823.3" cy="538.1" r="126.7" fill="none" stroke="#f06bc0" stroke-opacity="0.35" stroke-width="18.0"/><circle cx="823.3" cy="538.1" r="75.2" fill="url(#dot)"/></svg>

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 2.0 KiB

116
assets/icon-src/make.py Normal file
View File

@@ -0,0 +1,116 @@
#!/usr/bin/env python3
"""Generate the Health app icon set from one mark: a live heartbeat trace.
python3 assets/icon-src/make.py # needs `resvg` and `magick` (Homebrew)
The mark is a bold ECG trace in the dashboard's blue → violet → pink gradient
that fades in from the left and ends in a glowing "now" dot, like the live
point on a chart. The background is the app's near-black (#0d0d0f) with a
violet glow.
Writes the SVG sources next to this file and the PNGs into assets/images/:
icon.png 1024 opaque (iOS + fallback)
android-icon-background.png 1024 opaque (adaptive background)
android-icon-foreground.png 1024 alpha (adaptive foreground, inside the 66dp safe zone)
android-icon-monochrome.png 1024 alpha (themed icon, white glyph)
splash-icon.png 512 alpha (splash, glyph only)
favicon.png 64 opaque (web)
"""
import os
import subprocess
HERE = os.path.dirname(os.path.abspath(__file__))
IMAGES = os.path.join(HERE, '..', 'images')
BG_CENTER, BG_EDGE = '#1d1a33', '#0b0b0e'
TRACE = [(0, '#3fc8f2'), (0.5, '#7c6cf7'), (1, '#f06bc0')] # blue → accent violet → pink
# x in 0..1 across the glyph, y in -1..1 (negative = up)
PULSE = [(0.00, 0), (0.22, 0), (0.29, -0.17), (0.35, 0.0), (0.40, 0),
(0.49, -1.0), (0.59, 0.82), (0.67, -0.20), (0.72, 0), (0.90, 0)]
def svg(size, body, defs=''):
return (f'<svg xmlns="http://www.w3.org/2000/svg" width="{size}" height="{size}" '
f'viewBox="0 0 {size} {size}"><defs>{defs}</defs>{body}</svg>\n')
def background(size):
defs = (f'<radialGradient id="hb" cx="50%" cy="44%" r="72%">'
f'<stop offset="0" stop-color="{BG_CENTER}"/><stop offset="1" stop-color="{BG_EDGE}"/></radialGradient>')
return defs, f'<rect width="{size}" height="{size}" fill="url(#hb)"/>'
def pulse(size, scale, mono=False, glow=True, shift=0.0, halo=1.55):
"""scale = glyph width as a fraction of the canvas."""
w = size * scale
amp, stroke = w * 0.42, w * 0.105
c = size / 2
left = c - shift * w - w / 2
pts = [(left + x * w, c + amp * 0.08 + y * amp) for x, y in PULSE]
if mono: # no fade in a single colour: start the trace later instead
pts = [(left + 0.12 * w, pts[0][1])] + pts[2:]
d = 'M' + ' L'.join(f'{x:.1f} {y:.1f}' for x, y in pts)
ex, ey = pts[-1]
line = (f'<path d="{d}" fill="none" stroke="{{s}}" stroke-width="{stroke:.1f}" '
f'stroke-linecap="round" stroke-linejoin="round"/>')
if mono:
return '', line.format(s='#fff') + f'<circle cx="{ex:.1f}" cy="{ey:.1f}" r="{stroke * 0.95:.1f}" fill="#fff"/>'
stops = ''.join(f'<stop offset="{p}" stop-color="{col}"/>' for p, col in TRACE)
defs = (f'<linearGradient id="pl" gradientUnits="userSpaceOnUse" x1="{left:.1f}" y1="0" x2="{ex:.1f}" y2="0">{stops}</linearGradient>'
f'<linearGradient id="fadeg" gradientUnits="userSpaceOnUse" x1="{left:.1f}" y1="0" x2="{left + w * 0.22:.1f}" y2="0">'
f'<stop offset="0" stop-color="#fff" stop-opacity="0.05"/><stop offset="1" stop-color="#fff"/></linearGradient>'
f'<mask id="fm" maskUnits="userSpaceOnUse" x="0" y="0" width="{size}" height="{size}">'
f'<rect width="{size}" height="{size}" fill="url(#fadeg)"/></mask>'
f'<filter id="bl" x="-50%" y="-50%" width="200%" height="200%"><feGaussianBlur stdDeviation="{stroke * 0.55:.1f}"/></filter>'
f'<filter id="bl2" x="-100%" y="-100%" width="300%" height="300%"><feGaussianBlur stdDeviation="{stroke * 0.9:.1f}"/></filter>'
f'<radialGradient id="dot"><stop offset="0" stop-color="#ffffff"/><stop offset="0.55" stop-color="#ffe6f4"/>'
f'<stop offset="1" stop-color="{TRACE[-1][1]}"/></radialGradient>')
trace = line.format(s='url(#pl)')
body = ''
if glow:
body += f'<g mask="url(#fm)" filter="url(#bl)" opacity="0.75">{trace}</g>'
body += f'<circle cx="{ex:.1f}" cy="{ey:.1f}" r="{stroke * 1.9:.1f}" fill="{TRACE[-1][1]}" opacity="0.55" filter="url(#bl2)"/>'
body += f'<g mask="url(#fm)">{trace}</g>'
body += (f'<circle cx="{ex:.1f}" cy="{ey:.1f}" r="{stroke * halo:.1f}" fill="none" stroke="{TRACE[-1][1]}" '
f'stroke-opacity="0.35" stroke-width="{stroke * 0.22:.1f}"/>')
body += f'<circle cx="{ex:.1f}" cy="{ey:.1f}" r="{stroke * 0.92:.1f}" fill="url(#dot)"/>'
return defs, body
def main():
bd, bb = background(1024)
# iOS: full-bleed, glyph spans 76% (Apple rounds the corners itself)
gd, gb = pulse(1024, 0.76)
sources = {
'icon': (1024, svg(1024, bb + gb, bd + gd)),
'background': (1024, svg(1024, bb, bd)),
# Android adaptive: shifted left (the trace fades in) so the dot + halo clear the 66dp safe circle
'foreground': (1024, svg(1024, *reversed(pulse(1024, 0.55, shift=0.045, halo=1.35)))),
# themed icons read best a little smaller than the colour glyph
'monochrome': (1024, svg(1024, *reversed(pulse(1024, 0.46, mono=True, glow=False, shift=0.045)))),
'splash': (512, svg(512, *reversed(pulse(512, 0.94, glow=False)))),
}
out = {
'icon': 'icon.png', 'background': 'android-icon-background.png',
'foreground': 'android-icon-foreground.png', 'monochrome': 'android-icon-monochrome.png',
'splash': 'splash-icon.png',
}
for name, (size, text) in sources.items():
src = os.path.join(HERE, f'{name}.svg')
with open(src, 'w') as f:
f.write(text)
png = os.path.join(IMAGES, out[name])
subprocess.run(['resvg', '-w', str(size), '-h', str(size), src, png], check=True)
# iOS rejects icons with an alpha channel; the web favicon is the icon at 64px
icon = os.path.join(IMAGES, 'icon.png')
subprocess.run(['magick', icon, '-background', BG_EDGE, '-alpha', 'remove', '-alpha', 'off', icon], check=True)
bgp = os.path.join(IMAGES, 'android-icon-background.png')
subprocess.run(['magick', bgp, '-alpha', 'off', bgp], check=True)
subprocess.run(['magick', icon, '-resize', '64x64', os.path.join(IMAGES, 'favicon.png')], check=True)
print('wrote', ', '.join(out.values()), 'favicon.png')
if __name__ == '__main__':
main()

View File

@@ -1,21 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024">
<defs>
<mask id="cut">
<rect width="1024" height="1024" fill="white"/>
<polyline points="60,520 330,520 385,520 425,414 478,626 528,368 576,556 608,520 964,520"
fill="none" stroke="black" stroke-width="58"
stroke-linecap="round" stroke-linejoin="round"/>
</mask>
</defs>
<!-- single-silhouette version: heart with the ECG line cut out (launcher tints it) -->
<g transform="translate(512 512) scale(0.62) translate(-512 -512)">
<path d="M512 812
C 402 726, 232 616, 210 462
C 196 360, 268 268, 372 268
C 436 268, 486 304, 512 356
C 538 304, 588 268, 652 268
C 756 268, 828 360, 814 462
C 792 616, 622 726, 512 812 Z"
fill="#ffffff" mask="url(#cut)"/>
</g>
</svg>
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024"><defs></defs><path d="M311.8 527.8 L391.9 494.2 L420.1 527.8 L443.7 527.8 L486.1 330.0 L533.2 690.1 L570.9 488.3 L594.4 527.8 L679.2 527.8" fill="none" stroke="#fff" stroke-width="49.5" stroke-linecap="round" stroke-linejoin="round"/><circle cx="679.2" cy="527.8" r="47.0" fill="#fff"/></svg>

Before

Width:  |  Height:  |  Size: 881 B

After

Width:  |  Height:  |  Size: 384 B

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512"><defs><linearGradient id="pl" gradientUnits="userSpaceOnUse" x1="15.4" y1="0" x2="448.5" y2="0"><stop offset="0" stop-color="#3fc8f2"/><stop offset="0.5" stop-color="#7c6cf7"/><stop offset="1" stop-color="#f06bc0"/></linearGradient><linearGradient id="fadeg" gradientUnits="userSpaceOnUse" x1="15.4" y1="0" x2="121.2" y2="0"><stop offset="0" stop-color="#fff" stop-opacity="0.05"/><stop offset="1" stop-color="#fff"/></linearGradient><mask id="fm" maskUnits="userSpaceOnUse" x="0" y="0" width="512" height="512"><rect width="512" height="512" fill="url(#fadeg)"/></mask><filter id="bl" x="-50%" y="-50%" width="200%" height="200%"><feGaussianBlur stdDeviation="27.8"/></filter><filter id="bl2" x="-100%" y="-100%" width="300%" height="300%"><feGaussianBlur stdDeviation="45.5"/></filter><radialGradient id="dot"><stop offset="0" stop-color="#ffffff"/><stop offset="0.55" stop-color="#ffe6f4"/><stop offset="1" stop-color="#f06bc0"/></radialGradient></defs><g mask="url(#fm)"><path d="M15.4 272.2 L121.2 272.2 L154.9 237.8 L183.8 272.2 L207.9 272.2 L251.2 70.0 L299.3 437.9 L337.8 231.7 L361.9 272.2 L448.5 272.2" fill="none" stroke="url(#pl)" stroke-width="50.5" stroke-linecap="round" stroke-linejoin="round"/></g><circle cx="448.5" cy="272.2" r="78.3" fill="none" stroke="#f06bc0" stroke-opacity="0.35" stroke-width="11.1"/><circle cx="448.5" cy="272.2" r="46.5" fill="url(#dot)"/></svg>

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 451 B

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

After

Width:  |  Height:  |  Size: 249 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 KiB

After

Width:  |  Height:  |  Size: 245 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 21 KiB

195
package-lock.json generated
View File

@@ -8,9 +8,11 @@
"name": "health-app",
"version": "1.0.0",
"dependencies": {
"@expo-google-fonts/figtree": "^0.4.1",
"@expo/ui": "~57.0.9",
"expo": "~57.0.11",
"expo-constants": "~57.0.9",
"expo-dev-client": "~57.0.22",
"expo-device": "~57.0.1",
"expo-font": "~57.0.1",
"expo-glass-effect": "~57.0.1",
@@ -27,6 +29,8 @@
"react-dom": "19.2.3",
"react-native": "0.86.2",
"react-native-gesture-handler": "~2.32.0",
"react-native-health-connect": "^4.1.3",
"react-native-keyboard-controller": "1.21.9",
"react-native-reanimated": "4.5.1",
"react-native-safe-area-context": "~5.7.0",
"react-native-screens": "~4.26.0",
@@ -36,6 +40,7 @@
},
"devDependencies": {
"@types/react": "~19.2.2",
"expo-build-properties": "^57.0.9",
"typescript": "~6.0.3"
}
},
@@ -73,7 +78,6 @@
"resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz",
"integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/code-frame": "^7.29.7",
"@babel/generator": "^7.29.7",
@@ -958,6 +962,7 @@
"resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.29.7.tgz",
"integrity": "sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw==",
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/helper-plugin-utils": "^7.29.7"
},
@@ -973,6 +978,7 @@
"resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.29.7.tgz",
"integrity": "sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q==",
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/helper-plugin-utils": "^7.29.7"
},
@@ -1004,6 +1010,7 @@
"resolved": "https://registry.npmjs.org/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-7.29.8.tgz",
"integrity": "sha512-0UpIXPtdDtMXfnV2OJAVMLpj3H/92vmkA6lpSRakmycJvj3VUy6Xs1dM8tXRugupykr5WB+LpiVl0J8LMVg2mg==",
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/helper-plugin-utils": "^7.29.7"
},
@@ -1193,6 +1200,12 @@
"node": ">=0.8.0"
}
},
"node_modules/@expo-google-fonts/figtree": {
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/@expo-google-fonts/figtree/-/figtree-0.4.1.tgz",
"integrity": "sha512-6IQQddGeR3yZBSwiIjy2kd1gA+5s2esF8JAFw6M1qqU4RUlj4Zxkw9J+gixAtZFgd+QIS875EPHqeYlpaRcCRw==",
"license": "MIT AND OFL-1.1"
},
"node_modules/@expo-google-fonts/material-symbols": {
"version": "0.4.42",
"resolved": "https://registry.npmjs.org/@expo-google-fonts/material-symbols/-/material-symbols-0.4.42.tgz",
@@ -1582,9 +1595,9 @@
}
},
"node_modules/@expo/schema-utils": {
"version": "57.0.2",
"resolved": "https://registry.npmjs.org/@expo/schema-utils/-/schema-utils-57.0.2.tgz",
"integrity": "sha512-fMu/jyN0l1Wzv7XkeWR4IYCx1M8ryui3FdBNGrWwbRgJ7EhxXxK8E2jxP2W3pbgUwUY0V3hG8+GyfCZwny+Lxw==",
"version": "57.0.3",
"resolved": "https://registry.npmjs.org/@expo/schema-utils/-/schema-utils-57.0.3.tgz",
"integrity": "sha512-HcxLkgZbutEjhMVqOPw+MsSjQSqLLG6KtdjbNltms5AN7LibbGe32ae8TRnjeRcelE0+dGOdjdby8seGAO01IQ==",
"license": "MIT"
},
"node_modules/@expo/sdk-runtime-versions": {
@@ -2217,6 +2230,7 @@
"resolved": "https://registry.npmjs.org/@react-native/babel-preset/-/babel-preset-0.86.2.tgz",
"integrity": "sha512-4XKEJ6jKW9lXMB1O5o47gBoGgolde1fbX13gLW/erlcn+1ky+MHHo5UjuM3RWGdPJHIvIzekDDumSUHhB9x5iQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/core": "^7.25.2",
"@babel/plugin-proposal-export-default-from": "^7.24.7",
@@ -2379,6 +2393,7 @@
"resolved": "https://registry.npmjs.org/@react-native/metro-babel-transformer/-/metro-babel-transformer-0.86.2.tgz",
"integrity": "sha512-mX1wgLErdb2hDgXJr9zM9SWLe+ZteZTFTwRWGOQ53yEJwc9DVSnxdTlAtVdMeOj2ntycKh0R8jYdat2Am43cwQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/core": "^7.25.2",
"@react-native/babel-preset": "0.86.2",
@@ -2397,6 +2412,7 @@
"resolved": "https://registry.npmjs.org/@react-native/metro-config/-/metro-config-0.86.2.tgz",
"integrity": "sha512-hJno256j+MS0b3JD1aD3ouTGZVacKNVBuXL2atMQQ8BZ060vl1ptnZ83y569aDW+/rgFSOcqn6ydKeSz4uUKQQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@react-native/js-polyfills": "0.86.2",
"@react-native/metro-babel-transformer": "0.86.2",
@@ -2447,6 +2463,7 @@
"resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.1.tgz",
"integrity": "sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==",
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/code-frame": "^7.10.4",
"@babel/runtime": "^7.12.5",
@@ -2466,6 +2483,7 @@
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz",
"integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=10"
},
@@ -2478,6 +2496,7 @@
"resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz",
"integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"ansi-regex": "^5.0.1",
"ansi-styles": "^5.0.0",
@@ -2491,7 +2510,8 @@
"version": "17.0.2",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
"integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
"license": "MIT"
"license": "MIT",
"peer": true
},
"node_modules/@testing-library/jest-dom": {
"version": "6.9.1",
@@ -2535,7 +2555,8 @@
"version": "5.0.4",
"resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz",
"integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==",
"license": "MIT"
"license": "MIT",
"peer": true
},
"node_modules/@types/hammerjs": {
"version": "2.0.46",
@@ -2581,7 +2602,6 @@
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.18.tgz",
"integrity": "sha512-AnzbBERsrLKtk2XSfTbYRLjQPdy116Sty4q+T+Bp3IC4l6jNBvreVPAHmpq9qhXQM7CXZPjLVmGMw9sy+hxQ3w==",
"license": "MIT",
"peer": true,
"dependencies": {
"csstype": "^3.2.2"
}
@@ -3047,7 +3067,6 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"baseline-browser-mapping": "^2.10.44",
"caniuse-lite": "^1.0.30001806",
@@ -3574,7 +3593,8 @@
"version": "0.5.16",
"resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz",
"integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==",
"license": "MIT"
"license": "MIT",
"peer": true
},
"node_modules/dom-serializer": {
"version": "2.0.0",
@@ -3738,7 +3758,6 @@
"resolved": "https://registry.npmjs.org/expo/-/expo-57.0.11.tgz",
"integrity": "sha512-R97257N39Dw0kQFuI4/RvYx95GQ+dmePdo8hxcMOjDxAT4VcCckjILJeAWCE19Jxjb92hZ5NDXAfDPkkV1RB9w==",
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/runtime": "^7.20.0",
"@expo/cli": "^57.0.13",
@@ -3811,12 +3830,26 @@
"react-native": "*"
}
},
"node_modules/expo-build-properties": {
"version": "57.0.9",
"resolved": "https://registry.npmjs.org/expo-build-properties/-/expo-build-properties-57.0.9.tgz",
"integrity": "sha512-IX8Nz85yNDZyqBK7zbLEfn4ijMGaF6TmLjCY2KE0UKltUoV78DhgN6ksPZbDbPDvqLpU2fMY/5OD4CbYB7hHwg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@expo/schema-utils": "^57.0.2",
"resolve-from": "^5.0.0",
"semver": "^7.6.0"
},
"peerDependencies": {
"expo": "*"
}
},
"node_modules/expo-constants": {
"version": "57.0.9",
"resolved": "https://registry.npmjs.org/expo-constants/-/expo-constants-57.0.9.tgz",
"integrity": "sha512-Y47sGiF+U8fwicUSPdJPjB27PuU+FgLK4Mpai0ksZF5hv8jNN3HBqKuDNxsiu70uHBKf80TaR4gwMPh0pmETiQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@expo/env": "~2.4.2"
},
@@ -3825,6 +3858,59 @@
"react-native": "*"
}
},
"node_modules/expo-dev-client": {
"version": "57.0.22",
"resolved": "https://registry.npmjs.org/expo-dev-client/-/expo-dev-client-57.0.22.tgz",
"integrity": "sha512-h2D8crZoeD2Re2vMvmDrb1u1DQusfU/kqHYVPxTFxAt0H6J6OpPvR/O+1arXfthtTkQUbRNFkXPFLLrRZ+ds7Q==",
"license": "MIT",
"dependencies": {
"expo-dev-launcher": "~57.0.23",
"expo-dev-menu": "~57.0.22",
"expo-dev-menu-interface": "~57.0.0",
"expo-manifests": "~57.0.2",
"expo-updates-interface": "~57.0.2"
},
"peerDependencies": {
"expo": "*"
}
},
"node_modules/expo-dev-launcher": {
"version": "57.0.23",
"resolved": "https://registry.npmjs.org/expo-dev-launcher/-/expo-dev-launcher-57.0.23.tgz",
"integrity": "sha512-0G4LHr4+zvqGgIoiAsSLgJbPMggOT8eJ+bcN5t/bZXZMvFH8uu4yCoMHAGNZ1jkPH7Ia2hkqW30Zh5QMwQ/AwA==",
"license": "MIT",
"dependencies": {
"@expo/schema-utils": "^57.0.3",
"expo-dev-menu": "~57.0.22",
"expo-manifests": "~57.0.2"
},
"peerDependencies": {
"expo": "*",
"react-native": "*"
}
},
"node_modules/expo-dev-menu": {
"version": "57.0.22",
"resolved": "https://registry.npmjs.org/expo-dev-menu/-/expo-dev-menu-57.0.22.tgz",
"integrity": "sha512-G8QRNDLhb2CYsBNoS2FIrId8SWYdxlYk+BLEwodJFMnCbz31quLP50DHEcEtMjYuc3/szTnCoaQY8BFNrBAUzA==",
"license": "MIT",
"dependencies": {
"expo-dev-menu-interface": "~57.0.0"
},
"peerDependencies": {
"expo": "*",
"react-native": "*"
}
},
"node_modules/expo-dev-menu-interface": {
"version": "57.0.0",
"resolved": "https://registry.npmjs.org/expo-dev-menu-interface/-/expo-dev-menu-interface-57.0.0.tgz",
"integrity": "sha512-F47VdzOHYc19FhI/jBgctpO8a5UskTIxG6a1E5t3W5gF8VImuvBQffdXXfLHhsuCl7dS3v3U0R45cleeVXO1Zg==",
"license": "MIT",
"peerDependencies": {
"expo": "*"
}
},
"node_modules/expo-device": {
"version": "57.0.1",
"resolved": "https://registry.npmjs.org/expo-device/-/expo-device-57.0.1.tgz",
@@ -3852,7 +3938,6 @@
"resolved": "https://registry.npmjs.org/expo-font/-/expo-font-57.0.1.tgz",
"integrity": "sha512-QyS9L1Kh9sKJg4gfU6rdbpxpmH+DyzBX8z6jVvXMUDoqLr1GqmkO/Wu379KCXjL///kWbhpNlbi7AgBuj4VdIQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"fontfaceobserver": "^2.1.0"
},
@@ -3893,6 +3978,12 @@
}
}
},
"node_modules/expo-json-utils": {
"version": "57.0.2",
"resolved": "https://registry.npmjs.org/expo-json-utils/-/expo-json-utils-57.0.2.tgz",
"integrity": "sha512-9kYZECLKE3pYZQs+kt3+ggY83Lfryog9/UEo3HJKGcHUZeKKtlFBIPFjI4LzREubsvjP7AsvG0FdEX9EquIoAQ==",
"license": "MIT"
},
"node_modules/expo-keep-awake": {
"version": "57.0.1",
"resolved": "https://registry.npmjs.org/expo-keep-awake/-/expo-keep-awake-57.0.1.tgz",
@@ -3908,7 +3999,6 @@
"resolved": "https://registry.npmjs.org/expo-linking/-/expo-linking-57.0.5.tgz",
"integrity": "sha512-SmJI3wr0EVfeKPGf+Qgr9gUbrXk8mM0ATqYLvAX/EAzawDjohPzMJ5pTt7TYMX0Wknj4XCtyCQrGhnERMXT6cQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"expo-constants": "~57.0.9",
"invariant": "^2.2.4"
@@ -3918,6 +4008,18 @@
"react-native": "*"
}
},
"node_modules/expo-manifests": {
"version": "57.0.2",
"resolved": "https://registry.npmjs.org/expo-manifests/-/expo-manifests-57.0.2.tgz",
"integrity": "sha512-pPIIcKR73OShwlWMg8H90WRzKUd2krDdKlKAwuQV1FtUwE7H3hQEFw0ePFQY9yFoGMF/77ryYwNKfI5umMcCog==",
"license": "MIT",
"dependencies": {
"expo-json-utils": "~57.0.2"
},
"peerDependencies": {
"expo": "*"
}
},
"node_modules/expo-modules-autolinking": {
"version": "57.0.9",
"resolved": "https://registry.npmjs.org/expo-modules-autolinking/-/expo-modules-autolinking-57.0.9.tgz",
@@ -3968,7 +4070,6 @@
"resolved": "https://registry.npmjs.org/expo-router/-/expo-router-57.0.11.tgz",
"integrity": "sha512-kE2hz4lLkddZ94vN4nmbq5aXeo0t6FaZ8xJn/Hyn8/dQPsGlvDK0j4ZVayEUUdNmkNHsBVihgf1bl/2rCsYEzA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@expo/log-box": "^57.0.2",
"@expo/metro-runtime": "^57.0.8",
@@ -4052,7 +4153,6 @@
"resolved": "https://registry.npmjs.org/expo-server/-/expo-server-57.0.1.tgz",
"integrity": "sha512-sBfVDH6dmKVHZxqUxbfkzS00PZELMZt1IpnHKxcOTMZtR/t7CtRAFrbXcisG+EyzeqHSVDacZT+1tbYfZt5D8w==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=20.16.0"
}
@@ -4118,6 +4218,15 @@
}
}
},
"node_modules/expo-updates-interface": {
"version": "57.0.2",
"resolved": "https://registry.npmjs.org/expo-updates-interface/-/expo-updates-interface-57.0.2.tgz",
"integrity": "sha512-x3SA5toiHZEkW+5oeNdUM1Rvt6M3ExegQsSwS3Z1+S9gn9utGYTGBkb8MBQivhjIZiRlQYDIhauxA8kySQEWtQ==",
"license": "MIT",
"peerDependencies": {
"expo": "*"
}
},
"node_modules/expo-web-browser": {
"version": "57.0.2",
"resolved": "https://registry.npmjs.org/expo-web-browser/-/expo-web-browser-57.0.2.tgz",
@@ -4316,7 +4425,6 @@
"resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz",
"integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=10.0.0"
},
@@ -5426,6 +5534,7 @@
"resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz",
"integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==",
"license": "MIT",
"peer": true,
"bin": {
"lz-string": "bin/bin.js"
}
@@ -6430,7 +6539,6 @@
"resolved": "https://registry.npmjs.org/react/-/react-19.2.3.tgz",
"integrity": "sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=0.10.0"
}
@@ -6450,7 +6558,6 @@
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.3.tgz",
"integrity": "sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg==",
"license": "MIT",
"peer": true,
"dependencies": {
"scheduler": "^0.27.0"
},
@@ -6487,7 +6594,6 @@
"resolved": "https://registry.npmjs.org/react-native/-/react-native-0.86.2.tgz",
"integrity": "sha512-zbJXGZpwfZGA79Z9ob6Atvfx4nAQL8yJBa35s58E4Oo+khPykfQP2sTeumkKbjwajFYfVayg8pj7Il9nIfTk7A==",
"license": "MIT",
"peer": true,
"dependencies": {
"@react-native/assets-registry": "0.86.2",
"@react-native/codegen": "0.86.2",
@@ -6563,7 +6669,6 @@
"resolved": "https://registry.npmjs.org/react-native-gesture-handler/-/react-native-gesture-handler-2.32.0.tgz",
"integrity": "sha512-uYIMOKlKENORq2SABE+jIjbPU+h5I/sQKcq2v16zRq848nwEp1fWRVwML4QWqijc8UcXJC25o54S8GQd4Mf2OA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@egjs/hammerjs": "^2.0.17",
"@types/react-test-renderer": "^19.1.0",
@@ -6575,6 +6680,36 @@
"react-native": "*"
}
},
"node_modules/react-native-health-connect": {
"version": "4.1.3",
"resolved": "https://registry.npmjs.org/react-native-health-connect/-/react-native-health-connect-4.1.3.tgz",
"integrity": "sha512-osiWh4RD4tNHdHeggzOeGZFeEVaLQQr0+Yezq61WsPRvN1Yb6eA10rMfSU0+dqcfm6ZvIXSr2tYns+Yg1s37nw==",
"license": "MIT",
"workspaces": [
"example",
"docs"
],
"engines": {
"node": ">= 16.0.0"
},
"funding": {
"url": "https://github.com/matinzd/react-native-health-connect?sponsor=1"
},
"peerDependencies": {
"@expo/config-plugins": ">= 6.0.2",
"expo": "*",
"react": "*",
"react-native": "*"
},
"peerDependenciesMeta": {
"@expo/config-plugins": {
"optional": true
},
"expo": {
"optional": true
}
}
},
"node_modules/react-native-is-edge-to-edge": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/react-native-is-edge-to-edge/-/react-native-is-edge-to-edge-1.3.1.tgz",
@@ -6585,12 +6720,25 @@
"react-native": "*"
}
},
"node_modules/react-native-keyboard-controller": {
"version": "1.21.9",
"resolved": "https://registry.npmjs.org/react-native-keyboard-controller/-/react-native-keyboard-controller-1.21.9.tgz",
"integrity": "sha512-+TkkFldht4+AXBQeDy1hLE7iqiW8/NkY/ekhcFsKIiRdI9qC5JDzx0TfAg1iYZB2IeOXppmURIy2jFCUjOcV1w==",
"license": "MIT",
"dependencies": {
"react-native-is-edge-to-edge": "^1.2.1"
},
"peerDependencies": {
"react": "*",
"react-native": "*",
"react-native-reanimated": ">=3.0.0"
}
},
"node_modules/react-native-reanimated": {
"version": "4.5.1",
"resolved": "https://registry.npmjs.org/react-native-reanimated/-/react-native-reanimated-4.5.1.tgz",
"integrity": "sha512-RnMvtDuR+68ig864gAvZCOdZehqhC5rFmMo0kn+ARfgVSTvFeF6IFLBVgMPUu0KwihaapEyW24WRi6nEyy1kSA==",
"license": "MIT",
"peer": true,
"dependencies": {
"react-native-is-edge-to-edge": "^1.3.1",
"semver": "^7.7.3"
@@ -6606,7 +6754,6 @@
"resolved": "https://registry.npmjs.org/react-native-safe-area-context/-/react-native-safe-area-context-5.7.0.tgz",
"integrity": "sha512-/9/MtQz8ODphjsLdZ+GZAIcC/RtoqW9EeShf7Uvnfgm/pzYrJ75y3PV/J1wuAV1T5Dye5ygq4EAW20RoBq0ABQ==",
"license": "MIT",
"peer": true,
"peerDependencies": {
"react": "*",
"react-native": "*"
@@ -6646,7 +6793,6 @@
"resolved": "https://registry.npmjs.org/react-native-web/-/react-native-web-0.21.2.tgz",
"integrity": "sha512-SO2t9/17zM4iEnFvlu2DA9jqNbzNhoUP+AItkoCOyFmDMOhUnBBznBDCYN92fGdfAkfQlWzPoez6+zLxFNsZEg==",
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/runtime": "^7.18.6",
"@react-native/normalize-colors": "^0.74.1",
@@ -6679,7 +6825,6 @@
"resolved": "https://registry.npmjs.org/react-native-worklets/-/react-native-worklets-0.10.1.tgz",
"integrity": "sha512-62mRM19bDpfpdI8HLkEErcdOsrAPDtE9lA/sw+5lLRpzBHNhxaoj9QyY2KjXqUmirelxkX4zuPGTC3VdA0feJA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/plugin-transform-arrow-functions": "^7.27.1",
"@babel/plugin-transform-class-properties": "^7.28.6",
@@ -6715,7 +6860,6 @@
"resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.14.2.tgz",
"integrity": "sha512-jCvmsr+1IUSMUyzOkRcvnVbX3ZYC6g9TDrDbFuFmRDq7PD4yaGbLKNQL6k2jnArV8hjYxh7hVhAZB6s9HDGpZA==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=0.10.0"
}
@@ -7481,7 +7625,6 @@
"integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==",
"devOptional": true,
"license": "Apache-2.0",
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"

View File

@@ -3,9 +3,11 @@
"main": "expo-router/entry",
"version": "1.0.0",
"dependencies": {
"@expo-google-fonts/figtree": "^0.4.1",
"@expo/ui": "~57.0.9",
"expo": "~57.0.11",
"expo-constants": "~57.0.9",
"expo-dev-client": "~57.0.22",
"expo-device": "~57.0.1",
"expo-font": "~57.0.1",
"expo-glass-effect": "~57.0.1",
@@ -22,6 +24,8 @@
"react-dom": "19.2.3",
"react-native": "0.86.2",
"react-native-gesture-handler": "~2.32.0",
"react-native-health-connect": "^4.1.3",
"react-native-keyboard-controller": "1.21.9",
"react-native-reanimated": "4.5.1",
"react-native-safe-area-context": "~5.7.0",
"react-native-screens": "~4.26.0",
@@ -31,6 +35,7 @@
},
"devDependencies": {
"@types/react": "~19.2.2",
"expo-build-properties": "^57.0.9",
"typescript": "~6.0.3"
},
"scripts": {

View File

@@ -1,40 +1,52 @@
import {
Figtree_400Regular, Figtree_500Medium, Figtree_600SemiBold, Figtree_700Bold,
Figtree_800ExtraBold, useFonts,
} from '@expo-google-fonts/figtree';
import { Stack } from 'expo-router';
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { View } from 'react-native';
import { KeyboardProvider } from 'react-native-keyboard-controller';
import { AuthProvider, useAuth } from '../lib/api';
import { C } from '../lib/theme';
import { LoginScreen } from '../components/login';
import { C, F, isDark } from '../lib/theme';
function Gate() {
const { ready, authed } = useAuth();
if (!ready) return <View style={{ flex: 1, backgroundColor: C.bg }} />;
if (!authed) return <LoginScreen />;
const { ready } = useAuth();
const [fontsLoaded] = useFonts({
Figtree_400Regular, Figtree_500Medium, Figtree_600SemiBold, Figtree_700Bold, Figtree_800ExtraBold,
});
if (!ready || !fontsLoaded) return <View style={{ flex: 1, backgroundColor: C.bg }} />;
return (
<Stack
screenOptions={{
headerStyle: { backgroundColor: C.bg },
headerTintColor: C.text,
headerTitleStyle: { fontWeight: '600', fontSize: 17 },
headerTitleStyle: { fontFamily: F.bold, fontSize: 18 },
headerShadowVisible: false,
contentStyle: { backgroundColor: C.bg },
}}>
<Stack.Screen name="index" options={{ title: 'Health' }} />
<Stack.Screen name="index" options={{ headerShown: false }} />
<Stack.Screen name="systems" options={{ title: 'All systems' }} />
<Stack.Screen name="chat" options={{ title: 'Chat' }} />
<Stack.Screen name="blood" options={{ title: 'Bloodwork' }} />
<Stack.Screen name="sleep" options={{ title: 'Sleep' }} />
<Stack.Screen name="fitbit" options={{ title: 'Fitbit Air' }} />
<Stack.Screen name="train" options={{ title: 'Training' }} />
<Stack.Screen name="body" options={{ title: 'Body Composition' }} />
<Stack.Screen name="mind" options={{ title: 'Meditation' }} />
<Stack.Screen name="dna" options={{ title: 'Genetic Traits' }} />
<Stack.Screen name="settings" options={{ title: 'Settings' }} />
</Stack>
);
}
export default function RootLayout() {
return (
<KeyboardProvider>
<AuthProvider>
<StatusBar style="light" />
<StatusBar style={isDark ? 'light' : 'dark'} />
<Gate />
</AuthProvider>
</KeyboardProvider>
);
}

22
src/app/chat.tsx Normal file
View File

@@ -0,0 +1,22 @@
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { C, F } from '../lib/theme';
/* Placeholder until the chat endpoint exists on the server. */
export default function Chat() {
return (
<View style={s.wrap}>
<Text style={s.h}>Chat is not connected yet</Text>
<Text style={s.p}>
This is where you will ask about your data and log things by typing or speaking. The
server side is the next piece to be built.
</Text>
</View>
);
}
const s = StyleSheet.create({
wrap: { flex: 1, backgroundColor: C.bg, padding: 24, paddingTop: 40 },
h: { fontFamily: F.heavy, fontSize: 28, lineHeight: 33, letterSpacing: -0.5, color: C.text, marginBottom: 10 },
p: { fontFamily: F.regular, fontSize: 16.5, lineHeight: 24, color: C.muted },
});

237
src/app/fitbit.tsx Normal file
View File

@@ -0,0 +1,237 @@
import React, { useEffect, useRef, useState } from 'react';
import { Platform, Pressable, StyleSheet, Text, View, useWindowDimensions } from 'react-native';
import { DailyBars, DailyLine } from '../components/charts';
import { ErrBox, Loading, Panel, Screen, Sec, SrcNote, Tile, TileGrid } from '../components/ui';
import { load } from '../lib/api';
import { fmtDY, hm, num } from '../lib/format';
import { healthConnectStatus, healthConnectSupported, syncFitbit } from '../lib/fitbit';
import { C } from '../lib/theme';
import { useLoad } from '../lib/use-load';
interface DayVal { day: string; value: number }
interface DayAvg { day: string; avg: number; n: number }
interface Summary {
days: number;
steps: DayVal[];
hr_daily: { day: string; min: number; max: number; avg: number; n: number }[];
resting_hr: DayAvg[];
hrv: DayAvg[];
spo2: DayAvg[];
respiratory_rate: DayAvg[];
sleep: {
id: string; started_at: string; ended_at: string; total_seconds: number;
sleep_seconds: number; deep_seconds: number; rem_seconds: number;
light_seconds: number; awake_seconds: number;
}[];
sample_counts: Record<string, number>;
}
export default function Fitbit() {
const { width } = useWindowDimensions();
const chartW = Math.min(608, width - 32) - 28;
const { data, err, loading, refresh } = useLoad(() => load<Summary>('fitbitSummary'));
const [syncing, setSyncing] = useState(false);
const [syncMsg, setSyncMsg] = useState('');
const [hcStatus, setHcStatus] = useState<string>('');
const autoSynced = useRef(false);
useEffect(() => {
healthConnectStatus().then(setHcStatus);
}, []);
const runSync = async () => {
if (syncing) return;
setSyncing(true);
try {
const res = await syncFitbit(setSyncMsg);
setSyncMsg(res.message);
if (res.ok && (res.samples || res.daily || res.sleep)) refresh();
} catch (e) {
setSyncMsg(`Sync failed: ${e instanceof Error ? e.message : e}`);
} finally {
setSyncing(false);
}
};
// auto-sync once per screen visit on Android
useEffect(() => {
if (hcStatus === 'available' && !autoSynced.current) {
autoSynced.current = true;
runSync();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [hcStatus]);
let body: React.ReactNode = null;
if (loading && !data) body = <Loading />;
else if (err) body = <ErrBox msg={err} />;
else if (data) {
const lastVal = (arr: DayAvg[]) => (arr.length ? arr[arr.length - 1] : null);
const stepsToday = data.steps.length ? data.steps[data.steps.length - 1] : null;
const rhr = lastVal(data.resting_hr);
const hrv = lastVal(data.hrv);
const spo2 = lastVal(data.spo2);
const lastSleep = data.sleep.length ? data.sleep[data.sleep.length - 1] : null;
const empty = !data.steps.length && !data.hr_daily.length && !data.sleep.length;
body = (
<>
{empty ? (
<View style={s.emptyBox}>
<Text style={{ color: C.text, fontSize: 14, fontWeight: '600', marginBottom: 6 }}>
No Fitbit data yet
</Text>
<Text style={{ color: C.muted, fontSize: 12.5, lineHeight: 18 }}>
Make sure the Google Health app is installed, the Fitbit Air is paired, and
Google Health is sharing to Health Connect (Profile → Privacy → Health Connect).
Then tap Sync below.
</Text>
</View>
) : (
<TileGrid>
<Tile label="Steps" value={stepsToday ? num(Math.round(stepsToday.value)) : '—'}
sub={stepsToday ? fmtDY(stepsToday.day) : undefined} />
<Tile label="Resting HR" value={rhr ? String(Math.round(rhr.avg)) : '—'} unit="bpm"
sub={rhr ? fmtDY(rhr.day) : undefined} />
<Tile label="HRV (RMSSD)" value={hrv ? String(Math.round(hrv.avg)) : '—'} unit="ms"
sub={hrv ? fmtDY(hrv.day) : undefined} />
<Tile label="SpO2" value={spo2 ? spo2.avg.toFixed(1) : '—'} unit="%"
sub={spo2 ? fmtDY(spo2.day) : undefined} />
{lastSleep ? (
<Tile label="Last sleep" value={hm(lastSleep.sleep_seconds)}
sub={fmtDY(lastSleep.started_at)} />
) : null}
</TileGrid>
)}
{data.steps.length ? (
<>
<Sec title={`Steps · ${data.days} days`} />
<Panel title="Daily steps" sub="tap a bar">
<DailyBars data={data.steps} width={chartW} unit="Steps" />
</Panel>
</>
) : null}
{data.resting_hr.length > 1 ? (
<>
<Sec title="Resting heart rate" />
<Panel title="Daily resting HR (bpm)" sub="tap a point">
<DailyLine data={data.resting_hr} width={chartW} unit="bpm" color={C.s2} />
</Panel>
</>
) : null}
{data.hrv.length > 1 ? (
<>
<Sec title="Heart rate variability" />
<Panel title="Nightly HRV RMSSD (ms)" sub="tap a point">
<DailyLine data={data.hrv} width={chartW} unit="ms" color={C.s3} />
</Panel>
</>
) : null}
{data.spo2.length > 1 ? (
<>
<Sec title="Blood oxygen" />
<Panel title="Nightly SpO2 (%)" sub="tap a point">
<DailyLine data={data.spo2} width={chartW} unit="%" color={C.s1} decimals={1} />
</Panel>
</>
) : null}
{data.sleep.length ? (
<>
<Sec title="Sleep sessions" count={data.sleep.length} />
{[...data.sleep].reverse().slice(0, 14).map((sl) => (
<View key={sl.id} style={s.row}>
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
<Text style={{ color: C.text, fontSize: 13.5, fontWeight: '500' }}>
{hm(sl.sleep_seconds)}
</Text>
<Text style={{ color: C.muted, fontSize: 11 }}>{fmtDY(sl.started_at)}</Text>
</View>
<Text style={{ color: C.muted, fontSize: 12, marginTop: 3 }}>
{sl.deep_seconds ? `deep ${hm(sl.deep_seconds)} · ` : ''}
{sl.rem_seconds ? `REM ${hm(sl.rem_seconds)} · ` : ''}
{sl.light_seconds ? `light ${hm(sl.light_seconds)} · ` : ''}
awake {hm(sl.awake_seconds)}
</Text>
</View>
))}
</>
) : null}
<Sec title="Data on record" />
<View style={s.debugBox}>
{Object.entries(data.sample_counts).map(([k, v]) => (
<Text key={k} style={{ color: v ? C.muted : C.dim, fontSize: 12, marginVertical: 1 }}>
{k.replace(/_/g, ' ')}: {num(v)}
</Text>
))}
</View>
<SrcNote>
Fitbit Air → Google Health → Health Connect → health.rehbock.xyz. Data syncs from
this phone when you open this screen; the server is the system of record.
</SrcNote>
</>
);
}
return (
<Screen onRefresh={refresh}>
{/* sync bar */}
<View style={s.syncBar}>
<View style={{ flex: 1 }}>
<Text style={{ color: C.text, fontSize: 13, fontWeight: '600' }}>
{Platform.OS === 'android' ? 'Health Connect' : 'Sync (Android phone only)'}
</Text>
<Text style={{ color: C.muted, fontSize: 11.5, marginTop: 2 }}>
{healthConnectSupported()
? hcStatus === 'available'
? syncMsg || 'Ready'
: hcStatus === 'needs-update'
? 'Health Connect needs an update'
: hcStatus || 'Checking…'
: 'Viewing server data — sync runs on the Android phone'}
</Text>
</View>
{healthConnectSupported() && (
<Pressable
style={[s.syncBtn, (syncing || hcStatus !== 'available') && { opacity: 0.5 }]}
disabled={syncing || hcStatus !== 'available'}
onPress={runSync}>
<Text style={{ color: '#fff', fontWeight: '600', fontSize: 13 }}>
{syncing ? 'Syncing…' : 'Sync'}
</Text>
</Pressable>
)}
</View>
{body}
</Screen>
);
}
const s = StyleSheet.create({
syncBar: {
flexDirection: 'row', alignItems: 'center', gap: 12,
backgroundColor: C.surface, borderWidth: 1, borderColor: C.border,
borderRadius: 12, padding: 12, marginBottom: 14,
},
syncBtn: {
backgroundColor: C.accent, borderRadius: 10, paddingVertical: 9, paddingHorizontal: 18,
},
emptyBox: {
backgroundColor: C.surface, borderWidth: 1, borderColor: C.border,
borderRadius: 12, padding: 16, marginBottom: 4,
},
row: {
backgroundColor: C.surface, borderWidth: 1, borderColor: C.border, borderRadius: 12,
paddingVertical: 12, paddingHorizontal: 14, marginBottom: 8,
},
debugBox: {
backgroundColor: C.surface, borderWidth: 1, borderColor: C.border,
borderRadius: 12, padding: 12,
},
});

View File

@@ -1,143 +1,188 @@
import { Stack } from 'expo-router';
import React from 'react';
import { Alert, Pressable, Text, View } from 'react-native';
import { NavCard, PriorityCard, Screen, Sec } from '../components/ui';
import { useAuth } from '../lib/api';
import { agoTxt, fmtD, fmtDY, hm, num, cap } from '../lib/format';
import { shapeBiomarkers, shapeSleep, weekStart, workoutVolume } from '../lib/shape';
import { C } from '../lib/theme';
import type {
BiomarkersResponse, DexaResponse, HealthMeta, MeditationStats, SleepApiResponse,
SleepCycleExport, WorkoutsResponse,
} from '../lib/types';
import { router } from 'expo-router';
import React, { useMemo, useState } from 'react';
import { Pressable, RefreshControl, ScrollView, StyleSheet, Text, View } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import {
CHAT_BAR_SPACE, Card, ChatBar, GoalBar, HabitCard, HabitGrid, Heading, RoundButton, StreakGrid,
} from '../components/kit';
import { clearCache, useAuth } from '../lib/api';
import { buildBrief } from '../lib/brief';
import {
AdherenceResponse, GoalsResponse, Habit, dailyHabits, goalRows, habitStreaks, setCheckin,
} from '../lib/life';
import { shapeSleep } from '../lib/shape';
import { C, F } from '../lib/theme';
import type { SleepApiResponse, SleepCycleExport, WorkoutsResponse } from '../lib/types';
import { loadAll, useLoad } from '../lib/use-load';
const GOALS_SHOWN = 4;
export default function Today() {
const { logout } = useAuth();
const insets = useSafeAreaInsets();
const { hasToken } = useAuth();
const [refreshing, setRefreshing] = useState(false);
const [allGoals, setAllGoals] = useState(false);
/** check-ins tapped but not yet confirmed by the server, keyed protocol:rule */
const [pending, setPending] = useState<Record<string, boolean | null>>({});
const { data, loading, refresh } = useLoad(() =>
loadAll({
meta: 'meta', bio: 'biomarkers', wo: 'workouts', sApi: 'sleepApi',
sc: 'sleepCycle', dexa: 'dexa', med: 'medStats',
adh: 'lifeAdherence', goals: 'lifeGoals', wo: 'workouts', sApi: 'sleepApi', sc: 'sleepCycle',
} as const),
);
const r = data as
| {
meta: HealthMeta | null;
bio: BiomarkersResponse | null;
adh: AdherenceResponse | null;
goals: GoalsResponse | null;
wo: WorkoutsResponse | null;
sApi: SleepApiResponse | null;
sc: SleepCycleExport | null;
dexa: DexaResponse | null;
med: MeditationStats | null;
}
| undefined;
const cards: React.ReactNode[] = [];
if (r) {
if (r.sApi && r.sc) {
const nights = shapeSleep(r.sApi, r.sc);
const last = nights[nights.length - 1];
cards.push(
<NavCard key="sleep" title="Sleep" big={hm(last.asleep)} href="/sleep"
note={`Last night on record — ${fmtD(last.date)} (${last.src})`} />,
);
} else cards.push(<NavCard key="sleep" title="Sleep" big="—" note="Couldn’t load" href="/sleep" />);
const brief = useMemo(() => {
if (!r) return null;
const nights = r.sApi && r.sc ? shapeSleep(r.sApi, r.sc) : [];
const lastNight = nights[nights.length - 1];
const ws = r.wo ? [...r.wo.workouts].sort((a, b) => (a.start_time < b.start_time ? -1 : 1)) : [];
const lastWo = ws[ws.length - 1];
return buildBrief({
sleep: lastNight ? { date: lastNight.date, asleepSec: lastNight.asleep } : null,
workout: lastWo ? { title: lastWo.title, start: lastWo.start_time } : null,
adherence: r.adh,
goals: r.goals,
});
}, [r]);
if (r.wo) {
const ws = [...r.wo.workouts].sort((a, b) => (a.start_time < b.start_time ? -1 : 1));
const last = ws[ws.length - 1];
const { vol } = workoutVolume(last);
const wkCount = ws.filter(
(w) => weekStart(w.start_time) === weekStart(new Date().toISOString()),
).length;
cards.push(
<NavCard key="train" title="Training" big={last.title} href="/train"
note={`${agoTxt(last.start_time)} · ${num(Math.round(vol))} kg · ${wkCount} this week`} />,
);
} else cards.push(<NavCard key="train" title="Training" big="—" note="Couldn’t load" href="/train" />);
const habits = useMemo<Habit[]>(() => {
if (!r?.adh) return [];
return dailyHabits(r.adh).map((h) => {
const k = `${h.protocolId}:${h.ruleId}`;
return k in pending ? { ...h, done: !!pending[k] } : h;
});
}, [r, pending]);
if (r.bio) {
const marks = shapeBiomarkers(r.bio);
const latestDraw = r.bio.biomarkers.reduce((m, b) => (b.collected > m ? b.collected : m), '');
const flagged = marks.filter((m) => m.latest.flagged && m.latest.collected === latestDraw);
cards.push(
<NavCard key="blood" title="Blood" big={String(marks.length)} unit="markers" href="/blood"
flagline={
flagged.length
? `${flagged.length} flagged: ${flagged.slice(0, 3).map((f) => cap(f.name)).join(', ')}${flagged.length > 3 ? '…' : ''}`
: undefined
const rows = useMemo(() => (r?.adh ? habitStreaks(r.adh) : []), [r]);
const goals = useMemo(() => (r?.goals ? goalRows(r.goals) : []), [r]);
const doneCount = habits.filter((h) => h.done).length;
const toggle = async (h: Habit, done: boolean | null) => {
if (!r?.adh) return;
const k = `${h.protocolId}:${h.ruleId}`;
setPending((p) => ({ ...p, [k]: done }));
try {
await setCheckin(h, r.adh.today, done);
refresh();
} catch {
// put the card back the way the server has it
setPending((p) => {
const n = { ...p };
delete n[k];
return n;
});
}
okline={flagged.length ? undefined : 'All markers in range'}
note={`Latest draw ${fmtDY(latestDraw)}`} />,
);
} else cards.push(<NavCard key="blood" title="Blood" big="—" note="Couldn’t load" href="/blood" />);
};
if (r.dexa) {
const scan = r.dexa.scans[r.dexa.scans.length - 1];
cards.push(
<NavCard key="body" title="Body" big={`${scan.summary.total_body_fat_pct}`} unit="% fat"
href="/body"
note={`${scan.summary.total_lean_mass_kg} kg lean · DXA ${fmtD(scan.scan_date)}`} />,
);
} else cards.push(<NavCard key="body" title="Body" big="—" note="Couldn’t load" href="/body" />);
const onRefresh = () => {
setRefreshing(true);
clearCache();
setPending({});
refresh();
setTimeout(() => setRefreshing(false), 500);
};
if (r.med) {
cards.push(
<NavCard key="mind" title="Mind" big={String(r.med.totalMinutes)} unit="min" href="/mind"
note={`${r.med.totalSessions} sessions · streak ${r.med.currentStreak}`} />,
);
} else cards.push(<NavCard key="mind" title="Mind" big="—" note="Couldn’t load" href="/mind" />);
cards.push(
<NavCard key="dna" title="DNA" big="99" unit="traits" href="/dna"
note="AncestryDNA trait report" />,
);
}
const date = new Date().toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' });
return (
<>
<Stack.Screen
options={{
headerRight: () => (
<Pressable
hitSlop={10}
onPress={() =>
Alert.alert('Lock the dashboard?', 'You will need the password to get back in.', [
{ text: 'Cancel', style: 'cancel' },
{ text: 'Lock', style: 'destructive', onPress: logout },
])
}>
<Text style={{ fontSize: 16 }}>🔒</Text>
</Pressable>
),
<View style={{ flex: 1, backgroundColor: C.bg }}>
<ScrollView
contentContainerStyle={{
paddingTop: insets.top + 10, paddingHorizontal: 16,
paddingBottom: insets.bottom + CHAT_BAR_SPACE + 16,
}}
refreshControl={
<RefreshControl
refreshing={refreshing} onRefresh={onRefresh} tintColor={C.muted} colors={[C.accent]}
progressBackgroundColor={C.surface}
/>
<Screen onRefresh={refresh}>
<Sec
title={new Date().toLocaleDateString('en-US', {
weekday: 'long', month: 'long', day: 'numeric',
})}
/>
{loading && !r ? (
<Text style={{ color: C.muted, fontSize: 13, textAlign: 'center', padding: 24 }}>
Loading…
</Text>
}>
<View style={s.top}>
<Text style={s.date}>{date}</Text>
<RoundButton glyph="⚙︎" label="Settings" onPress={() => router.push('/settings')} />
</View>
{!hasToken ? (
<Card style={{ padding: 20, marginTop: 8 }}>
<Text style={s.headline}>Connect your data</Text>
<Text style={s.line}>Add your API token in Settings and your day will appear here.</Text>
<Pressable style={s.cta} onPress={() => router.push('/settings')} accessibilityRole="button">
<Text style={s.ctaT}>Open Settings</Text>
</Pressable>
</Card>
) : loading && !r ? (
<Text style={[s.line, { marginTop: 24 }]}>Loading your day…</Text>
) : (
<View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 10 }}>{cards}</View>
)}
{r?.meta?.current_priorities?.length ? (
<>
<Sec title="Priorities" count={r.meta.current_priorities.length} />
{r.meta.current_priorities.map((p, i) => (
<PriorityCard key={p.title} p={p} rank={i + 1} />
{brief ? (
<View style={{ paddingHorizontal: 4 }}>
<Text style={s.headline}>{brief.headline}</Text>
{brief.lines.map((l) => (
<Text key={l} style={s.line}>{l}</Text>
))}
</View>
) : null}
{r?.adh && habits.length ? (
<>
<Heading title="Today" meta={`${doneCount} of ${habits.length} done`} />
<HabitGrid>
{habits.map((h) => (
<HabitCard key={h.ruleId} habit={h} onToggle={(done) => toggle(h, done)} />
))}
</HabitGrid>
<Heading title="Last 14 days" action="All systems" onAction={() => router.push('/systems')} />
<Card style={{ paddingVertical: 10 }}>
<StreakGrid rows={rows} />
</Card>
</>
) : (
<Card style={{ padding: 16, marginTop: 24 }}>
<Text style={s.line}>Your daily habits could not be loaded. Pull down to try again.</Text>
</Card>
)}
{goals.length ? (
<>
<Heading
title="Goals"
action={goals.length > GOALS_SHOWN ? (allGoals ? 'Show fewer' : `All ${goals.length}`) : undefined}
onAction={() => setAllGoals((v) => !v)}
/>
<Card style={{ paddingVertical: 6 }}>
{(allGoals ? goals : goals.slice(0, GOALS_SHOWN)).map((g) => (
<GoalBar key={g.id} goal={g} />
))}
</Card>
</>
) : null}
<Text style={{ fontSize: 11, color: C.dim, marginTop: 32 }}>
Personal health data · served from rehbock.xyz over HTTPS · nothing cached on device
</Text>
</Screen>
</>
)}
</ScrollView>
<ChatBar />
</View>
);
}
const s = StyleSheet.create({
top: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14, paddingLeft: 4 },
date: { fontFamily: F.semibold, fontSize: 15, color: C.muted },
headline: { fontFamily: F.heavy, fontSize: 32, lineHeight: 37, letterSpacing: -0.7, color: C.text, marginBottom: 10 },
line: { fontFamily: F.regular, fontSize: 16.5, lineHeight: 24, color: C.muted, marginBottom: 2 },
cta: {
marginTop: 16, height: 54, borderRadius: 16, backgroundColor: C.accent,
alignItems: 'center', justifyContent: 'center',
},
ctaT: { fontFamily: F.bold, fontSize: 17, color: C.onAccent },
});

74
src/app/settings.tsx Normal file
View File

@@ -0,0 +1,74 @@
import React, { useState } from 'react';
import { Pressable, StyleSheet, Text, TextInput, View } from 'react-native';
import { Screen } from '../components/ui';
import { BASE, useAuth } from '../lib/api';
import { C } from '../lib/theme';
export default function Settings() {
const { hasToken, saveToken, clearToken } = useAuth();
const [value, setValue] = useState('');
const [msg, setMsg] = useState('');
const [busy, setBusy] = useState(false);
const save = async () => {
setBusy(true);
setMsg('');
try {
if (await saveToken(value)) {
setValue('');
setMsg('Saved.');
} else setMsg('The server rejected that token.');
} catch {
setMsg('Network error — are you online?');
} finally {
setBusy(false);
}
};
return (
<Screen>
<Text style={s.lbl}>SERVER</Text>
<Text style={s.val}>{BASE}</Text>
<Text style={s.lbl}>API TOKEN {hasToken ? '· saved' : '· not set'}</Text>
<TextInput
style={s.input}
value={value}
onChangeText={setValue}
placeholder={hasToken ? '•••••••• (enter a new one to replace)' : 'Paste your API token'}
placeholderTextColor={C.dim}
autoCapitalize="none"
autoCorrect={false}
secureTextEntry
onSubmitEditing={save}
returnKeyType="done"
/>
<Pressable
style={[s.go, (busy || !value.trim()) && { opacity: 0.5 }]}
disabled={busy || !value.trim()}
onPress={save}>
<Text style={s.goTxt}>Save token</Text>
</Pressable>
{hasToken ? (
<Pressable style={s.clear} onPress={clearToken}>
<Text style={{ color: C.red, fontSize: 14 }}>Remove token from this device</Text>
</Pressable>
) : null}
<View style={{ minHeight: 24 }}>
<Text style={s.msg}>{msg}</Text>
</View>
</Screen>
);
}
const s = StyleSheet.create({
lbl: { fontSize: 11, color: C.muted, letterSpacing: 0.5, marginTop: 16, marginBottom: 6 },
val: { fontSize: 15, color: C.text },
input: {
paddingVertical: 11, paddingHorizontal: 12, borderRadius: 10, borderWidth: 1,
borderColor: C.border, backgroundColor: C.surface2, color: C.text, fontSize: 15,
},
go: { marginTop: 16, padding: 12, borderRadius: 10, backgroundColor: C.accent, alignItems: 'center' },
goTxt: { color: '#fff', fontWeight: '600', fontSize: 15 },
clear: { marginTop: 20, alignItems: 'center', padding: 8 },
msg: { marginTop: 12, fontSize: 12.5, color: C.muted },
});

View File

@@ -13,15 +13,19 @@ export default function Sleep() {
const { width } = useWindowDimensions();
const chartW = Math.min(608, width - 32) - 28;
const { data, err, loading, refresh } = useLoad(() =>
Promise.all([load<SleepApiResponse>('sleepApi'), load<SleepCycleExport>('sleepCycle')]),
Promise.all([
load<SleepApiResponse>('sleepApi'),
load<SleepCycleExport>('sleepCycle'),
load<{ sleep: import('../lib/shape').HcSleepRow[] }>('fitbitSummary').catch(() => null),
]),
);
let body: React.ReactNode = null;
if (loading && !data) body = <Loading />;
else if (err) body = <ErrBox msg={err} />;
else if (data) {
const [api, sc] = data;
const nights = shapeSleep(api, sc);
const [api, sc, fb] = data;
const nights = shapeSleep(api, sc, fb?.sleep ?? []);
const recent = nights.slice(-30);
const last7 = nights.slice(-7);
const avg = (arr: typeof nights, f: (t: (typeof nights)[0]) => number) =>
@@ -56,8 +60,9 @@ export default function Sleep() {
/>
</Panel>
<SrcNote>
Sources: Eight Sleep pod (through Feb 2026, incl. HRV/HR) and Sleep Cycle app export
(through {sc.exported_at}). {num(nights.length)} nights total on record.
Sources: Fitbit Air (via Health Connect), Eight Sleep pod (through Feb 2026, incl.
HRV/HR), Sleep Cycle export (through {sc.exported_at}). {num(nights.length)} nights
total on record.
</SrcNote>
</>
);

146
src/app/systems.tsx Normal file
View File

@@ -0,0 +1,146 @@
import { Link } from 'expo-router';
import React from 'react';
import { Text, View } from 'react-native';
import { NavCard, PriorityCard, Screen, Sec } from '../components/ui';
import { useAuth } from '../lib/api';
import { agoTxt, fmtD, fmtDY, hm, num, cap } from '../lib/format';
import { shapeBiomarkers, shapeSleep, weekStart, workoutVolume } from '../lib/shape';
import { C } from '../lib/theme';
import type {
BiomarkersResponse, DexaResponse, HealthMeta, MeditationStats, SleepApiResponse,
SleepCycleExport, WorkoutsResponse,
} from '../lib/types';
import { loadAll, useLoad } from '../lib/use-load';
export default function Systems() {
const { hasToken } = useAuth();
const { data, loading, refresh } = useLoad(() =>
loadAll({
meta: 'meta', bio: 'biomarkers', wo: 'workouts', sApi: 'sleepApi',
sc: 'sleepCycle', dexa: 'dexa', med: 'medStats', fitbit: 'fitbitSummary',
} as const),
);
const r = data as
| {
meta: HealthMeta | null;
bio: BiomarkersResponse | null;
wo: WorkoutsResponse | null;
sApi: SleepApiResponse | null;
sc: SleepCycleExport | null;
dexa: DexaResponse | null;
med: MeditationStats | null;
fitbit: {
steps: { day: string; value: number }[];
resting_hr: { day: string; avg: number }[];
hrv: { day: string; avg: number }[];
} | null;
}
| undefined;
const cards: React.ReactNode[] = [];
if (r) {
if (r.sApi && r.sc) {
const nights = shapeSleep(r.sApi, r.sc);
const last = nights[nights.length - 1];
cards.push(
<NavCard key="sleep" title="Sleep" big={hm(last.asleep)} href="/sleep"
note={`Last night on record — ${fmtD(last.date)} (${last.src})`} />,
);
} else cards.push(<NavCard key="sleep" title="Sleep" big="—" note="Couldn’t load" href="/sleep" />);
if (r.wo) {
const ws = [...r.wo.workouts].sort((a, b) => (a.start_time < b.start_time ? -1 : 1));
const last = ws[ws.length - 1];
const { vol } = workoutVolume(last);
const wkCount = ws.filter(
(w) => weekStart(w.start_time) === weekStart(new Date().toISOString()),
).length;
cards.push(
<NavCard key="train" title="Training" big={last.title} href="/train"
note={`${agoTxt(last.start_time)} · ${num(Math.round(vol))} kg · ${wkCount} this week`} />,
);
} else cards.push(<NavCard key="train" title="Training" big="—" note="Couldn’t load" href="/train" />);
if (r.bio) {
const marks = shapeBiomarkers(r.bio);
const latestDraw = r.bio.biomarkers.reduce((m, b) => (b.collected > m ? b.collected : m), '');
const flagged = marks.filter((m) => m.latest.flagged && m.latest.collected === latestDraw);
cards.push(
<NavCard key="blood" title="Blood" big={String(marks.length)} unit="markers" href="/blood"
flagline={
flagged.length
? `${flagged.length} flagged: ${flagged.slice(0, 3).map((f) => cap(f.name)).join(', ')}${flagged.length > 3 ? '…' : ''}`
: undefined
}
okline={flagged.length ? undefined : 'All markers in range'}
note={`Latest draw ${fmtDY(latestDraw)}`} />,
);
} else cards.push(<NavCard key="blood" title="Blood" big="—" note="Couldn’t load" href="/blood" />);
if (r.dexa) {
const scan = r.dexa.scans[r.dexa.scans.length - 1];
cards.push(
<NavCard key="body" title="Body" big={`${scan.summary.total_body_fat_pct}`} unit="% fat"
href="/body"
note={`${scan.summary.total_lean_mass_kg} kg lean · DXA ${fmtD(scan.scan_date)}`} />,
);
} else cards.push(<NavCard key="body" title="Body" big="—" note="Couldn’t load" href="/body" />);
if (r.med) {
cards.push(
<NavCard key="mind" title="Mind" big={String(r.med.totalMinutes)} unit="min" href="/mind"
note={`${r.med.totalSessions} sessions · streak ${r.med.currentStreak}`} />,
);
} else cards.push(<NavCard key="mind" title="Mind" big="—" note="Couldn’t load" href="/mind" />);
{
const fb = r.fitbit;
const steps = fb?.steps?.length ? fb.steps[fb.steps.length - 1] : null;
const hrv = fb?.hrv?.length ? fb.hrv[fb.hrv.length - 1] : null;
cards.push(
<NavCard key="fitbit" title="Fitbit" href="/fitbit"
big={steps ? num(Math.round(steps.value)) : '—'} unit={steps ? 'steps' : undefined}
note={
steps
? `${fmtD(steps.day)}${hrv ? ` · HRV ${Math.round(hrv.avg)} ms` : ''}`
: 'Open to sync from Health Connect'
} />,
);
}
cards.push(
<NavCard key="dna" title="DNA" big="99" unit="traits" href="/dna"
note="AncestryDNA trait report" />,
);
}
return (
<>
<Screen onRefresh={refresh}>
{!hasToken ? (
<Link href="/settings" style={{ padding: 24, textAlign: 'center', color: C.accent, fontSize: 15 }}>
Add your API token in Settings to load your data →
</Link>
) : loading && !r ? (
<Text style={{ color: C.muted, fontSize: 13, textAlign: 'center', padding: 24 }}>
Loading…
</Text>
) : (
<View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 10 }}>{cards}</View>
)}
{r?.meta?.current_priorities?.length ? (
<>
<Sec title="Priorities" count={r.meta.current_priorities.length} />
{r.meta.current_priorities.map((p, i) => (
<PriorityCard key={p.title} p={p} rank={i + 1} />
))}
</>
) : null}
<Text style={{ fontSize: 11, color: C.dim, marginTop: 32 }}>
Personal health data · served from rehbock.xyz over HTTPS · nothing cached on device
</Text>
</Screen>
</>
);
}

View File

@@ -157,6 +157,108 @@ export function VolumeChart({ weeks, width }: { weeks: Week[]; width: number })
);
}
/* generic daily bars (steps, kcal…) — tap for value */
export function DailyBars({
data, width, unit, color = C.s1, fmt = (v: number) => kfmt(v),
}: {
data: { day: string; value: number }[];
width: number;
unit: string;
color?: string;
fmt?: (v: number) => string;
}) {
const [sel, setSel] = useState<number | null>(null);
if (!data.length) return null;
const H = 130, padL = 34, padB = 16, W = width;
const iw = W - padL, n = data.length, bw = Math.max(3, iw / n - 2);
const maxV = Math.max(...data.map((d) => d.value), 1);
const y = (v: number) => H - padB - (v / maxV) * (H - padB - 8);
const selD = sel != null ? data[sel] : null;
return (
<View>
<Svg width={W} height={H} viewBox={`0 0 ${W} ${H}`}>
{[0, 0.5, 1].map((f) => (
<G key={f}>
<Line x1={padL} y1={y(maxV * f)} x2={W} y2={y(maxV * f)} stroke={C.gridline} strokeWidth={1} />
<SvgText x={padL - 5} y={y(maxV * f) + 3} textAnchor="end" fill={C.muted} fontSize={9.5}>
{fmt(maxV * f)}
</SvgText>
</G>
))}
{data.map((d, i) => {
const x = padL + (i + 0.5) * (iw / n) - bw / 2;
return (
<G key={d.day} onPress={() => setSel(i === sel ? null : i)}>
<Rect x={x - 1} y={8} width={bw + 2} height={H - padB - 8} fill="transparent" />
<Rect x={x} y={y(d.value)} width={bw} height={Math.max(1, H - padB - y(d.value))}
rx={1.5} fill={color} opacity={sel == null || sel === i ? 1 : 0.35} />
</G>
);
})}
<SvgText x={padL} y={H - 3} fill={C.muted} fontSize={9.5}>{fmtD(data[0].day)}</SvgText>
<SvgText x={W} y={H - 3} textAnchor="end" fill={C.muted} fontSize={9.5}>
{fmtD(data[n - 1].day)}
</SvgText>
</Svg>
{selD && (
<DetailCard title={fmtDY(selD.day)} rows={[[unit, `${num(Math.round(selD.value))}`]]} />
)}
</View>
);
}
/* daily line with dots (resting HR, HRV, SpO2…) — tap a point for value */
export function DailyLine({
data, width, unit, color = C.s3, decimals = 0,
}: {
data: { day: string; avg: number }[];
width: number;
unit: string;
color?: string;
decimals?: number;
}) {
const [sel, setSel] = useState<number | null>(null);
if (data.length < 2) return null;
const H = 110, padL = 34, padB = 16, padT = 8, W = width;
const iw = W - padL, n = data.length;
const vs = data.map((d) => d.avg);
const min = Math.min(...vs), max = Math.max(...vs);
const span = max - min || 1;
const x = (i: number) => padL + (i + 0.5) * (iw / n);
const y = (v: number) => H - padB - ((v - min) / span) * (H - padB - padT);
const path = data.map((d, i) => (i ? 'L' : 'M') + x(i).toFixed(1) + ' ' + y(d.avg).toFixed(1)).join(' ');
const selD = sel != null ? data[sel] : null;
return (
<View>
<Svg width={W} height={H} viewBox={`0 0 ${W} ${H}`}>
{[min, max].map((v) => (
<G key={v}>
<Line x1={padL} y1={y(v)} x2={W} y2={y(v)} stroke={C.gridline} strokeWidth={1} />
<SvgText x={padL - 5} y={y(v) + 3} textAnchor="end" fill={C.muted} fontSize={9.5}>
{v.toFixed(decimals)}
</SvgText>
</G>
))}
<Path d={path} fill="none" stroke={color} strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" opacity={0.85} />
{data.map((d, i) => (
<G key={d.day} onPress={() => setSel(i === sel ? null : i)}>
<Rect x={x(i) - iw / n / 2} y={0} width={iw / n} height={H - padB} fill="transparent" />
<Circle cx={x(i)} cy={y(d.avg)} r={sel === i ? 4.5 : 2.5} fill={color}
stroke={C.surface} strokeWidth={1} />
</G>
))}
<SvgText x={padL} y={H - 3} fill={C.muted} fontSize={9.5}>{fmtD(data[0].day)}</SvgText>
<SvgText x={W} y={H - 3} textAnchor="end" fill={C.muted} fontSize={9.5}>
{fmtD(data[n - 1].day)}
</SvgText>
</Svg>
{selD && (
<DetailCard title={fmtDY(selD.day)} rows={[[unit, selD.avg.toFixed(decimals)]]} />
)}
</View>
);
}
/* biomarker sparkline */
export function Sparkline({
pts, flagged, width,

328
src/components/kit.tsx Normal file
View File

@@ -0,0 +1,328 @@
/* Jarvis component kit: the pieces the Today screen is built from.
Plain React Native on the tokens in lib/theme, so every surface is ours to shape. */
import { router } from 'expo-router';
import React from 'react';
import { Pressable, StyleSheet, Text, View, ViewStyle } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import type { CellState, GoalRow, Habit, StreakRow, TodayItem } from '../lib/life';
import { C, F, R, SYS } from '../lib/theme';
/* ---- surfaces ---- */
export function Card({ children, style }: { children: React.ReactNode; style?: ViewStyle }) {
return <View style={[s.card, style]}>{children}</View>;
}
/** Section heading with an optional action on the right. */
export function Heading({
title, action, onAction, meta,
}: {
title: string;
action?: string;
onAction?: () => void;
meta?: string;
}) {
return (
<View style={s.heading}>
<Text style={s.headingT}>{title}</Text>
{action ? (
<Pressable onPress={onAction} hitSlop={10} accessibilityRole="button">
<Text style={s.headingA}>{action}</Text>
</Pressable>
) : meta ? (
<Text style={s.headingM}>{meta}</Text>
) : null}
</View>
);
}
/** Round icon button, as on a map screen. */
export function RoundButton({
glyph, onPress, label,
}: {
glyph: string;
onPress: () => void;
label: string;
}) {
return (
<Pressable
onPress={onPress} hitSlop={8} accessibilityRole="button" accessibilityLabel={label}
style={({ pressed }) => [s.round, pressed && { opacity: 0.7 }]}>
<Text style={s.roundT}>{glyph}</Text>
</Pressable>
);
}
/* ---- today's protocol ---- */
/** One rule. Manual rules toggle on tap and turn green when done; auto rules show their state. */
export function CheckRow({
item, onToggle, last,
}: {
item: TodayItem;
onToggle?: (done: boolean | null) => void;
last?: boolean;
}) {
const done = item.status === 'met';
const missed = item.status === 'missed';
const tappable = !item.auto && !item.week && !!onToggle;
let sub: string | null = null;
if (item.week) sub = `${item.week.count} of ${item.week.need} this week`;
else if (item.auto) {
sub = done ? 'Met, from your trackers'
: missed ? 'Missed, from your trackers'
: item.status === 'nodata' ? 'No tracker data yet'
: 'Ticks itself from your trackers';
}
const body = (
<View style={[s.row, done && s.rowDone, !last && s.rowLine]}>
<View style={[s.box, done && s.boxDone, missed && s.boxMiss]}>
{done ? <Text style={s.boxTick}>✓</Text> : missed ? <Text style={s.boxX}>✕</Text> : null}
</View>
<View style={{ flex: 1 }}>
<Text style={[s.rowT, done && { color: C.text }]}>{item.label}</Text>
{sub ? <Text style={s.rowSub}>{sub}</Text> : null}
</View>
{item.auto ? <Text style={s.auto}>auto</Text> : null}
<View style={[s.sysDot, { backgroundColor: SYS[item.system] ?? C.dim }]} />
</View>
);
if (!tappable) return body;
return (
<Pressable
onPress={() => onToggle!(done ? null : true)}
accessibilityRole="checkbox" accessibilityState={{ checked: done }}
style={({ pressed }) => pressed && { opacity: 0.6 }}>
{body}
</Pressable>
);
}
/* ---- 14-day streak grid ---- */
function Cell({ state, color, today }: { state: CellState; color: string; today: boolean }) {
const bg =
state === 'met' ? color
: state === 'part' ? color + '66' // 40% of the system colour
: state === 'miss' ? C.border
: 'transparent';
return (
<View
style={[
s.cell,
{ backgroundColor: bg },
state === 'none' && { borderWidth: 1, borderColor: C.border },
today && { borderWidth: 1.5, borderColor: C.text },
]}
/>
);
}
export function StreakGrid({
rows, onRow,
}: {
rows: StreakRow[];
/** omit for rows that lead nowhere */
onRow?: (key: string) => void;
}) {
return (
<View>
{rows.map((r) => {
const color = SYS[r.color ?? r.key] ?? C.accent;
const inner = (
<>
<Text style={s.streakName} numberOfLines={1}>{r.label}</Text>
<View style={s.cells}>
{r.cells.map((c, i) => (
<Cell key={i} state={c} color={color} today={i === r.cells.length - 1} />
))}
</View>
<Text style={s.streakPct}>{r.pct == null ? '' : `${r.pct}%`}</Text>
</>
);
return onRow ? (
<Pressable
key={r.key} onPress={() => onRow(r.key)} accessibilityRole="button"
accessibilityLabel={`${r.label}, ${r.pct == null ? 'no data' : r.pct + ' percent'}`}
style={({ pressed }) => [s.streakRow, pressed && { opacity: 0.6 }]}>
{inner}
</Pressable>
) : (
<View key={r.key} style={s.streakRow}>{inner}</View>
);
})}
<View style={s.axis}>
<Text style={s.axisT}>14 days ago</Text>
<Text style={s.axisT}>today</Text>
</View>
</View>
);
}
/* ---- the daily six: one big square per habit, tap to mark it done ---- */
export function HabitCard({ habit, onToggle }: { habit: Habit; onToggle: (done: boolean | null) => void }) {
const color = SYS[habit.system] ?? C.accent;
return (
<Pressable
onPress={() => onToggle(habit.done ? null : true)}
accessibilityRole="checkbox" accessibilityState={{ checked: habit.done }}
accessibilityLabel={habit.label}
style={({ pressed }) => [
s.habit,
habit.done && { backgroundColor: color },
pressed && { transform: [{ scale: 0.97 }] },
]}>
<View style={[s.habitRing, { borderColor: habit.done ? '#FFFFFF' : color }, habit.done && { backgroundColor: '#FFFFFF' }]}>
{habit.done ? <Text style={[s.habitTick, { color }]}>✓</Text> : null}
</View>
<View>
<Text style={[s.habitT, habit.done && { color: '#FFFFFF' }]}>{habit.label}</Text>
<Text style={[s.habitS, habit.done && { color: 'rgba(255,255,255,0.85)' }]}>
{habit.done ? 'Done today' : 'Tap when done'}
</Text>
</View>
</Pressable>
);
}
export function HabitGrid({ children }: { children: React.ReactNode }) {
return <View style={s.habits}>{children}</View>;
}
/* ---- goals ---- */
export function GoalBar({ goal }: { goal: GoalRow }) {
const color = SYS[goal.system] ?? C.accent;
return (
<View style={s.goal}>
<View style={s.goalHead}>
<Text style={s.goalT} numberOfLines={1}>{goal.title}</Text>
<Text style={s.goalV}>{goal.value}</Text>
</View>
<View style={s.track}>
<View
style={{
width: `${Math.round((goal.progress ?? 0) * 100)}%`, height: '100%',
borderRadius: 3, backgroundColor: color,
}}
/>
</View>
</View>
);
}
/* ---- chat bar, pinned to the bottom of a screen ---- */
export const CHAT_BAR_SPACE = 92;
export function ChatBar() {
const insets = useSafeAreaInsets();
return (
<View pointerEvents="box-none" style={[s.chatWrap, { paddingBottom: Math.max(insets.bottom, 12) }]}>
<Pressable
onPress={() => router.push('/chat')} accessibilityRole="button"
accessibilityLabel="Ask or log anything"
style={({ pressed }) => [s.chat, pressed && { opacity: 0.85 }]}>
<Text style={s.chatT}>Ask or log anything</Text>
<View style={s.mic}>
<View style={s.micBody} />
<View style={s.micStem} />
</View>
</Pressable>
</View>
);
}
const s = StyleSheet.create({
card: {
backgroundColor: C.surface, borderRadius: R.card, borderCurve: 'continuous',
overflow: 'hidden',
},
heading: {
flexDirection: 'row', justifyContent: 'space-between', alignItems: 'baseline',
marginTop: 26, marginBottom: 10, paddingHorizontal: 4,
},
headingT: { fontFamily: F.bold, fontSize: 19, color: C.text, letterSpacing: -0.2 },
headingA: { fontFamily: F.semibold, fontSize: 15, color: C.accent },
headingM: { fontFamily: F.medium, fontSize: 14, color: C.muted },
round: {
width: 44, height: 44, borderRadius: 22, backgroundColor: C.surface,
alignItems: 'center', justifyContent: 'center',
shadowColor: '#0C1730', shadowOpacity: 0.08, shadowRadius: 8, shadowOffset: { width: 0, height: 2 },
elevation: 2,
},
roundT: { fontSize: 19, color: C.text },
row: { flexDirection: 'row', alignItems: 'center', gap: 13, paddingVertical: 13, paddingHorizontal: 16 },
rowDone: { backgroundColor: C.greenDim },
rowLine: { borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: C.border },
rowT: { fontFamily: F.semibold, fontSize: 16, color: C.text },
rowSub: { fontFamily: F.regular, fontSize: 13, color: C.muted, marginTop: 2 },
box: {
width: 28, height: 28, borderRadius: 9, borderCurve: 'continuous',
backgroundColor: C.surface2, alignItems: 'center', justifyContent: 'center',
},
boxDone: { backgroundColor: C.green },
boxMiss: { backgroundColor: C.redDim },
boxTick: { color: '#FFFFFF', fontSize: 16, fontFamily: F.heavy, lineHeight: 19 },
boxX: { color: C.red, fontSize: 13, fontFamily: F.bold, lineHeight: 16 },
auto: {
fontFamily: F.medium, fontSize: 12, color: C.muted, backgroundColor: C.surface2,
paddingHorizontal: 9, paddingVertical: 3, borderRadius: R.pill, overflow: 'hidden',
},
sysDot: { width: 8, height: 8, borderRadius: 4 },
streakRow: { flexDirection: 'row', alignItems: 'center', paddingVertical: 7, paddingHorizontal: 16 },
streakName: { width: 74, fontFamily: F.semibold, fontSize: 15, color: C.text },
cells: { flex: 1, flexDirection: 'row', gap: 4 },
cell: { flex: 1, aspectRatio: 1, borderRadius: 5, borderCurve: 'continuous' },
streakPct: {
width: 44, textAlign: 'right', fontFamily: F.medium, fontSize: 13, color: C.muted,
fontVariant: ['tabular-nums'],
},
axis: {
flexDirection: 'row', justifyContent: 'space-between',
marginLeft: 90, marginRight: 60, marginTop: 4,
},
axisT: { fontFamily: F.regular, fontSize: 11.5, color: C.dim },
habits: { flexDirection: 'row', flexWrap: 'wrap', gap: 12 },
habit: {
width: '48.2%', aspectRatio: 1, borderRadius: R.card, borderCurve: 'continuous',
backgroundColor: C.surface, padding: 16, justifyContent: 'space-between',
},
habitRing: {
width: 40, height: 40, borderRadius: 20, borderWidth: 3,
alignItems: 'center', justifyContent: 'center',
},
habitTick: { fontFamily: F.heavy, fontSize: 21, lineHeight: 25 },
habitT: { fontFamily: F.bold, fontSize: 19, lineHeight: 23, letterSpacing: -0.2, color: C.text },
habitS: { fontFamily: F.medium, fontSize: 13.5, color: C.muted, marginTop: 5 },
goal: { paddingVertical: 11, paddingHorizontal: 16 },
goalHead: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'baseline', gap: 12, marginBottom: 8 },
goalT: { flex: 1, fontFamily: F.semibold, fontSize: 15.5, color: C.text },
goalV: { fontFamily: F.medium, fontSize: 13.5, color: C.muted, fontVariant: ['tabular-nums'] },
track: { height: 6, borderRadius: 3, backgroundColor: C.surface2, overflow: 'hidden' },
chatWrap: { position: 'absolute', left: 0, right: 0, bottom: 0, paddingHorizontal: 14, paddingTop: 10 },
chat: {
height: 58, borderRadius: 29, backgroundColor: C.surface, paddingLeft: 22, paddingRight: 9,
flexDirection: 'row', alignItems: 'center',
shadowColor: '#0C1730', shadowOpacity: 0.16, shadowRadius: 18, shadowOffset: { width: 0, height: 6 },
elevation: 8,
},
chatT: { flex: 1, fontFamily: F.medium, fontSize: 16.5, color: C.muted },
mic: {
width: 42, height: 42, borderRadius: 21, backgroundColor: C.accent,
alignItems: 'center', justifyContent: 'center',
},
micBody: { width: 9, height: 15, borderRadius: 5, backgroundColor: C.onAccent },
micStem: { width: 2, height: 4, backgroundColor: C.onAccent, marginTop: 2, borderRadius: 1 },
});

View File

@@ -1,84 +0,0 @@
import React, { useState } from 'react';
import {
KeyboardAvoidingView, Platform, Pressable, StyleSheet, Text, TextInput, View,
} from 'react-native';
import { useAuth } from '../lib/api';
import { C } from '../lib/theme';
export function LoginScreen() {
const { login } = useAuth();
const [user, setUser] = useState('admin');
const [pass, setPass] = useState('');
const [err, setErr] = useState('');
const [busy, setBusy] = useState(false);
const go = async () => {
setBusy(true);
setErr('');
try {
const ok = await login(user.trim(), pass);
if (!ok) setErr('Wrong password.');
else setPass('');
} catch {
setErr('Network error — are you online?');
} finally {
setBusy(false);
}
};
return (
<KeyboardAvoidingView
style={s.wrap}
behavior={Platform.OS === 'ios' ? 'padding' : undefined}>
<View style={s.card}>
<Text style={{ fontSize: 34, marginBottom: 10 }}>⚕️</Text>
<Text style={s.h1}>Health Dashboard</Text>
<Text style={s.sub}>health.rehbock.xyz — private</Text>
<Text style={s.lbl}>USER</Text>
<TextInput
style={s.input}
value={user}
onChangeText={setUser}
autoCapitalize="none"
autoCorrect={false}
textContentType="username"
/>
<Text style={s.lbl}>PASSWORD</Text>
<TextInput
style={s.input}
value={pass}
onChangeText={setPass}
secureTextEntry
textContentType="password"
onSubmitEditing={go}
returnKeyType="go"
/>
<Pressable style={[s.go, busy && { opacity: 0.5 }]} disabled={busy} onPress={go}>
<Text style={{ color: '#fff', fontWeight: '600', fontSize: 15 }}>Unlock</Text>
</Pressable>
<Text style={s.err}>{err}</Text>
</View>
</KeyboardAvoidingView>
);
}
const s = StyleSheet.create({
wrap: {
flex: 1, backgroundColor: C.bg, alignItems: 'center', justifyContent: 'center', padding: 24,
},
card: {
width: '100%', maxWidth: 340, backgroundColor: C.surface, borderWidth: 1,
borderColor: C.border, borderRadius: 16, paddingVertical: 28, paddingHorizontal: 24,
},
h1: { fontSize: 18, fontWeight: '600', color: C.text, marginBottom: 4 },
sub: { fontSize: 12, color: C.muted, marginBottom: 20 },
lbl: { fontSize: 11, color: C.muted, letterSpacing: 0.5, marginTop: 12, marginBottom: 5 },
input: {
paddingVertical: 11, paddingHorizontal: 12, borderRadius: 10, borderWidth: 1,
borderColor: C.border, backgroundColor: C.surface2, color: C.text, fontSize: 15,
},
go: {
marginTop: 20, padding: 12, borderRadius: 10, backgroundColor: C.accent, alignItems: 'center',
},
err: { marginTop: 12, fontSize: 12.5, color: C.red, minHeight: 18 },
});

View File

@@ -14,51 +14,43 @@ export const EP = {
medStats: `${BASE}/api/meditation/v1/stats`,
medSessions: `${BASE}/api/meditation/v1/sessions?limit=1000`,
traits: `${BASE}/ancestry-traits.json`,
fitbitSummary: `${BASE}/api/health/v1/fitbit/summary?days=30`,
fitbitLatest: `${BASE}/api/health/v1/fitbit/latest`,
lifeAdherence: `${BASE}/api/health/v1/life/adherence?days=14`,
lifeGoals: `${BASE}/api/health/v1/life/goals`,
} as const;
export const FITBIT_SYNC_URL = `${BASE}/api/health/v1/fitbit/sync`;
/* authenticated POST (fitbit sync) */
export async function postJson<T>(url: string, body: unknown): Promise<T> {
if (!token) throw new Error(NO_TOKEN);
const r = await fetch(url, {
method: 'POST',
headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
if (r.status === 401 || r.status === 403) throw new Error(BAD_TOKEN);
if (!r.ok) throw new Error(`${url} → ${r.status}`);
return r.json();
}
export type EpKey = keyof typeof EP;
const AUTH_KEY = 'hd.auth';
const AUTH_KEY = 'hd.token';
export const NO_TOKEN = 'No API token — add one in Settings.';
export const BAD_TOKEN = 'API token rejected — check it in Settings.';
let token: string | null = null;
let onUnauthorized: (() => void) | null = null;
/* base64 without Buffer/btoa dependency quirks across Hermes versions */
const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
export function b64(str: string): string {
const bytes: number[] = [];
for (let i = 0; i < str.length; i++) {
const code = str.codePointAt(i)!;
if (code > 0xffff) i++;
if (code < 0x80) bytes.push(code);
else if (code < 0x800) bytes.push(0xc0 | (code >> 6), 0x80 | (code & 63));
else if (code < 0x10000)
bytes.push(0xe0 | (code >> 12), 0x80 | ((code >> 6) & 63), 0x80 | (code & 63));
else
bytes.push(
0xf0 | (code >> 18), 0x80 | ((code >> 12) & 63),
0x80 | ((code >> 6) & 63), 0x80 | (code & 63),
);
}
let out = '';
for (let i = 0; i < bytes.length; i += 3) {
const [a, b, c] = [bytes[i], bytes[i + 1], bytes[i + 2]];
out += B64[a >> 2] + B64[((a & 3) << 4) | (b ?? 0) >> 4];
out += b === undefined ? '=' : B64[((b & 15) << 2) | (c ?? 0) >> 6];
out += c === undefined ? '=' : B64[c & 63];
}
return out;
}
async function authFetch<T>(url: string): Promise<T> {
if (!token) throw new Error(NO_TOKEN);
const r = await fetch(url, {
headers: { Authorization: 'Basic ' + token },
headers: { Authorization: 'Bearer ' + token },
cache: 'no-store',
});
if (r.status === 401 || r.status === 403) {
onUnauthorized?.();
throw new Error('unauthorized');
}
if (r.status === 401 || r.status === 403) throw new Error(BAD_TOKEN);
if (!r.ok) throw new Error(`${url} → ${r.status}`);
return r.json();
}
@@ -79,66 +71,67 @@ export function clearCache() {
cache = {};
}
/* drop specific endpoints from the cache so the next load() refetches */
export function invalidate(...keys: EpKey[]) {
for (const k of keys) delete cache[k];
}
/* ---- auth context ---- */
interface AuthCtx {
ready: boolean;
authed: boolean;
login: (user: string, pass: string) => Promise<boolean>;
logout: () => void;
/** an API token is stored (it may still be rejected by the server) */
hasToken: boolean;
/** verify against the server, then store; false = server rejected it */
saveToken: (t: string) => Promise<boolean>;
clearToken: () => void;
}
const Ctx = createContext<AuthCtx>({
ready: false,
authed: false,
login: async () => false,
logout: () => {},
hasToken: false,
saveToken: async () => false,
clearToken: () => {},
});
export const useAuth = () => useContext(Ctx);
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [ready, setReady] = useState(false);
const [authed, setAuthed] = useState(false);
const [hasToken, setHasToken] = useState(false);
useEffect(() => {
SecureStore.getItemAsync(AUTH_KEY)
.then((t) => {
if (t) {
token = t;
setAuthed(true);
setHasToken(true);
}
})
.catch(() => {})
.finally(() => setReady(true));
}, []);
const logout = useCallback(() => {
const clearToken = useCallback(() => {
token = null;
clearCache();
SecureStore.deleteItemAsync(AUTH_KEY).catch(() => {});
setAuthed(false);
setHasToken(false);
}, []);
useEffect(() => {
onUnauthorized = logout;
return () => {
onUnauthorized = null;
};
}, [logout]);
const login = useCallback(async (user: string, pass: string) => {
const tok = b64(`${user}:${pass}`);
const saveToken = useCallback(async (raw: string) => {
const t = raw.trim();
const r = await fetch(EP.meta, {
headers: { Authorization: 'Basic ' + tok },
headers: { Authorization: 'Bearer ' + t },
cache: 'no-store',
});
if (!r.ok) return false;
token = tok;
token = t;
clearCache();
await SecureStore.setItemAsync(AUTH_KEY, tok);
setAuthed(true);
await SecureStore.setItemAsync(AUTH_KEY, t);
setHasToken(true);
return true;
}, []);
return <Ctx.Provider value={{ ready, authed, login, logout }}>{children}</Ctx.Provider>;
return <Ctx.Provider value={{ ready, hasToken, saveToken, clearToken }}>{children}</Ctx.Provider>;
}

72
src/lib/brief.ts Normal file
View File

@@ -0,0 +1,72 @@
/* The Today brief, written from data already on the screen.
A later version will come from the chat model; this one only states facts. */
import { agoTxt, daysAgo, fmtD } from './format';
import type { AdherenceResponse, GoalsResponse } from './life';
export interface Brief {
headline: string;
lines: string[];
}
export interface BriefInput {
/** most recent recorded night */
sleep?: { date: string; asleepSec: number } | null;
/** most recent workout */
workout?: { title: string; start: string } | null;
adherence?: AdherenceResponse | null;
goals?: GoalsResponse | null;
}
const hmText = (sec: number) => {
const h = Math.floor(sec / 3600);
const m = Math.round((sec % 3600) / 60);
return `${h} h ${String(m).padStart(2, '0')}`;
};
function greeting(): string {
const h = new Date().getHours();
return h < 12 ? 'Good morning' : h < 18 ? 'Good afternoon' : 'Good evening';
}
export function buildBrief(i: BriefInput): Brief {
const lines: string[] = [];
let headline = greeting();
// sleep: only talk about last night if the tracker actually reported it
if (i.sleep) {
const age = daysAgo(i.sleep.date);
if (age <= 1) {
headline = `You slept ${hmText(i.sleep.asleepSec)}`;
const sleepRule = i.adherence?.protocols
.find((p) => p.system === 'sleep')?.rules.find((r) => r.metric === 'sleep.hours');
const target = typeof sleepRule?.value === 'number' ? sleepRule.value * 3600 : null;
if (target != null) {
const diff = Math.round((i.sleep.asleepSec - target) / 60);
lines.push(diff >= 0
? `That is ${diff} minutes over your ${sleepRule!.value} hour protocol.`
: `That is ${-diff} minutes short of your ${sleepRule!.value} hour protocol.`);
}
} else {
lines.push(`No sleep data since ${fmtD(i.sleep.date)}. Eight Sleep has stopped syncing.`);
}
}
// training: last session and this week's count against the weekly rule
if (i.workout) {
const train = i.adherence?.protocols.find((p) => p.system === 'train');
const weekly = train?.rules.find((r) => r.period === 'week' && r.metric === 'train.workouts');
const weeks = train ? Object.keys(train.weeks).sort() : [];
const cur = weekly && weeks.length ? train!.weeks[weeks[weeks.length - 1]]?.[weekly.id] : null;
const last = `Your last lift was ${i.workout.title}, ${agoTxt(i.workout.start)}.`;
lines.push(cur ? `${last} ${cur.count} of ${cur.need} sessions this week.` : last);
}
// mind: minutes this week against the goal
const med = i.goals?.goals.find((g) => g.metric === 'mind.minutes_7d');
if (med && med.current != null) {
lines.push(`Meditation is at ${Math.round(med.current)} of ${med.target} minutes this week.`);
}
if (!lines.length) lines.push('Pull down to refresh once your trackers have synced.');
return { headline, lines };
}

193
src/lib/fitbit.ts Normal file
View File

@@ -0,0 +1,193 @@
/* Fitbit Air → Health Connect → health.rehbock.xyz sync.
Android-only: react-native-health-connect is loaded lazily so the module's
absence (iOS, Expo Go) never crashes the app. */
import { Platform } from 'react-native';
import { FITBIT_SYNC_URL, invalidate, load, postJson } from './api';
export interface SyncResult {
ok: boolean;
samples: number;
daily: number;
sleep: number;
message: string;
}
interface Sample { type: string; t: string; value: number }
interface DailyRow { type: string; day: string; value: number }
interface SleepRow {
id: string; started_at: string; ended_at: string;
total_seconds: number; sleep_seconds: number;
deep_seconds: number; rem_seconds: number; light_seconds: number; awake_seconds: number;
}
const READ_PERMISSIONS = [
'HeartRate', 'RestingHeartRate', 'HeartRateVariabilityRmssd', 'OxygenSaturation',
'SleepSession', 'Steps', 'RespiratoryRate', 'Distance',
'ActiveCaloriesBurned', 'TotalCaloriesBurned', 'FloorsClimbed',
] as const;
const FIRST_SYNC_LOOKBACK_DAYS = 60;
const OVERLAP_MS = 6 * 3600 * 1000; // re-read a little so late-arriving records land
function hc() {
// require at call time — the native module only exists in the Android build
return require('react-native-health-connect');
}
export function healthConnectSupported(): boolean {
return Platform.OS === 'android';
}
export async function healthConnectStatus(): Promise<'available' | 'needs-update' | 'unavailable' | 'unsupported'> {
if (!healthConnectSupported()) return 'unsupported';
try {
const { getSdkStatus, SdkAvailabilityStatus } = hc();
const s = await getSdkStatus();
if (s === SdkAvailabilityStatus.SDK_AVAILABLE) return 'available';
if (s === SdkAvailabilityStatus.SDK_UNAVAILABLE_PROVIDER_UPDATE_REQUIRED) return 'needs-update';
return 'unavailable';
} catch {
return 'unavailable';
}
}
async function readAll(recordType: string, startTime: string, endTime: string): Promise<any[]> {
const { readRecords } = hc();
const out: any[] = [];
let pageToken: string | undefined;
do {
const res = await readRecords(recordType, {
timeRangeFilter: { operator: 'between', startTime, endTime },
pageSize: 1000,
...(pageToken ? { pageToken } : {}),
});
out.push(...(res.records || []));
pageToken = res.pageToken || undefined;
} while (pageToken && out.length < 200000);
return out;
}
const localDay = (iso: string) => {
const d = new Date(iso);
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
};
/* HC sleep stage constants (androidx.health.connect SleepStageType) */
const STAGE = { AWAKE: 1, SLEEPING: 2, OUT_OF_BED: 3, LIGHT: 4, DEEP: 5, REM: 6, AWAKE_IN_BED: 7 };
export async function syncFitbit(onProgress?: (msg: string) => void): Promise<SyncResult> {
if (!healthConnectSupported())
return { ok: false, samples: 0, daily: 0, sleep: 0, message: 'Health Connect is Android-only' };
const { initialize, requestPermission } = hc();
const say = (m: string) => onProgress?.(m);
say('Initializing Health Connect…');
const ok = await initialize();
if (!ok) return { ok: false, samples: 0, daily: 0, sleep: 0, message: 'Health Connect init failed' };
say('Requesting permissions…');
await requestPermission(READ_PERMISSIONS.map((r) => ({ accessType: 'read', recordType: r })));
say('Checking server watermark…');
invalidate('fitbitLatest'); // watermark must be fresh, never the session-cached copy
const latest = await load<{
samples: Record<string, string | null>;
daily: Record<string, string | null>;
sleep: string | null;
}>('fitbitLatest');
const now = new Date();
const endTime = now.toISOString();
const fallback = new Date(now.getTime() - FIRST_SYNC_LOOKBACK_DAYS * 86400000).toISOString();
const sinceFor = (watermark: string | null) =>
watermark ? new Date(new Date(watermark).getTime() - OVERLAP_MS).toISOString() : fallback;
const samples: Sample[] = [];
const daily = new Map<string, DailyRow>();
const sleep: SleepRow[] = [];
// continuous heart rate (records carry arrays of samples)
say('Reading heart rate…');
for (const rec of await readAll('HeartRate', sinceFor(latest.samples.heart_rate), endTime))
for (const s of rec.samples || [])
samples.push({ type: 'heart_rate', t: s.time, value: s.beatsPerMinute });
say('Reading vitals…');
for (const rec of await readAll('RestingHeartRate', sinceFor(latest.samples.resting_hr), endTime))
samples.push({ type: 'resting_hr', t: rec.time, value: rec.beatsPerMinute });
for (const rec of await readAll('HeartRateVariabilityRmssd', sinceFor(latest.samples.hrv_rmssd), endTime))
samples.push({ type: 'hrv_rmssd', t: rec.time, value: rec.heartRateVariabilityMillis });
for (const rec of await readAll('OxygenSaturation', sinceFor(latest.samples.spo2), endTime))
samples.push({ type: 'spo2', t: rec.time, value: rec.percentage });
for (const rec of await readAll('RespiratoryRate', sinceFor(latest.samples.respiratory_rate), endTime))
samples.push({ type: 'respiratory_rate', t: rec.time, value: rec.rate });
// interval records → per-local-day sums
say('Reading activity…');
const addDaily = (type: string, day: string, value: number) => {
const k = `${type}|${day}`;
const cur = daily.get(k);
if (cur) cur.value += value;
else daily.set(k, { type, day, value });
};
const dailyStart = (t: string | null) => sinceFor(t);
for (const rec of await readAll('Steps', dailyStart(latest.daily.steps ? latest.daily.steps + 'T00:00:00Z' : null), endTime))
addDaily('steps', localDay(rec.startTime), rec.count || 0);
for (const rec of await readAll('Distance', dailyStart(latest.daily.distance_m ? latest.daily.distance_m + 'T00:00:00Z' : null), endTime))
addDaily('distance_m', localDay(rec.startTime), rec.distance?.inMeters ?? 0);
for (const rec of await readAll('ActiveCaloriesBurned', dailyStart(latest.daily.active_kcal ? latest.daily.active_kcal + 'T00:00:00Z' : null), endTime))
addDaily('active_kcal', localDay(rec.startTime), rec.energy?.inKilocalories ?? 0);
for (const rec of await readAll('TotalCaloriesBurned', dailyStart(latest.daily.total_kcal ? latest.daily.total_kcal + 'T00:00:00Z' : null), endTime))
addDaily('total_kcal', localDay(rec.startTime), rec.energy?.inKilocalories ?? 0);
for (const rec of await readAll('FloorsClimbed', dailyStart(latest.daily.floors ? latest.daily.floors + 'T00:00:00Z' : null), endTime))
addDaily('floors', localDay(rec.startTime), rec.floors || 0);
say('Reading sleep…');
for (const rec of await readAll('SleepSession', sinceFor(latest.sleep), endTime)) {
const startMs = new Date(rec.startTime).getTime();
const endMs = new Date(rec.endTime).getTime();
let deep = 0, rem = 0, light = 0, awake = 0, asleep = 0;
for (const st of rec.stages || []) {
const sec = (new Date(st.endTime).getTime() - new Date(st.startTime).getTime()) / 1000;
if (st.stage === STAGE.DEEP) deep += sec;
else if (st.stage === STAGE.REM) rem += sec;
else if (st.stage === STAGE.LIGHT || st.stage === STAGE.SLEEPING) light += sec;
else if (st.stage === STAGE.AWAKE || st.stage === STAGE.AWAKE_IN_BED || st.stage === STAGE.OUT_OF_BED) awake += sec;
}
asleep = deep + rem + light;
const total = (endMs - startMs) / 1000;
if (asleep === 0) asleep = Math.max(0, total - awake); // unstaged session
sleep.push({
id: rec.metadata?.id || `${rec.startTime}-${rec.endTime}`,
started_at: rec.startTime, ended_at: rec.endTime,
total_seconds: Math.round(total), sleep_seconds: Math.round(asleep),
deep_seconds: Math.round(deep), rem_seconds: Math.round(rem),
light_seconds: Math.round(light), awake_seconds: Math.round(awake),
});
}
say('Uploading…');
let ns = 0, nd = 0, nl = 0;
const dailyRows = [...daily.values()];
const CHUNK = 4000;
for (let i = 0; i < Math.max(1, Math.ceil(samples.length / CHUNK)); i++) {
const chunk = samples.slice(i * CHUNK, (i + 1) * CHUNK);
const body = {
samples: chunk,
daily: i === 0 ? dailyRows : [],
sleep: i === 0 ? sleep : [],
};
if (!chunk.length && i > 0) break;
const res = await postJson<{ samples: number; daily: number; sleep: number }>(FITBIT_SYNC_URL, body);
ns += res.samples; nd += res.daily; nl += res.sleep;
}
// new rows exist server-side — cached copies of these are now stale
invalidate('fitbitSummary', 'fitbitLatest');
return {
ok: true, samples: ns, daily: nd, sleep: nl,
message: `Synced ${ns} samples, ${nd} daily rows, ${nl} sleep sessions`,
};
}

275
src/lib/life.ts Normal file
View File

@@ -0,0 +1,275 @@
/* Life systems: protocols, check-ins, streaks and goals.
Types mirror health-api `life.ts` (GET /v1/life/adherence, /v1/life/goals). */
import { EP, invalidate, postJson } from './api';
export type RuleStatus = 'met' | 'missed' | 'unlogged' | 'nodata' | 'pending';
export interface LifeRule {
id: string;
label: string;
/** present = evaluated automatically from tracker data; absent = manual check-in */
metric?: string;
op?: '>=' | '<=' | '>' | '<' | '==';
value?: number | string;
period?: 'day' | 'week';
count?: number;
}
export interface LifeProtocol {
id: string;
key: string;
system: string;
name: string;
version: number;
started_on: string;
ended_on: string | null;
notes?: string | null;
rules: LifeRule[];
pct: number | null;
streak: number;
daily: Record<string, {
pct: number | null;
rules: Record<string, { status: RuleStatus; value: number | boolean | null }>;
}>;
weeks: Record<string, Record<string, { status: RuleStatus; count: number; need: number }>>;
}
export interface AdherenceResponse {
tz: string;
today: string;
from: string;
days: string[];
overall: { pct: number | null; today: number | null };
systems: Record<string, number | null>;
protocols: LifeProtocol[];
metrics: Record<string, Record<string, number>>;
}
export interface LifeGoal {
id: string;
system: string;
title: string;
metric: string | null;
unit: string | null;
baseline: number | null;
target: number;
current_manual: number | null;
current: number | null;
/** 0–1, or null when there is nothing to measure yet */
progress: number | null;
deadline: string | null;
achieved_at: string | null;
}
export interface GoalsResponse {
goals: LifeGoal[];
}
/* ---- systems ---- */
export type SystemKey = 'sleep' | 'train' | 'diet' | 'mind' | 'wealth' | 'relate';
export const SYSTEMS: { key: SystemKey; label: string }[] = [
{ key: 'sleep', label: 'Sleep' },
{ key: 'train', label: 'Train' },
{ key: 'diet', label: 'Diet' },
{ key: 'mind', label: 'Mind' },
{ key: 'wealth', label: 'Wealth' },
{ key: 'relate', label: 'People' },
];
const systemOrder = (s: string) => {
const i = SYSTEMS.findIndex((x) => x.key === s);
return i < 0 ? SYSTEMS.length : i;
};
/* ---- today's protocol ---- */
export interface TodayItem {
protocolId: string;
ruleId: string;
system: string;
label: string;
/** ticks itself from tracker data; cannot be tapped */
auto: boolean;
status: RuleStatus;
/** weekly rules: progress through the week, e.g. 2 of 4 */
week?: { count: number; need: number };
}
/** Monday of the week containing `day` (YYYY-MM-DD), matching the server's weekOf(). */
function weekOf(day: string): string {
const [y, m, d] = day.split('-').map(Number);
const dt = new Date(Date.UTC(y, m - 1, d));
const dow = (dt.getUTCDay() + 6) % 7;
dt.setUTCDate(dt.getUTCDate() - dow);
return dt.toISOString().slice(0, 10);
}
export function todayItems(a: AdherenceResponse): TodayItem[] {
const out: TodayItem[] = [];
const wk = weekOf(a.today);
for (const p of a.protocols) {
const day = p.daily[a.today];
for (const r of p.rules) {
if (r.period === 'week') {
const w = p.weeks[wk]?.[r.id];
if (!w) continue;
out.push({
protocolId: p.id, ruleId: r.id, system: p.system, label: r.label,
auto: !!r.metric, status: w.status, week: { count: w.count, need: w.need },
});
} else {
const e = day?.rules[r.id];
if (!e) continue;
out.push({
protocolId: p.id, ruleId: r.id, system: p.system, label: r.label,
auto: !!r.metric, status: e.status,
});
}
}
}
return out.sort((x, y) => systemOrder(x.system) - systemOrder(y.system));
}
/** Tick or untick a manual rule for a day. `done: null` clears the check-in. */
export async function setCheckin(
item: Pick<TodayItem, 'protocolId' | 'ruleId'>, day: string, done: boolean | null,
): Promise<void> {
await postJson(EP_CHECKINS, { protocol_id: item.protocolId, rule_id: item.ruleId, day, done });
invalidate('lifeAdherence');
}
const EP_CHECKINS = EP.lifeAdherence.replace(/\/adherence.*$/, '/checkins');
/* ---- 14-day streak grid ---- */
/** met = every evaluated rule met; part = some met; miss = none met; none = nothing to evaluate */
export type CellState = 'met' | 'part' | 'miss' | 'none';
export interface StreakRow {
key: string;
label: string;
/** cell colour; defaults to the system colour for `key` */
color?: string;
cells: CellState[];
/** share of evaluated rules met over the window, 0–100, or null with no data */
pct: number | null;
}
export function streakRows(a: AdherenceResponse): StreakRow[] {
return SYSTEMS.map(({ key, label }) => {
const protos = a.protocols.filter((p) => p.system === key);
const cells = a.days.map<CellState>((day) => {
let met = 0, missed = 0;
for (const p of protos) {
const rules = p.daily[day]?.rules;
if (!rules) continue;
for (const id in rules) {
if (rules[id].status === 'met') met++;
else if (rules[id].status === 'missed') missed++;
}
}
if (met + missed === 0) return 'none';
if (missed === 0) return 'met';
return met > 0 ? 'part' : 'miss';
});
const hasData = cells.some((c) => c !== 'none');
return { key, label, cells, pct: hasData ? (a.systems[key] ?? null) : null };
});
}
/* ---- goals ---- */
export interface GoalRow {
id: string;
system: string;
title: string;
/** 0–1 for the bar; null draws an empty bar */
progress: number | null;
/** right-hand value, e.g. "707k of 1.6M" or "not tracked yet" */
value: string;
}
const compact = (n: number) => {
const a = Math.abs(n);
if (a >= 1e6) return (n / 1e6).toFixed(2).replace(/\.?0+$/, '') + 'M';
if (a >= 1e4) return Math.round(n / 1e3) + 'k';
return Number.isInteger(n) ? String(n) : n.toFixed(1);
};
export function goalRows(g: GoalsResponse): GoalRow[] {
return g.goals
.filter((x) => !x.achieved_at)
.map<GoalRow>((x) => {
const cur = x.current ?? x.current_manual;
return {
id: x.id,
system: x.system,
title: x.title,
progress: x.progress == null ? null : Math.max(0, Math.min(1, x.progress)),
value: cur == null ? 'Not tracked yet' : `${compact(cur)} of ${compact(x.target)}`,
};
})
// measured goals first, in system order
.sort((x, y) =>
Number(y.progress != null) - Number(x.progress != null) ||
systemOrder(x.system) - systemOrder(y.system));
}
/* ---- the daily six: small habits shown as big tap cards on Today ---- */
/** Protocol key on the server that holds the daily habits (all manual rules). */
export const DAILY_KEY = 'daily';
/** Short name for the streak grid and a colour, by rule id. Unknown ids fall back to the label. */
const HABIT_META: Record<string, { short: string; system: SystemKey }> = {
read: { short: 'Read', system: 'wealth' },
move: { short: 'Exercise', system: 'train' },
sit: { short: 'Meditate', system: 'mind' },
sleep: { short: 'Sleep', system: 'sleep' },
eat: { short: 'Eat well', system: 'diet' },
write: { short: 'Write', system: 'relate' },
};
export interface Habit {
protocolId: string;
ruleId: string;
label: string;
short: string;
/** which system colour the card uses */
system: SystemKey;
done: boolean;
}
export function dailyHabits(a: AdherenceResponse): Habit[] {
const p = a.protocols.find((x) => x.key === DAILY_KEY);
if (!p) return [];
const today = p.daily[a.today]?.rules ?? {};
return p.rules
.filter((r) => !r.metric && r.period !== 'week')
.map((r) => ({
protocolId: p.id,
ruleId: r.id,
label: r.label,
short: HABIT_META[r.id]?.short ?? r.label,
system: HABIT_META[r.id]?.system ?? 'mind',
done: today[r.id]?.status === 'met',
}));
}
/** One row per habit over the window. Days before the habit existed, and days not ticked, are empty. */
export function habitStreaks(a: AdherenceResponse): StreakRow[] {
const p = a.protocols.find((x) => x.key === DAILY_KEY);
if (!p) return [];
return dailyHabits(a).map((h) => {
const cells = a.days.map<CellState>((day) =>
p.daily[day]?.rules[h.ruleId]?.status === 'met' ? 'met' : 'none');
const tracked = a.days.filter((day) => p.daily[day]).length;
const met = cells.filter((c) => c === 'met').length;
return {
key: h.ruleId, label: h.short, cells, color: h.system,
pct: tracked ? Math.round((met / tracked) * 100) : null,
};
});
}

View File

@@ -3,7 +3,17 @@ import type {
Week, Workout,
} from './types';
export function shapeSleep(api: SleepApiResponse, sc: SleepCycleExport): Night[] {
export interface HcSleepRow {
id: string; started_at: string; ended_at: string;
total_seconds: number; sleep_seconds: number;
deep_seconds: number; rem_seconds: number; light_seconds: number; awake_seconds: number;
}
export function shapeSleep(
api: SleepApiResponse,
sc: SleepCycleExport,
fitbit: HcSleepRow[] = [],
): Night[] {
const byDate = new Map<string, Night>();
(sc.sessions || []).forEach((r) => {
const o: Record<string, any> = Object.fromEntries(sc.fields.map((f, i) => [f, r[i]]));
@@ -39,6 +49,23 @@ export function shapeSleep(api: SleepApiResponse, sc: SleepCycleExport): Night[]
src: 'Eight Sleep',
});
});
// Fitbit Air wins where sources overlap — it's the current device.
fitbit.forEach((f) => {
const date = f.ended_at.slice(0, 10);
byDate.set(date, {
date,
total: f.total_seconds,
asleep: f.sleep_seconds,
deep: f.deep_seconds,
rem: f.rem_seconds,
light: f.light_seconds,
awake: f.awake_seconds,
quality: null,
hrv: null,
hr: null,
src: 'Fitbit Air',
});
});
return [...byDate.values()].sort((a, b) => (a.date < b.date ? -1 : 1));
}

View File

@@ -1,25 +1,85 @@
/* Dark palette ported from the health.rehbock.xyz PWA */
export const C = {
bg: '#0d0d0f',
surface: '#141417',
surface2: '#1c1c21',
border: '#252529',
text: '#e8e8ed',
muted: '#8a8a99',
dim: '#4a4a55',
green: '#34c759',
greenDim: 'rgba(52,199,89,0.12)',
yellow: '#f5c542',
yellowDim: 'rgba(245,197,66,0.12)',
red: '#ff453a',
redDim: 'rgba(255,69,58,0.12)',
accent: '#6e6af0',
accentDim: 'rgba(110,106,240,0.12)',
// validated series palette (dark, surface #141417)
s1: '#3987e5',
s2: '#d95926',
s3: '#199e70',
s4: '#c98500',
awake: '#3c3c46',
gridline: '#232328',
/* Jarvis design tokens.
Direction: Waymo's calm surfaces, big rounded cards and bold geometric type,
with Hevy's dense rows, blue accent and green "done" rows.
The palette is chosen once at launch from the phone's light/dark setting;
changing that setting takes effect the next time the app starts. */
import { Appearance } from 'react-native';
const light = {
bg: '#EEF1F7',
surface: '#FFFFFF',
surface2: '#F2F4F9',
border: '#E1E5EE',
text: '#0C1730',
muted: '#5F6B80',
dim: '#A3ACBD',
green: '#1FA94B',
greenDim: '#DDF6CF',
yellow: '#C98A00',
yellowDim: 'rgba(201,138,0,0.12)',
red: '#E5484D',
redDim: 'rgba(229,72,77,0.10)',
accent: '#0B6BFF',
accentDim: 'rgba(11,107,255,0.10)',
onAccent: '#FFFFFF',
// chart series
s1: '#2F7BEA',
s2: '#E2622B',
s3: '#17A673',
s4: '#D49100',
awake: '#C9CFDB',
gridline: '#E6E9F0',
shadow: 'rgba(12,23,48,0.10)',
};
const dark: typeof light = {
bg: '#0B1220',
surface: '#162032',
surface2: '#1E2A3F',
border: '#26334A',
text: '#F1F4F9',
muted: '#93A0B5',
dim: '#55627A',
green: '#3DCB63',
greenDim: 'rgba(61,203,99,0.18)',
yellow: '#F5C542',
yellowDim: 'rgba(245,197,66,0.14)',
red: '#FF5A5F',
redDim: 'rgba(255,90,95,0.14)',
accent: '#3B8BFF',
accentDim: 'rgba(59,139,255,0.16)',
onAccent: '#FFFFFF',
s1: '#4C96F5',
s2: '#EC7A45',
s3: '#2BBF8A',
s4: '#E0A21A',
awake: '#33415A',
gridline: '#223049',
shadow: 'rgba(0,0,0,0.5)',
};
export const isDark = Appearance.getColorScheme() === 'dark';
/** Colours. Existing screens import this as `C`. */
export const C = isDark ? dark : light;
/** One colour per life system, used for streak cells and goal bars. */
export const SYS: Record<string, string> = {
sleep: C.s1,
train: C.s2,
diet: C.s3,
mind: isDark ? '#9A8BFF' : '#7C6CF0',
wealth: C.s4,
relate: isDark ? '#F06FA3' : '#DB4F8A',
};
/** Figtree, loaded in the root layout. */
export const F = {
regular: 'Figtree_400Regular',
medium: 'Figtree_500Medium',
semibold: 'Figtree_600SemiBold',
bold: 'Figtree_700Bold',
heavy: 'Figtree_800ExtraBold',
};
export const R = { card: 22, control: 16, chip: 10, pill: 999 };

View File

@@ -19,8 +19,7 @@ export function useLoad<T>(fn: () => Promise<T>): LoadState<T> & { refresh: () =
.then((data) => live && setState({ data, loading: false }))
.catch((e) => {
if (!live) return;
const msg = e instanceof Error ? e.message : String(e);
if (msg !== 'unauthorized') setState({ err: msg, loading: false });
setState({ err: e instanceof Error ? e.message : String(e), loading: false });
});
return () => {
live = false;