dashPi: a self-hosted home dashboard, its sync server and phone app

The dashboard (Raspberry Pi 3.5" screen + web pages), the end-to-end
encrypted sync mailbox (PHP + SQLite) and the Android companion app
(Flutter), with docs, clean-install checks and screenshots made from
demo data.

Built mostly with an AI coding assistant; not yet reviewed line by line
by a human (see README and SECURITY.md).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Bashy 2026-10-24 09:35:12 +02:00
commit fb3c01cdd7
333 changed files with 45151 additions and 0 deletions

52
app/.gitignore vendored Normal file
View file

@ -0,0 +1,52 @@
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.build/
.buildlog/
.history
.svn/
.swiftpm/
migrate_working_dir/
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/
# Flutter/Dart/Pub related
**/doc/api/
**/ios/Flutter/.last_build_id
.dart_tool/
.flutter-plugins-dependencies
.pub-cache/
.pub/
/build/
/coverage/
# Symbolication related
app.*.symbols
# Obfuscation related
app.*.map.json
# Android Studio will place build artifacts here
/android/app/debug
/android/app/profile
/android/app/release
# Syncthing, if you sync the source between computers
.stignore
.stfolder
# your publish settings (tool/publish.env.example)
tool/publish.env

30
app/.metadata Normal file
View file

@ -0,0 +1,30 @@
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: "6b182d2c7585eba26d4edce0f97630effd256c33"
channel: "stable"
project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: 6b182d2c7585eba26d4edce0f97630effd256c33
base_revision: 6b182d2c7585eba26d4edce0f97630effd256c33
- platform: android
create_revision: 6b182d2c7585eba26d4edce0f97630effd256c33
base_revision: 6b182d2c7585eba26d4edce0f97630effd256c33
# User provided section
# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'

69
app/CHANGELOG.md Normal file
View file

@ -0,0 +1,69 @@
# Changelog
What changed in each published build of the app. `tool/publish.sh` shows the entry for the version in
`pubspec.yaml` as the update notes on the phones (Sync page ▸ App) — write it before publishing.
## Unreleased
- Connect by scanning the code from the dashboard (Settings ▸ General ▸ Devices ▸ Add a device).
- Weather: the dashboard's home and extra places come with the sync.
- Sync page: the dashboard's address for "sync now" can be set there.
- Food: the targets follow the dashboard's Settings ▸ Food (weight goal, macro split, limits) instead of
fixed values in the app.
- The band's data goes with the phone's time zone, so the dashboard reads its times right without a
setting.
## 1.1.2 — 2026-10-23
- Work: grips at the top and bottom of a block — hold one and drag to start earlier / later or end
earlier / later (15-minute steps, never shorter than 15 minutes; Undo).
- Work: moving a block, drawing a new one and the grips start after a shorter hold (¼ s instead of ½ s).
- Work: dragging near the top or bottom edge scrolls the day, so a block can be drawn or moved past
what's on screen.
- Food: "Search all products" — 2 million+ Open Food Facts products from every country, with country,
brand and Nutri-Score filters (needs a connection); a product you pick is kept and synced, so it works
like any other food afterwards, on the dashboard too.
- Food: barcode scanner (the camera button in the search box) — finds the product here, else in all
products. Reads the code on the phone (ZXing), no Google services.
- Weather: "Current location" asks Android itself (no Google services in the app any more); when it
can't tell — not allowed, switched off, no fix — a red banner on top says why and what to do, and
home (the first place) is shown instead.
- Food: the built-in food database has the shop products of the countries it was built for only (the
rest are in "all products"; ones you've used stay).
- Food: added sugar — USDA's own added-sugar figures for its prepared foods; shop products by their
ingredients (any language) and the label's figure; names matched without accents and in more languages
(RO, SK, CZ, HU, DE, PL, FR, IT, ES, PT); plain oats and grits count as natural.
- Food: My foods have "Sugar counts as" (estimated / all added / milk's own / natural) for when the
estimate is wrong.
## 1.1.1 — 2026-10-22
- Work: hold an empty spot on the timeline and drag up or down to book that span; the times show
while you drag, letting go opens the entry with them filled in.
- "Undo" messages (cycle day, moved work block, note to the trash) disappear on their own
instead of staying on screen until tapped.
- Food: "Free sugar" is now "Added sugar" — the same estimate (added sugar, honey, syrups, fruit juice),
a clearer name.
- Food: whole and dried fruit no longer count as added sugar (every fruit did, through USDA's
"Fruits and Fruit Juices" category).
- Food: snacks, fast food, drinks and baby food are judged by what they are (cola, bars, coleslaw count;
coffee, crisps, burgers, plain baby fruit don't); wine, cider and beer count like juice.
- Sync: the dashboards' raw ActivityWatch data is skipped — the phone never reads it.
## 1.1.0 — 2026-10-21
- Notes: markdown notes with folders, #tags, pinned notes, checklists, search and trash — synced with
the dashboard.
## 1.0.0 (build 2) — 2026-10-21
- Work: the week (a day's timeline on a phone, all seven days in landscape), booking and editing time,
the report (CSV to the clipboard), customers and their editor; the calendar's events behind the week
and Activity's blocks beside it; drag blocks to another time or day.
- After sending the band's data, the Pi on the home network syncs at once.
- The app updates itself from the sync server.
## 1.0.0 (build 1) — 2026-10-21
- First build: Health (overview, cycle, body, sleep, heart, activity), Food, Weather (with the home
stations), sync through the sync server, the Gadgetbridge band relay and the hourly background sync.

58
app/README.md Normal file
View file

@ -0,0 +1,58 @@
# The phone app
The dashboard's companion for Android (Flutter). It keeps its own copy of your data, works offline, and
syncs end-to-end encrypted through your sync server with the dashboard and your other devices.
- **Health:**
- Body measurements, BMI and body fat by several formulas.
- Sleep, heart rate and workouts as the dashboard works them out.
- The cycle tracker.
- **Food:** a diary with the bundled food database, a barcode scanner, and the server's product archive.
- **Work:** book time in a week view by dragging.
- **Notes:** Markdown, folders, tags, checklists.
- **Weather:** your places, the dashboard's places and where you are.
- **Band relay:** reads Gadgetbridge's database export on the phone and sends the band's new data to the
dashboard. No Syncthing needed.
- **Updates itself** from your server (optional).
| | | | |
|---|---|---|---|
| ![Health](../docs/screenshots/app-health.png) | ![Sleep](../docs/screenshots/app-sleep.png) | ![Body](../docs/screenshots/app-body.png) | ![Cycle](../docs/screenshots/app-cycle.png) |
| **Health** overview | **Sleep** | **Body** | **Cycle** |
| ![Food](../docs/screenshots/app-food.png) | ![Work](../docs/screenshots/app-work.png) | ![Notes](../docs/screenshots/app-notes.png) | ![Weather](../docs/screenshots/app-weather.png) |
| **Food** diary | **Work** week | **Notes** | **Weather** |
The pictures come from the demo dashboard's made-up data on an emulator:
[docs/screenshots/app.py](../docs/screenshots/app.py).
## Build and connect
```bash
cd app
flutter pub get
flutter test
flutter build apk --release # → build/app/outputs/flutter-apk/app-release.apk
```
You need Flutter 3.44 (Dart 3.12+) and the Android SDK. Sign it with your own key, or your next build
can't update it. Then on the dashboard go to **Settings ▸ General ▸ Devices ▸ Add a device**, and in the
app tap **Scan the code from the dashboard** and type the passphrase.
Signing, optional built-in defaults (`DEV_SERVER`, `PI_URL`, `HOME_PLACES`), the band relay and
publishing updates: [../docs/app.md](../docs/app.md). What changed in each build:
[CHANGELOG.md](CHANGELOG.md).
## Layout
```
lib/main.dart start, the connect screen
lib/app/ the shell (tabs), background sync, the updater, location, the code scanner
lib/sync/ the sync: store.dart (the local copy + merge), client.dart, crypto.dart, the kick, the band relay
lib/health/ work/ notes/ weather/ the sections
packages/gb_export/ a small Android plugin: Gadgetbridge's export, the phone's time zone (works in the background too)
assets/foods.db the food database (also the dashboard's starting one)
tool/publish.sh build + upload an update (tool/publish.env)
```
The sync format is the dashboard's ([../server/PROTOCOL.md](../server/PROTOCOL.md)); both sides merge the
same way, last writer wins per row.

28
app/analysis_options.yaml Normal file
View file

@ -0,0 +1,28 @@
# This file configures the analyzer, which statically analyzes Dart code to
# check for errors, warnings, and lints.
#
# The issues identified by the analyzer are surfaced in the UI of Dart-enabled
# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be
# invoked from the command line by running `flutter analyze`.
# The following line activates a set of recommended lints for Flutter apps,
# packages, and plugins designed to encourage good coding practices.
include: package:flutter_lints/flutter.yaml
linter:
# The lint rules applied to this project can be customized in the
# section below to disable rules from the `package:flutter_lints/flutter.yaml`
# included above or to enable additional rules. A list of all available lints
# and their documentation is published at https://dart.dev/lints.
#
# Instead of disabling a lint rule for the entire project in the
# section below, it can also be suppressed for a single line of code
# or a specific dart file by using the `// ignore: name_of_lint` and
# `// ignore_for_file: name_of_lint` syntax on the line or in the file
# producing the lint.
rules:
# avoid_print: false # Uncomment to disable the `avoid_print` rule
# prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule
# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options

14
app/android/.gitignore vendored Normal file
View file

@ -0,0 +1,14 @@
gradle-wrapper.jar
/.gradle
/captures/
/gradlew
/gradlew.bat
/local.properties
GeneratedPluginRegistrant.java
.cxx/
# Remember to never publicly share your keystore.
# See https://flutter.dev/to/reference-keystore
key.properties
**/*.keystore
**/*.jks

View file

@ -0,0 +1,68 @@
import java.util.Properties
plugins {
id("com.android.application")
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
id("dev.flutter.flutter-gradle-plugin")
}
// Release signing: android/key.properties (not in git) → the keystore in ~/keys (storeFile, storePassword,
// keyAlias, keyPassword). Without it, release builds fall back to the debug key (and can't update a release install).
val keyProps = Properties().apply {
val f = rootProject.file("key.properties")
if (f.exists()) f.inputStream().use { load(it) }
}
android {
namespace = "dev.bashynx.dash_app"
compileSdk = flutter.compileSdkVersion
ndkVersion = flutter.ndkVersion
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId = "dev.bashynx.dash_app"
// You can update the following values to match your application needs.
// For more information, see: https://flutter.dev/to/review-gradle-config.
minSdk = flutter.minSdkVersion
targetSdk = flutter.targetSdkVersion
versionCode = flutter.versionCode
versionName = flutter.versionName
}
signingConfigs {
if (keyProps.getProperty("storeFile") != null) {
create("release") {
storeFile = file(keyProps.getProperty("storeFile"))
storePassword = keyProps.getProperty("storePassword")
keyAlias = keyProps.getProperty("keyAlias")
keyPassword = keyProps.getProperty("keyPassword")
}
}
}
if (keyProps.getProperty("storeFile") == null) {
logger.warn("android/key.properties is missing: this release build is signed with the debug key " +
"(it can't update an installed release). See docs/app.md.")
}
buildTypes {
release {
signingConfig = signingConfigs.findByName("release") ?: signingConfigs.getByName("debug")
}
}
}
kotlin {
compilerOptions {
jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17
}
}
flutter {
source = "../.."
}

View file

@ -0,0 +1,9 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- The INTERNET permission is required for development. Specifically,
the Flutter tool needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<!-- debug builds only: plain http to the local test mailbox (10.0.2.2 = this PC from the emulator) -->
<application android:usesCleartextTraffic="true"/>
</manifest>

View file

@ -0,0 +1,61 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CAMERA"/> <!-- the food barcode scanner (flutter_zxing) -->
<!-- the app updates itself from the sync server (lib/app/updater.dart): Android asks before installing -->
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
<!-- Weather ▸ Current location: the town is enough -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
android:label="dashPi"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher"
android:allowBackup="false"
android:fullBackupContent="false"
android:networkSecurityConfig="@xml/network_security_config">
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.updates"
android:exported="false"
android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/update_paths" />
</provider>
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:taskAffinity=""
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
<!-- Required to query activities that can process text, see:
https://developer.android.com/training/package-visibility and
https://developer.android.com/reference/android/content/Intent#ACTION_PROCESS_TEXT.
In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. -->
<queries>
<intent>
<action android:name="android.intent.action.PROCESS_TEXT"/>
<data android:mimeType="text/plain"/>
</intent>
</queries>
</manifest>

View file

@ -0,0 +1,141 @@
package dev.bashynx.dash_app
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.net.ConnectivityManager
import android.net.Uri
import android.os.Build
import android.os.CancellationSignal
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import androidx.core.content.FileProvider
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import java.io.File
import java.security.MessageDigest
// The Gadgetbridge export bridge lives in packages/gb_export (a plugin, so background tasks have it too).
// "dash/update" (lib/app/updater.dart), only while the app is on screen:
// info() → {code, name, metered, canInstall}
// install(path, sha256) → "started" | "allow" (opened the "install unknown apps" setting first) | "bad" (checksum)
// "dash/location" (lib/app/location.dart) — Android's own LocationManager, never Google's Play services:
// status() → {allowed, enabled} ask() → allowed (the permission dialog; refused for good: false at once)
// last() → the newest last-known fix {lat, lon, time, accuracy} | null current(timeoutMs) → a new fix | null
class MainActivity : FlutterActivity() {
private var asking: MethodChannel.Result? = null
private fun allowed() = checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
private fun fix(l: Location) = mapOf("lat" to l.latitude, "lon" to l.longitude, "time" to l.time, "accuracy" to l.accuracy.toDouble())
override fun onRequestPermissionsResult(code: Int, permissions: Array<out String>, grants: IntArray) {
super.onRequestPermissionsResult(code, permissions, grants)
if (code == ASK_LOCATION) {
asking?.success(allowed())
asking = null
}
}
override fun configureFlutterEngine(engine: FlutterEngine) {
super.configureFlutterEngine(engine)
MethodChannel(engine.dartExecutor.binaryMessenger, "dash/location").setMethodCallHandler { call, result ->
val lm = getSystemService(LOCATION_SERVICE) as LocationManager
try {
when (call.method) {
"status" -> result.success(mapOf(
"allowed" to allowed(),
"enabled" to if (Build.VERSION.SDK_INT >= 28) lm.isLocationEnabled else lm.getProviders(true).isNotEmpty()))
"ask" -> if (allowed()) result.success(true) else {
asking?.success(false)
asking = result
requestPermissions(arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION), ASK_LOCATION)
}
"last" -> result.success(if (!allowed()) null else
lm.getProviders(true).mapNotNull { lm.getLastKnownLocation(it) }.maxByOrNull { it.time }?.let(::fix))
"current" -> {
val provider = listOf(LocationManager.NETWORK_PROVIDER, LocationManager.GPS_PROVIDER)
.firstOrNull { lm.isProviderEnabled(it) }
if (!allowed() || provider == null) return@setMethodCallHandler result.success(null)
var done = false
val main = Handler(Looper.getMainLooper())
fun reply(l: Location?) {
if (!done) {
done = true
result.success(l?.let(::fix))
}
}
val wait = (call.argument<Int>("timeoutMs") ?: 20000).toLong()
if (Build.VERSION.SDK_INT >= 30) {
val cancel = CancellationSignal()
lm.getCurrentLocation(provider, cancel, mainExecutor) { reply(it) }
main.postDelayed({ cancel.cancel(); reply(null) }, wait)
} else {
val once = object : LocationListener {
override fun onLocationChanged(l: Location) {
lm.removeUpdates(this)
reply(l)
}
}
@Suppress("DEPRECATION")
lm.requestSingleUpdate(provider, once, Looper.getMainLooper())
main.postDelayed({ lm.removeUpdates(once); reply(null) }, wait)
}
}
else -> result.notImplemented()
}
} catch (e: SecurityException) {
result.success(null) // the permission went away meanwhile
}
}
MethodChannel(engine.dartExecutor.binaryMessenger, "dash/update").setMethodCallHandler { call, result ->
when (call.method) {
"info" -> {
val p = packageManager.getPackageInfo(packageName, 0)
val code = if (Build.VERSION.SDK_INT >= 28) p.longVersionCode else @Suppress("DEPRECATION") p.versionCode.toLong()
val cm = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
result.success(mapOf("code" to code, "name" to (p.versionName ?: ""), "metered" to cm.isActiveNetworkMetered,
"canInstall" to packageManager.canRequestPackageInstalls()))
}
"install" -> {
val f = File(call.argument<String>("path")!!)
val want = call.argument<String>("sha256") ?: ""
if (!f.exists() || (want.isNotEmpty() && sha256(f) != want.lowercase())) {
result.success("bad")
} else if (!packageManager.canRequestPackageInstalls()) {
startActivity(Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:$packageName")))
result.success("allow")
} else {
val uri = FileProvider.getUriForFile(this, "$packageName.updates", f)
startActivity(Intent(Intent.ACTION_VIEW).setDataAndType(uri, "application/vnd.android.package-archive")
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK))
result.success("started")
}
}
else -> result.notImplemented()
}
}
}
companion object {
private const val ASK_LOCATION = 41
}
private fun sha256(f: File): String {
val md = MessageDigest.getInstance("SHA-256")
f.inputStream().use { s ->
val buf = ByteArray(1 shl 16)
while (true) {
val n = s.read(buf)
if (n < 0) break
md.update(buf, 0, n)
}
}
return md.digest().joinToString("") { "%02x".format(it) }
}
}

View file

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="?android:colorBackground" />
<!-- You can insert your own image assets here -->
<!-- <item>
<bitmap
android:gravity="center"
android:src="@mipmap/launch_image" />
</item> -->
</layer-list>

View file

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/white" />
<!-- You can insert your own image assets here -->
<!-- <item>
<bitmap
android:gravity="center"
android:src="@mipmap/launch_image" />
</item> -->
</layer-list>

View file

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
</adaptive-icon>

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

View file

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on -->
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
the Flutter engine draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
Flutter UI initializes, as well as behind your Flutter UI while its
running.
This Theme is only used starting with V2 of Flutter's Android embedding. -->
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="android:windowBackground">?android:colorBackground</item>
</style>
</resources>

View file

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#0D1017</color>
</resources>

View file

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off -->
<style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
the Flutter engine draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
Flutter UI initializes, as well as behind your Flutter UI while its
running.
This Theme is only used starting with V2 of Flutter's Android embedding. -->
<style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
<item name="android:windowBackground">?android:colorBackground</item>
</style>
</resources>

View file

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Plain HTTP is allowed because the dashboard on the home network has whatever address it has (kick.dart,
the Sync page). What goes there is sealed with the data key; the sync server must be https (main.dart),
and every other address the app uses is https. -->
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>

View file

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- The downloaded app update (lib/app/updater.dart) is handed to the installer from here. -->
<paths>
<cache-path name="updates" path="updates/" />
</paths>

View file

@ -0,0 +1,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- The INTERNET permission is required for development. Specifically,
the Flutter tool needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>

View file

@ -0,0 +1,24 @@
allprojects {
repositories {
google()
mavenCentral()
}
}
val newBuildDir: Directory =
rootProject.layout.buildDirectory
.dir("../../build")
.get()
rootProject.layout.buildDirectory.value(newBuildDir)
subprojects {
val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name)
project.layout.buildDirectory.value(newSubprojectBuildDir)
}
subprojects {
project.evaluationDependsOn(":app")
}
tasks.register<Delete>("clean") {
delete(rootProject.layout.buildDirectory)
}

View file

@ -0,0 +1,6 @@
org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
android.useAndroidX=true
# This newDsl flag was added by the Flutter template
android.newDsl=false
# This builtInKotlin flag was added by the Flutter template
android.builtInKotlin=false

View file

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-all.zip

View file

@ -0,0 +1,26 @@
pluginManagement {
val flutterSdkPath =
run {
val properties = java.util.Properties()
file("local.properties").inputStream().use { properties.load(it) }
val flutterSdkPath = properties.getProperty("flutter.sdk")
require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" }
flutterSdkPath
}
includeBuild("$flutterSdkPath/packages/flutter_tools/gradle")
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
plugins {
id("dev.flutter.flutter-plugin-loader") version "1.0.0"
id("com.android.application") version "9.0.1" apply false
id("org.jetbrains.kotlin.android") version "2.3.20" apply false
}
include(":app")

BIN
app/assets/foods.db Normal file

Binary file not shown.

BIN
app/assets/weather/01d.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 KiB

BIN
app/assets/weather/01n.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

BIN
app/assets/weather/02d.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9 KiB

BIN
app/assets/weather/02n.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

BIN
app/assets/weather/03d.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

BIN
app/assets/weather/03n.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

BIN
app/assets/weather/04d.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

BIN
app/assets/weather/04n.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

BIN
app/assets/weather/09d.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

BIN
app/assets/weather/09n.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

BIN
app/assets/weather/10d.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

BIN
app/assets/weather/10n.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

BIN
app/assets/weather/11d.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

BIN
app/assets/weather/11n.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

BIN
app/assets/weather/13d.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

BIN
app/assets/weather/13n.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

BIN
app/assets/weather/50d.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

BIN
app/assets/weather/50n.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020-present Bas Milius
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,64 @@
// The sync in the background (Android WorkManager), also while the app is closed: about once an hour
// with a network — relay the band's new rows from Gadgetbridge's export (gb_relay.dart), then sync.
// Runs in its own engine and isolate; shares the data file with the app (SQLite waits for the other).
import 'package:flutter/widgets.dart';
import 'package:path_provider/path_provider.dart';
import 'package:workmanager/workmanager.dart';
import '../sync/client.dart';
import '../sync/crypto.dart';
import '../sync/gb_relay.dart';
import '../sync/kick.dart';
import '../sync/store.dart';
import '../weather/stations.dart' show stationDays;
const _task = 'band-sync';
const every = Duration(hours: 1);
Future<String> dataPath() async => '${(await getApplicationSupportDirectory()).path}/data.db';
@pragma('vm:entry-point')
void backgroundDispatcher() {
Workmanager().executeTask((task, input) async {
WidgetsFlutterBinding.ensureInitialized();
final s = await SyncSettings.load();
if (s == null) return true; // disconnected meanwhile
final store = SyncStore(await dataPath(), s.device);
try {
var band = 0;
try {
band = await GbRelay(store).run() ?? 0;
} catch (e) {
debugPrint('background: gb relay: $e');
}
final crypto = await SyncCrypto.create();
var res = await runSync(s, store, crypto);
if (band > 0 && res.pushed > 0 && await kickPi(s, store, crypto)) res = await runSync(s, store, crypto); // kick.dart
store.dropOld('stations.hourly', 't', DateTime.now().millisecondsSinceEpoch ~/ 1000 - stationDays * 86400);
store.setMeta('bg_ok', DateTime.now().millisecondsSinceEpoch);
debugPrint('background: $res');
return true;
} catch (e) {
debugPrint('background: $e');
return false; // WorkManager tries again later
} finally {
store.db.close();
}
});
}
/// Start (or keep) the hourly background sync — after connecting and at every app start.
Future<void> scheduleBackground() async {
await Workmanager().initialize(backgroundDispatcher);
await Workmanager().registerPeriodicTask(_task, _task,
frequency: every,
constraints: Constraints(networkType: NetworkType.connected),
existingWorkPolicy: ExistingPeriodicWorkPolicy.update);
// test builds only (--dart-define=BG_TEST=true): the same work once, 30 s after start — kill the app to see it run
if (const bool.fromEnvironment('BG_TEST')) {
await Workmanager().registerOneOffTask('$_task-test', _task,
initialDelay: const Duration(seconds: 30), existingWorkPolicy: ExistingWorkPolicy.replace);
}
}
Future<void> stopBackground() => Workmanager().cancelByUniqueName(_task);

33
app/lib/app/location.dart Normal file
View file

@ -0,0 +1,33 @@
// Where the phone is, from Android itself (MainActivity's "dash/location": LocationManager — never Google's Play
// services): the permission asked once, the newest last-known fix, else a new one. The town is enough (coarse).
import 'package:flutter/services.dart';
const _ch = MethodChannel('dash/location');
/// A fix (lat, lon), or why there's none: "location not allowed" / "location off" / "no location found".
Future<({double lat, double lon})?> whereAmI({void Function(String why)? none}) async {
try {
final st = (await _ch.invokeMapMethod<String, dynamic>('status'))!;
if (st['allowed'] != true && await _ch.invokeMethod<bool>('ask') != true) {
none?.call('location not allowed');
return null;
}
if (st['enabled'] != true) {
none?.call('location off');
return null;
}
final fix = await _ch.invokeMapMethod<String, dynamic>('last') ??
await _ch.invokeMapMethod<String, dynamic>('current', {'timeoutMs': 20000});
if (fix == null) {
none?.call('no location found');
return null;
}
return (lat: (fix['lat'] as num).toDouble(), lon: (fix['lon'] as num).toDouble());
} on PlatformException {
none?.call('no location found');
return null;
} on MissingPluginException {
none?.call('no location found'); // not on Android (tests)
return null;
}
}

43
app/lib/app/scanner.dart Normal file
View file

@ -0,0 +1,43 @@
// The camera, until a code is read: ZXing (flutter_zxing: open source, on the phone — no Google services)
// over Flutter's camera plugin. The food barcodes (health/food_archive.dart) and the connect screen's QR
// code from the dashboard's Settings ▸ General ▸ Sync (main.dart).
import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart';
/// → the code's text once `accept` takes it, or null (closed).
Future<String?> scanCode(BuildContext context,
{required String title, required int format, required bool Function(String) accept}) =>
Navigator.of(context).push<String>(MaterialPageRoute(
builder: (_) => _Scanner(title: title, format: format, accept: accept), fullscreenDialog: true));
class _Scanner extends StatefulWidget {
const _Scanner({required this.title, required this.format, required this.accept});
final String title;
final int format;
final bool Function(String) accept;
@override
State<_Scanner> createState() => _ScannerState();
}
class _ScannerState extends State<_Scanner> {
bool done = false;
@override
Widget build(BuildContext context) => Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(title: Text(widget.title)),
body: ReaderWidget(
codeFormat: widget.format,
tryHarder: true,
showGallery: false,
showToggleCamera: false,
scanDelay: const Duration(milliseconds: 300),
onScan: (code) {
final v = code.text;
if (done || !code.isValid || v == null || !widget.accept(v)) return;
done = true;
Navigator.of(context).pop(v);
},
),
);
}

346
app/lib/app/shell.dart Normal file
View file

@ -0,0 +1,346 @@
// The app's frame: Health | Food | Work | Notes | Weather at the bottom (Work's ⋮: Report, Customers); Health's sections as tabs at the
// top (Overview, Cycle, Body, Sleep, Heart, Activity — the band's parts from the Pi's summaries).
// The sync icon (top right) shows the state and opens the Sync page.
import 'package:flutter/material.dart';
import '../health/activity_page.dart';
import '../notes/notes_page.dart';
import '../sync/gb_relay.dart';
import '../weather/weather_page.dart';
import '../work/customers_page.dart';
import '../work/report_page.dart';
import '../work/work_page.dart';
import '../health/body_page.dart';
import '../health/cycle_doctor.dart';
import '../health/cycle_model.dart' show CycleSettings;
import '../health/cycle_page.dart';
import '../health/food_history.dart';
import '../health/food_page.dart';
import '../health/my_foods.dart';
import '../health/heart_page.dart';
import '../health/overview_page.dart';
import '../health/range.dart';
import '../health/sleep_page.dart';
import '../sync/client.dart';
import '../sync/kick.dart' show piUrl;
import 'sync_service.dart';
import 'updater.dart';
import 'theme.dart';
class Shell extends StatefulWidget {
const Shell({super.key, required this.sync, required this.onForget});
final SyncService sync;
final Future<void> Function() onForget;
@override
State<Shell> createState() => _ShellState();
}
class _ShellState extends State<Shell> {
int section = 0;
late final range = HealthRange(widget.sync.store); // the period every Health chart shows
/// Food's ⋮: History, My foods.
Widget _foodMenu() => PopupMenuButton<String>(
icon: const Icon(Icons.more_vert),
color: card2,
onSelected: (k) => Navigator.push(context, MaterialPageRoute(builder: (_) => k == 'history'
? FoodHistoryPage(sync: widget.sync, range: range)
: MyFoodsPage(sync: widget.sync))),
itemBuilder: (_) => const [
PopupMenuItem(value: 'history', child: Text('History')),
PopupMenuItem(value: 'foods', child: Text('My foods')),
],
);
/// Work's ⋮: Report, Customers.
Widget _workMenu() => PopupMenuButton<String>(
icon: const Icon(Icons.more_vert),
color: card2,
onSelected: (k) => Navigator.push(context, MaterialPageRoute(builder: (_) => k == 'report'
? ReportPage(sync: widget.sync)
: CustomersPage(sync: widget.sync))),
itemBuilder: (_) => const [
PopupMenuItem(value: 'report', child: Text('Report')),
PopupMenuItem(value: 'customers', child: Text('Customers')),
],
);
/// Health's ⋮ (next to the sync icon): what isn't a tab — the doctor summary.
Widget _healthMenu() => PopupMenuButton<String>(
icon: const Icon(Icons.more_vert),
color: card2,
onSelected: (k) {
if (k == 'doctor') {
Navigator.push(context, MaterialPageRoute(builder: (_) => DoctorPage(sync: widget.sync, settings: const CycleSettings())));
}
},
itemBuilder: (_) => const [PopupMenuItem(value: 'doctor', child: Text('For your doctor'))],
);
static const healthTabs = ['Overview', 'Cycle', 'Body', 'Sleep', 'Heart', 'Activity'];
Widget _syncIcon() => ListenableBuilder(
listenable: Listenable.merge([widget.sync, widget.sync.updater]),
builder: (context, _) => Badge(
isLabelVisible: const {UpdateState.available, UpdateState.ready}.contains(widget.sync.updater.state),
smallSize: 8,
backgroundColor: accent,
offset: const Offset(-6, 6),
child: IconButton( // the dot: an app update (Sync page ▸ App)
tooltip: widget.sync.error ?? (widget.sync.lastOk == null ? 'Not synced yet' : 'Synced'),
onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (_) => SyncPage(sync: widget.sync, onForget: widget.onForget))),
icon: widget.sync.busy
? const SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2))
: Icon(widget.sync.error != null ? Icons.cloud_off : Icons.cloud_done, color: widget.sync.error != null ? muted : accent),
),
),
);
static const sections = [
(Icons.favorite_border, Icons.favorite, 'Health'),
(Icons.restaurant_outlined, Icons.restaurant, 'Food'),
(Icons.work_outline, Icons.work, 'Work'),
(Icons.sticky_note_2_outlined, Icons.sticky_note_2, 'Notes'),
(Icons.cloud_outlined, Icons.cloud, 'Weather'),
];
@override
Widget build(BuildContext context) {
// landscape: the sections as a rail on the left, Health's tabs inside the top bar — the height is for the page
final wide = MediaQuery.of(context).orientation == Orientation.landscape;
final tabs = TabBar(isScrollable: true, tabAlignment: TabAlignment.start, dividerColor: Colors.transparent,
tabs: [for (final t in healthTabs) Tab(text: t)]);
final body = switch (section) {
0 => DefaultTabController(
length: healthTabs.length,
child: Scaffold(
appBar: wide
? AppBar(titleSpacing: 0, title: tabs, actions: [_syncIcon(), _healthMenu()])
: AppBar(title: const Text('Health'), actions: [_syncIcon(), _healthMenu()], bottom: tabs),
body: TabBarView(children: [
OverviewPage(sync: widget.sync, onFood: () => setState(() => section = 1)),
CyclePage(sync: widget.sync),
BodyPage(sync: widget.sync, range: range),
SleepPage(sync: widget.sync, range: range),
HeartPage(sync: widget.sync, range: range),
ActivityPage(sync: widget.sync, range: range),
]),
),
),
1 => Scaffold(appBar: AppBar(title: const Text('Food'), actions: [_syncIcon(), _foodMenu()]), body: FoodPage(sync: widget.sync)),
2 => WorkPage(sync: widget.sync, actions: [_syncIcon(), _workMenu()]), // its own bar: in landscape the week's ‹ CW › is in it
3 => NotesPage(sync: widget.sync, actions: [_syncIcon()]), // its own bar: the title picks folder / tag
_ => WeatherPage(sync: widget.sync, actions: [_syncIcon()]), // its own bar: the place is the title's dropdown
};
void go(int i) => setState(() => section = i);
if (wide) {
return Scaffold(
body: SafeArea(
right: false,
child: Row(children: [
NavigationRail(
backgroundColor: card,
selectedIndex: section,
onDestinationSelected: go,
labelType: NavigationRailLabelType.none, // icons only (the name shows on long-press)
indicatorColor: card2,
destinations: [for (final (o, s, l) in sections) NavigationRailDestination(icon: Icon(o), selectedIcon: Icon(s), label: Text(l))],
),
Expanded(child: body),
]),
),
);
}
return Scaffold(
body: body,
bottomNavigationBar: NavigationBar(
height: 56, // icons only (the name shows on long-press)
labelBehavior: NavigationDestinationLabelBehavior.alwaysHide,
selectedIndex: section,
onDestinationSelected: go,
destinations: [for (final (o, s, l) in sections) NavigationDestination(icon: Icon(o), selectedIcon: Icon(s), label: l)],
),
);
}
}
/// Sync state: the server, last sync, what's here per table, Sync now, disconnect.
class SyncPage extends StatelessWidget {
const SyncPage({super.key, required this.sync, required this.onForget});
final SyncService sync;
final Future<void> Function() onForget;
/// This app: its version and a newer build on the sync server (updater.dart).
Widget _app(BuildContext context) => ListenableBuilder(
listenable: sync.updater,
builder: (context, _) {
final u = sync.updater;
final mb = (u.size / 1e6).round();
final (text, Widget? action) = switch (u.state) {
UpdateState.unknown => ('Looking for updates after the next sync', null),
UpdateState.current => ('Up to date', null),
UpdateState.available => (
'Update ${u.label} available · $mb MB${u.metered ? ' (mobile data)' : ''}',
FilledButton(onPressed: u.download, child: const Text('Download')),
),
UpdateState.downloading => ('Downloading ${u.label} · ${(u.progress * 100).round()} %', null),
UpdateState.ready => (
'Update ${u.label} downloaded',
FilledButton(
onPressed: () async {
final m = await u.install();
if (m != null && context.mounted) ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(m)));
},
child: const Text('Install'),
),
),
UpdateState.failed => ('The download failed', OutlinedButton(onPressed: u.download, child: const Text('Try again'))),
};
return Card(child: Padding(
padding: const EdgeInsets.fromLTRB(14, 10, 10, 10),
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
Row(children: [
const Expanded(child: Text('App', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold))),
if (u.name.isNotEmpty) Text('${u.name} (${u.code})', style: const TextStyle(color: muted)),
]),
const SizedBox(height: 4),
Row(children: [
Expanded(child: Text(text)),
?action,
]),
if (u.state == UpdateState.downloading) Padding(
padding: const EdgeInsets.only(top: 6),
child: LinearProgressIndicator(value: u.progress),
),
if ((u.latest?['notes'] as String?)?.isNotEmpty == true && u.state != UpdateState.current)
Text(u.latest!['notes'] as String, style: const TextStyle(color: muted)),
if (u.error != null && u.state != UpdateState.current) Text(u.error!, style: const TextStyle(color: muted, fontSize: 12)),
]),
));
},
);
/// The band: Gadgetbridge's export file on this phone, relayed to the dashboard at every sync.
Widget _band(BuildContext context) {
final r = GbRelay(sync.store);
return Card(child: Padding(
padding: const EdgeInsets.fromLTRB(14, 10, 8, 10),
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
Row(children: [
const Expanded(child: Text('Band (Gadgetbridge)', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold))),
Tooltip(
triggerMode: TooltipTriggerMode.tap,
showDuration: const Duration(seconds: 10),
message: 'In Gadgetbridge: Settings ▸ Automations ▸ Auto export — a database export, e.g. every hour. '
'Choose that file here once; every sync then sends the band\'s new data to the dashboard.',
child: const Padding(padding: EdgeInsets.all(6), child: Icon(Icons.info_outline, size: 18, color: muted)),
),
]),
Text(r.uri == null ? 'No export chosen — the band\'s data reaches the dashboard only through Syncthing.'
: Uri.decodeComponent(r.uri!.split('/').last).split(':').last, style: const TextStyle(color: muted)),
if (r.lastResult != null)
Text('${TimeOfDay.fromDateTime(DateTime.fromMillisecondsSinceEpoch(r.lastRun)).format(context)} · ${r.lastResult}'),
Row(children: [
TextButton.icon(
icon: const Icon(Icons.folder_open),
label: Text(r.uri == null ? 'Choose the export' : 'Choose again'),
onPressed: () async {
if (await r.pick()) sync.syncNow();
},
),
if (r.uri != null)
TextButton(onPressed: () {
r.forget();
sync.changed();
}, child: const Text('Stop', style: TextStyle(color: muted))),
]),
]),
));
}
/// The dashboard on the home network: after the band's rows go out it's asked to work on them at once.
Widget _pi(BuildContext context) {
final url = piUrl(sync.store);
return ListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Dashboard on the home network'),
subtitle: Text(url.isEmpty ? 'Not set — the band\'s data reaches the app in the usual rhythm' : url,
style: const TextStyle(color: muted)),
trailing: const Icon(Icons.edit),
onTap: () async {
final c = TextEditingController(text: url);
final v = await showDialog<String>(
context: context,
builder: (d) => AlertDialog(
title: const Text('Dashboard address'),
content: TextField(
controller: c,
keyboardType: TextInputType.url,
decoration: const InputDecoration(hintText: 'http://192.168.1.50:8080')),
actions: [
TextButton(onPressed: () => Navigator.pop(d), child: const Text('Cancel')),
TextButton(onPressed: () => Navigator.pop(d, c.text), child: const Text('Save')),
],
),
);
if (v != null) sync.setPiUrl(v);
},
);
}
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('Sync'), actions: [
IconButton(onPressed: () {
sync.syncNow();
sync.updater.check(force: true);
}, icon: const Icon(Icons.sync), tooltip: 'Sync now'),
]),
body: ListenableBuilder(
listenable: sync,
builder: (context, _) {
final s = sync.settings;
return ListView(padding: const EdgeInsets.all(16), children: [
Text('${s.account} · ${s.name} · ${s.server}', style: const TextStyle(color: muted)),
const SizedBox(height: 6),
if (sync.busy) const LinearProgressIndicator(),
Text(sync.lastOk == null ? 'Not synced yet' : 'Last sync ${TimeOfDay.fromDateTime(sync.lastOk!).format(context)}'
'${sync.last == null ? '' : ' · ${sync.last}'}'),
if (sync.error != null) Text(sync.error!, style: const TextStyle(color: bad)),
Text(sync.store.meta('bg_ok') == 0 ? 'In the background: about every hour (none yet)'
: 'In the background: about every hour · last ${TimeOfDay.fromDateTime(DateTime.fromMillisecondsSinceEpoch(sync.store.meta('bg_ok'))).format(context)}',
style: const TextStyle(color: muted)),
const SizedBox(height: 12),
_band(context),
const SizedBox(height: 12),
_app(context),
const SizedBox(height: 12),
_pi(context),
const SizedBox(height: 12),
for (final e in sync.store.counts().entries)
ListTile(dense: true, title: Text(e.key), trailing: Text('${e.value}')),
const SizedBox(height: 24),
OutlinedButton(
onPressed: () => showDialog(
context: context,
builder: (d) => AlertDialog(
title: const Text('Disconnect this phone?'),
content: const Text('The data on this phone is deleted; the dashboard keeps everything. '
'Connecting again needs the device token and the passphrase.'),
actions: [
TextButton(onPressed: () => Navigator.pop(d), child: const Text('Cancel')),
TextButton(onPressed: () async {
await SyncSettings.forget();
if (d.mounted) Navigator.of(d).popUntil((r) => r.isFirst);
await onForget();
}, child: const Text('Disconnect', style: TextStyle(color: bad))),
],
),
),
child: const Text('Disconnect'),
),
]);
},
),
);
}

View file

@ -0,0 +1,89 @@
// One place that owns the connection: syncs on start, when the app comes back to the screen,
// every 5 minutes while it's open, and a few seconds after a local change (pages call changed()).
// Each sync first relays the band's new rows from Gadgetbridge's export (gb_relay.dart); when some went
// out, the Pi is told to sync now (kick.dart) and the app pulls its results right after.
// Pages listen to it and rebuild when data arrived or a sync finished.
import 'dart:async';
import 'package:flutter/widgets.dart';
import '../sync/client.dart';
import '../sync/crypto.dart';
import '../sync/gb_relay.dart';
import '../sync/kick.dart';
import 'updater.dart';
import '../weather/stations.dart' show stationDays;
import '../sync/store.dart';
class SyncService extends ChangeNotifier with WidgetsBindingObserver {
SyncService(this.settings, this.store) {
WidgetsBinding.instance.addObserver(this);
_timer = Timer.periodic(const Duration(minutes: 5), (_) => syncNow());
syncNow();
}
final SyncSettings settings;
final SyncStore store;
late final updater = Updater(settings); // a newer app build on the server (updater.dart), looked for after syncs
SyncCrypto? _crypto;
Timer? _timer, _soon;
bool busy = false;
DateTime? lastOk;
String? error;
SyncResult? last;
/// The dashboard's address on the home network for "sync now" (kick.dart); empty = none.
void setPiUrl(String v) {
store.setMetaText('pi_url', v.trim());
notifyListeners();
}
/// A local change was saved: refresh the pages now, send it in a few seconds (edits in a row → one batch).
void changed() {
notifyListeners();
_soon?.cancel();
_soon = Timer(const Duration(seconds: 3), syncNow);
}
Future<void> syncNow() async {
if (busy) return;
busy = true;
notifyListeners();
try {
_crypto ??= await SyncCrypto.create();
var band = 0;
try {
band = await GbRelay(store).run() ?? 0; // the band's new rows go out with this sync
} catch (e) {
debugPrint('gb relay: $e');
}
last = await runSync(settings, store, _crypto!);
if (band > 0 && last!.pushed > 0 && await kickPi(settings, store, _crypto!)) {
last = await runSync(settings, store, _crypto!); // the Pi's summaries of them, already there
}
store.dropOld('stations.hourly', 't', DateTime.now().millisecondsSinceEpoch ~/ 1000 - stationDays * 86400);
lastOk = DateTime.now();
error = null;
unawaited(updater.check());
} catch (e) {
error = '$e'; // offline is normal: the data stays here, sent next time
} finally {
busy = false;
notifyListeners();
}
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) syncNow();
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_timer?.cancel();
_soon?.cancel();
updater.dispose();
super.dispose();
}
}

34
app/lib/app/theme.dart Normal file
View file

@ -0,0 +1,34 @@
// The dashboard's look (config.THEME / dash.css): one dark background, amber for highlights.
import 'package:flutter/material.dart';
const bg = Color(0xFF0D1017), card = Color(0xFF161A23), card2 = Color(0xFF262D3B);
const accent = Color(0xFFFFB33A), muted = Color(0xFF8B929E), bad = Color(0xFFFF9A9A), good = Color(0xFF7FD6A3);
ThemeData appTheme() => ThemeData(
brightness: Brightness.dark,
scaffoldBackgroundColor: bg,
colorScheme: const ColorScheme.dark(primary: accent, secondary: accent, surface: card),
appBarTheme: const AppBarTheme(backgroundColor: bg, foregroundColor: accent, surfaceTintColor: Colors.transparent),
cardTheme: const CardThemeData(color: card, margin: EdgeInsets.zero,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(12)))),
// the selected section's icon in amber (Material's default is dark on the indicator)
navigationBarTheme: NavigationBarThemeData(
backgroundColor: card,
indicatorColor: card2,
iconTheme: WidgetStateProperty.resolveWith(
(st) => IconThemeData(color: st.contains(WidgetState.selected) ? accent : Colors.white)),
labelTextStyle: WidgetStateProperty.resolveWith((st) => TextStyle(
fontSize: 12.5, fontWeight: FontWeight.w600, color: st.contains(WidgetState.selected) ? accent : Colors.white)),
),
snackBarTheme: const SnackBarThemeData(backgroundColor: card2, contentTextStyle: TextStyle(color: Colors.white),
actionTextColor: accent, behavior: SnackBarBehavior.floating),
navigationRailTheme: const NavigationRailThemeData(
backgroundColor: card,
indicatorColor: card2,
selectedIconTheme: IconThemeData(color: accent),
unselectedIconTheme: IconThemeData(color: Colors.white),
selectedLabelTextStyle: TextStyle(color: accent, fontWeight: FontWeight.w600),
unselectedLabelTextStyle: TextStyle(color: Colors.white),
),
chipTheme: const ChipThemeData(backgroundColor: card2, selectedColor: Color(0xFF4A3B1E)),
);

138
app/lib/app/updater.dart Normal file
View file

@ -0,0 +1,138 @@
// The app updates itself from the sync server (dash-sync-server: GET /v1/app, /v1/app/apk — uploaded by
// tool/publish.sh): after a sync (at most every 3 hours, or when asked) it looks for a newer build; on
// Wi-Fi it downloads it by itself, on mobile data only when asked (~70 MB); then Install hands it to
// Android's installer (MainActivity "dash/update": checks the SHA-256 first; Android asks, and refuses an
// update not signed with this app's key). Works anywhere the sync works — not only at home.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
import '../sync/client.dart';
enum UpdateState { unknown, current, available, downloading, ready, failed }
class Updater extends ChangeNotifier {
Updater(this.settings);
final SyncSettings settings;
static const _ch = MethodChannel('dash/update');
static const every = Duration(hours: 3);
UpdateState state = UpdateState.unknown;
Map<String, dynamic>? latest; // {version, build, size, sha256, published, notes}
int code = 0; // this install's build number
String name = '';
bool metered = true;
double progress = 0;
String? error;
DateTime? checked;
bool _busy = false;
int get size => (latest?['size'] as num?)?.toInt() ?? 0;
String get label => latest == null ? '' : '${latest!['version']} (${latest!['build']})';
Future<File> _file() async {
final d = Directory('${(await getTemporaryDirectory()).path}/updates'); // = the FileProvider's cache-path
if (!d.existsSync()) d.createSync(recursive: true);
return File('${d.path}/dash-app.apk');
}
Uri _uri(String path) => Uri.parse(settings.server.replaceAll(RegExp(r'/+$'), '') + path);
/// Look for a newer build (quietly; [force] = now, not every 3 hours).
Future<void> check({bool force = false}) async {
if (_busy || (!force && checked != null && DateTime.now().difference(checked!) < every)) return;
_busy = true;
try {
final me = await _ch.invokeMapMethod<String, dynamic>('info');
code = (me?['code'] as num?)?.toInt() ?? 0;
name = me?['name'] as String? ?? '';
metered = me?['metered'] as bool? ?? true;
final r = await http.get(_uri('/v1/app'), headers: {'Authorization': 'Bearer ${settings.token}'}).timeout(const Duration(seconds: 20));
checked = DateTime.now();
if (r.statusCode == 404) {
latest = null;
state = UpdateState.current;
} else if (r.statusCode == 200) {
latest = jsonDecode(r.body) as Map<String, dynamic>;
final build = (latest!['build'] as num?)?.toInt() ?? 0;
if (build <= code) {
state = UpdateState.current;
final f = await _file();
if (f.existsSync()) f.deleteSync(); // installed: the download isn't needed any more
} else {
final f = await _file();
state = f.existsSync() && f.lengthSync() == size ? UpdateState.ready : UpdateState.available;
}
error = null;
} else {
error = 'Server: ${r.statusCode}';
}
} catch (e) {
error = e is SocketException || e is http.ClientException || e is TimeoutException
? "Can't reach the sync server — trying again later" // offline is normal
: '$e';
} finally {
_busy = false;
notifyListeners();
}
if (state == UpdateState.available && !metered) unawaited(download());
}
/// Fetch the APK (to the cache; .part until it's complete).
Future<void> download() async {
if (_busy || latest == null) return;
_busy = true;
state = UpdateState.downloading;
progress = 0;
notifyListeners();
final f = await _file(), part = File('${f.path}.part');
final client = http.Client();
try {
final req = http.Request('GET', _uri('/v1/app/apk'))..headers['Authorization'] = 'Bearer ${settings.token}';
final res = await client.send(req);
if (res.statusCode != 200) throw HttpException('Server: ${res.statusCode}');
final sink = part.openWrite();
var got = 0;
await for (final chunk in res.stream) {
sink.add(chunk);
got += chunk.length;
if (size > 0) progress = got / size;
notifyListeners();
}
await sink.close();
if (size > 0 && got != size) throw const HttpException('the download was cut off');
part.renameSync(f.path);
state = UpdateState.ready;
error = null;
} catch (e) {
if (part.existsSync()) part.deleteSync();
state = UpdateState.failed;
error = '$e';
} finally {
client.close();
_busy = false;
notifyListeners();
}
}
/// Hand it to Android's installer → a message for the user, or null when the installer opened.
Future<String?> install() async {
final f = await _file();
final r = await _ch.invokeMethod<String>('install', {'path': f.path, 'sha256': latest?['sha256'] ?? ''});
switch (r) {
case 'allow':
return 'Allow "Install unknown apps" for dashPi, then tap Install again.';
case 'bad':
if (f.existsSync()) f.deleteSync();
state = UpdateState.available;
notifyListeners();
return "The download didn't check out — download it again.";
}
return null;
}
}

View file

@ -0,0 +1,401 @@
// Health ▸ Activity (as on the web page's Activity tab), from the Pi's summaries: tiles (steps, workouts,
// fitness · form, vitality), steps and energy per day, training (fitness / fatigue / form) and the
// workouts — tap one for its heart rate on the zone bands and time in zones (WorkoutPage).
import 'dart:math';
import 'package:flutter/material.dart';
import '../app/sync_service.dart';
import '../app/theme.dart';
import '../widgets/bar_chart.dart';
import '../widgets/line_chart.dart';
import 'body_page.dart' show dm, dmy;
import 'cycle_model.dart' show iso, parseDay, today;
import 'range.dart';
import 'summaries.dart';
const vitalityGoal = 150; // intensity minutes a week (calc.VITALITY_GOAL, WHO)
const zoneNames = ['Resting', 'Warm-up', 'Fat burn', 'Aerobic', 'Anaerobic', 'Maximum'];
const zoneColors = [Color(0xFF4A5266), Color(0xFF8FA3BF), Color(0xFF5CC8FF), Color(0xFF7FD6A3), Color(0xFFFFB33A), Color(0xFFFF6B7A)];
const _fitC = Color(0xFF5CC8FF), _fatC = Color(0xFFFF8FC8);
/// watch.FORM
(String, String) formLabel(double v) => v < -30
? ('Overload', 'fatigue far above fitness — rest soon')
: v < -10
? ('Building', 'training hard, fitness rising')
: v < 10
? ('Neutral', 'steady')
: ('Fresh', 'rested, ready for a hard session');
/// watch.hm: minutes → "1h 05m"
String hm(num? minutes) {
if (minutes == null) return '—';
final m = minutes.round();
return '${m ~/ 60}h ${(m % 60).toString().padLeft(2, '0')}m';
}
String thousands(num v) => v.round().toString().replaceAllMapped(RegExp(r'\B(?=(\d{3})+$)'), (_) => ',');
class ActivityPage extends StatelessWidget {
const ActivityPage({super.key, required this.sync, required this.range});
final SyncService sync;
final HealthRange range;
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: Listenable.merge([sync, range]),
builder: (context, _) {
final sm = Summaries(sync.store);
final days = sm.all('day');
final wks = sm.all('workout');
if (days.isEmpty && wks.isEmpty) {
return const Center(child: Padding(
padding: EdgeInsets.all(24),
child: Text('Nothing from the band yet — it comes from the dashboard once it has synced.',
textAlign: TextAlign.center, style: TextStyle(color: muted)),
));
}
final now = today();
final first = parseDay([...days, ...wks].map((x) => x['_day'] as String).reduce((a, b) => a.compareTo(b) < 0 ? a : b));
final a = range.from(first, now);
bool inRange(Map x) => !parseDay(x['_day'] as String).isBefore(a);
final rd = days.where(inRange).toList(), rw = wks.where(inRange).toList();
DateTime at(Map x) => parseDay(x['_day'] as String);
final steps = [for (final x in rd) if (x['steps'] != null) (at(x), (x['steps'] as num).toDouble())];
final energy = [
for (final x in rd)
if (x['energy'] != null && (x['steps'] != null || rw.any((w) => w['_day'] == x['_day'])))
(at(x), ((x['energy'] as Map)['total'] as num).toDouble())
];
final todays = days.isNotEmpty && days.last['_day'] == iso(now) ? days.last : null;
final train = [for (final x in days) if (x['fitness'] != null) x];
final cur = train.isEmpty ? null : train.last;
final vit = days.where((x) => now.difference(at(x)).inDays < 7).fold<num>(0, (s, x) => s + ((x['vitality'] as num?) ?? 0));
double avg(List<(DateTime, double)> xs) => xs.isEmpty ? 0 : xs.map((p) => p.$2).reduce((p, q) => p + q) / xs.length;
final mins = rw.fold<num>(0, (s, w) => s + (w['minutes'] as num)), kcal = rw.fold<num>(0, (s, w) => s + ((w['kcal'] as num?) ?? 0));
final wide = MediaQuery.of(context).size.width >= 700;
return ListView(padding: const EdgeInsets.fromLTRB(12, 12, 12, 24), children: [
GridView.count(
crossAxisCount: wide ? 4 : 2,
shrinkWrap: true, physics: const NeverScrollableScrollPhysics(),
mainAxisSpacing: 10, crossAxisSpacing: 10, childAspectRatio: 1.75,
children: [
_tile('Steps', steps.isEmpty ? '—' : thousands(avg(steps)), 'a day · today ${todays?['steps'] == null ? '—' : thousands(todays!['steps'] as num)}',
'The band\'s steps, the average day of the ${steps.length} days with steps in this period'),
_tile('Workouts', '${rw.length}', '${hm(mins)} · ${thousands(kcal)} kcal',
'Workouts in this period: their time and the energy above resting (from heart rate)'),
_tile('Fitness · form', cur == null ? '—' : '${(cur['fitness'] as num).round()} · ${(cur['form'] as num).round()}',
cur == null ? 'no workouts yet' : formLabel((cur['form'] as num).toDouble()).$1,
'Fitness = your training load over 42 days, fatigue over 7, form = fitness − fatigue.'
'${cur == null ? '' : ' Now: ${formLabel((cur['form'] as num).toDouble()).$2}.'}'),
_tile('Vitality', '${vit.round()} / $vitalityGoal', 'intensity minutes, 7 days',
'Moderate minutes + 2 × vigorous ones, from the whole day\'s heart rate — WHO: at least 150 a week',
color: vit >= vitalityGoal ? good : null),
],
),
const SizedBox(height: 12),
_card('Steps', 'The band\'s steps per day (per week from 4 months: the average day)',
BarChart(points: steps, from: a, to: now, color: good, range: range,
fmt: (v) => '${thousands(v)} steps')),
const SizedBox(height: 12),
if (energy.isNotEmpty) ...[
_card('Energy', 'Estimated energy a day: resting (Mifflin–St Jeor) + walking (steps outside workouts) '
'+ workouts (heart rate). Average ${thousands(avg(energy))} kcal a day.',
BarChart(points: energy, from: a, to: now, color: accent, fmt: (v) => '${thousands(v)} kcal')),
const SizedBox(height: 12),
],
if (train.isNotEmpty) ...[
_card('Training', 'Fitness (42-day load), fatigue (7-day load) and form = fitness − fatigue. '
'Below −10: building, below −30: overload; above 10: fresh.',
Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
Wrap(spacing: 14, children: [
for (final (n, col) in [('Fitness', _fitC), ('Fatigue', _fatC), ('Form', accent)])
Row(mainAxisSize: MainAxisSize.min, children: [
Container(width: 10, height: 10, decoration: BoxDecoration(color: col, shape: BoxShape.circle)),
const SizedBox(width: 5), Text(n, style: const TextStyle(color: muted, fontSize: 12.5)),
]),
]),
const SizedBox(height: 6),
LineChart(from: a, to: now, decimals: 0, series: [
Series('Fitness', [for (final x in train) (at(x), (x['fitness'] as num).toDouble())], _fitC),
Series('Fatigue', [for (final x in train) (at(x), (x['fatigue'] as num).toDouble())], _fatC),
Series('Form', [for (final x in train) (at(x), (x['form'] as num).toDouble())], accent),
]),
])),
const SizedBox(height: 12),
],
_workouts(context, rw),
]);
},
);
Widget _tile(String label, String value, String sub, String tip, {Color? color}) => Tooltip(
triggerMode: TooltipTriggerMode.tap,
showDuration: const Duration(seconds: 6),
message: tip,
child: Card(child: Padding(
padding: const EdgeInsets.all(12),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [
Text(label.toUpperCase(), style: const TextStyle(color: muted, fontSize: 11.5)),
FittedBox(fit: BoxFit.scaleDown, child: Text(value, style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: color))),
Text(sub, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: muted, fontSize: 12)),
]),
)),
);
Widget _card(String title, String tip, Widget child) => Card(child: Padding(
padding: const EdgeInsets.fromLTRB(14, 8, 10, 10),
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
Row(children: [
Expanded(child: Text(title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold))),
_info(tip),
]),
child,
]),
));
Widget _workouts(BuildContext context, List<Map<String, dynamic>> rw) {
final rows = rw.reversed.take(60).toList();
return Card(child: Padding(
padding: const EdgeInsets.fromLTRB(14, 8, 10, 6),
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
Row(children: [
const Expanded(child: Text('Workouts', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold))),
_info('Calories = above resting, from heart rate. Effect = this workout\'s load vs your usual one (6 weeks before). '
'The strip = time in each heart-rate zone.'),
]),
if (rows.isEmpty) const Padding(padding: EdgeInsets.symmetric(vertical: 12), child: Text('None in this period', style: TextStyle(color: muted))),
for (final w in rows)
InkWell(
onTap: () => Navigator.push(context, MaterialPageRoute(builder: (_) => WorkoutPage(w: w))),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
Row(children: [
Expanded(child: Text(w['name'] as String, style: const TextStyle(fontWeight: FontWeight.bold))),
Text('${(w['kcal'] as num?)?.round() ?? '—'} kcal', style: const TextStyle(color: accent)),
]),
Text([dmy(parseDay(w['_day'] as String)), hm(w['minutes'] as num), if (w['avg_hr'] != null) '${(w['avg_hr'] as num).round()} bpm', if (w['effect'] != null) w['effect']].join(' · '),
style: const TextStyle(color: muted, fontSize: 12.5)),
const SizedBox(height: 5),
ZoneStrip(pct: ((w['zone_pct'] as List?) ?? const []).cast<num>()),
]),
),
),
if (rw.length > rows.length)
Padding(padding: const EdgeInsets.only(bottom: 6), child: Text('… and ${rw.length - rows.length} more', style: const TextStyle(color: muted))),
]),
));
}
}
Widget _info(String tip) => Tooltip(
triggerMode: TooltipTriggerMode.tap,
showDuration: const Duration(seconds: 8),
message: tip,
child: const Padding(padding: EdgeInsets.all(6), child: Icon(Icons.info_outline, size: 18, color: muted)),
);
class ZoneStrip extends StatelessWidget {
const ZoneStrip({super.key, required this.pct, this.height = 6});
final List<num> pct;
final double height;
@override
Widget build(BuildContext context) => ClipRRect(
borderRadius: BorderRadius.circular(3),
child: SizedBox(height: height, child: Row(children: [
for (var i = 0; i < pct.length && i < zoneColors.length; i++)
if (pct[i] > 0) Expanded(flex: max(1, pct[i].round()), child: Container(color: zoneColors[i])),
if (pct.every((p) => p <= 0)) Expanded(child: Container(color: card2)),
])),
);
}
/// One workout (the web's workout page): stats, heart rate on the zone bands, time in zones.
class WorkoutPage extends StatelessWidget {
const WorkoutPage({super.key, required this.w});
final Map<String, dynamic> w;
@override
Widget build(BuildContext context) {
final start = DateTime.parse(w['start'] as String);
final zones = ((w['zones'] as List?) ?? const []).cast<num>(), pct = ((w['zone_pct'] as List?) ?? const []).cast<num>();
final bounds = ((w['bounds'] as List?) ?? const []).cast<num>();
final hr = [for (final p in (w['hr'] as List? ?? const [])) ((p as List)[0] as num, p[1] as num)];
String t(DateTime d) => d.toIso8601String().substring(11, 16);
final end = DateTime.parse(w['end'] as String);
final stats = [
('Time', hm(w['minutes'] as num)),
('Calories', '${(w['kcal'] as num?)?.round() ?? '—'} kcal'),
('Average', w['avg_hr'] == null ? '—' : '${(w['avg_hr'] as num).round()} bpm'),
('Highest', w['max_hr'] == null ? '—' : '${w['max_hr']} bpm'),
if (w['distance'] != null) ('Distance', '${((w['distance'] as num) / 1000).toStringAsFixed(2)} km'),
if (w['steps'] != null && (w['steps'] as num) > 0) ('Steps', thousands(w['steps'] as num)),
if (w['load'] != null) ('Load', '${(w['load'] as num).round()}'),
if (w['effect'] != null) ('Effect', w['effect'] as String),
];
return Scaffold(
appBar: AppBar(title: Text(w['name'] as String)),
body: ListView(padding: const EdgeInsets.all(12), children: [
Text('${dm(start)} ${start.year} · ${t(start)} – ${t(end)}', style: const TextStyle(color: muted)),
const SizedBox(height: 10),
Card(child: Padding(
padding: const EdgeInsets.all(12),
child: Wrap(spacing: 18, runSpacing: 10, children: [
for (final (l, v) in stats)
Tooltip(
triggerMode: TooltipTriggerMode.tap,
message: switch (l) {
'Calories' => 'Above resting, from your heart rate (with resting: ${(w['kcal_total'] as num?)?.round() ?? '—'} kcal)',
'Load' => 'Training load (TRIMP): minutes × how hard, from heart rate',
'Effect' => 'This load vs your usual one (the workouts of the 6 weeks before${w['usual'] == null ? '' : ': ${(w['usual'] as num).round()}'})',
_ => l,
},
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text(l.toUpperCase(), style: const TextStyle(color: muted, fontSize: 11)),
Text(v, style: const TextStyle(fontSize: 17, fontWeight: FontWeight.bold)),
]),
),
]),
)),
const SizedBox(height: 12),
if (hr.length > 1)
Card(child: Padding(
padding: const EdgeInsets.fromLTRB(8, 12, 12, 8),
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
const Padding(padding: EdgeInsets.only(left: 6, bottom: 8), child: Text('Heart rate', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold))),
_HrGraph(hr: hr, bounds: bounds, start: start, seconds: end.difference(start).inSeconds.toDouble()),
]),
)),
const SizedBox(height: 12),
if (zones.isNotEmpty)
Card(child: Padding(
padding: const EdgeInsets.all(12),
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
const Text('Time in zones', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
const SizedBox(height: 8),
for (var i = zones.length - 1; i >= 0; i--)
Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Row(children: [
SizedBox(width: 118, child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text(zoneNames[i]),
Text(_range(i, bounds), style: const TextStyle(color: muted, fontSize: 11.5)),
])),
Expanded(child: ClipRRect(
borderRadius: BorderRadius.circular(3),
child: LinearProgressIndicator(value: (i < pct.length ? pct[i] : 0) / 100, minHeight: 8,
color: zoneColors[i], backgroundColor: card2),
)),
SizedBox(width: 90, child: Text('${(zones[i] / 60).round()} min · ${i < pct.length ? pct[i] : 0} %',
textAlign: TextAlign.right, style: const TextStyle(fontSize: 12.5))),
]),
),
]),
)),
]),
);
}
static String _range(int i, List<num> b) {
if (b.isEmpty) return '';
if (i == 0) return 'under ${b[0]}';
return i < b.length ? '${b[i - 1]}–${b[i] - 1} bpm' : '${b[i - 1]}+ bpm';
}
}
class _HrGraph extends StatefulWidget {
const _HrGraph({required this.hr, required this.bounds, required this.start, required this.seconds});
final List<(num, num)> hr; // (seconds from start, bpm)
final List<num> bounds;
final DateTime start;
final double seconds;
@override
State<_HrGraph> createState() => _HrGraphState();
}
class _HrGraphState extends State<_HrGraph> {
int? hit;
@override
Widget build(BuildContext context) {
final h = hit == null ? null : widget.hr[hit!];
return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
LayoutBuilder(builder: (context, box) {
void pick(Offset o) {
final s = (o.dx - 34) / (box.maxWidth - 34) * widget.seconds;
var best = 0;
for (var i = 1; i < widget.hr.length; i++) {
if ((widget.hr[i].$1 - s).abs() < (widget.hr[best].$1 - s).abs()) best = i;
}
setState(() => hit = best);
}
return GestureDetector(
onTapDown: (d) => pick(d.localPosition),
onHorizontalDragUpdate: (d) => pick(d.localPosition),
child: CustomPaint(size: Size(box.maxWidth, 200), painter: _HrPainter(widget, hit)),
);
}),
SizedBox(
height: 20,
child: h == null
? const Text('Tap the graph for a minute\'s heart rate', textAlign: TextAlign.center, style: TextStyle(color: muted, fontSize: 12.5))
: Text('${(h.$1 / 60).floor()} min: ${h.$2} bpm', textAlign: TextAlign.center, style: const TextStyle(fontSize: 13)),
),
]);
}
}
class _HrPainter extends CustomPainter {
_HrPainter(this.g, this.hit);
final _HrGraph g;
final int? hit;
@override
void paint(Canvas c, Size size) {
const ml = 34.0, mb = 16.0, mt = 4.0;
final vs = g.hr.map((p) => p.$2.toDouble());
final lo = (min(vs.reduce(min), g.bounds.isEmpty ? 999 : g.bounds.first.toDouble()) / 10).floor() * 10.0 - 5;
final hi = (vs.reduce(max) / 10).ceil() * 10.0 + 5;
final h = size.height - mb - mt, w = size.width - ml;
double y(double v) => mt + h - h * (v - lo) / (hi - lo);
double x(num s) => ml + w * s / max(1, g.seconds);
// zone bands (z1…z5), faint
for (var i = 0; i < g.bounds.length; i++) {
final top = i + 1 < g.bounds.length ? g.bounds[i + 1].toDouble() : hi;
final a = y(min(top, hi)), b = y(max(g.bounds[i].toDouble(), lo));
if (b > a) c.drawRect(Rect.fromLTRB(ml, a, size.width, b), Paint()..color = zoneColors[i + 1].withValues(alpha: .13));
}
final txt = const TextStyle(color: muted, fontSize: 10.5);
void label(String s, Offset o, {bool right = false}) {
final tp = TextPainter(text: TextSpan(text: s, style: txt), textDirection: TextDirection.ltr)..layout();
tp.paint(c, right ? o - Offset(tp.width, tp.height / 2) : o - Offset(tp.width / 2, 0));
}
for (var v = (lo / 20).ceil() * 20.0; v <= hi; v += 20) {
label('${v.round()}', Offset(ml - 4, y(v)), right: true);
}
final mins = g.seconds / 60, every = mins <= 30 ? 5 : mins <= 75 ? 15 : mins <= 150 ? 30 : 60;
for (var m = 0; m <= mins; m += every) {
label('$m′', Offset(x(m * 60), size.height - mb + 3));
}
final path = Path();
for (var i = 0; i < g.hr.length; i++) {
final p = Offset(x(g.hr[i].$1), y(g.hr[i].$2.toDouble()));
i == 0 ? path.moveTo(p.dx, p.dy) : path.lineTo(p.dx, p.dy);
}
c.drawPath(path, Paint()..color = const Color(0xFFFF6B7A)..strokeWidth = 2..style = PaintingStyle.stroke..strokeJoin = StrokeJoin.round);
if (hit != null) {
final p = Offset(x(g.hr[hit!].$1), y(g.hr[hit!].$2.toDouble()));
c.drawLine(Offset(p.dx, mt), Offset(p.dx, size.height - mb), Paint()..color = muted.withValues(alpha: .5));
c.drawCircle(p, 4, Paint()..color = Colors.white);
}
}
@override
bool shouldRepaint(covariant _HrPainter old) => true;
}

View file

@ -0,0 +1,344 @@
// Body measurements + vitals — a port of the dashboard's plugins/health calc.py (formulas,
// categories), views.py (latest per field, changes, series) and db.py (what a save does).
// Keep them in step with the web pages.
//
// Synced rows: "health.measure" id "measure:<day>" {day, weight, waist, hip, neck, chest, arm,
// thigh, fat_scale, note, updated}; "health.vital" {t "YYYY-MM-DD HH:MM", sys, dia, spo2, pulse,
// note, source} — imported ones have id "vital:<t>", ones typed here a random id.
import 'dart:math';
import '../sync/store.dart';
import 'cycle_model.dart' show iso, parseDay, daysBetween, today;
import 'summaries.dart';
const female = 'female';
const stale = 90; // days a measurement is still used for "now" / carried forward
/// key: (label, unit, min, max)
const fields = {
'weight': ('Weight', 'kg', 20.0, 400.0),
'waist': ('Waist', 'cm', 30.0, 250.0),
'hip': ('Hips', 'cm', 30.0, 250.0),
'neck': ('Neck', 'cm', 15.0, 80.0),
'chest': ('Chest', 'cm', 40.0, 250.0),
'arm': ('Upper arm', 'cm', 10.0, 80.0),
'thigh': ('Thigh', 'cm', 20.0, 120.0),
'fat_scale': ('Body fat from a scale', '%', 2.0, 75.0),
};
const fatDayFields = {'weight', 'waist', 'hip', 'neck', 'fat_scale'};
/// The values set on the dashboard (Settings ▸ Health), from its person summary (profileOf).
class Profile {
const Profile({this.sex = female, this.birth, this.height});
final String sex;
final DateTime? birth;
final double? height;
int? ageOn(DateTime d) {
final b = birth;
if (b == null) return null;
return d.year - b.year - ((d.month < b.month || (d.month == b.month && d.day < b.day)) ? 1 : 0);
}
}
/// The dashboard's Settings ▸ Health (sex, birth date, height) as its summary brings them; none yet = no age / height.
Profile profileOf(SyncStore store) {
final p = Summaries(store).meta('person') ?? {};
final b = DateTime.tryParse('${p['birth'] ?? ''}');
final h = (p['height'] as num?)?.toDouble();
return Profile(sex: p['sex'] == 'male' ? 'male' : female,
birth: b == null ? null : DateTime.utc(b.year, b.month, b.day), height: h == null || h <= 0 ? null : h);
}
// ---- formulas (calc.py) ---------------------------------------------------------------------
double _log10(double x) => log(x) / ln10;
double? bmi(double? w, double? h) => (w == null || h == null || w == 0 || h == 0) ? null : w / pow(h / 100, 2);
const bmiClasses = [(18.5, 'underweight'), (25.0, 'normal'), (30.0, 'overweight'), (35.0, 'obese (class I)'),
(40.0, 'obese (class II)'), (999.0, 'obese (class III)')];
String? bmiClass(double? b) => b == null ? null : bmiClasses.firstWhere((c) => b < c.$1).$2;
(double, double)? healthyWeight(double? h) => h == null ? null : (18.5 * pow(h / 100, 2), 24.9 * pow(h / 100, 2));
double? whtr(double? waist, double? h) => waist != null && h != null ? waist / h : null;
String? whtrClass(double? r) => r == null ? null : r < 0.4 ? 'low' : r < 0.5 ? 'healthy' : r < 0.6 ? 'raised' : 'high';
double? whr(double? waist, double? hip) => waist != null && hip != null ? waist / hip : null;
String? whrClass(double? r, String sex) => r == null ? null : r >= (sex == female ? 0.85 : 0.90) ? 'raised (WHO)' : 'healthy';
String? waistClass(double? w, String sex) {
if (w == null) return null;
final (a, b) = sex == female ? (80, 88) : (94, 102);
return w < a ? 'healthy' : w < b ? 'raised' : 'high';
}
double? navy(Map<String, double> m, double? h, String sex) {
final w = m['waist'], n = m['neck'], hip = m['hip'];
if (w == null || n == null || h == null) return null;
if (sex == female) {
if (hip == null || w + hip - n <= 0) return null;
return 495 / (1.29579 - 0.35004 * _log10(w + hip - n) + 0.22100 * _log10(h)) - 450;
}
if (w - n <= 0) return null;
return 495 / (1.0324 - 0.19077 * _log10(w - n) + 0.15456 * _log10(h)) - 450;
}
double? rfm(Map<String, double> m, double? h, String sex) {
final w = m['waist'];
return w == null || h == null ? null : (sex == female ? 76 : 64) - 20 * h / w;
}
double? ymca(Map<String, double> m, double? h, String sex) {
final w = m['waist'], kg = m['weight'];
if (w == null || kg == null) return null;
final lb = kg * 2.20462, inch = w / 2.54;
return (4.15 * inch - 0.082 * lb - (sex == female ? 76.76 : 98.42)) / lb * 100;
}
class FatResult {
FatResult(this.key, this.name, this.value, this.missing, this.note);
final String key, name, note;
final double? value;
final List<String> missing;
}
/// (key, name, needs, note) — BMI-based formulas and skinfolds left out on purpose (calc.FAT).
const fatFormulas = [
('navy', 'U.S. Navy', ['waist', 'neck', 'hip?', 'height'], 'tape: waist, neck, hips · about ±3–4 % in studies'),
('rfm', 'Relative fat mass', ['waist', 'height'], 'waist and height · checked against DEXA scans'),
('ymca', 'YMCA', ['waist', 'weight'], 'waist and weight · simple, less tested in women'),
('scale', 'Your scale', ['fat_scale'], 'bioimpedance · shifts with water, time of day'),
];
List<FatResult> fatAll(Map<String, double> m, double? h, String sex) => [
for (final (key, name, needs, note) in fatFormulas)
() {
var v = switch (key) {
'navy' => navy(m, h, sex),
'rfm' => rfm(m, h, sex),
'ymca' => ymca(m, h, sex),
_ => m['fat_scale'],
};
if (v != null && (v < 2 || v > 75)) v = null; // implausible: bad inputs
final missing = <String>[];
if (v == null) {
for (final n in needs) {
if (n == 'hip?') {
if (sex == female && m['hip'] == null) missing.add('hip');
} else if (n == 'height') {
if (h == null) missing.add('height');
} else if (m[n] == null) {
missing.add(n);
}
}
}
return FatResult(key, name, v, missing, note);
}()
];
/// Healthy body-fat ranges (Gallagher et al. 2000): (age from, to, healthy from, high from, very high from).
const fatRanges = {
female: [(20, 39, 21.0, 33.0, 39.0), (40, 59, 23.0, 34.0, 40.0), (60, 79, 24.0, 36.0, 42.0)],
'male': [(20, 39, 8.0, 20.0, 25.0), (40, 59, 11.0, 22.0, 28.0), (60, 79, 13.0, 25.0, 30.0)],
};
const fatNames = ['low', 'healthy', 'high', 'very high'];
(int, int, double, double, double)? fatBand(String sex, int? age) {
if (age == null || age < 20) return null;
final rows = fatRanges[sex == female ? female : 'male']!;
return rows.firstWhere((r) => r.$1 <= age && age <= r.$2, orElse: () => rows.last);
}
String? fatClass(double? v, String sex, int? age) {
final b = fatBand(sex, age);
if (v == null || b == null) return null;
return fatNames[[b.$3, b.$4, b.$5].where((x) => v >= x).length];
}
/// Desirable BMI by age (NRC 1989): (age from, to, lo, hi).
const bmiAge = [(19, 24, 19, 24), (25, 34, 20, 25), (35, 44, 21, 26), (45, 54, 22, 27), (55, 64, 23, 28), (65, 200, 24, 29)];
(int, int, int, int)? bmiAgeBand(int? age) =>
age == null || age < 19 ? null : bmiAge.firstWhere((r) => r.$1 <= age && age <= r.$2);
double? bmrMifflin(double? w, double? h, String sex, int? age) =>
w == null || h == null || age == null ? null : 10 * w + 6.25 * h - 5 * age + (sex == female ? -161 : 5);
double? bmrKatch(double? w, double? fat) => w == null || fat == null ? null : 370 + 21.6 * w * (1 - fat / 100);
double? median(List<double> xs) {
if (xs.isEmpty) return null;
final s = [...xs]..sort();
final n = s.length;
return n.isOdd ? s[n ~/ 2] : (s[n ~/ 2 - 1] + s[n ~/ 2]) / 2;
}
// ---- the page's numbers (views.py) ----------------------------------------------------------
class Measure {
Measure(this.row) : day = parseDay(row['day'] as String);
final Map<String, dynamic> row;
final DateTime day;
double? operator [](String k) => (row[k] as num?)?.toDouble();
String get note => (row['note'] as String?) ?? '';
}
class Latest {
Latest(this.v, this.day, this.stale);
final double v;
final DateTime day;
final bool stale;
}
class BodyView {
BodyView(SyncStore store, this.p, {DateTime? now}) : now = now ?? today() {
rows = [for (final r in store.rows('health.measure')) Measure(r)]..sort((a, b) => a.day.compareTo(b.day));
for (final r in rows) {
for (final k in fields.keys) {
if (r[k] != null) cur[k] = Latest(r[k]!, r.day, daysBetween(r.day, this.now) > stale);
}
}
final m = {for (final e in cur.entries) if (!e.value.stale) e.key: e.value.v};
fresh = m;
age = p.ageOn(this.now);
fat = fatAll(m, p.height, p.sex);
final est = [for (final f in fat) if (f.value != null) f.value!];
fatMid = median(est);
fatRange = est.length > 1 ? (est.reduce(min), est.reduce(max)) : null;
}
final Profile p;
final DateTime now;
late final List<Measure> rows;
final cur = <String, Latest>{};
late final Map<String, double> fresh;
late final int? age;
late final List<FatResult> fat;
late final double? fatMid;
late final (double, double)? fatRange;
double? get weight => fresh['weight'];
double? get waist => fresh['waist'];
double? get hip => fresh['hip'];
double? get bmiNow => bmi(weight, p.height);
/// Change of [key] from the value nearest [days] ago (at least 7 days back) to the latest.
(double, DateTime, int)? change(String key, {int days = 30}) {
final pts = [for (final r in rows) if (r[key] != null) (r.day, r[key]!)];
if (pts.length < 2) return null;
final (lastD, lastV) = pts.last;
final old = pts.where((p) => daysBetween(p.$1, lastD) >= 7).toList();
if (old.isEmpty) return null;
old.sort((a, b) => (daysBetween(a.$1, lastD) - days).abs().compareTo((daysBetween(b.$1, lastD) - days).abs()));
final (d, v) = old.first;
return (lastV - v, d, daysBetween(d, lastD));
}
/// Per measured day: weight, waist, BMI and each fat formula (other inputs carried forward ≤ stale days).
Map<String, List<(DateTime, double)>> series() {
final out = <String, List<(DateTime, double)>>{
'weight': [], 'waist': [], 'bmi': [], for (final f in fatFormulas) f.$1: []};
final last = <String, (double, DateTime)>{};
for (final r in rows) {
for (final k in fields.keys) {
if (r[k] != null) last[k] = (r[k]!, r.day);
}
final m = {for (final e in last.entries) if (daysBetween(e.value.$2, r.day) <= stale) e.key: e.value.$1};
for (final k in ['weight', 'waist']) {
if (r[k] != null) out[k]!.add((r.day, r[k]!));
}
if (r['weight'] != null && p.height != null) out['bmi']!.add((r.day, bmi(r['weight'], p.height)!));
if (fatDayFields.any((k) => r[k] != null)) {
for (final f in fatAll(m, p.height, p.sex)) {
if (f.value != null) out[f.key]!.add((r.day, f.value!));
}
}
}
return out;
}
}
/// db.save: replace the day's row; `was` (another day) moves it; nothing in it → deleted.
String? saveMeasure(SyncStore store, DateTime d, Map<String, double?> vals, String note, {DateTime? was}) {
if (d.isAfter(today())) return "That day hasn't happened yet.";
for (final e in vals.entries) {
final f = fields[e.key]!;
if (e.value != null && (e.value! < f.$3 || e.value! > f.$4)) return '${f.$1}: between ${f.$3.round()} and ${f.$4.round()} ${f.$2}.';
}
final u = 'measure:${iso(d)}';
if (was != null && was != d) {
if (store.row('health.measure', u) != null) return 'That day already has measurements — edit it instead.';
store.delete('health.measure', 'measure:${iso(was)}');
}
if (vals.values.every((v) => v == null) && note.trim().isEmpty) {
if (store.row('health.measure', u) != null) store.delete('health.measure', u);
return null;
}
final old = store.row('health.measure', u) ?? {};
final now = DateTime.now();
store.put('health.measure', u, {
...old, // columns this app doesn't show (old skinfolds) stay
'day': iso(d), 'note': note.trim(), 'updated': '${iso(now)} ${now.toIso8601String().substring(11, 19)}',
for (final k in fields.keys) k: vals[k],
});
return null;
}
// ---- vitals ------------------------------------------------------------------------------
const vitalSources = {'mi_fitness': 'Mi Fitness', 'health_connect': 'Health Connect', 'gadgetbridge': 'Gadgetbridge'};
class Vital {
Vital(this.row) : t = DateTime.parse('${(row['t'] as String).replaceFirst(' ', 'T')}:00Z');
final Map<String, dynamic> row;
final DateTime t; // local wall time (stored as UTC so nothing shifts)
String get u => row['_u'] as String;
int? get sys => (row['sys'] as num?)?.toInt();
int? get dia => (row['dia'] as num?)?.toInt();
double? get spo2 => (row['spo2'] as num?)?.toDouble();
String get note => (row['note'] as String?) ?? '';
String? get source => row['source'] as String?;
bool get isBp => sys != null && dia != null;
}
List<Vital> vitals(SyncStore store) =>
[for (final r in store.rows('health.vital')) Vital(r)]..sort((a, b) => b.t.compareTo(a.t)); // newest first
/// (name, colour key) — ESC 2024 office categories; the higher of the two numbers decides.
(String, String)? bpClass(int? sys, int? dia) {
if (sys == null || dia == null) return null;
const classes = [('non-elevated', 0, 0, 'ok'), ('elevated', 120, 70, 'mid'), ('hypertension', 140, 90, 'high'),
('severe hypertension', 180, 110, 'vhigh')];
var pick = classes.first;
for (final c in classes) {
if (sys >= c.$2 || dia >= c.$3) pick = c;
}
return (pick.$1, pick.$4);
}
(String, String)? spo2Class(double? p) => p == null ? null : p >= 95 ? ('normal', 'ok') : p > 90 ? ('low', 'mid') : ('very low', 'vhigh');
/// db.save_vital: one kind per reading (bp: sys + dia, ox: spo2). Returns an error or null.
String? saveVital(SyncStore store, {String? u, required String kind, required DateTime t, int? sys, int? dia, double? spo2,
String note = ''}) {
if (t.isAfter(DateTime.now().toUtc().add(const Duration(hours: 14)))) return "That time hasn't come yet.";
if (kind == 'bp') {
if (sys == null || dia == null) return 'Blood pressure needs both numbers (e.g. 120 / 80).';
if (sys < 60 || sys > 260) return 'Systolic: between 60 and 260 mmHg.';
if (dia < 30 || dia > 160) return 'Diastolic: between 30 and 160 mmHg.';
if (sys <= dia) return 'The upper number (systolic) is the bigger one.';
} else {
if (spo2 == null) return 'Enter the oxygen %.';
if (spo2 < 50 || spo2 > 100) return 'Blood oxygen: between 50 and 100 %.';
}
final old = u == null ? null : store.row('health.vital', u);
final ts = '${iso(t)} ${t.toIso8601String().substring(11, 16)}';
store.put('health.vital', u ?? SyncStore.randomId(), {
...?old,
't': ts, 'sys': kind == 'bp' ? sys : null, 'dia': kind == 'bp' ? dia : null,
'spo2': kind == 'ox' ? (spo2! * 10).round() / 10 : null, 'pulse': null, 'note': note.trim(),
'source': old?['source'],
});
return null;
}
/// Readings of one kind as chart points (oldest first).
List<(DateTime, double)> vitalSeries(List<Vital> vs, double? Function(Vital) pick) =>
[for (final v in vs.reversed) if (pick(v) != null) (v.t, pick(v)!)];

View file

@ -0,0 +1,419 @@
// Health ▸ Body: tiles (weight + change, BMI, waist, body fat), the chart (weight / waist / BMI /
// body fat over 3 months · 1 year · all), body fat by every formula, ratios + resting energy, the
// measurements (tap = edit, + = add). The numbers are the web page's (body_model.dart).
// Categories: tap a tile (the web page shows them on hover).
import 'package:flutter/material.dart';
import '../app/sync_service.dart';
import '../app/theme.dart';
import '../widgets/line_chart.dart';
import 'body_model.dart';
import 'cycle_model.dart' show plus, today;
import 'range.dart';
const _mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
String dm(DateTime d) => '${d.day} ${_mon[d.month - 1]}';
String dmy(DateTime d) => '${d.day} ${_mon[d.month - 1]} ${d.year}';
String n1(double? v) => v == null ? '—' : v.toStringAsFixed(1);
/// 115 not 115.0; 124.6 stays.
String trim1(double? v) => v == null ? '—' : n1(v).replaceFirst(RegExp(r'\.0$'), '');
const _short = {'weight': 'weight', 'waist': 'waist', 'hip': 'hips', 'neck': 'neck', 'chest': 'chest', 'arm': 'arm',
'thigh': 'thigh', 'fat_scale': 'scale fat'};
/// A category word → its colour (healthy green, raised amber, high red, low blue).
Color classColor(String? c) {
if (c == null) return muted;
if (RegExp(r'very high|obese|severe|vhigh|very low').hasMatch(c)) return bad;
if (RegExp(r'^(healthy|normal|non-elevated|ok)').hasMatch(c)) return good;
if (RegExp(r'^(low|underweight)').hasMatch(c)) return const Color(0xFF5CC8FF);
return accent;
}
class BodyPage extends StatefulWidget {
const BodyPage({super.key, required this.sync, required this.range});
final SyncService sync;
final HealthRange range;
@override
State<BodyPage> createState() => _BodyPageState();
}
class _BodyPageState extends State<BodyPage> {
String chart = 'weight';
int shown = 5;
@override
Widget build(BuildContext context) => Scaffold(
floatingActionButton: FloatingActionButton(
backgroundColor: accent,
foregroundColor: bg,
tooltip: 'Add measurements',
onPressed: () => _edit(BodyView(widget.sync.store, profileOf(widget.sync.store)), null),
child: const Icon(Icons.add),
),
body: ListenableBuilder(
listenable: Listenable.merge([widget.sync, widget.range]),
builder: (context, _) {
final v = BodyView(widget.sync.store, profileOf(widget.sync.store));
if (v.rows.isEmpty) {
return const Center(child: Text('No measurements yet — + to add the first.', style: TextStyle(color: muted)));
}
return LayoutBuilder(builder: (context, box) {
final wide = box.maxWidth >= 700;
final left = [_tiles(v, wide), const SizedBox(height: 12), _chart(v)];
final right = [_fat(v), const SizedBox(height: 12), _ratios(v), const SizedBox(height: 12), _list(v)];
return ListView(padding: const EdgeInsets.fromLTRB(12, 12, 12, 88), children: [
if (wide)
Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
Expanded(child: Column(children: left)),
const SizedBox(width: 12),
Expanded(child: Column(children: right)),
])
else ...[...left, const SizedBox(height: 12), ...right],
]);
});
},
),
);
// ---- tiles
Widget _tiles(BodyView v, bool wide) {
final wc = v.change('weight');
final b = v.bmiNow;
String from(String k) {
final c = v.cur[k];
if (c == null) return '';
return c.day == v.now ? 'today' : c.stale ? 'old: ${dmy(c.day)}' : dm(c.day);
}
final tiles = [
_Tile('Weight', v.weight == null ? '—' : '${trim1(v.weight)} kg',
wc == null ? from('weight') : '${wc.$1 >= 0 ? '+' : '−'}${wc.$1.abs().toStringAsFixed(1)} kg in ${wc.$3} days',
null, () => _info('Weight', _weightInfo(v))),
_Tile('BMI', b == null ? '—' : n1(b), bmiClass(b) ?? 'needs height + weight', bmiClass(b), () => _info('BMI', _bmiInfo(v))),
_Tile('Waist', v.waist == null ? '—' : '${trim1(v.waist)} cm', waistClass(v.waist, v.p.sex) ?? from('waist'),
waistClass(v.waist, v.p.sex), () => _info('Waist', _waistInfo(v))),
_Tile('Body fat', v.fatMid == null ? '—' : '${n1(v.fatMid)} %',
fatClass(v.fatMid, v.p.sex, v.age) ?? 'needs measurements', fatClass(v.fatMid, v.p.sex, v.age),
() => _info('Body fat', _fatInfo(v))),
];
return GridView.count(
crossAxisCount: 2, shrinkWrap: true, physics: const NeverScrollableScrollPhysics(),
mainAxisSpacing: 10, crossAxisSpacing: 10, childAspectRatio: 1.9,
children: tiles,
);
}
Widget _weightInfo(BodyView v) {
final hw = healthyWeight(v.p.height);
return Text(hw == null ? 'Set your height on the dashboard.' :
'Healthy weight for ${v.p.height} cm (BMI 18.5–24.9): ${hw.$1.toStringAsFixed(1)}–${hw.$2.toStringAsFixed(1)} kg.');
}
Widget _bmiInfo(BodyView v) {
final band = bmiAgeBand(v.age);
return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
const Text('WHO classes (all adults): under 18.5 underweight · 18.5–25 normal · 25–30 overweight · 30+ obese (I 30–35, II 35–40, III 40+).'),
const SizedBox(height: 10),
const Text('Desirable BMI by age (NRC 1989):', style: TextStyle(color: muted)),
for (final r in bmiAge)
Text('${r.$1}–${r.$2 > 100 ? '+' : r.$2}: ${r.$3}–${r.$4}',
style: TextStyle(color: band == r ? accent : null, fontWeight: band == r ? FontWeight.bold : null)),
const SizedBox(height: 8),
const Text('BMI reads muscle as fat; the waist and body fat say more.', style: TextStyle(color: muted)),
]);
}
Widget _waistInfo(BodyView v) => Text(v.p.sex == female
? 'WHO (European women): under 80 cm healthy · 80–88 raised · 88+ high.'
: 'WHO (European men): under 94 cm healthy · 94–102 raised · 102+ high.');
Widget _fatInfo(BodyView v) {
final rows = fatRanges[v.p.sex == female ? female : 'male']!;
final band = fatBand(v.p.sex, v.age);
return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text('Healthy body fat by age (${v.p.sex}, Gallagher et al. 2000):', style: const TextStyle(color: muted)),
for (final r in rows)
Text('${r.$1}–${r.$2}: healthy ${r.$3.round()}–${r.$4.round()} % · high from ${r.$4.round()} · very high from ${r.$5.round()}',
style: TextStyle(color: band == r ? accent : null, fontWeight: band == r ? FontWeight.bold : null)),
const SizedBox(height: 8),
const Text('The middle (median) of every formula that has its measurements; they disagree by a few points.',
style: TextStyle(color: muted)),
]);
}
void _info(String title, Widget body) => showModalBottomSheet(
context: context,
backgroundColor: card,
builder: (_) => Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 28),
child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [
Text(title, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)),
const SizedBox(height: 10),
body,
]),
),
);
// ---- chart
Widget _chart(BodyView v) {
final sr = v.series();
final from = widget.range.from(v.rows.first.day, v.now);
final hw = healthyWeight(v.p.height);
const fatColors = [Color(0xFFFFB33A), Color(0xFF5CC8FF), Color(0xFFC792EA), Color(0xFF7FD6A3)];
final (List<Series> s, String unit, (double, double)? band) = switch (chart) {
'waist' => ([Series('Waist', sr['waist']!, accent)], 'cm', null),
'bmi' => ([Series('BMI', sr['bmi']!, accent)], '', (18.5, 25.0)),
'fat' => ([for (var i = 0; i < fatFormulas.length; i++) Series(fatFormulas[i].$2, sr[fatFormulas[i].$1]!, fatColors[i])], '%', null),
_ => ([Series('Weight', sr['weight']!, accent)], 'kg', hw),
};
return Card(
child: Padding(
padding: const EdgeInsets.fromLTRB(12, 10, 12, 6),
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(children: [
for (final (k, l) in [('weight', 'Weight'), ('waist', 'Waist'), ('bmi', 'BMI'), ('fat', 'Body fat')])
Padding(padding: const EdgeInsets.only(right: 6),
child: ChoiceChip(label: Text(l), selected: chart == k, onSelected: (_) => setState(() => chart = k))),
]),
),
const SizedBox(height: 8),
LineChart(series: s, from: from, to: plus(v.now, 1), unit: unit, band: band, range: widget.range),
if (chart == 'fat')
Wrap(spacing: 10, children: [
for (var i = 0; i < fatFormulas.length; i++)
Text('● ${fatFormulas[i].$2}', style: TextStyle(color: fatColors[i], fontSize: 12)),
]),
]),
),
);
}
// ---- body fat by formula
Widget _fat(BodyView v) => _Card('Body fat', [
for (final f in v.fat)
Tooltip(
triggerMode: TooltipTriggerMode.tap,
message: f.note,
child: _Row(f.name, f.value != null ? '${n1(f.value)} %' : 'needs ${f.missing.map(_need).join(', ')}',
f.value == null ? muted : classColor(fatClass(f.value, v.p.sex, v.age))),
),
const Divider(color: card2),
_Row('Middle of ${v.fat.where((f) => f.value != null).length}', v.fatMid == null ? '—' :
'${n1(v.fatMid)} %${v.fatRange == null ? '' : ' (${n1(v.fatRange!.$1)}–${n1(v.fatRange!.$2)})'}',
classColor(fatClass(v.fatMid, v.p.sex, v.age))),
if (v.weight != null && v.fatMid != null)
_Row('Fat · lean', '${(v.weight! * v.fatMid! / 100).toStringAsFixed(1)} kg · ${(v.weight! * (1 - v.fatMid! / 100)).toStringAsFixed(1)} kg', null),
]);
static String _need(String k) => k == 'height' ? 'height' : k == 'fat_scale' ? 'a scale reading' : fields[k]!.$1.toLowerCase();
// ---- ratios + energy
Widget _ratios(BodyView v) {
final r1 = whtr(v.waist, v.p.height), r2 = whr(v.waist, v.hip);
final m = bmrMifflin(v.weight, v.p.height, v.p.sex, v.age), k = bmrKatch(v.weight, v.fatMid);
return _Card('Ratios & energy', [
_Row('Waist ÷ height', r1 == null ? '—' : '${r1.toStringAsFixed(2)} · ${whtrClass(r1)}', classColor(whtrClass(r1))),
_Row('Waist ÷ hips', r2 == null ? '—' : '${r2.toStringAsFixed(2)} · ${whrClass(r2, v.p.sex)}', classColor(whrClass(r2, v.p.sex))),
_Row('Resting energy', m == null ? '—' : '${m.round()} kcal/day${k == null ? '' : ' · ${k.round()} from lean mass'}', null),
]);
}
// ---- the measurements
Widget _list(BodyView v) {
final from = widget.range.from(v.rows.first.day, v.now); // the charts' period
final rows = v.rows.reversed.where((r) => !r.day.isBefore(from)).toList();
return _Card('Measurements', [
if (rows.isEmpty) const Padding(padding: EdgeInsets.symmetric(vertical: 6),
child: Text('Nothing measured in this period', style: TextStyle(color: muted))),
for (final r in rows.take(shown))
InkWell(
onTap: () => _edit(v, r),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 7),
child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
SizedBox(width: 92, child: Text(r.day.year == v.now.year ? dm(r.day) : dmy(r.day), style: const TextStyle(color: muted))),
Expanded(child: Text([
for (final k in fields.keys) if (r[k] != null) '${_short[k]} ${trim1(r[k])}',
if (r.note.isNotEmpty) '“${r.note}”',
].join(' · '))),
]),
),
),
if (rows.length > shown)
TextButton(onPressed: () => setState(() => shown += 5), child: Text('Show more (${rows.length - shown})')),
]);
}
Future<void> _edit(BodyView v, Measure? m) => showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: card,
builder: (_) => MeasureSheet(v: v, m: m, onSave: (d, vals, note, was) {
final err = saveMeasure(widget.sync.store, d, vals, note, was: was);
if (err == null) widget.sync.changed();
return err;
}, onDelete: m == null ? null : () {
saveMeasure(widget.sync.store, m.day, {}, '');
widget.sync.changed();
}),
);
}
class _Tile extends StatelessWidget {
const _Tile(this.label, this.value, this.sub, this.cls, this.onTap);
final String label, value, sub;
final String? cls;
final VoidCallback onTap;
@override
Widget build(BuildContext context) => Card(
child: InkWell(
borderRadius: BorderRadius.circular(12),
onTap: onTap,
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [
Text(label.toUpperCase(), style: const TextStyle(color: muted, fontSize: 11.5)),
Text(value, style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold)),
Text(sub, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: cls == null ? muted : classColor(cls), fontSize: 12.5)),
]),
),
),
);
}
class _Card extends StatelessWidget {
const _Card(this.title, this.children);
final String title;
final List<Widget> children;
@override
Widget build(BuildContext context) => Card(
child: Padding(
padding: const EdgeInsets.fromLTRB(14, 12, 14, 10),
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
Text(title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
const SizedBox(height: 6),
...children,
]),
),
);
}
class _Row extends StatelessWidget {
const _Row(this.k, this.v, this.color);
final String k, v;
final Color? color;
@override
Widget build(BuildContext context) => Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Row(children: [
Expanded(child: Text(k, style: const TextStyle(color: muted))),
Flexible(child: Text(v, textAlign: TextAlign.right, style: TextStyle(color: color))),
]),
);
}
/// Add / edit a day's measurements: date, every field (placeholders = your last values), note.
class MeasureSheet extends StatefulWidget {
const MeasureSheet({super.key, required this.v, required this.m, required this.onSave, this.onDelete});
final BodyView v;
final Measure? m;
final String? Function(DateTime d, Map<String, double?> vals, String note, DateTime? was) onSave;
final VoidCallback? onDelete;
@override
State<MeasureSheet> createState() => _MeasureSheetState();
}
class _MeasureSheetState extends State<MeasureSheet> {
late DateTime d = widget.m?.day ?? today();
late final ctl = {
for (final k in fields.keys) k: TextEditingController(text: widget.m?[k] == null ? '' : trim1(widget.m![k]))
};
late final note = TextEditingController(text: widget.m?.note ?? '');
String? error;
bool armed = false;
void _loadDay(DateTime nd) {
// picking a day that already has measurements (when adding) loads them, like the web dialog
final other = widget.v.rows.where((r) => r.day == nd).firstOrNull;
setState(() {
d = nd;
if (widget.m == null && other != null) {
for (final k in fields.keys) {
ctl[k]!.text = other[k] == null ? '' : trim1(other[k]);
}
note.text = other.note;
}
});
}
@override
Widget build(BuildContext context) => Padding(
padding: EdgeInsets.fromLTRB(16, 16, 16, 16 + MediaQuery.of(context).viewInsets.bottom),
child: SingleChildScrollView(
child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
Row(children: [
Expanded(child: Text(widget.m == null ? 'Add measurements' : 'Edit measurements',
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent))),
TextButton.icon(
icon: const Icon(Icons.event, size: 18),
label: Text(dmy(d)),
onPressed: () async {
final p = await showDatePicker(context: context, initialDate: d, firstDate: DateTime.utc(2000), lastDate: today());
if (p != null) _loadDay(DateTime.utc(p.year, p.month, p.day));
},
),
]),
const SizedBox(height: 4),
GridView.count(
crossAxisCount: 2, shrinkWrap: true, physics: const NeverScrollableScrollPhysics(),
crossAxisSpacing: 12, childAspectRatio: 3.2,
children: [
for (final e in fields.entries)
TextField(
controller: ctl[e.key],
keyboardType: const TextInputType.numberWithOptions(decimal: true),
textInputAction: TextInputAction.next,
decoration: InputDecoration(
labelText: e.key == 'fat_scale' ? 'Scale body fat' : e.value.$1, suffixText: e.value.$2,
hintText: widget.v.cur[e.key] == null ? null : n1(widget.v.cur[e.key]!.v),
),
),
]),
TextField(controller: note, maxLength: 2000, decoration: const InputDecoration(labelText: 'Note')),
if (error != null) Padding(padding: const EdgeInsets.only(bottom: 8), child: Text(error!, style: const TextStyle(color: bad))),
Row(children: [
if (widget.onDelete != null)
TextButton(
onPressed: () {
if (!armed) return setState(() => armed = true);
widget.onDelete!();
Navigator.pop(context);
},
child: Text(armed ? 'Tap again to delete' : 'Delete', style: const TextStyle(color: bad)),
),
const Spacer(),
FilledButton(
onPressed: () {
final vals = <String, double?>{};
for (final k in fields.keys) {
final t = ctl[k]!.text.trim().replaceAll(',', '.');
if (t.isEmpty) {
vals[k] = null;
} else if (double.tryParse(t) == null) {
return setState(() => error = '${fields[k]!.$1}: not a number.');
} else {
vals[k] = double.parse(t);
}
}
final err = widget.onSave(d, vals, note.text, widget.m?.day);
if (err != null) return setState(() => error = err);
Navigator.pop(context);
},
child: const Text('Save'),
),
]),
]),
),
);
}

View file

@ -0,0 +1,74 @@
// Cycle ▸ For your doctor: the last 12 months as on the web page's History (cycle.views.history's
// doctor part): last period, cycle / period length (average + range), periods logged, pain,
// most common symptoms + moods, and what's worth mentioning by the common guidelines.
import 'package:flutter/material.dart';
import '../app/sync_service.dart';
import '../app/theme.dart';
import 'cycle_model.dart';
const _mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
String dmy(DateTime d) => '${d.day} ${_mon[d.month - 1]} ${d.year}';
String _range((int, int)? r) => r == null ? '—' : r.$1 == r.$2 ? '${r.$1} days' : '${r.$1}–${r.$2} days';
class DoctorPage extends StatelessWidget {
const DoctorPage({super.key, required this.sync, required this.settings});
final SyncService sync;
final CycleSettings settings;
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('For your doctor')),
body: ListenableBuilder(
listenable: sync,
builder: (context, _) {
final v = CycleView(sync.store, settings);
if (v.periods.isEmpty) {
return const Center(child: Text('Nothing logged yet.', style: TextStyle(color: muted)));
}
final d = doctor(v);
final rows = <(String, String)>[
('First day of last period', d.last == null ? '—' : dmy(d.last!)),
('Cycle length', d.cycle == null ? 'not enough data yet' : '${d.cycle} days on average · ${_range(d.cycleRange)}'),
('Period length', d.period == null ? 'not enough data yet' : '${d.period} days on average · ${_range(d.periodRange)}'),
('Periods logged', '${d.periods}'),
('Pain', d.painDays == 0 ? 'none logged' : 'on ${d.painDays} day${d.painDays != 1 ? 's' : ''}, ${d.painAvg} / 5 on average'),
('Most common', d.symptoms.isEmpty ? 'no symptoms logged' : d.symptoms.map((s) => '${s.$1} (${s.$2}×)').join(', ')),
];
return ListView(padding: const EdgeInsets.all(12), children: [
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Row(children: [
Expanded(child: Text('${dmy(d.since)} – ${dmy(d.now)}', style: const TextStyle(color: muted))),
const Tooltip(
triggerMode: TooltipTriggerMode.tap,
message: 'From self-logged data; general guidance, not a diagnosis.',
child: Icon(Icons.info_outline, size: 18, color: muted),
),
]),
const SizedBox(height: 12),
for (final (k, val) in rows) ...[
Text(k, style: const TextStyle(color: muted, fontSize: 13)),
Padding(padding: const EdgeInsets.only(top: 2, bottom: 12), child: Text(val, style: const TextStyle(fontSize: 16))),
],
const Divider(color: card2),
const SizedBox(height: 6),
if (d.flags.isEmpty)
const Text('Nothing unusual by the common guidelines (cycles 21–35 days, periods up to 7 days, '
'no spotting between periods, …).', style: TextStyle(color: good))
else ...[
const Text('Worth mentioning', style: TextStyle(fontWeight: FontWeight.bold, color: accent)),
const SizedBox(height: 6),
for (final f in d.flags)
Padding(padding: const EdgeInsets.only(bottom: 4), child: Text('• $f')),
],
]),
),
),
]);
},
),
);
}

View file

@ -0,0 +1,334 @@
// The cycle tracker's numbers — a port of the dashboard's plugins/cycle/views.py (keep them in
// step: same rules, same results as the web page) + db.save_day's rules for writing a day.
//
// Data: synced rows "cycle.day", id "day:YYYY-MM-DD": {day, period 0/1, flow 1–5, pain 1–5,
// pain_len, tags "a,b", note, source, updated}. Days are UTC dates here (no DST surprises).
import 'dart:math';
import '../sync/store.dart';
const history = 12; // cycles averaged (at most)
const halfLife = 180; // days: a cycle this much older counts half as much
const maxCycle = 60; // longer "cycles" are gaps in logging
const luteal = 14; // ovulation -> next period, days
const gap = 2; // unmarked days that don't split a period
const painLen = {'0-1': 'under 1 h', '1-3': '1–3 h', '3-6': '3–6 h', '6-24': '6–24 h'};
const tagGroups = {
'Symptoms': {
'spotting': 'Spotting', 'headache': 'Headache', 'backache': 'Backache', 'tiredness': 'Tiredness',
'bloating': 'Bloating', 'breasts': 'Tender breasts', 'acne': 'Acne', 'nausea': 'Nausea',
'cravings': 'Cravings', 'stomach': 'Upset stomach', 'sleep': 'Poor sleep', 'dizzy': 'Dizziness'},
'Mood': {
'happy': 'Happy', 'calm': 'Calm', 'energetic': 'Energetic', 'sensitive': 'Sensitive',
'irritable': 'Irritable', 'anxious': 'Anxious', 'sad': 'Sad', 'swings': 'Mood swings',
'stressed': 'Stressed', 'unmotivated': 'Unmotivated'},
'Sex': {
'sex_prot': 'Sex, protected', 'sex_unprot': 'Sex, unprotected', 'drive': 'Sex drive',
'drive_low': 'Low sex drive', 'solo': 'Masturbation', 'sex_pain': 'Pain during sex'},
};
const flowNames = ['very light', 'light', 'medium', 'heavy', 'very heavy'];
const sources = {
'xiaomi': ('⌚', 'Imported from Xiaomi (Mi Fitness)'),
'mymonthlycycles': ('📱', 'Imported from My Monthly Cycles'),
'calculated': ('≈', 'Calculated: not logged, placed between the periods around it'),
};
/// Calendar symbols for some tags: (tags, glyph, label); "spot" = a small droplet.
const symbols = [
({'sex_prot', 'sex_unprot'}, '♥', 'had sex'),
({'happy', 'calm', 'energetic'}, '☺', 'good mood'),
({'sensitive', 'irritable', 'anxious', 'sad', 'swings', 'stressed', 'unmotivated'}, '☹', 'low mood'),
({'spotting'}, 'spot', 'spotting'),
({'tiredness'}, '💤', 'tired'),
({'headache'}, '⚡', 'headache'),
];
DateTime day(DateTime d) => DateTime.utc(d.year, d.month, d.day);
/// Python's round(): halves go to the even number (round(28.5) == 28), so averages match the web page.
int pyRound(double x) {
final f = x.floorToDouble(), diff = x - f;
if (diff > 0.5) return f.toInt() + 1;
if (diff < 0.5) return f.toInt();
return f.toInt().isEven ? f.toInt() : f.toInt() + 1;
}
DateTime today() => day(DateTime.now());
DateTime parseDay(String s) => DateTime.parse('${s}T00:00:00Z');
String iso(DateTime d) => d.toIso8601String().substring(0, 10);
int daysBetween(DateTime a, DateTime b) => b.difference(a).inDays; // b - a
DateTime plus(DateTime d, int n) => d.add(Duration(days: n));
class CycleSettings {
const CycleSettings({this.cycleLength = 28, this.periodLength = 5, this.showFertile = true});
final int cycleLength, periodLength;
final bool showFertile;
}
class DayLog {
DayLog(this.row);
final Map<String, dynamic> row;
bool get period => (row['period'] ?? 0) == 1;
int? get flow => row['flow'] as int?;
int? get pain => row['pain'] as int?;
String? get painLength => row['pain_len'] as String?;
List<String> get tags => ((row['tags'] as String?) ?? '').split(',').where((t) => t.isNotEmpty).toList();
String get note => (row['note'] as String?) ?? '';
String? get source => row['source'] as String?;
bool get hasLog => pain != null || tags.isNotEmpty || note.isNotEmpty;
String summary() {
final names = {for (final g in tagGroups.values) ...g};
return [
if (pain != null) 'pain $pain/5${painLen[painLength] != null ? ' (${painLen[painLength]})' : ''}',
...tags.where(names.containsKey).map((t) => names[t]!),
if (note.isNotEmpty) note,
if (sources[source] != null) sources[source]!.$2,
].join(' · ');
}
List<(String, String)> get symbolList =>
[for (final (ts, g, label) in symbols) if (ts.intersection(tags.toSet()).isNotEmpty) (g, label)];
}
class Period {
Period(this.start, this.end, this.calc);
DateTime start, end;
bool calc;
int get length => daysBetween(start, end) + 1;
}
class CycleStats {
CycleStats(this.cycle, this.period, this.cycles, this.fromData);
final int cycle, period;
final List<int> cycles;
final bool fromData;
}
int _avg(List<(int, DateTime)> xs, int fallback, DateTime now) {
final last = xs.length > history ? xs.sublist(xs.length - history) : xs;
if (last.isEmpty) return fallback;
final w = [for (final (_, d) in last) pow(0.5, max(0, daysBetween(d, now)) / halfLife).toDouble()];
var s = 0.0;
for (var i = 0; i < last.length; i++) {
s += last[i].$1 * w[i];
}
return pyRound(s / w.reduce((a, b) => a + b));
}
/// Sorted period days -> runs; up to [gap] unmarked days inside one don't split it.
List<Period> periodsOf(List<DateTime> days, Set<DateTime> calc) {
final out = <Period>[];
for (final d in days) {
if (out.isNotEmpty && daysBetween(out.last.end, d) <= gap + 1) {
out.last.end = d;
out.last.calc = out.last.calc && calc.contains(d);
} else {
out.add(Period(d, d, calc.contains(d)));
}
}
return out;
}
bool going(Period p, DateTime now) => !p.end.isBefore(plus(now, -1));
/// (length, start of the next period) between consecutive logged periods.
List<(int, DateTime)> realCycles(List<Period> ps) => [
for (var i = 0; i + 1 < ps.length; i++)
if (!ps[i].calc && !ps[i + 1].calc) (daysBetween(ps[i].start, ps[i + 1].start), ps[i + 1].start)
];
CycleStats stats(List<Period> ps, CycleSettings s, DateTime now) {
final cyc = realCycles(ps);
final ok = [for (final c in cyc) if (c.$1 >= 15 && c.$1 <= maxCycle) c];
final lens = [for (final p in ps) if (!going(p, now) && !p.calc) (p.length, p.start)];
return CycleStats(_avg(ok, s.cycleLength, now), _avg(lens, s.periodLength, now), [for (final c in cyc) c.$1],
ok.isNotEmpty);
}
/// The next n predicted periods (start, end) + days late (0 = not late).
(List<(DateTime, DateTime)>, int) predict(List<Period> ps, CycleStats st, DateTime now, {int n = 4}) {
if (ps.isEmpty) return (const [], 0);
var next = plus(ps.last.start, st.cycle);
final late = next.isBefore(now) ? daysBetween(next, now) : 0;
if (late > 0) next = plus(now, st.cycle); // overdue: "any day now"; the one after counts from today
return ([for (var k = 0; k < n; k++) (plus(next, k * st.cycle), plus(next, k * st.cycle + st.period - 1))], late);
}
/// {day: "ovul" | "fertile"} before each given period start.
Map<DateTime, String> fertile(List<DateTime> starts) {
final out = <DateTime, String>{};
for (final a in starts) {
final ov = plus(a, -luteal);
for (var k = -5; k <= 1; k++) {
out[plus(ov, k)] = 'fertile';
}
out[ov] = 'ovul';
}
return out;
}
enum Status { empty, period, late, wait }
/// Everything the Cycle page shows, from the synced rows.
class CycleView {
CycleView(SyncStore store, this.s, {DateTime? now}) : now = now ?? today() {
for (final r in store.rows('cycle.day')) {
final d = parseDay(r['day'] as String);
logs[d] = DayLog(r);
}
final days = [for (final e in logs.entries) if (e.value.period) e.key]..sort();
marked = days.toSet();
final calc = {for (final e in logs.entries) if (e.value.source == 'calculated') e.key};
periods = periodsOf(days, calc);
st = stats(periods, s, this.now);
final (p, l) = predict(periods, st, this.now);
preds = p;
late = l;
final last = periods.isEmpty ? null : periods.last;
if (last != null) {
cycleDay = daysBetween(last.start, this.now) + 1;
status = going(last, this.now) ? Status.period : late > 0 ? Status.late : Status.wait;
}
predDays = {for (final (a, z) in preds) for (var k = 0; k <= daysBetween(a, z); k++) plus(a, k)};
if (status == Status.period) {
for (var k = 0; k < st.period; k++) {
if (plus(last!.start, k).isAfter(last.end)) predDays.add(plus(last.start, k));
}
}
final starts = [for (final (a, _) in preds) a];
if (last != null) starts.add(plus(last.start, st.cycle));
fert = s.showFertile ? fertile(starts) : {};
}
final CycleSettings s;
final DateTime now;
final logs = <DateTime, DayLog>{};
late final Set<DateTime> marked;
late final List<Period> periods;
late final CycleStats st;
late final List<(DateTime, DateTime)> preds;
late final int late;
late final Set<DateTime> predDays;
late final Map<DateTime, String> fert;
Status status = Status.empty;
int? cycleDay;
Period? get last => periods.isEmpty ? null : periods.last;
bool get todayOn => marked.contains(now);
DateTime? get expected => last == null ? null : plus(last!.start, st.cycle);
int? get daysToNext => preds.isEmpty ? null : daysBetween(now, preds.first.$1);
/// The fertile window that matters now (this cycle's if not over, else the next one's).
(DateTime, DateTime, DateTime)? fertileWindow() {
if (last == null || !s.showFertile) return null;
for (final a in [plus(last!.start, st.cycle), ...preds.map((p) => p.$1)]) {
final ov = plus(a, -luteal);
if (!plus(ov, 1).isBefore(now)) return (plus(ov, -5), plus(ov, 1), ov);
}
return null;
}
}
// ---- for a doctor (views.history's doctor part + views.flags) --------------------------------
const doctorMonths = 12;
class Doctor {
Doctor({required this.since, required this.now, required this.last, required this.periods, required this.cycle,
required this.cycleRange, required this.period, required this.periodRange, required this.symptoms,
required this.painDays, required this.painAvg, required this.flags});
final DateTime since, now;
final DateTime? last;
final int periods, painDays;
final int? cycle, period;
final (int, int)? cycleRange, periodRange;
final List<(String, int)> symptoms;
final double? painAvg;
final List<String> flags;
}
(int, int)? _spread(List<int> xs) => xs.isEmpty ? null : (xs.reduce(min), xs.reduce(max));
/// Things worth mentioning to a doctor (common guidance, not a diagnosis).
List<String> flags(List<Period> ps, List<int> cycles, Map<DateTime, DayLog> logs, DateTime now) {
final out = <String>[];
final within = cycles.where((c) => c <= maxCycle).toList(); // longer = a gap in logging
final recent = within.length > 6 ? within.sublist(within.length - 6) : within;
final short = recent.where((c) => c < 21).length, long = recent.where((c) => c > 35).length;
if (short >= 2) out.add('$short of the last ${recent.length} cycles were shorter than 21 days.');
if (long >= 2) out.add('$long of the last ${recent.length} cycles were longer than 35 days.');
if (recent.length >= 3 && recent.reduce(max) - recent.reduce(min) > 7) {
out.add('Cycle length varies a lot: ${recent.reduce(min)}–${recent.reduce(max)} days.');
}
final finished = ps.where((p) => !going(p, now)).toList();
final done = finished.length > 6 ? finished.sublist(finished.length - 6) : finished;
final longp = done.where((p) => p.length > 7).length;
if (longp > 0) out.add('$longp of the last ${done.length} periods lasted more than 7 days.');
bool inside(Period p, DateTime d) => !d.isBefore(p.start) && !d.isAfter(p.end);
final heavy = done.where((p) => logs.entries.where((e) => inside(p, e.key) && (e.value.flow ?? 0) >= 4).length >= 3).length;
if (heavy > 0) out.add('$heavy of the last ${done.length} periods had 3 or more heavy days.');
final since = plus(now, -90);
final spot = logs.entries.where((e) => !e.key.isBefore(since) && e.value.tags.contains('spotting') && !e.value.period).length;
if (spot > 0) out.add('Spotting between periods on $spot day${spot != 1 ? 's' : ''} in the last 3 months.');
final strong = logs.entries.where((e) => !e.key.isBefore(since) && (e.value.pain ?? 0) >= 4).length;
if (strong >= 3) out.add('Strong pain (4–5 of 5) on $strong days in the last 3 months.');
if (ps.isNotEmpty && daysBetween(ps.last.start, now) > 90) out.add('No period for ${daysBetween(ps.last.start, now)} days.');
return out;
}
Doctor doctor(CycleView v) {
final now = v.now, since = plus(now, -doctorMonths * 30);
final real = v.periods.where((p) => !p.calc).toList();
final dp = real.where((p) => !p.start.isBefore(since)).toList();
final dcycles = [
for (final (c, d) in realCycles(v.periods))
if (!d.isBefore(since) && c <= maxCycle && !plus(d, -c).isBefore(since)) c
];
final dlens = [for (final p in dp) if (!going(p, now)) p.length];
final names = {for (final g in tagGroups.values) ...g};
final counts = <String, int>{};
final pains = <int>[];
for (final e in v.logs.entries.where((e) => !e.key.isBefore(since))) {
for (final t in e.value.tags) {
if (tagGroups['Symptoms']!.containsKey(t) || tagGroups['Mood']!.containsKey(t)) counts[t] = (counts[t] ?? 0) + 1;
}
if (e.value.pain != null) pains.add(e.value.pain!);
}
final sym = [for (final e in counts.entries) (names[e.key]!, e.value)]..sort((a, b) => b.$2.compareTo(a.$2));
return Doctor(
since: dp.isNotEmpty && dp.first.start.isAfter(since) ? dp.first.start : since,
now: now,
last: real.isEmpty ? null : real.last.start,
periods: dp.length,
cycle: dcycles.isEmpty ? null : pyRound(dcycles.reduce((a, b) => a + b) / dcycles.length),
cycleRange: _spread(dcycles),
period: dlens.isEmpty ? null : pyRound(dlens.reduce((a, b) => a + b) / dlens.length),
periodRange: _spread(dlens),
symptoms: sym.take(10).toList(),
painDays: pains.length,
painAvg: pains.isEmpty ? null : pyRound(pains.reduce((a, b) => a + b) / pains.length * 10) / 10,
flags: flags(real, v.st.cycles, v.logs, now),
);
}
/// db.save_day: set the given fields of a day (the rest stay); a day with nothing left is deleted.
void saveDay(SyncStore store, DateTime d, Map<String, dynamic> fields) {
if (d.isAfter(today())) throw ArgumentError("That day hasn't happened yet.");
final u = 'day:${iso(d)}';
final row = store.row('cycle.day', u) ??
{'day': iso(d), 'period': 0, 'note': '', 'flow': null, 'pain': null, 'pain_len': null, 'tags': '', 'source': null};
row.addAll(fields);
if (fields.containsKey('tags')) {
final picked = (fields['tags'] as List).cast<String>().toSet();
row['tags'] = [for (final g in tagGroups.values) ...g.keys.where(picked.contains)].join(','); // stable order
}
final now = DateTime.now();
row['updated'] = '${iso(now)} ${now.toIso8601String().substring(11, 19)}';
final empty = row['period'] != 1 && (row['note'] ?? '') == '' && row['flow'] == null && row['pain'] == null &&
row['pain_len'] == null && (row['tags'] ?? '') == '';
if (empty) {
if (store.row('cycle.day', u) != null) store.delete('cycle.day', u);
} else {
store.put('cycle.day', u, row);
}
}

View file

@ -0,0 +1,351 @@
// The Cycle page (Health ▸ Cycle): the status ring + one button for today (as on the web page),
// the month calendar, and a day's log as a sheet. Phone difference: tapping a day opens its log; holding
// it marks / unmarks it as a period day (the web's click — not on a tap, so no marks by a stray tap; Undo).
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../app/sync_service.dart';
import '../app/theme.dart';
import 'cycle_model.dart';
const periodRed = Color(0xFFE5576B), fertileTeal = Color(0xFF3FB5A0);
const _months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October',
'November', 'December'];
const _dows = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
String niceDay(DateTime d) => '${_dows[d.weekday - 1]} ${d.day} ${_months[d.month - 1].substring(0, 3)}';
class CyclePage extends StatefulWidget {
const CyclePage({super.key, required this.sync});
final SyncService sync;
@override
State<CyclePage> createState() => _CyclePageState();
}
class _CyclePageState extends State<CyclePage> {
int offset = 0; // months from this one
final settings = const CycleSettings(); // TODO: from synced settings once those sync (Pi: 28 / 5 / fertile on)
void _save(DateTime d, Map<String, dynamic> fields) {
saveDay(widget.sync.store, d, fields);
widget.sync.changed();
}
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: widget.sync,
builder: (context, _) {
final v = CycleView(widget.sync.store, settings);
final status = _StatusCard(v: v, onToday: (on) => _save(v.now, {'period': on ? 1 : 0}));
final month = _Month(v: v, offset: offset, onMove: (d) => setState(() => offset += d), onDay: (d) => _openDay(v, d),
onHold: (d) => _toggle(v, d));
return LayoutBuilder(builder: (context, box) {
if (box.maxWidth >= 700) { // landscape / tablet: side by side
return SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(12, 12, 12, 24),
child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
Expanded(flex: 2, child: status),
const SizedBox(width: 12),
Expanded(flex: 3, child: month),
]),
);
}
return ListView(padding: const EdgeInsets.fromLTRB(12, 12, 12, 24), children: [
status,
const SizedBox(height: 12),
month,
]);
});
},
);
/// Hold a day: period on that day on / off at once (the web calendar's click); Undo in the snackbar.
void _toggle(CycleView v, DateTime d) {
if (d.isAfter(v.now)) return;
final was = v.marked.contains(d);
HapticFeedback.mediumImpact();
_save(d, {'period': was ? 0 : 1});
final m = ScaffoldMessenger.of(context);
m.hideCurrentSnackBar();
m.showSnackBar(SnackBar(
content: Text('${was ? 'Not a period day' : 'Period'}: ${niceDay(d)}'),
duration: const Duration(seconds: 4),
persist: false, // with an action Flutter keeps it up until tapped
action: SnackBarAction(label: 'Undo', textColor: accent, onPressed: () => _save(d, {'period': was ? 1 : 0})),
));
}
Future<void> _openDay(CycleView v, DateTime d) async {
if (d.isAfter(v.now)) return;
await showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: card,
builder: (_) => DaySheet(day: d, log: v.logs[d], onSave: (f) => _save(d, f)),
);
}
}
/// The status card's two lines (also Health ▸ Overview's period tile).
(String, String) cycleStatus(CycleView v) => switch (v.status) {
Status.empty => ('No periods logged yet', 'Mark the first day of your period.'),
Status.period => ('Period · day ${v.cycleDay}', 'since ${niceDay(v.last!.start)}'),
Status.late => ('${v.late} ${v.late == 1 ? 'day' : 'days'} late', 'expected ${niceDay(v.expected!)}'),
Status.wait => (
v.daysToNext == 0 ? 'Period expected today' : 'Next period in ${v.daysToNext} ${v.daysToNext == 1 ? 'day' : 'days'}',
'${niceDay(v.preds.first.$1)} · cycle day ${v.cycleDay}'),
};
class _StatusCard extends StatelessWidget {
const _StatusCard({required this.v, required this.onToday});
final CycleView v;
final void Function(bool on) onToday;
@override
Widget build(BuildContext context) {
final t = Theme.of(context).textTheme;
final (head, sub) = cycleStatus(v);
final button = v.todayOn ? 'Not today — undo' : v.status == Status.period ? 'Period today too' : 'Period started today';
final fw = v.fertileWindow();
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
Row(children: [
SizedBox(width: 96, height: 96, child: CustomPaint(painter: _Ring(v), child: Center(
child: Text(v.cycleDay == null || v.status == Status.late ? '' : '${v.cycleDay}',
style: t.headlineMedium?.copyWith(fontWeight: FontWeight.bold))))),
const SizedBox(width: 16),
Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text(head, style: t.titleLarge?.copyWith(fontWeight: FontWeight.bold)),
const SizedBox(height: 2),
Text(sub, style: const TextStyle(color: muted)),
if (fw != null) ...[
const SizedBox(height: 6),
Text(fw.$1.isAfter(v.now) ? 'Fertile ${niceDay(fw.$1)} – ${niceDay(fw.$2)}' : 'Fertile window now, until ${niceDay(fw.$2)}',
style: const TextStyle(color: fertileTeal)),
],
])),
]),
const SizedBox(height: 14),
FilledButton(
style: FilledButton.styleFrom(backgroundColor: v.todayOn ? card2 : periodRed, foregroundColor: Colors.white),
onPressed: () => onToday(!v.todayOn),
child: Text(button),
),
const SizedBox(height: 10),
Tooltip(
message: v.st.fromData ? 'Recent cycles count more (half as much every 180 days of age)' : 'From the settings until there are logged cycles',
child: Text('Usual cycle ${v.st.cycle} days · period ${v.st.period} days',
textAlign: TextAlign.center, style: const TextStyle(color: muted, fontSize: 13)),
),
]),
),
);
}
}
/// The cycle as a circle: the period arc, the fertile arc, today's dot (cycle.views.ring).
class _Ring extends CustomPainter {
_Ring(this.v);
final CycleView v;
@override
void paint(Canvas c, Size size) {
final r = size.width / 2 - 6, o = Offset(size.width / 2, size.height / 2);
final n = max(v.st.cycle, max(v.cycleDay ?? 0, 1));
Paint p(Color col, double w) => Paint()..color = col..style = PaintingStyle.stroke..strokeWidth = w..strokeCap = StrokeCap.round;
c.drawCircle(o, r, p(card2, 8));
if (v.last == null) return;
void arc(int d0, int d1, Color col) {
final a0 = (d0 - 1) / n * 2 * pi - pi / 2, sweep = (d1 - d0 + 1) / n * 2 * pi;
c.drawArc(Rect.fromCircle(center: o, radius: r), a0, sweep, false, p(col, 8));
}
arc(1, min(v.st.period, n), periodRed);
final ov = v.st.cycle - luteal;
if (v.s.showFertile && ov - 5 > v.st.period) arc(ov - 5, ov + 1, fertileTeal);
if (v.cycleDay != null && v.status != Status.late) {
final a = (v.cycleDay! - .5) / n * 2 * pi - pi / 2;
final at = o + Offset(cos(a), sin(a)) * r;
c.drawCircle(at, 8.5, Paint()..color = card); // the web's dot outline (stroke: var(--card))
c.drawCircle(at, 7, Paint()..color = Colors.white);
}
}
@override
bool shouldRepaint(covariant _Ring old) => true;
}
class _Month extends StatelessWidget {
const _Month({required this.v, required this.offset, required this.onMove, required this.onDay, required this.onHold});
final CycleView v;
final int offset;
final void Function(int) onMove;
final void Function(DateTime) onDay, onHold;
@override
Widget build(BuildContext context) {
final m0 = DateTime.utc(v.now.year, v.now.month + offset, 1);
final g0 = plus(m0, -(m0.weekday - 1));
final mEnd = DateTime.utc(m0.year, m0.month + 1, 0);
final g1 = plus(mEnd, 7 - mEnd.weekday);
final weeks = <List<DateTime>>[];
for (var d = g0; !d.isAfter(g1); d = plus(d, 7)) {
weeks.add([for (var k = 0; k < 7; k++) plus(d, k)]);
}
return Card(
child: Padding(
padding: const EdgeInsets.fromLTRB(8, 4, 8, 12),
child: Column(children: [
Row(children: [
IconButton(onPressed: () => onMove(-1), icon: const Icon(Icons.chevron_left)),
Expanded(child: Text('${_months[m0.month - 1]} ${m0.year}', textAlign: TextAlign.center,
style: const TextStyle(fontSize: 17, fontWeight: FontWeight.bold))),
IconButton(onPressed: offset < 12 ? () => onMove(1) : null, icon: const Icon(Icons.chevron_right)),
]),
Row(children: [for (final d in _dows) Expanded(child: Text(d, textAlign: TextAlign.center, style: const TextStyle(color: muted, fontSize: 12)))]),
const SizedBox(height: 4),
for (final w in weeks)
Row(children: [for (final d in w) Expanded(child: _Cell(v: v, d: d, out: d.month != m0.month, onTap: () => onDay(d), onHold: () => onHold(d)))]),
]),
),
);
}
}
class _Cell extends StatelessWidget {
const _Cell({required this.v, required this.d, required this.out, required this.onTap, required this.onHold});
final CycleView v;
final DateTime d;
final bool out;
final VoidCallback onTap, onHold; // tap = the day's log, hold = period on / off
@override
Widget build(BuildContext context) {
final on = v.marked.contains(d), pred = !on && v.predDays.contains(d), fert = on ? null : v.fert[d];
final log = v.logs[d];
final isToday = d == v.now, future = d.isAfter(v.now);
final syms = log?.symbolList ?? const [];
return GestureDetector(
onTap: future ? null : onTap,
onLongPress: future ? null : onHold,
child: Opacity(
opacity: out ? 0.35 : 1,
child: Container(
height: MediaQuery.of(context).orientation == Orientation.landscape ? 44 : 52,
margin: const EdgeInsets.all(1.5),
decoration: BoxDecoration(
color: fert != null ? fertileTeal.withValues(alpha: 0.14) : null,
borderRadius: BorderRadius.circular(8),
border: isToday ? Border.all(color: accent, width: 1.5) : null,
),
child: Stack(children: [
Center(
child: Container(
width: 32, height: 32,
alignment: Alignment.center,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: on ? periodRed.withValues(alpha: 0.35 + 0.13 * ((log?.flow ?? 3) - 1)) : null,
border: pred ? Border.all(color: periodRed, width: 1.5) : fert == 'ovul' ? Border.all(color: fertileTeal, width: 2) : null,
),
child: Text('${d.day}', style: TextStyle(color: future ? muted : Colors.white, fontWeight: isToday ? FontWeight.bold : null)),
),
),
if (syms.isNotEmpty)
Positioned(left: 3, top: 1, child: Text(syms.map((s) => s.$1 == 'spot' ? '•' : s.$1).join(), style: const TextStyle(fontSize: 9))),
if (log?.hasLog ?? false) const Positioned(right: 4, top: 3, child: Icon(Icons.edit, size: 9, color: accent)),
if (sources[log?.source] != null)
Positioned(left: 3, bottom: 1, child: Text(sources[log!.source]!.$1, style: const TextStyle(fontSize: 8, color: muted))),
]),
),
),
);
}
}
/// A day's log: period on / off + flow, pain + how long, tags, note — saved together.
class DaySheet extends StatefulWidget {
const DaySheet({super.key, required this.day, required this.log, required this.onSave});
final DateTime day;
final DayLog? log;
final void Function(Map<String, dynamic>) onSave;
@override
State<DaySheet> createState() => _DaySheetState();
}
class _DaySheetState extends State<DaySheet> {
late bool period = widget.log?.period ?? false;
late int? flow = widget.log?.flow, pain = widget.log?.pain;
late String? len = widget.log?.painLength;
late final Set<String> tags = {...?widget.log?.tags};
late final note = TextEditingController(text: widget.log?.note ?? '');
@override
Widget build(BuildContext context) => Padding(
padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
child: DraggableScrollableSheet(
expand: false,
initialChildSize: 0.75,
maxChildSize: 0.95,
builder: (context, scroll) => ListView(controller: scroll, padding: const EdgeInsets.fromLTRB(16, 8, 16, 24), children: [
Center(child: Container(width: 36, height: 4, decoration: BoxDecoration(color: muted, borderRadius: BorderRadius.circular(2)))),
const SizedBox(height: 12),
Text(niceDay(widget.day), style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: accent)),
SwitchListTile(contentPadding: EdgeInsets.zero, title: const Text('Period day'), value: period,
activeThumbColor: periodRed, onChanged: (x) => setState(() => period = x)),
if (period) ...[
const Text('Flow', style: TextStyle(color: muted)),
Row(children: [
for (var i = 1; i <= 5; i++)
IconButton(
tooltip: flowNames[i - 1],
onPressed: () => setState(() => flow = flow == i ? null : i),
icon: Icon(Icons.water_drop, size: 16.0 + i * 3, color: (flow ?? 0) >= i ? periodRed : card2),
),
]),
],
const SizedBox(height: 8),
const Text('Pain', style: TextStyle(color: muted)),
Wrap(spacing: 6, children: [
for (var i = 1; i <= 5; i++)
ChoiceChip(label: Text('$i'), selected: pain == i, onSelected: (x) => setState(() => pain = x ? i : null)),
]),
if (pain != null)
Wrap(spacing: 6, children: [
for (final e in painLen.entries)
ChoiceChip(label: Text(e.value), selected: len == e.key, onSelected: (x) => setState(() => len = x ? e.key : null)),
]),
for (final g in tagGroups.entries) ...[
const SizedBox(height: 10),
Text(g.key, style: const TextStyle(color: muted)),
Wrap(spacing: 6, runSpacing: 2, children: [
for (final t in g.value.entries)
FilterChip(
label: Text(t.value),
selected: tags.contains(t.key),
onSelected: (x) => setState(() {
x ? tags.add(t.key) : tags.remove(t.key);
if (x && t.key == 'drive') tags.remove('drive_low'); // exclusive, like the web page
if (x && t.key == 'drive_low') tags.remove('drive');
}),
),
]),
],
const SizedBox(height: 10),
TextField(controller: note, maxLines: 3, maxLength: 2000, decoration: const InputDecoration(labelText: 'Note')),
const SizedBox(height: 8),
FilledButton(
onPressed: () {
widget.onSave({'period': period ? 1 : 0, 'flow': flow, 'pain': pain, 'pain_len': pain == null ? null : len,
'tags': tags.toList(), 'note': note.text.trim()});
Navigator.pop(context);
},
child: const Text('Save'),
),
]),
),
);
}

View file

@ -0,0 +1,226 @@
// Every Open Food Facts product (2 million+, every country), searched on the sync server's archive
// (GET /v1/food/search — sync-server/src/food.php), with filters: country, brand, Nutri-Score; a
// barcode finds that product. A pick is kept ("food.product", food_model.dart keepProduct) and synced,
// so entries made from it work on every device. Also the camera barcode scanner (ZXing, no Google services).
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_zxing/flutter_zxing.dart' show Format;
import '../app/scanner.dart';
import '../app/sync_service.dart';
import '../app/theme.dart';
import 'food_model.dart';
const _countries = [('', 'Any country'), ('ro', 'Romania'), ('sk', 'Slovakia'), ('cz', 'Czechia'), ('hu', 'Hungary'), ('at', 'Austria'),
('de', 'Germany'), ('pl', 'Poland'), ('it', 'Italy'), ('fr', 'France'), ('es', 'Spain'), ('uk', 'UK'), ('us', 'USA')];
const _scores = [('', 'Any Nutri-Score'), ('a', 'A'), ('ab', 'A–B'), ('abc', 'A–C')];
/// The archive's search: [q] (or a barcode), filters → its products (as it sends them), or throws a message.
Future<List<Map<String, dynamic>>> archiveSearch(SyncService sync, Map<String, String> p) async {
final s = sync.settings;
final query = {for (final e in p.entries) if (e.value.isNotEmpty) e.key: e.value, 'limit': '25'};
final uri = Uri.parse('${s.server.replaceAll(RegExp(r'/+$'), '')}/v1/food/search').replace(queryParameters: query);
final http.Response r;
try {
r = await http.get(uri, headers: {'Authorization': 'Bearer ${s.token}', 'Accept': 'application/json'})
.timeout(const Duration(seconds: 20));
} catch (_) {
throw 'The sync server can\'t be reached — no connection?';
}
final j = jsonDecode(r.body);
if (r.statusCode != 200) throw (j is Map ? j['error'] : null) ?? 'Error ${r.statusCode}';
return ((j as Map)['items'] as List).cast<Map<String, dynamic>>();
}
/// The archive's search sheet → the product picked (kept already), or null.
Future<Food?> openArchive(BuildContext context, SyncService sync, FoodDb? fdb, String q) => showModalBottomSheet<Food>(
context: context,
isScrollControlled: true,
backgroundColor: card,
builder: (_) => ArchiveSheet(sync: sync, fdb: fdb, q: q),
);
class ArchiveSheet extends StatefulWidget {
const ArchiveSheet({super.key, required this.sync, required this.fdb, required this.q});
final SyncService sync;
final FoodDb? fdb;
final String q;
@override
State<ArchiveSheet> createState() => _ArchiveSheetState();
}
class _ArchiveSheetState extends State<ArchiveSheet> {
late final q = TextEditingController(text: widget.q);
final brand = TextEditingController();
String country = '', score = '';
List<Map<String, dynamic>> items = [];
String? status;
Timer? timer;
int seq = 0;
@override
void initState() {
super.initState();
_run();
}
@override
void dispose() {
timer?.cancel();
super.dispose();
}
void _soon() {
timer?.cancel();
timer = Timer(const Duration(milliseconds: 350), _run);
}
Future<void> _run() async {
final text = q.text.trim(), n = ++seq;
final code = RegExp(r'^\d{8,14}$').hasMatch(text);
if (!code && text.length < 3 && brand.text.trim().isEmpty && country.isEmpty) {
setState(() {
items = [];
status = 'Type at least 3 letters, or pick a filter.';
});
return;
}
setState(() => status = 'Searching…');
try {
final got = await archiveSearch(widget.sync, {
if (code) 'barcode': text else 'q': text,
'country': country, 'brand': brand.text.trim(), 'nutriscore': score,
});
if (!mounted || n != seq) return;
setState(() {
items = got;
status = got.isEmpty ? 'Nothing found.' : null;
});
} catch (e) {
if (mounted && n == seq) {
setState(() {
items = [];
status = '$e';
});
}
}
}
String _home(String c) {
final cs = c.split(' ').where((x) => x.isNotEmpty).toList();
return cs.take(3).map((x) => x[0].toUpperCase() + x.substring(1).replaceAll('-', ' ')).join(', ') + (cs.length > 3 ? ' …' : '');
}
void _pick(Map<String, dynamic> it) {
final id = (it['id'] as num).toInt();
final f = widget.fdb?.food(id) ?? keepProduct(widget.sync.store, it); // one you have already: that one
if (f == null) {
setState(() => status = 'That product came back garbled.');
return;
}
widget.sync.changed();
Navigator.of(context).pop(f);
}
Widget _drop(List<(String, String)> opts, String value, void Function(String) set) => DropdownButton<String>(
value: value,
isDense: true,
underline: const SizedBox(),
dropdownColor: card2,
items: [for (final (k, l) in opts) DropdownMenuItem(value: k, child: Text(l, style: const TextStyle(fontSize: 13.5)))],
onChanged: (v) {
set(v ?? '');
_run();
},
);
@override
Widget build(BuildContext context) {
final h = MediaQuery.of(context).size.height;
return Padding(
padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
child: ConstrainedBox(
constraints: BoxConstraints(maxHeight: h * 0.85),
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 14, 16, 12),
child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
const Text('All products', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)),
const Text('Open Food Facts — every country, through the sync server', style: TextStyle(color: muted, fontSize: 12.5)),
const SizedBox(height: 6),
TextField(
controller: q,
autofocus: widget.q.isEmpty,
decoration: InputDecoration(
prefixIcon: const Icon(Icons.search),
hintText: 'Name, brand or barcode…',
suffixIcon: IconButton(
tooltip: 'Scan a barcode',
icon: const Icon(Icons.qr_code_scanner),
onPressed: () async {
final code = await scanBarcode(context);
if (code != null) {
q.text = code;
_run();
}
},
),
),
onChanged: (_) => _soon(),
onSubmitted: (_) => _run(),
),
Wrap(spacing: 12, crossAxisAlignment: WrapCrossAlignment.center, children: [
_drop(_countries, country, (v) => country = v),
_drop(_scores, score, (v) => score = v),
SizedBox(
width: 120,
child: TextField(
controller: brand,
style: const TextStyle(fontSize: 13.5),
decoration: const InputDecoration(isDense: true, hintText: 'Brand'),
onChanged: (_) => _soon(),
),
),
]),
if (status != null) Padding(padding: const EdgeInsets.only(top: 10), child: Text(status!, style: const TextStyle(color: muted))),
Flexible(
child: ListView(shrinkWrap: true, children: [
for (final it in items)
ListTile(
dense: true,
contentPadding: EdgeInsets.zero,
title: Text('${it['name']}', maxLines: 1, overflow: TextOverflow.ellipsis),
subtitle: Text(
[
if ('${it['brand'] ?? ''}'.isNotEmpty) '${it['brand']}',
_home('${it['countries'] ?? ''}'),
if (widget.fdb?.food((it['id'] as num).toInt()) != null) '✓ you have it',
].where((x) => x.isNotEmpty).join(' · '),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(color: muted),
),
trailing: Column(mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.end, children: [
Text('${((it['per100'] as Map?)?['kcal'] as num? ?? 0).round()} kcal', style: const TextStyle(fontSize: 13.5)),
if (it['nutriscore'] != null)
Text('Nutri-Score ${'${it['nutriscore']}'.toUpperCase()}', style: const TextStyle(color: muted, fontSize: 11.5)),
]),
onTap: () => _pick(it),
),
]),
),
]),
),
),
);
}
}
/// The camera, until a product barcode (EAN / UPC) is read → its digits, or null (closed) — app/scanner.dart.
Future<String?> scanBarcode(BuildContext context) => scanCode(context,
title: 'Scan a barcode',
format: Format.ean13 | Format.ean8 | Format.upca | Format.upce,
accept: (v) => RegExp(r'^\d{8,14}$').hasMatch(v));

View file

@ -0,0 +1,208 @@
// Food ▸ History (views.history): over the shared Health period — tiles (the average *logged* day:
// empty days don't count as zero; days logged + within 10 % of the target; protein, fibre; where the
// energy came from), energy per day (per week from 120 days: the average logged day) stacked by macro
// with the target as a dashed line (tap a bar = its numbers), and the foods eaten most.
import 'dart:math';
import 'package:flutter/material.dart';
import '../app/sync_service.dart';
import '../app/theme.dart';
import 'cycle_model.dart' show daysBetween, parseDay, plus, today;
import 'food_model.dart';
import 'food_page.dart' show macroColors;
import '../widgets/line_chart.dart' show RangeChip;
import 'range.dart';
const weeklyFrom = 120;
const _mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
class FoodHistoryPage extends StatefulWidget {
const FoodHistoryPage({super.key, required this.sync, required this.range});
final SyncService sync;
final HealthRange range;
@override
State<FoodHistoryPage> createState() => _FoodHistoryPageState();
}
class _FoodHistoryPageState extends State<FoodHistoryPage> {
String? tip;
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('Food history')),
body: ListenableBuilder(
listenable: Listenable.merge([widget.sync, widget.range]),
builder: (context, _) {
final store = widget.sync.store;
final now = today();
final first = store.db.select("SELECT min(json_extract(data, '\$.day')) AS d FROM rec WHERE t = 'food.entry'").first['d'] as String?;
final a = widget.range.from(first == null ? now : parseDay(first), now);
final days = dayTotals(store, dayIso(a), dayIso(now));
final logged = days.values.where((v) => (v['kcal'] ?? 0) > 0).toList();
double? avg(String k) => logged.isEmpty ? null : logged.map((v) => v[k] ?? 0).reduce((x, y) => x + y) / logged.length;
final target = targets(store, FoodSettings.of(store))['kcal']!.$1;
final onTarget = logged.where((v) => ((v['kcal'] ?? 0) - target).abs() <= target * 0.1).length;
final e = {for (final m in macros) m: (avg(m) ?? 0) * kcalPerG[m]!};
final tot = e.values.fold<double>(0, (x, y) => x + y);
final top = topFoods(store, dayIso(a), dayIso(now));
String r(double? v) => v == null ? '—' : v.round().toString();
return ListView(padding: const EdgeInsets.all(12), children: [
GridView.count(
crossAxisCount: MediaQuery.of(context).size.width >= 700 ? 4 : 2,
shrinkWrap: true, physics: const NeverScrollableScrollPhysics(),
mainAxisSpacing: 10, crossAxisSpacing: 10, childAspectRatio: 1.9,
children: [
_tile('Average day', '${r(avg('kcal'))} kcal', 'target ${target.round()}'),
_tile('Days logged', '${logged.length} of ${daysBetween(a, now) + 1}', '$onTarget within 10 % of target'),
_tile('Protein', '${r(avg('protein'))} g', 'a logged day on average'),
_tile('Fibre', '${r(avg('fiber'))} g', 'at least 25 g'),
],
),
const SizedBox(height: 10),
if (tot > 0)
Card(child: Padding(
padding: const EdgeInsets.all(12),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
const Text('Where the energy came from', style: TextStyle(color: muted, fontSize: 13)),
const SizedBox(height: 6),
ClipRRect(borderRadius: BorderRadius.circular(5), child: Row(children: [
for (final m in macros) Expanded(flex: max(1, (100 * e[m]! / tot).round()),
child: Container(height: 12, color: macroColors[m])),
])),
const SizedBox(height: 4),
Text(macros.map((m) => '${m[0].toUpperCase()}${m.substring(1)} ${(100 * e[m]! / tot).round()} %').join(' · '),
style: const TextStyle(fontSize: 13)),
]),
)),
const SizedBox(height: 10),
Card(child: Padding(
padding: const EdgeInsets.fromLTRB(10, 10, 10, 6),
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
Row(children: [
const Expanded(child: Text('Energy per day', style: TextStyle(fontWeight: FontWeight.bold))),
RangeChip(widget.range),
]),
const SizedBox(height: 8),
_Bars(days: days, a: a, z: now, target: target, onTip: (t) => setState(() => tip = t)),
SizedBox(height: 20, child: Text(tip ?? 'Tap a bar for its numbers', textAlign: TextAlign.center,
style: const TextStyle(color: muted, fontSize: 12.5))),
]),
)),
const SizedBox(height: 10),
if (top.isNotEmpty)
Card(child: Padding(
padding: const EdgeInsets.all(12),
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
const Text('Eaten most', style: TextStyle(fontWeight: FontWeight.bold)),
for (final (name, n, kcal) in top)
Padding(padding: const EdgeInsets.symmetric(vertical: 4), child: Row(children: [
Expanded(child: Text(name)),
Text('$n× · ${kcal.round()} kcal', style: const TextStyle(color: muted)),
])),
]),
)),
]);
},
),
);
Widget _tile(String label, String value, String sub) => Card(child: Padding(
padding: const EdgeInsets.all(12),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [
Text(label.toUpperCase(), style: const TextStyle(color: muted, fontSize: 11.5)),
Text(value, style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
Text(sub, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: muted, fontSize: 12)),
]),
));
}
/// Bars per day (or per week, the average logged day), stacked protein / carbs / fat by energy, the rest grey.
class _Bars extends StatelessWidget {
const _Bars({required this.days, required this.a, required this.z, required this.target, required this.onTip});
final Map<String, Map<String, double>> days;
final DateTime a, z;
final double target;
final void Function(String) onTip;
List<(DateTime, List<Map<String, double>>, String)> _buckets() {
final n = daysBetween(a, z) + 1;
final out = <(DateTime, List<Map<String, double>>, String)>[];
if (n >= weeklyFrom) {
for (var s = plus(a, -(a.weekday - 1)); !s.isAfter(z); s = plus(s, 7)) {
final vs = [for (var i = 0; i < 7; i++) days[dayIso(plus(s, i))]].whereType<Map<String, double>>()
.where((v) => (v['kcal'] ?? 0) > 0).toList();
out.add((s, vs, 'Week of ${s.day} ${_mon[s.month - 1]} ${s.year}'));
}
} else {
for (var i = 0; i < n; i++) {
final x = plus(a, i), v = days[dayIso(x)];
out.add((x, v != null && (v['kcal'] ?? 0) > 0 ? [v] : [], '${x.day} ${_mon[x.month - 1]} ${x.year}'));
}
}
return out;
}
@override
Widget build(BuildContext context) {
final b = _buckets();
return LayoutBuilder(builder: (context, box) => GestureDetector(
onTapDown: (d) {
final i = (d.localPosition.dx / box.maxWidth * b.length).floor().clamp(0, b.length - 1);
final (_, vs, label) = b[i];
if (vs.isEmpty) return onTip('$label · nothing logged');
double av(String k) => vs.map((v) => v[k] ?? 0).reduce((x, y) => x + y) / vs.length;
onTip('$label · ${av('kcal').round()} kcal${vs.length > 1 ? ' (${vs.length} days)' : ''} · '
'P ${av('protein').round()} g, C ${av('carbs').round()} g, F ${av('fat').round()} g');
},
child: CustomPaint(size: Size(box.maxWidth, 170), painter: _BarsPainter(b, target)),
));
}
}
class _BarsPainter extends CustomPainter {
_BarsPainter(this.b, this.target);
final List<(DateTime, List<Map<String, double>>, String)> b;
final double target;
@override
void paint(Canvas c, Size size) {
const mb = 16.0;
final h = size.height - mb;
double avg(List<Map<String, double>> vs, String k) => vs.map((v) => v[k] ?? 0).reduce((x, y) => x + y) / vs.length;
final peak = [target * 1.25, for (final (_, vs, _) in b) if (vs.isNotEmpty) avg(vs, 'kcal')].reduce(max);
double y(double k) => h - h * k / peak;
final bw = size.width / max(1, b.length), pad = bw > 4 ? bw * 0.18 : 0.0;
for (var i = 0; i < b.length; i++) {
final (x, vs, _) = b[i];
if (vs.isNotEmpty) {
final k = avg(vs, 'kcal');
final e = {for (final m in macros) m: avg(vs, m) * kcalPerG[m]!};
final sum = e.values.reduce((p, q) => p + q);
final scale = sum > k ? k / sum : 1.0; // labels' macros can add up past the kcal
var base = 0.0;
for (final m in macros) {
final hh = e[m]! * scale;
if (hh > 0) c.drawRect(Rect.fromLTRB(i * bw + pad, y(base + hh), (i + 1) * bw - pad, y(base)), Paint()..color = macroColors[m]!);
base += hh;
}
if (k - base > 1) c.drawRect(Rect.fromLTRB(i * bw + pad, y(k), (i + 1) * bw - pad, y(base)), Paint()..color = muted);
}
final weekly = b.length > 1 && b[1].$1.difference(b[0].$1).inDays == 7;
final label = weekly ? (x.day <= 7 && (b.length <= 30 || x.month % 3 == 1) ? _mon[x.month - 1] : null)
: b.length > 35 ? (x.day == 1 ? _mon[x.month - 1] : null) : (x.weekday == 1 || b.length <= 8 ? '${x.day} ${_mon[x.month - 1]}' : null);
if (label != null) {
final tp = TextPainter(text: TextSpan(text: label, style: const TextStyle(color: muted, fontSize: 10.5)),
textDirection: TextDirection.ltr)..layout();
tp.paint(c, Offset(i * bw + bw / 2 - tp.width / 2, h + 3));
}
}
final ty = y(target);
for (var x = 0.0; x < size.width; x += 8) {
c.drawLine(Offset(x, ty), Offset(min(x + 4, size.width), ty), Paint()..color = accent..strokeWidth = 1.2);
}
}
@override
bool shouldRepaint(covariant _BarsPainter old) => true;
}

View file

@ -0,0 +1,720 @@
// The food diary — a port of the dashboard's plugins/food: db.py (what an entry is, recent foods),
// fooddb.py (the food database: search, portions → grams → nutrients), views.py (totals, targets,
// the ring, the bars). Keep them in step with the web pages.
//
// Synced rows: "food.entry" {day, time, meal, name, kcal, protein, carbs, sugar, fiber, fat, sat_fat,
// mono_fat, poly_fat, trans_fat, sodium_mg, cholesterol_mg, potassium_mg, micros, source, src_id,
// amount, unit, note, food_id (foods.db id), grams, my_food_id (a "food.food" id)}; "food.food" =
// My foods + meals (per 100 g, portions JSON, recipe JSON, gone).
// foods.db (USDA + Open Food Facts, read-only) ships with the app — the same file as on the Pi, so
// food_id means the same food on both. "food.product" = shop products picked from the archive on the
// sync server (every Open Food Facts product; uid "p:<food_id>", {food_id, name, brand, barcode, data
// JSON = the product, added}) — FoodDb.food finds them too, so entries made from them work everywhere.
import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqlite3/sqlite3.dart';
import '../sync/store.dart';
import 'body_model.dart' show BodyView, bmrMifflin, female, profileOf;
import 'cycle_model.dart' show iso;
import 'summaries.dart';
const mealKeys = ['breakfast', 'lunch', 'dinner', 'snack'];
const mealLabels = {'breakfast': 'Breakfast', 'lunch': 'Lunch', 'dinner': 'Dinner', 'snack': 'Snacks', '': 'Other'};
const kcalPerG = {'protein': 4, 'carbs': 4, 'fat': 9};
const macros = ['protein', 'carbs', 'fat'];
const foodCols = ['kcal', 'protein', 'carbs', 'sugar', 'fiber', 'fat', 'sat_fat', 'mono_fat', 'poly_fat', 'trans_fat',
'sodium_mg', 'cholesterol_mg', 'potassium_mg'];
const reuseSources = {'manual', 'parsed'}; // entries worth offering again (imports are too rough)
const generic = {'tbsp (15 ml)': 15.0, 'tsp (5 ml)': 5.0}; // spoons every food can be measured in (ml as g)
/// The dashboard's Settings ▸ Food, as its Health summary brings it (meta:food); its defaults until then.
class FoodSettings {
const FoodSettings({this.goalRate = 0, this.split = (20, 50, 30), this.kcalTarget = 0, this.fiberMin = 25,
this.sugarMax = 50, this.sodiumMax = 2000});
final double goalRate; // % of the weight a week (0 = keep it)
final (int, int, int) split; // protein / carbs / fat % of the energy
final int kcalTarget, fiberMin, sugarMax, sodiumMax;
static FoodSettings of(SyncStore store) {
final m = Summaries(store).meta('food');
if (m == null) return const FoodSettings();
final sp = (m['split'] as List?)?.map((v) => (v as num).toInt()).toList();
int n(String k, int d) => (m[k] as num?)?.toInt() ?? d;
return FoodSettings(
goalRate: (m['goal_rate'] as num?)?.toDouble() ?? 0,
split: sp != null && sp.length == 3 ? (sp[0], sp[1], sp[2]) : (20, 50, 30),
kcalTarget: n('kcal_target', 0), fiberMin: n('fiber_min', 25), sugarMax: n('sugar_max', 50),
sodiumMax: n('sodium_max', 2000));
}
}
// ---- a food (the database's or one of My foods) ---------------------------------------------
class Portion {
const Portion(this.label, this.grams);
final String label;
final double grams;
}
class Food {
Food({required this.ref, required this.kind, required this.name, this.category = '', this.brand, this.barcode, required this.per100,
required this.portions, this.nutriscore, this.nova, this.foodId, this.myUid, this.isMeal = false, this.source = '',
this.labels = '', this.sugarsIn, this.dairy, this.addedSugar});
final String ref, kind, name, category; // ref "usda:ID" / "my:UID"; kind usda / off / my
final String source, labels; // foods.db: foundation / sr_legacy / survey / off; OFF labels ("no added sugar" …)
final String? brand, barcode, nutriscore;
final int? nova, foodId;
// off.py's facts for the added-sugar estimate (sugar.dart): the sweet ingredients ("" = none; null = not known),
// filed as dairy (1 / 0), the label's added sugars g / 100 g
final String? sugarsIn;
final int? dairy;
final double? addedSugar;
final String? myUid;
final Map<String, double?> per100;
final List<Portion> portions;
final bool isMeal;
/// g, ml, its portions, and the generic spoons unless it has its own (food.js unitsOf).
List<String> get units {
final own = portions.map((p) => p.label).toList();
final hasSpoon = own.any((l) => RegExp(r'^(tablespoon|tbsp|teaspoon|tsp)', caseSensitive: false).hasMatch(l));
return ['g', 'ml', ...own, if (!hasSpoon) ...generic.keys];
}
/// Grams of [amount] [unit] (fooddb.portion for the units the form offers), or null.
double? grams(double amount, String unit) {
if (unit == 'g' || unit == 'ml') return amount;
if (generic.containsKey(unit)) return amount * generic[unit]!;
for (final p in portions) {
if (p.label == unit) return amount * p.grams;
}
return null;
}
/// The food's columns for that many grams (fooddb.nutrients).
Map<String, double?> nutrients(double grams) =>
{for (final c in foodCols) c: per100[c] == null ? null : (per100[c]! * grams / 100 * 100).round() / 100};
}
// ---- foods.db (the database) ---------------------------------------------------------------
class FoodDb {
FoodDb._(this.db);
final Database db;
static FoodDb? _one;
static SyncStore? store; // the synced data: products kept from the archive ("food.product") — set in main.dart
/// Copies the shipped foods.db out of the app (once per version of the file) and opens it read-only.
static Future<FoodDb> open() async {
if (_one != null) return _one!;
final data = await rootBundle.load('assets/foods.db');
final path = '${(await getApplicationSupportDirectory()).path}/foods.db';
final f = File(path);
if (!f.existsSync() || f.lengthSync() != data.lengthInBytes) {
await f.writeAsBytes(data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes), flush: true);
}
return _one = FoodDb._(sqlite3.open(path, mode: OpenMode.readOnly));
}
static const _stop = {'with', 'and', 'of', 'a', 'an', 'the', 'in', 'on', 'some', 'my'};
static const _plain = {'nfs', 'raw', 'whole', 'plain', 'regular', 'fresh', 'cooked', 'boiled'};
static const _rank = {'foundation': 0, 'sr_legacy': 1, 'survey': 2, 'off': 3};
static List<String> words(String q) => RegExp(r'\w+', unicode: true)
.allMatches(q.toLowerCase())
.map((m) => m.group(0)!)
.where((w) => (w.length > 1 || int.tryParse(w) != null) && !_stop.contains(w))
.toList();
Food _food(Row r) {
final off = r['source'] == 'off';
return Food(
ref: 'usda:${r['id']}', kind: off ? 'off' : 'usda', name: r['name'] as String, category: r['category'] as String? ?? '',
brand: r['brand'] as String?, barcode: r.containsKey('barcode') ? r['barcode'] as String? : null,
nutriscore: r['nutriscore'] as String?, nova: (r['nova'] as num?)?.toInt(),
foodId: r['id'] as int, source: r['source'] as String? ?? '', labels: r['labels'] as String? ?? '',
// a foods.db older than these columns: none of them (the old rule)
sugarsIn: r.containsKey('sugars_in') ? r['sugars_in'] as String? : null,
dairy: r.containsKey('dairy') ? (r['dairy'] as num?)?.toInt() : null,
addedSugar: r.containsKey('added_sugar') ? (r['added_sugar'] as num?)?.toDouble() : null,
per100: {for (final c in foodCols) c: (r[c] as num?)?.toDouble()},
portions: [
for (final p in db.select('SELECT label, grams FROM portion WHERE food_id = ? ORDER BY seq, grams', [r['id']]))
Portion(p['label'] as String, (p['grams'] as num).toDouble())
],
);
}
/// A food of the database by id: foods.db's, else a product kept from the archive.
Food? food(int id) {
final r = db.select('SELECT * FROM food WHERE id = ?', [id]).firstOrNull;
return r != null ? _food(r) : store == null ? null : keptProduct(store!, id);
}
/// The products with that barcode (foods.db keeps it as on the pack), else kept ones.
List<Food> byBarcode(String code) {
final rs = db.select("SELECT * FROM food WHERE barcode = ? OR barcode = ?", [code, code.replaceFirst(RegExp(r'^0+'), '')]);
return rs.isNotEmpty ? [for (final r in rs) _food(r)] : store == null ? [] : keptByBarcode(store!, code);
}
/// fooddb.search: every word a prefix in name / brand / category; all in the name first, the name starting
/// with the first word, plain versions (raw, NFS …), fewer words, relevance, shorter names; one per name.
List<Food> search(String q, {int limit = 10}) {
final ws = words(q);
if (ws.isEmpty) return [];
final terms = ws.map((w) => '"$w"*').join(' ');
final rs = db.select(
'SELECT f.*, bm25(food_fts, 10, 1) AS rank FROM food_fts JOIN food f ON f.id = food_fts.rowid '
'WHERE food_fts MATCH ? ORDER BY rank LIMIT 200', [terms]);
final first = ws.first;
List<num> key(Row r) {
final name = (r['name'] as String).toLowerCase();
final nameWords = RegExp(r'\w+', unicode: true).allMatches(name).map((m) => m.group(0)!).toList();
final lead = nameWords.isEmpty ? '' : nameWords.first;
final exact = (lead == first || lead == '${first}s' || lead == '${first}es' || first == '${lead}s' || first == '${lead}es')
? 0 : lead.startsWith(first) ? 1 : 2;
final inName = ws.every((w) => nameWords.any((x) => x.startsWith(w))) ? 0 : 1;
final plain = nameWords.any(_plain.contains) ? 0 : 1;
return [inName, exact, plain, nameWords.length, ((r['rank'] as num) * 10).round() / 10, name.length,
_rank[r['source']] ?? 3];
}
final sorted = rs.toList()
..sort((a, b) {
final ka = key(a), kb = key(b);
for (var i = 0; i < ka.length; i++) {
final c = ka[i].compareTo(kb[i]);
if (c != 0) return c;
}
return 0;
});
final seen = <String>{}, out = <Food>[];
for (final r in sorted) {
if (seen.add((r['name'] as String).toLowerCase())) out.add(_food(r));
if (out.length >= limit) break;
}
return out;
}
}
// ---- My foods ------------------------------------------------------------------------------
Food myFood(Map<String, dynamic> r) {
final ps = (jsonDecode((r['portions'] as String?) ?? '[]') as List).cast<Map<String, dynamic>>();
return Food(
ref: 'my:${r['_u']}', kind: 'my', name: r['name'] as String, category: 'My foods', myUid: r['_u'] as String,
per100: {for (final c in foodCols) c: (r[c] as num?)?.toDouble()},
portions: [for (final p in ps) Portion(p['label'] as String, (p['grams'] as num).toDouble())],
isMeal: r['recipe'] != null,
);
}
/// My foods (not deleted) with every word of q in the name; exact / starting first, then the most used.
List<Food> myFoods(SyncStore store, String q, {int limit = 8}) {
final ws = q.toLowerCase().split(RegExp(r'\s+')).where((w) => w.isNotEmpty).toList();
final uses = <String, int>{};
for (final e in store.rows('food.entry')) {
final m = e['my_food_id'];
if (m is String) uses[m] = (uses[m] ?? 0) + 1;
}
final all = [
for (final r in store.rows('food.food'))
if ((r['gone'] ?? 0) == 0 && ws.every((w) => (r['name'] as String).toLowerCase().contains(w))) r
];
final ql = q.trim().toLowerCase();
all.sort((a, b) {
int k(Map<String, dynamic> r) {
final n = (r['name'] as String).toLowerCase();
return n == ql ? 0 : n.startsWith(ql) ? 1 : 2;
}
final c = k(a).compareTo(k(b));
return c != 0 ? c : (uses[b['_u']] ?? 0).compareTo(uses[a['_u']] ?? 0);
});
return all.take(limit).map(myFood).toList();
}
Food? myFoodByUid(SyncStore store, String uid) {
final r = store.row('food.food', uid);
return r == null ? null : myFood(r);
}
// ---- entries ------------------------------------------------------------------------------
class Entry {
Entry(this.row);
final Map<String, dynamic> row;
String get u => row['_u'] as String;
String get day => row['day'] as String;
String get meal => mealKeys.contains(row['meal']) ? row['meal'] as String : '';
String get name => (row['name'] as String?) ?? '';
double? n(String k) => (row[k] as num?)?.toDouble();
double get kcal => n('kcal') ?? 0;
double? get amount => n('amount');
String? get unit => row['unit'] as String?;
int? get foodId => (row['food_id'] as num?)?.toInt();
String? get myFoodId => row['my_food_id'] is String ? row['my_food_id'] as String : null;
String get source => (row['source'] as String?) ?? '';
String get portion => amount == null ? '' : '${_num(amount!)} ${unit ?? ''}'.trim();
int get stamp => (row['_h'] as num?)?.toInt() ?? 0;
}
String _num(double v) => v == v.roundToDouble() ? v.round().toString() : v.toStringAsFixed(v < 10 ? 2 : 1).replaceFirst(RegExp(r'0+$'), '');
List<Entry> entriesOn(SyncStore store, String day) {
final es = [for (final r in store.rows('food.entry', where: "json_extract(data, '\$.day') = ?", args: [day])) Entry(r)];
es.sort((a, b) {
final c = a.stamp.compareTo(b.stamp);
if (c != 0) return c;
return ((a.row['time'] as String?) ?? '').compareTo((b.row['time'] as String?) ?? '');
});
return es;
}
/// {day: kcal} for the days in [a, z] (the week strip).
Map<String, double> kcalByDay(SyncStore store, String a, String z) {
final out = <String, double>{};
for (final r in store.db.select(
"SELECT json_extract(data, '\$.day') AS dday, sum(json_extract(data, '\$.kcal')) AS k FROM rec "
"WHERE t = 'food.entry' AND json_extract(data, '\$.day') BETWEEN ? AND ? GROUP BY dday", [a, z])) { // not 'd': rec.d is the device
out[r['dday'] as String] = (r['k'] as num?)?.toDouble() ?? 0;
}
return out;
}
/// Foods eaten before (db.foods): one per name — its latest entry — most eaten first; q anywhere in the name.
List<(Entry, int)> recentFoods(SyncStore store, String q, {int limit = 8}) {
final groups = <String, (Entry, int)>{};
for (final r in store.rows('food.entry')) {
final e = Entry(r);
if (!reuseSources.contains(e.source) || e.name.trim().isEmpty) continue;
final k = e.name.trim().toLowerCase();
final g = groups[k];
final newer = g == null || e.day.compareTo(g.$1.day) > 0 || (e.day == g.$1.day && e.stamp > g.$1.stamp);
groups[k] = (newer ? e : g.$1, (g?.$2 ?? 0) + 1);
}
final ql = q.trim().toLowerCase();
final hits = groups.entries.where((e) => e.key.contains(ql)).map((e) => e.value).toList()
..sort((a, b) {
final sa = a.$1.name.toLowerCase().startsWith(ql) ? 0 : 1, sb = b.$1.name.toLowerCase().startsWith(ql) ? 0 : 1;
if (sa != sb) return sa.compareTo(sb);
if (a.$2 != b.$2) return b.$2.compareTo(a.$2);
return b.$1.day.compareTo(a.$1.day);
});
return hits.take(limit).toList();
}
// ---- products kept from the archive ("food.product", the dashboard's db.product) ---------------
const tProduct = 'food.product';
const offId = 20000000000000; // off.OFF_ID: + the barcode
/// A product from the archive (or as kept: the same keys) → a Food (kind "off").
Food productFood(Map<String, dynamic> d) {
final per = (d['per100'] as Map?)?.cast<String, dynamic>() ?? {};
return Food(
ref: 'usda:${d['id']}', kind: 'off', name: d['name'] as String? ?? '?', category: d['category'] as String? ?? '',
brand: d['brand'] as String?, barcode: d['barcode'] as String?, nutriscore: d['nutriscore'] as String?,
nova: (d['nova'] as num?)?.toInt(), foodId: (d['id'] as num).toInt(), source: 'off', labels: d['labels'] as String? ?? '',
sugarsIn: d['sugars_in'] as String?, dairy: (d['dairy'] as num?)?.toInt(), addedSugar: (d['added_sugar'] as num?)?.toDouble(),
per100: {for (final c in foodCols) c: (per[c] as num?)?.toDouble()},
portions: [
for (final p in ((d['portions'] as List?) ?? []).cast<Map>())
if ((p['grams'] as num?) != null) Portion('${p['label']}', (p['grams'] as num).toDouble())
],
);
}
Food? _kept(Map<String, dynamic>? row) {
try {
return row == null ? null : productFood(jsonDecode(row['data'] as String) as Map<String, dynamic>);
} catch (_) {
return null;
}
}
Food? keptProduct(SyncStore store, int id) => _kept(store.row(tProduct, 'p:$id'));
List<Food> keptByBarcode(SyncStore store, String code) =>
[for (final r in store.rows(tProduct, where: "json_extract(data, '\$.barcode') = ?", args: [code])) ?_kept(r)];
/// Kept products whose name / brand has every word of [q] (folded: no diacritics).
List<Food> keptProducts(SyncStore store, String q, {required String Function(String) fold, int limit = 4}) {
final ws = fold(q).split(RegExp(r'\s+')).where((w) => w.isNotEmpty).toList();
if (ws.isEmpty) return [];
return [
for (final r in store.rows(tProduct))
if (ws.every(fold('${r['name']} ${r['brand'] ?? ''}').contains)) ?_kept(r),
].take(limit).toList();
}
/// Keep a product picked from the archive (the dashboard's db.save_product: checked, then stored and synced).
Food? keepProduct(SyncStore store, Map<String, dynamic> d) {
final id = (d['id'] as num?)?.toInt();
final per = d['per100'];
if (id == null || id < offId || id >= offId * 1.5 || per is! Map || '${d['name'] ?? ''}'.trim().isEmpty) return null;
String? t(String k, int n) => d[k] == null ? null : '${d[k]}'.substring(0, min(n, '${d[k]}'.length));
final v = <String, dynamic>{
for (final (k, n) in [('name', 120), ('category', 120), ('brand', 60), ('barcode', 14), ('countries', 200), ('nutriscore', 1),
('allergens', 400), ('labels', 400), ('ingredients', 1600), ('sugars_in', 200)]) k: t(k, n),
'id': id,
'per100': {for (final c in foodCols) c: (per[c] as num?)?.toDouble()},
'portions': [
for (final p in ((d['portions'] as List?) ?? []).cast<Map>().take(6))
if ((p['grams'] as num? ?? 0) > 0 && (p['grams'] as num) <= 10000) {'label': '${p['label']}', 'grams': (p['grams'] as num).toDouble()}
],
'nova': [1, 2, 3, 4].contains(d['nova']) ? d['nova'] : null,
'dairy': [0, 1].contains(d['dairy']) ? d['dairy'] : null,
'added_sugar': (d['added_sugar'] as num?)?.toDouble(),
};
final old = store.row(tProduct, 'p:$id');
final data = jsonEncode(v);
if (old?['data'] != data) {
store.put(tProduct, 'p:$id', {'food_id': id, 'name': v['name'], 'brand': v['brand'] ?? '', 'barcode': v['barcode'], 'data': data,
'added': old?['added'] ?? DateTime.now().toUtc().toIso8601String().substring(0, 19).replaceFirst('T', ' ')});
}
return productFood(v);
}
/// The food an entry was made from, if it still exists (database or My foods).
Food? foodOf(SyncStore store, FoodDb? fdb, Entry e) {
if (e.myFoodId != null) return myFoodByUid(store, e.myFoodId!);
if (e.foodId != null) return fdb?.food(e.foodId!);
return null;
}
/// Save an entry made from [food] (amount × unit → grams → its nutrients) — new (u null) or changed.
/// The numbers are the entry's own, worked out now (later changes to the food don't touch it).
String? saveFromFood(SyncStore store, {String? u, required String day, required String meal, required Food food,
required double amount, required String unit, String note = ''}) {
final g = food.grams(amount, unit);
if (g == null) return "Can't tell the grams of that portion.";
final old = u == null ? null : store.row('food.entry', u);
store.put('food.entry', u ?? SyncStore.randomId(), {
'micros': '{}', 'src_id': null, 'time': null,
...?old,
'day': day, 'meal': meal, 'name': food.name, ...food.nutrients(g),
'amount': amount, 'unit': unit, 'grams': g, 'note': note,
'food_id': food.foodId, 'my_food_id': food.myUid, 'source': old?['source'] ?? 'manual',
});
return null;
}
/// Save an entry without a food (its numbers typed, or copied from an older one and scaled by amount).
String? saveTotals(SyncStore store, {String? u, required String day, required String meal, required String name,
required Map<String, double?> values, double? amount, String? unit, Map<String, dynamic>? copyFrom, String note = ''}) {
if (name.trim().isEmpty) return 'What was it?';
if (values['kcal'] == null) return 'How much energy? A guess is fine.';
final old = u == null ? null : store.row('food.entry', u);
final extra = <String, dynamic>{};
if (old == null && copyFrom != null && (copyFrom['kcal'] as num?) != null && (copyFrom['kcal'] as num) > 0) {
final f = values['kcal']! / (copyFrom['kcal'] as num); // db.save `from`: the other nutrients, scaled
for (final k in foodCols) {
if (!values.containsKey(k) && copyFrom[k] != null) extra[k] = ((copyFrom[k] as num) * f * 1000).round() / 1000;
}
}
store.put('food.entry', u ?? SyncStore.randomId(), {
'micros': '{}', 'src_id': null, 'time': null, 'food_id': null, 'grams': null, 'my_food_id': null,
...?old, ...extra,
'day': day, 'meal': meal, 'name': name.trim(), ...values, 'amount': amount, 'unit': unit, 'note': note,
'source': old?['source'] ?? 'manual',
});
return null;
}
/// Add an older entry again as it was (yesterday's +): a food entry is worked out again, else copied.
void addAgain(SyncStore store, FoodDb? fdb, Entry e, String day, String meal) {
final f = foodOf(store, fdb, e);
if (f != null && e.amount != null && e.unit != null && f.grams(e.amount!, e.unit!) != null) {
saveFromFood(store, day: day, meal: meal, food: f, amount: e.amount!, unit: e.unit!);
return;
}
saveTotals(store, day: day, meal: meal, name: e.name, amount: e.amount, unit: e.unit,
values: {for (final k in ['kcal', 'protein', 'carbs', 'sugar', 'fiber', 'fat', 'sat_fat', 'sodium_mg']) k: e.n(k)},
copyFrom: e.row);
}
// ---- totals, targets, ring (views.py) ----------------------------------------------------------
Map<String, double?> totals(Iterable<Entry> es) {
final out = <String, double?>{};
for (final k in ['kcal', 'protein', 'carbs', 'sugar', 'fiber', 'fat', 'sat_fat', 'sodium_mg']) {
final vs = es.map((e) => e.n(k)).whereType<double>().toList();
out[k] = vs.isEmpty ? null : vs.reduce((a, b) => a + b);
}
out['kcal'] ??= 0;
return out;
}
class Plan {
Plan(this.kcal, this.maint, this.basis, this.deficit, this.capped);
final int kcal;
final int? maint;
final String basis;
final int deficit;
final bool capped;
}
/// views.plan: your usual day from Health (the Pi's energy summary: resting + walking + workouts,
/// averaged over 28 days with step data — at least 7) minus the weight goal; resting × 1.4 until then.
Plan plan(SyncStore store, FoodSettings s) {
final e = Summaries(store).meta('energy') ?? {};
final b = BodyView(store, profileOf(store));
final w = (e['weight'] as num?)?.toDouble() ?? b.weight;
final bmr = (e['bmr'] as num?)?.toDouble() ?? bmrMifflin(w, b.p.height, b.p.sex, b.age);
if (s.kcalTarget > 0) return Plan(s.kcalTarget, null, 'set by hand', 0, false);
final tdee = (e['tdee'] as num?)?.toInt(), days = (e['days'] as num?)?.toInt() ?? 0;
final int? maint;
final String basis;
if (tdee != null && days >= 7) {
maint = tdee;
basis = 'your average day in Health (resting + walking + workouts, $days days)';
} else if (bmr != null) {
maint = (bmr * 1.4).round();
basis = 'resting energy × 1.4 (not enough step data in Health yet)';
} else {
return Plan(2000, null, 'no weight yet — 2000 kcal', 0, false);
}
if (w == null) return Plan(2000, maint, basis, 0, false);
var deficit = w * s.goalRate / 100 * 7700 / 7;
var capped = deficit > 1000;
deficit = min(deficit, 1000);
var kcal = maint - deficit;
final floor = b.p.sex == female ? 1200 : 1500;
if (kcal < floor) {
kcal = floor.toDouble();
capped = true;
}
return Plan((kcal / 10).round() * 10, maint, basis, deficit.round(), capped);
}
/// {key: (target, kind)} — kind goal / min / max (views.targets).
Map<String, (double, String)> targets(SyncStore store, FoodSettings s) {
final kcal = plan(store, s).kcal.toDouble();
final pct = [s.split.$1, s.split.$2, s.split.$3];
return {
'kcal': (kcal, 'goal'),
for (var i = 0; i < 3; i++) macros[i]: ((kcal * pct[i] / 100 / kcalPerG[macros[i]]!).roundToDouble(), 'goal'),
'fiber': (s.fiberMin.toDouble(), 'min'),
'sugar': (0, 'info'), // total sugar: shown, no limit (natural sugar counts too)
'added_sugar': ((kcal * 0.10 / 4).roundToDouble(), 'max'), // WHO: added ("free") sugars under 10 % of the energy (sugar.dart)
'sat_fat': ((kcal * 0.10 / 9).roundToDouble(), 'max'),
'sodium_mg': (s.sodiumMax.toDouble(), 'max'),
};
}
String dayIso(DateTime d) => iso(d);
String num1(double v) => _num(v);
// ---- My foods: save / delete (db.clean_food, save_food, delete_food) ---------------------------
/// What the food editor edits per 100 g (db.FIELDS): key → (label, unit, max).
const foodFields = {
'kcal': ('Energy', 'kcal', 10000.0), 'protein': ('Protein', 'g', 1000.0), 'carbs': ('Carbs', 'g', 1000.0),
'sugar': ('of which sugar', 'g', 1000.0), 'fat': ('Fat', 'g', 1000.0), 'sat_fat': ('of which saturated', 'g', 1000.0),
'fiber': ('Fibre', 'g', 500.0), 'sodium_mg': ('Sodium', 'mg', 50000.0),
};
/// New (uid null) or changed food: name unique among the live ones, energy required, portions need a
/// name + grams. The nutrients the editor doesn't show stay as they were. → (uid, error).
/// [sugarKind]: "Sugar counts as" (added / dairy / natural; '' = estimated; null = left as it is).
(String?, String?) saveMyFood(SyncStore store, {String? uid, required String name, required Map<String, double?> per100,
required List<Portion> portions, String note = '', String? sugarKind}) {
final n = name.trim().split(RegExp(r'\s+')).join(' ');
if (n.isEmpty) return (null, 'Name the food.');
if (per100['kcal'] == null) return (null, 'Energy per 100 g — from the label.');
for (final e in per100.entries) {
final max = foodFields[e.key]?.$3;
if (e.value != null && max != null && (e.value! < 0 || e.value! > max)) return (null, '${foodFields[e.key]!.$1}: 0–${max.round()}.');
}
for (final p in portions) {
if (p.label.trim().isEmpty || p.grams <= 0) return (null, 'A portion needs a name and its grams.');
if (['g', 'ml'].contains(p.label.trim().toLowerCase())) return (null, 'g and ml are there already.');
}
final clash = store.rows('food.food').any((r) =>
(r['gone'] ?? 0) == 0 && r['_u'] != uid && (r['name'] as String).toLowerCase() == n.toLowerCase());
if (clash) return (null, 'You already have a food with that name in My foods — pick it, or name this one differently.');
final now = DateTime.now().toIso8601String().substring(0, 19);
final old = uid == null ? null : store.row('food.food', uid);
final u = uid ?? SyncStore.randomId();
store.put('food.food', u, {
'based_on': null, 'based_on_name': null, 'recipe': null, 'gone': 0, 'created': now,
for (final c in foodCols) c: null,
...?old,
'name': n, ...per100, 'note': note.trim(), 'updated': now,
if (sugarKind != null) 'sugar_kind': const ['added', 'dairy', 'natural'].contains(sugarKind) ? sugarKind : null,
'portions': jsonEncode([for (final p in portions) {'label': p.label.trim().split(RegExp(r'\s+')).join(' '), 'grams': p.grams}]),
});
return (u, null);
}
/// Deleted foods are only hidden (gone): entries made from them keep pointing at them.
void deleteMyFood(SyncStore store, String uid) {
final r = store.row('food.food', uid);
if (r == null) return;
store.put('food.food', uid, {...r, 'gone': 1, 'updated': DateTime.now().toIso8601String().substring(0, 19)});
}
/// All My foods (not deleted), by name, with how often each was used.
List<(Map<String, dynamic>, int)> allMyFoods(SyncStore store) {
final uses = <String, int>{};
for (final e in store.rows('food.entry')) {
if (e['my_food_id'] is String) uses[e['my_food_id'] as String] = (uses[e['my_food_id'] as String] ?? 0) + 1;
}
final rs = store.rows('food.food').where((r) => (r['gone'] ?? 0) == 0).toList()
..sort((a, b) => (a['name'] as String).toLowerCase().compareTo((b['name'] as String).toLowerCase()));
return [for (final r in rs) (r, uses[r['_u']] ?? 0)];
}
// ---- history (views.history) -------------------------------------------------------------------
/// {day: totals} for [a, z] (ISO days) — one pass over the entries.
Map<String, Map<String, double>> dayTotals(SyncStore store, String a, String z) {
final out = <String, Map<String, double>>{};
for (final r in store.rows('food.entry', where: "json_extract(data, '\$.day') BETWEEN ? AND ?", args: [a, z])) {
final t = out.putIfAbsent(r['day'] as String, () => {});
for (final k in ['kcal', 'protein', 'carbs', 'fat', 'fiber', 'sugar', 'sodium_mg', 'sat_fat']) {
t[k] = (t[k] ?? 0) + ((r[k] as num?)?.toDouble() ?? 0);
}
}
return out;
}
/// The foods eaten most in [a, z]: (name, times, average kcal).
List<(String, int, double)> topFoods(SyncStore store, String a, String z, {int limit = 12}) {
final g = <String, (String, int, double)>{};
for (final r in store.rows('food.entry', where: "json_extract(data, '\$.day') BETWEEN ? AND ?", args: [a, z])) {
final name = (r['name'] as String?)?.trim() ?? '';
if (name.isEmpty) continue;
final k = name.toLowerCase(), cur = g[k];
final kcal = (r['kcal'] as num?)?.toDouble() ?? 0;
g[k] = cur == null ? (name, 1, kcal) : (cur.$1, cur.$2 + 1, cur.$3 + kcal);
}
final out = [for (final v in g.values) (v.$1, v.$2, v.$3 / v.$2)]
..sort((x, y) => x.$2 != y.$2 ? y.$2.compareTo(x.$2) : (y.$3 * y.$2).compareTo(x.$3 * x.$2));
return out.take(limit).toList();
}
// ---- meals (db.save_meal) ------------------------------------------------------------------------
const mealMax = 40; // ingredients
/// One ingredient of a meal: a food + amount + unit, or (an entry logged without a food) its own numbers.
class Ingredient {
Ingredient.food(Food this.food, this.amount, this.unit) : fixed = null, name = food.name, grams = null;
Ingredient.fixed(Map<String, double?> this.fixed, this.name, this.amount, this.unit, this.grams) : food = null;
final Food? food;
final Map<String, double?>? fixed;
final String name;
double? amount, grams;
String? unit;
double? get g => food != null ? (amount == null ? null : food!.grams(amount!, unit ?? 'g')) : grams;
Map<String, double?> get values => food != null ? (g == null ? {} : food!.nutrients(g!)) : fixed!;
}
/// The meal's ingredients from its synced recipe (refs "usda:ID" / "my:~ID").
List<Ingredient> recipeOf(SyncStore store, FoodDb? fdb, Map<String, dynamic> row) {
final r = row['recipe'] is String ? jsonDecode(row['recipe'] as String) as Map<String, dynamic> : null;
final out = <Ingredient>[];
for (final i in ((r?['ingredients'] as List?) ?? []).cast<Map<String, dynamic>>()) {
final amount = (i['amount'] as num?)?.toDouble(), unit = i['unit'] as String?;
if (i['fixed'] is Map) {
out.add(Ingredient.fixed({for (final e in (i['fixed'] as Map).entries) e.key as String: (e.value as num?)?.toDouble()},
(i['name'] as String?) ?? '', amount, unit, (i['grams'] as num?)?.toDouble()));
continue;
}
final ref = (i['food'] as String?) ?? '';
final f = ref.startsWith('usda:') ? fdb?.food(int.parse(ref.substring(5)))
: ref.startsWith('my:') ? myFoodByUid(store, ref.substring(3).replaceFirst('~', '')) : null;
if (f != null) {
out.add(Ingredient.food(f, amount, unit));
} else {
// gone: keep it as its own numbers so the meal still adds up (the web says "remove it and pick it again")
out.add(Ingredient.fixed({}, '${(i['name'] as String?) ?? '?'} (gone)', amount, unit, (i['grams'] as num?)?.toDouble()));
}
}
return out;
}
double? doneGramsOf(Map<String, dynamic> row) {
final r = row['recipe'] is String ? jsonDecode(row['recipe'] as String) as Map<String, dynamic> : null;
return (r?['done_grams'] as num?)?.toDouble();
}
/// The meals inside a meal (by id) — a meal may hold another meal, not itself.
Set<String> mealIds(SyncStore store, String uid, [int depth = 0]) {
final row = store.row('food.food', uid);
final r = row?['recipe'] is String ? jsonDecode(row!['recipe'] as String) as Map<String, dynamic> : null;
final out = <String>{};
for (final i in ((r?['ingredients'] as List?) ?? []).cast<Map<String, dynamic>>()) {
final ref = (i['food'] as String?) ?? '';
if (ref.startsWith('my:')) {
final id = ref.substring(3).replaceFirst('~', '');
out.add(id);
if (depth < 4) out.addAll(mealIds(store, id, depth + 1));
}
}
return out;
}
/// Save a meal (new: uid null): its values per 100 g worked out from the ingredients as they are now;
/// portions get "whole meal" (its whole weight). → (uid, error).
(String?, String?) saveMeal(SyncStore store, {String? uid, required String name, required List<Ingredient> ings,
double? doneGrams, required List<Portion> portions, String note = ''}) {
if (name.trim().isEmpty) return (null, 'Name the meal.');
if (ings.isEmpty) return (null, 'Add what goes into it.');
if (ings.length > mealMax) return (null, 'At most $mealMax ingredients.');
final tot = <String, double?>{for (final c in foodCols) c: null};
var grams = 0.0;
final unweighed = <String>[], recipe = <Map<String, dynamic>>[];
for (final i in ings) {
if (i.food != null) {
if (uid != null && i.food!.myUid != null && (i.food!.myUid == uid || mealIds(store, i.food!.myUid!).contains(uid))) {
return (null, '${i.name}: a meal can’t contain itself.');
}
final g = i.g;
if (g == null || g <= 0) return (null, '${i.name}: how much of it — amount and unit?');
i.food!.nutrients(g).forEach((c, v) {
if (v != null) tot[c] = (tot[c] ?? 0) + v;
});
grams += g;
recipe.add({'food': i.food!.myUid != null ? 'my:~${i.food!.myUid}' : 'usda:${i.food!.foodId}', 'name': i.food!.name,
'amount': i.amount, 'unit': i.unit ?? 'g', 'grams': (g * 100).round() / 100});
} else {
if (i.fixed!['kcal'] == null) return (null, '${i.name}: no energy on that one.');
i.fixed!.forEach((c, v) {
if (v != null && tot.containsKey(c)) tot[c] = (tot[c] ?? 0) + v;
});
if (i.grams != null && i.grams! > 0) {
grams += i.grams!;
} else {
unweighed.add(i.name);
}
recipe.add({'fixed': i.fixed, 'name': i.name, 'amount': i.amount, 'unit': i.unit, 'grams': i.grams});
}
}
final weight = doneGrams ?? grams;
if (unweighed.isNotEmpty && doneGrams == null) {
return (null, 'No weight for ${unweighed.take(3).join(', ')}${unweighed.length > 3 ? ' …' : ''} — weigh the meal (or guess) and enter it as the weight when done.');
}
if (weight <= 0) return (null, 'How much does it weigh?');
final per100 = {for (final e in tot.entries) e.key: e.value == null ? null : (e.value! * 100 / weight * 1000).round() / 1000};
final (u, err) = saveMyFood(store, uid: uid, name: name, per100: per100,
portions: [...portions.where((p) => p.label.trim().toLowerCase() != 'whole meal'), Portion('whole meal', (weight * 10).round() / 10)],
note: note);
if (err != null) return (null, err);
final row = store.row('food.food', u!)!;
store.put('food.food', u, {...row, 'recipe': jsonEncode({'ingredients': recipe, 'done_grams': doneGrams})});
return (u, null);
}
/// An entry dragged into another meal (db.move: only the meal changes).
void moveEntry(SyncStore store, String u, String meal) {
final r = store.row('food.entry', u);
if (r != null && r['meal'] != meal) store.put('food.entry', u, {...r, 'meal': meal});
}

View file

@ -0,0 +1,397 @@
// Food: one day — ‹ day ›, the week strip, the energy ring (eaten ÷ target, split by where the energy
// came from: protein / carbs / fat) + the nutrient bars, and the four meals (tap a food = edit it,
// long-press = drag it to another meal, + = add to that meal), Make a meal. Days up to 60 ahead for
// planning, like the web page.
import 'dart:math';
import 'package:flutter/material.dart';
import '../app/sync_service.dart';
import '../app/theme.dart';
import 'cycle_model.dart' show plus, today, daysBetween;
import 'food_model.dart';
import 'food_sheet.dart';
import 'meal_builder.dart';
import 'summaries.dart';
import 'sugar.dart';
const proteinC = Color(0xFF5CC8FF), carbsC = Color(0xFFFFB33A), fatC = Color(0xFFC792EA);
const macroColors = {'protein': proteinC, 'carbs': carbsC, 'fat': fatC};
const _mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const _dow = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
const ahead = 60;
/// P / C / F as coloured dots + grams (the web page's macDots).
Widget macroDots(Map<String, double?> t, {double size = 12.5}) => Row(mainAxisSize: MainAxisSize.min, children: [
for (final m in macros) ...[
Icon(Icons.circle, size: 7, color: macroColors[m]),
Padding(padding: const EdgeInsets.only(left: 2, right: 7),
child: Text('${(t[m] ?? 0).round()}', style: TextStyle(fontSize: size, color: muted))),
],
]);
class FoodPage extends StatefulWidget {
const FoodPage({super.key, required this.sync});
final SyncService sync;
@override
State<FoodPage> createState() => _FoodPageState();
}
class _FoodPageState extends State<FoodPage> {
DateTime d = today();
FoodDb? fdb;
FoodSettings get s => FoodSettings.of(widget.sync.store); // Settings ▸ Food on the dashboard
@override
void initState() {
super.initState();
FoodDb.open().then((x) => mounted ? setState(() => fdb = x) : null);
}
String _title() {
final n = daysBetween(today(), d);
final name = n == 0 ? 'Today' : n == -1 ? 'Yesterday' : n == 1 ? 'Tomorrow' : _dow[d.weekday - 1];
return '$name · ${d.day} ${_mon[d.month - 1]}${d.year != today().year ? ' ${d.year}' : ''}';
}
Future<void> _sheet({Entry? e, String? meal}) => showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: card,
builder: (_) => FoodSheet(sync: widget.sync, fdb: fdb, day: dayIso(d), meal: meal ?? e?.meal ?? _mealNow(), entry: e),
);
Future<void> _makeMeal(List<Entry> es) async {
final picked = es.isEmpty ? <Entry>[] : await pickEntries(context, es);
if (picked == null || !mounted) return;
Navigator.push(context, MaterialPageRoute(builder: (_) => MealBuilder(sync: widget.sync, fdb: fdb, fromEntries: picked)));
}
static String _mealNow() {
final h = DateTime.now().hour;
return h < 10 ? 'breakfast' : h < 15 ? 'lunch' : h < 21 ? 'dinner' : 'snack';
}
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: widget.sync,
builder: (context, _) {
final store = widget.sync.store;
final es = entriesOn(store, dayIso(d));
final tg = targets(store, s);
return LayoutBuilder(builder: (context, box) {
final wide = box.maxWidth >= 700;
final head = [_nav(), const SizedBox(height: 6), _week(tg['kcal']!.$1), const SizedBox(height: 10),
FoodDayCard(sync: widget.sync, day: d, fdb: fdb)];
final meals = [
for (final m in [...mealKeys, if (es.any((e) => e.meal == '')) ''])
Padding(padding: const EdgeInsets.only(bottom: 10), child: _meal(m, es.where((e) => e.meal == m).toList())),
OutlinedButton.icon(
onPressed: () => _makeMeal(es),
icon: const Icon(Icons.soup_kitchen_outlined),
label: Text(es.isEmpty ? 'Make a meal' : 'Make a meal (from this day’s entries)'),
),
];
return ListView(padding: const EdgeInsets.fromLTRB(12, 10, 12, 24), children: [
if (wide)
Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
Expanded(child: Column(children: head)),
const SizedBox(width: 12),
Expanded(child: Column(children: meals)),
])
else ...[...head, const SizedBox(height: 10), ...meals],
]);
});
},
);
Widget _nav() => Row(children: [
IconButton(onPressed: () => setState(() => d = plus(d, -1)), icon: const Icon(Icons.chevron_left)),
Expanded(
child: GestureDetector(
onTap: () => setState(() => d = today()),
child: Text(_title(), textAlign: TextAlign.center,
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)),
),
),
IconButton(
onPressed: daysBetween(today(), d) < ahead ? () => setState(() => d = plus(d, 1)) : null,
icon: const Icon(Icons.chevron_right)),
]);
Widget _week(double target) {
final mon = plus(d, -(d.weekday - 1));
final k = kcalByDay(widget.sync.store, dayIso(mon), dayIso(plus(mon, 6)));
return Row(children: [
for (var i = 0; i < 7; i++)
() {
final x = plus(mon, i), kc = k[dayIso(x)];
final h = min(1.15, (kc ?? 0) / target);
final sel = x == d, over = kc != null && kc > target * 1.05;
return Expanded(
child: GestureDetector(
onTap: () => setState(() => d = x),
child: Container(
margin: const EdgeInsets.symmetric(horizontal: 2),
padding: const EdgeInsets.symmetric(vertical: 5),
decoration: BoxDecoration(color: sel ? card2 : null, borderRadius: BorderRadius.circular(8)),
child: Column(children: [
Text(_dow[i].substring(0, 2), style: TextStyle(fontSize: 11.5, color: x == today() ? accent : muted)),
const SizedBox(height: 3),
Container(
width: 12, height: 32, alignment: Alignment.bottomCenter,
decoration: BoxDecoration(color: card2, borderRadius: BorderRadius.circular(3)),
child: FractionallySizedBox(heightFactor: h / 1.15,
child: Container(decoration: BoxDecoration(color: over ? bad : good, borderRadius: BorderRadius.circular(3)))),
),
const SizedBox(height: 2),
Text(kc == null ? '' : '${kc.round()}', style: const TextStyle(fontSize: 10.5, color: muted)),
]),
),
),
);
}(),
]);
}
Widget _meal(String m, List<Entry> es) {
final t = totals(es);
// a long-pressed food can be dropped on another meal's card (db.move: only the meal changes)
return DragTarget<Entry>(
onWillAcceptWithDetails: (d) => m != '' && d.data.meal != m,
onAcceptWithDetails: (d) {
moveEntry(widget.sync.store, d.data.u, m);
widget.sync.changed();
},
builder: (context, cand, _) => Card(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12),
side: cand.isNotEmpty ? const BorderSide(color: accent, width: 2) : BorderSide.none),
child: Padding(
padding: const EdgeInsets.fromLTRB(14, 6, 6, 8),
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
Row(children: [
Text(mealLabels[m]!, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
const SizedBox(width: 10),
if (es.isNotEmpty) Text('${(t['kcal'] ?? 0).round()} kcal', style: const TextStyle(color: accent)),
const Spacer(),
if (es.isNotEmpty) macroDots(t),
if (m != '')
IconButton(tooltip: 'Add to ${mealLabels[m]!.toLowerCase()}', onPressed: () => _sheet(meal: m),
icon: const Icon(Icons.add_circle_outline, color: accent)),
]),
if (es.isEmpty && m != '')
InkWell(
onTap: () => _sheet(meal: m),
child: const Padding(padding: EdgeInsets.symmetric(vertical: 6), child: Text('Nothing yet — add', style: TextStyle(color: muted))),
),
for (final e in es)
LongPressDraggable<Entry>(
data: e,
feedback: Material(
color: card2,
borderRadius: BorderRadius.circular(10),
elevation: 6,
child: Padding(padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
child: Text('${e.name} · ${e.kcal.round()} kcal', style: const TextStyle(color: Colors.white))),
),
childWhenDragging: Opacity(opacity: 0.35, child: _row(e)),
child: InkWell(onTap: () => _sheet(e: e), child: _row(e)),
),
]),
),
),
);
}
Widget _row(Entry e) => Padding(
padding: const EdgeInsets.fromLTRB(0, 6, 8, 6),
child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text(e.name),
Row(children: [
if (e.portion.isNotEmpty) Padding(padding: const EdgeInsets.only(right: 8),
child: Text(e.portion, style: const TextStyle(color: muted, fontSize: 12.5))),
macroDots({for (final k in macros) k: e.n(k)}, size: 11.5),
]),
])),
Text('${e.kcal.round()}', style: const TextStyle(fontWeight: FontWeight.bold)),
]),
);
}
/// The energy ring (views.ring): as far round as eaten ÷ target, split by the macros' share of
/// the energy; past 105 % the track turns red.
/// The day's energy ring (eaten ÷ target, split by macro), what's left, burned (Health) and the nutrient
/// bars — the Food page's top card, also on Health ▸ Overview.
class FoodDayCard extends StatelessWidget {
const FoodDayCard({super.key, required this.sync, required this.day, this.fdb});
final SyncService sync;
final DateTime day;
final FoodDb? fdb;
FoodSettings get s => FoodSettings.of(sync.store);
@override
Widget build(BuildContext context) {
final store = sync.store;
final es = entriesOn(store, dayIso(day));
final t = totals(es);
if (fdb != null) {
final fs = AddedSugar(store, fdb);
t['added_sugar'] = es.fold<double>(0, (a, e) => a + fs.entry(e));
}
return _ringCard(t, targets(store, s), plan(store, s), es.isNotEmpty);
}
Widget _ringCard(Map<String, double?> t, Map<String, (double, String)> tg, Plan p, bool any) {
final target = tg['kcal']!.$1, kcal = t['kcal'] ?? 0, left = target - kcal;
final rows = [('protein', 'Protein', 'g'), ('carbs', 'Carbs', 'g'), ('fat', 'Fat', 'g'), ('fiber', 'Fibre', 'g'),
('sugar', 'Sugar', 'g'), if (t['added_sugar'] != null) ('added_sugar', 'Added sugar ≈', 'g'), ('sat_fat', 'Saturated fat', 'g'),
('sodium_mg', 'Sodium', 'mg')];
return Card(
child: Padding(
padding: const EdgeInsets.all(14),
child: Column(children: [
Row(children: [
Tooltip(
triggerMode: TooltipTriggerMode.tap,
showDuration: const Duration(seconds: 8),
message: 'Target ${target.round()} kcal: ${p.basis}'
'${p.maint != null ? ' = ${p.maint} kcal, minus ${p.deficit} to lose 0.5 % a week' : ''}'
'${p.capped ? ' (limited)' : ''}.',
child: SizedBox(
width: 120, height: 120,
child: CustomPaint(
painter: _Ring(t, target),
child: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
Text('${kcal.round()}', style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold)),
Text('of ${target.round()} kcal', style: const TextStyle(fontSize: 11.5, color: muted)),
])),
),
),
),
const SizedBox(width: 16),
Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text(left >= 0 ? '${left.round()} left' : '${(-left).round()} over',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: kcal > target * 1.05 ? bad : null)),
const SizedBox(height: 6),
if (any) macroDots(t, size: 14) else const Text('Nothing logged yet', style: TextStyle(color: muted)),
..._burned(kcal, any),
])),
]),
const SizedBox(height: 12),
for (final (k, label, unit) in rows) _bar(label, unit, t[k], tg[k]!, macroColors[k]),
]),
),
);
}
/// The day's activity from Health (the Pi's summary): "Burned ≈ N kcal" (breakdown on tap) and
/// eaten − burned (only when something's logged) — past days and today ("so far").
List<Widget> _burned(double kcal, bool any) {
if (day.isAfter(today())) return [];
final e = (Summaries(sync.store).day(dayIso(day))?['energy'] as Map?)?.cast<String, dynamic>();
if (e == null) return [];
final total = (e['total'] as num).toDouble(), bal = kcal - total;
return [
const SizedBox(height: 8),
Tooltip(
triggerMode: TooltipTriggerMode.tap,
message: 'Resting ${e['bmr']} + walking ${e['walk']} + workouts ${e['workouts']} kcal — estimated from your band',
child: Text('Burned ≈ ${total.round()} kcal${day == today() ? ' so far' : ''}', style: const TextStyle(color: muted)),
),
if (any)
Text('eaten − burned ${bal >= 0 ? '+' : '−'}${bal.abs().round()}',
style: TextStyle(color: bal <= 0 ? good : accent, fontWeight: FontWeight.bold)),
];
}
Widget _bar(String label, String unit, double? v, (double, String) tg, Color? c) {
final (target, kind) = tg;
if (kind == 'info') { // total sugar: the value, no limit
return Tooltip(
triggerMode: TooltipTriggerMode.tap,
message: 'All sugar, natural sugar included (fruit, vegetables, milk) — the limit is on added sugar, below.',
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 3.5),
child: Row(children: [
SizedBox(width: 104, child: Text(label, style: const TextStyle(color: muted, fontSize: 13.5))),
const Spacer(),
Text('${v == null ? '—' : v.round()} $unit', style: const TextStyle(fontSize: 12.5)),
]),
),
);
}
final frac = target > 0 ? (v ?? 0) / target : 0.0;
final over = kind == 'max' && (v ?? 0) > target, ok = kind == 'min' && (v ?? 0) >= target,
high = kind == 'goal' && (v ?? 0) > target * 1.15;
final color = over || high ? bad : ok ? good : (c ?? muted);
final word = kind == 'min' ? 'at least ' : kind == 'max' ? 'at most ' : '';
final row = Padding(
padding: const EdgeInsets.symmetric(vertical: 3.5),
child: Row(children: [
SizedBox(width: 104, child: Text(label, style: const TextStyle(color: muted, fontSize: 13.5))),
Expanded(
child: ClipRRect(
borderRadius: BorderRadius.circular(4),
child: LinearProgressIndicator(value: min(1.0, frac), minHeight: 8, backgroundColor: card2, color: color),
),
),
SizedBox(
width: 118,
child: Text('${v == null ? '—' : v.round()} / $word${target.round()} $unit', textAlign: TextAlign.right,
style: TextStyle(fontSize: 12.5, color: over || high ? bad : null)),
),
]),
);
if (label != 'Added sugar ≈') return row;
return Tooltip(
triggerMode: TooltipTriggerMode.tap,
showDuration: const Duration(seconds: 8),
message: 'Added sugar, estimated: sugar, honey, syrups added to food, plus fruit juice (WHO\'s "free sugars") — '
'not the sugar inside whole fruit, '
'vegetables and plain milk / yogurt. WHO: under 10 % of the energy.',
child: row,
);
}
}
class _Ring extends CustomPainter {
_Ring(this.t, this.target);
final Map<String, double?> t;
final double target;
@override
void paint(Canvas c, Size size) {
final r = size.width / 2 - 8, o = Offset(size.width / 2, size.height / 2);
final kcal = t['kcal'] ?? 0;
final over = kcal > target * 1.05;
// rounded ends like the web page's ring (stroke-linecap: round)
Paint p(Color col, {StrokeCap cap = StrokeCap.round}) =>
Paint()..color = col..style = PaintingStyle.stroke..strokeWidth = 11..strokeCap = cap;
c.drawCircle(o, r, p(over ? bad.withValues(alpha: .45) : card2, cap: StrokeCap.butt));
final frac = target > 0 ? min(1.0, kcal / target) : 0.0;
if (frac == 0) return;
final energy = {for (final m in macros) m: (t[m] ?? 0) * kcalPerG[m]!};
final known = energy.values.reduce((a, b) => a + b);
final rect = Rect.fromCircle(center: o, radius: r);
var at = -pi / 2;
if (known == 0) {
c.drawArc(rect, at, frac * 2 * pi, false, p(accent));
return;
}
// thin separators between the macros only (views.ring's gap: 0.006 of the circle each side), none at 12 o'clock
final gap = frac > 0.05 ? 0.006 * 2 * pi : 0.0;
final parts = [for (final m in macros) if (energy[m]! > 0) m];
for (var i = 0; i < parts.length; i++) {
final sweep = frac * energy[parts[i]]! / known * 2 * pi;
final g0 = i == 0 ? 0.0 : gap, g1 = i == parts.length - 1 ? 0.0 : gap;
if (sweep > g0 + g1) c.drawArc(rect, at + g0, sweep - g0 - g1, false, p(macroColors[parts[i]]!));
at += sweep;
}
}
@override
bool shouldRepaint(covariant _Ring old) => true;
}

View file

@ -0,0 +1,420 @@
// Adding / editing a food entry (the web page's inline editor as a bottom sheet, lifted by the
// keyboard). Modes:
// search — the box: empty = yesterday's foods (this meal first; + adds one as it was, a tap picks
// it to change the portion); typed = My foods · Eaten before · Food database · Products
// (+ ones kept from the archive); a barcode (typed or scanned — the camera button) = that
// product; "Search all products…" = the archive on the sync server (food_archive.dart)
// food — the picked food: amount + unit (g, ml, its portions, tbsp / tsp), the numbers live, meal
// totals — an entry without a food (Lifesum imports, estimates): name, kcal / P / C / F
// Editing an entry opens it in food or totals mode; Delete = tap twice.
import 'package:flutter/material.dart';
import '../app/sync_service.dart';
import '../app/theme.dart';
import 'cycle_model.dart' show parseDay, plus;
import 'food_archive.dart';
import 'food_model.dart';
import 'food_page.dart' show macroDots;
import 'my_foods.dart';
import 'sugar.dart' show fold;
class FoodSheet extends StatefulWidget {
const FoodSheet({super.key, required this.sync, required this.fdb, required this.day, required this.meal, this.entry});
final SyncService sync;
final FoodDb? fdb;
final String day, meal;
final Entry? entry;
@override
State<FoodSheet> createState() => _FoodSheetState();
}
class _FoodSheetState extends State<FoodSheet> {
late String meal = widget.meal.isEmpty ? 'snack' : widget.meal;
String mode = 'search';
final q = TextEditingController();
Food? food;
final amount = TextEditingController(), name = TextEditingController(), unitCtl = TextEditingController();
String unit = 'g';
final totalsCtl = {for (final k in ['kcal', 'protein', 'carbs', 'fat']) k: TextEditingController()};
Map<String, dynamic>? copyFrom; // totals mode from an older entry: its other nutrients come along, scaled
String? error;
bool armed = false;
@override
void initState() {
super.initState();
final e = widget.entry;
if (e != null) {
final f = foodOf(widget.sync.store, widget.fdb, e);
if (f != null && e.amount != null && e.unit != null && f.units.contains(e.unit)) {
_pick(f, e.amount!, e.unit!);
} else {
_totals(e);
}
}
}
void _pick(Food f, [double? a, String? u]) => setState(() {
food = f;
mode = 'food';
unit = u ?? (f.portions.isNotEmpty ? f.portions.first.label : 'g');
amount.text = num1(a ?? (unit == 'g' ? 100 : 1));
error = null;
});
void _totals(Entry e, {bool copy = false}) => setState(() {
mode = 'totals';
name.text = e.name;
amount.text = e.amount == null ? '' : num1(e.amount!);
unit = e.unit ?? '';
unitCtl.text = unit;
for (final k in totalsCtl.keys) {
totalsCtl[k]!.text = e.n(k) == null ? '' : num1(e.n(k)!);
}
copyFrom = copy ? e.row : null;
error = null;
});
void _done() {
widget.sync.changed();
Navigator.pop(context);
}
void _save() {
final store = widget.sync.store;
final u = widget.entry?.u;
String? err;
if (mode == 'food') {
final a = double.tryParse(amount.text.trim().replaceAll(',', '.'));
if (a == null || a <= 0) return setState(() => error = 'How much?');
err = saveFromFood(store, u: u, day: widget.entry?.day ?? widget.day, meal: meal, food: food!, amount: a, unit: unit,
note: (widget.entry?.row['note'] as String?) ?? '');
} else {
double? v(String k) => double.tryParse(totalsCtl[k]!.text.trim().replaceAll(',', '.'));
err = saveTotals(store, u: u, day: widget.entry?.day ?? widget.day, meal: meal, name: name.text,
values: {for (final k in totalsCtl.keys) k: v(k)},
amount: double.tryParse(amount.text.trim().replaceAll(',', '.')), unit: unit.isEmpty ? null : unit,
copyFrom: copyFrom, note: (widget.entry?.row['note'] as String?) ?? '');
}
if (err != null) return setState(() => error = err);
_done();
}
@override
Widget build(BuildContext context) {
final h = MediaQuery.of(context).size.height;
return Padding(
padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
child: ConstrainedBox(
constraints: BoxConstraints(maxHeight: h * 0.8),
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 14, 16, 12),
child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
Row(children: [
Expanded(child: Text(widget.entry == null ? 'Add to ${mealLabels[meal]!.toLowerCase()}' : 'Edit',
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent))),
DropdownButton<String>(
value: meal,
underline: const SizedBox(),
dropdownColor: card2,
items: [for (final m in mealKeys) DropdownMenuItem(value: m, child: Text(mealLabels[m]!))],
onChanged: (m) => setState(() => meal = m!),
),
]),
if (mode == 'search') Flexible(child: _search()) else if (mode == 'food') _foodForm() else _totalsForm(),
]),
),
),
);
}
// ---- search
Widget _search() {
final store = widget.sync.store;
final text = q.text.trim();
final sections = <(String, List<Widget>)>[];
if (text.isEmpty) {
final yday = parseDay(widget.day);
final ys = entriesOn(store, dayIso(plus(yday, -1))).where((e) => e.meal.isNotEmpty).toList();
final here = entriesOn(store, widget.day);
bool already(Entry y) => here.any((e) => e.meal == meal && e.name == y.name && e.amount == y.amount && e.unit == y.unit);
final mine = ys.where((e) => e.meal == meal).toList(), rest = ys.where((e) => e.meal != meal).toList();
if (mine.isNotEmpty) sections.add(('Yesterday · ${mealLabels[meal]!.toLowerCase()}', [for (final e in mine) _yday(e, already(e))]));
if (rest.isNotEmpty) sections.add(('Yesterday · other meals', [for (final e in rest) _yday(e, already(e))]));
final recent = recentFoods(store, '', limit: 8);
if (recent.isNotEmpty) sections.add(('Eaten often', [for (final (e, n) in recent) _recent(e, n)]));
} else if (RegExp(r'^\d{8,14}$').hasMatch(text)) { // a barcode: that product, here or kept
final found = widget.fdb?.byBarcode(text) ?? keptByBarcode(store, text);
sections.add(('Barcode $text', [
for (final f in found) _foodTile(f),
if (found.isEmpty) const Padding(padding: EdgeInsets.symmetric(vertical: 6),
child: Text('Not in the food database here — look it up in all products:', style: TextStyle(color: muted))),
]));
} else {
final my = myFoods(store, text);
final recent = recentFoods(store, text, limit: 5);
final db = widget.fdb?.search(text, limit: 14) ?? [];
if (my.isNotEmpty) sections.add(('My foods', [for (final f in my) _foodTile(f)]));
if (recent.isNotEmpty) sections.add(('Eaten before', [for (final (e, n) in recent) _recent(e, n)]));
final kept = keptProducts(store, text, fold: fold);
final usda = db.where((f) => f.kind == 'usda').take(8).toList(),
off = [...kept, ...db.where((f) => f.kind == 'off' && !kept.any((k) => k.foodId == f.foodId))].take(6).toList();
if (usda.isNotEmpty) sections.add(('Food database', [for (final f in usda) _foodTile(f)]));
if (off.isNotEmpty) sections.add(('Products', [for (final f in off) _foodTile(f)]));
if (widget.fdb == null) sections.add(('', [const Text('Loading the food database…', style: TextStyle(color: muted))]));
}
return Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
TextField(
controller: q,
autofocus: true,
decoration: InputDecoration(
prefixIcon: const Icon(Icons.search),
hintText: 'Search foods…',
suffixIcon: IconButton(tooltip: 'Scan a barcode', icon: const Icon(Icons.qr_code_scanner), onPressed: _scan),
),
onChanged: (_) => setState(() {}),
),
const SizedBox(height: 6),
Flexible(
child: ListView(shrinkWrap: true, children: [
for (final (title, items) in sections) ...[
if (title.isNotEmpty)
Padding(padding: const EdgeInsets.only(top: 10, bottom: 2),
child: Text(title, style: const TextStyle(color: muted, fontSize: 12.5, fontWeight: FontWeight.bold))),
...items,
],
if (sections.isEmpty && text.isNotEmpty) const Padding(padding: EdgeInsets.all(12),
child: Text('Nothing found', style: TextStyle(color: muted))),
if (text.length >= 3)
TextButton.icon(
onPressed: () => _archive(text),
icon: const Icon(Icons.travel_explore),
label: Text(RegExp(r'^\d{8,14}$').hasMatch(text) ? 'Look up barcode $text in all products' : 'Search all products for “$text”'),
),
if (text.isNotEmpty)
TextButton.icon(
onPressed: () async {
final uid = await openFoodEditor(context, widget.sync, name: text);
final f = uid == null ? null : myFoodByUid(widget.sync.store, uid);
if (f != null && mounted) _pick(f);
},
icon: const Icon(Icons.add),
label: Text('New food “$text” (from its label)'),
),
if (text.isNotEmpty)
TextButton.icon(
onPressed: () => setState(() {
mode = 'totals';
name.text = text;
amount.text = '';
unit = '';
unitCtl.text = '';
copyFrom = null;
}),
icon: const Icon(Icons.edit_note),
label: Text('“$text” with my own numbers'),
),
]),
),
]);
}
/// The archive (every Open Food Facts product) → the one picked, kept, then as any food.
Future<void> _archive(String text) async {
final f = await openArchive(context, widget.sync, widget.fdb, text);
if (f != null && mounted) _pick(f);
}
/// The camera → a barcode: its product here, else straight to the archive.
Future<void> _scan() async {
final code = await scanBarcode(context);
if (code == null || !mounted) return;
final here = widget.fdb?.byBarcode(code) ?? keptByBarcode(widget.sync.store, code);
if (here.length == 1) return _pick(here.first);
setState(() => q.text = code);
if (here.isEmpty) await _archive(code);
}
Widget _yday(Entry e, bool done) => ListTile(
dense: true,
contentPadding: EdgeInsets.zero,
title: Text(e.name),
subtitle: Text('${e.portion.isEmpty ? '' : '${e.portion} · '}${e.kcal.round()} kcal', style: const TextStyle(color: muted)),
onTap: () => _fromEntry(e),
trailing: done
? const Icon(Icons.check, color: good)
: IconButton(
tooltip: 'Add as it was',
icon: const Icon(Icons.add_circle, color: accent),
onPressed: () {
addAgain(widget.sync.store, widget.fdb, e, widget.day, meal);
widget.sync.changed();
setState(() {});
},
),
);
Widget _recent(Entry e, int n) => ListTile(
dense: true,
contentPadding: EdgeInsets.zero,
title: Text(e.name),
subtitle: Text('${e.portion.isEmpty ? '' : '${e.portion} · '}${e.kcal.round()} kcal · $n×', style: const TextStyle(color: muted)),
onTap: () => _fromEntry(e),
);
/// An older entry picked: its food with its portion, else its numbers (scaled with the amount).
void _fromEntry(Entry e) {
final f = foodOf(widget.sync.store, widget.fdb, e);
if (f != null && e.amount != null && e.unit != null && f.units.contains(e.unit)) {
_pick(f, e.amount!, e.unit!);
} else {
_totals(e, copy: true);
}
}
Widget _foodTile(Food f) {
final k = f.per100['kcal'];
final sub = [
if (f.kind == 'off') f.brand ?? '' else if (f.kind != 'my') f.category,
if (k != null) '${k.round()} kcal / 100 g',
if (f.isMeal) 'meal',
].where((x) => x.isNotEmpty).join(' · ');
return ListTile(
dense: true,
contentPadding: EdgeInsets.zero,
title: Text(f.name),
subtitle: Text(sub, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: muted)),
trailing: f.nutriscore == null ? null : _score(f.nutriscore!),
onTap: () => _pick(f),
);
}
static Widget _score(String s) {
const colors = {'a': Color(0xFF1E8F4E), 'b': Color(0xFF7AC547), 'c': Color(0xFFF2C40F), 'd': Color(0xFFEE8100), 'e': Color(0xFFE63E11)};
return Container(
padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 2),
decoration: BoxDecoration(color: colors[s] ?? card2, borderRadius: BorderRadius.circular(5)),
child: Text(s.toUpperCase(), style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
);
}
// ---- food: amount + unit
Widget _foodForm() {
final f = food!;
final a = double.tryParse(amount.text.trim().replaceAll(',', '.'));
final g = a == null ? null : f.grams(a, unit);
final nut = g == null ? null : f.nutrients(g);
final source = switch (f.kind) {
'my' => f.isMeal ? 'My meal' : 'My food',
'off' => 'Product (Open Food Facts)${f.brand != null ? ' · ${f.brand}' : ''}',
_ => 'Food database (USDA)',
};
return Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
InkWell(
onTap: () => setState(() => mode = 'search'),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: Row(children: [
Expanded(child: Text(f.name, style: const TextStyle(fontSize: 16.5, fontWeight: FontWeight.bold))),
const Icon(Icons.search, color: muted, size: 18),
]),
),
),
Text(source, style: const TextStyle(color: muted, fontSize: 12.5)),
const SizedBox(height: 10),
Row(children: [
SizedBox(
width: 100,
child: TextField(
controller: amount,
autofocus: widget.entry == null,
keyboardType: const TextInputType.numberWithOptions(decimal: true),
decoration: const InputDecoration(labelText: 'Amount'),
onChanged: (_) => setState(() {}),
onSubmitted: (_) => _save(),
),
),
const SizedBox(width: 12),
Expanded(
child: DropdownButtonFormField<String>(
initialValue: f.units.contains(unit) ? unit : 'g',
isExpanded: true,
dropdownColor: card2,
decoration: const InputDecoration(labelText: 'Unit'),
items: [
for (final u in f.units)
DropdownMenuItem(value: u, child: Text(f.portions.any((p) => p.label == u)
? '$u (${num1(f.portions.firstWhere((p) => p.label == u).grams)} g)' : u, overflow: TextOverflow.ellipsis)),
],
onChanged: (u) => setState(() => unit = u!),
),
),
]),
const SizedBox(height: 10),
if (nut != null)
Row(children: [
Text('${(nut['kcal'] ?? 0).round()} kcal', style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
Text(' · ${num1(g!)} g · ', style: const TextStyle(color: muted)),
macroDots(nut),
]),
if (nut != null && (nut['fiber'] != null || nut['sugar'] != null))
Padding(
padding: const EdgeInsets.only(top: 3),
child: Text([
if (nut['fiber'] != null) 'fibre ${num1(nut['fiber']!)} g',
if (nut['sugar'] != null) 'sugar ${num1(nut['sugar']!)} g',
if (nut['sat_fat'] != null) 'sat. fat ${num1(nut['sat_fat']!)} g',
if (nut['sodium_mg'] != null) 'sodium ${nut['sodium_mg']!.round()} mg',
].join(' · '), style: const TextStyle(color: muted, fontSize: 12.5)),
),
_actions(),
]);
}
// ---- totals: an entry without a food
Widget _totalsForm() => Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
TextField(controller: name, decoration: const InputDecoration(labelText: 'What was it?')),
Row(children: [
SizedBox(width: 100, child: TextField(controller: amount, keyboardType: const TextInputType.numberWithOptions(decimal: true),
decoration: const InputDecoration(labelText: 'Amount'))),
const SizedBox(width: 12),
Expanded(child: TextField(controller: unitCtl, onChanged: (v) => unit = v.trim(),
decoration: const InputDecoration(labelText: 'Unit (g, pcs, bowl…)'))),
]),
Row(children: [
for (final (k, l) in [('kcal', 'kcal'), ('protein', 'Protein g'), ('carbs', 'Carbs g'), ('fat', 'Fat g')])
Expanded(child: Padding(
padding: const EdgeInsets.only(right: 8),
child: TextField(controller: totalsCtl[k], keyboardType: const TextInputType.numberWithOptions(decimal: true),
textInputAction: TextInputAction.next, decoration: InputDecoration(labelText: l)),
)),
]),
if (widget.entry != null && widget.entry!.source != 'manual')
Padding(padding: const EdgeInsets.only(top: 6),
child: Text('Imported from ${widget.entry!.source} — its other nutrients stay as they are.',
style: const TextStyle(color: muted, fontSize: 12.5))),
_actions(),
]);
Widget _actions() => Padding(
padding: const EdgeInsets.only(top: 12),
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
if (error != null) Padding(padding: const EdgeInsets.only(bottom: 6), child: Text(error!, style: const TextStyle(color: bad))),
Row(children: [
if (widget.entry != null)
TextButton.icon(
icon: Icon(Icons.delete_outline, color: armed ? Colors.white : bad),
style: TextButton.styleFrom(backgroundColor: armed ? const Color(0xFF8A2B2B) : null),
label: Text(armed ? 'Tap again to delete' : 'Delete', style: TextStyle(color: armed ? Colors.white : bad)),
onPressed: () {
if (!armed) return setState(() => armed = true);
widget.sync.store.delete('food.entry', widget.entry!.u);
_done();
},
),
const Spacer(),
FilledButton(onPressed: _save, child: Text(widget.entry == null ? 'Add' : 'Save')),
]),
]),
);
}

View file

@ -0,0 +1,309 @@
// Health ▸ Heart (as on the web page's Heart tab): heart rate from the band (the Pi's summaries:
// the latest day, resting, lowest / highest / resting per day), then the vitals — Blood pressure and
// Blood oxygen, each its own card: latest + category (ESC 2024 / SpO₂ bands), 30-day average, chart,
// the readings (tap = edit) and + Add.
import 'package:flutter/material.dart';
import '../app/sync_service.dart';
import '../app/theme.dart';
import '../widgets/line_chart.dart';
import 'body_model.dart';
import 'body_page.dart' show classColor, dm, dmy;
import 'cycle_model.dart' show day, parseDay, plus, today;
import 'range.dart';
import 'summaries.dart';
String _hm(DateTime t) => t.toIso8601String().substring(11, 16);
class HeartPage extends StatefulWidget {
const HeartPage({super.key, required this.sync, required this.range});
final SyncService sync;
final HealthRange range;
@override
State<HeartPage> createState() => _HeartPageState();
}
class _HeartPageState extends State<HeartPage> {
final shown = {'bp': 5, 'ox': 5};
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: Listenable.merge([widget.sync, widget.range]),
builder: (context, _) {
final all = vitals(widget.sync.store);
final bp = all.where((v) => v.isBp).toList(), ox = all.where((v) => v.spo2 != null).toList();
return LayoutBuilder(builder: (context, box) {
final cards = [_bp(bp), _ox(ox)];
final hrCard = _hr();
return ListView(padding: const EdgeInsets.fromLTRB(12, 12, 12, 24), children: [
if (hrCard != null) ...[hrCard, const SizedBox(height: 12)],
if (box.maxWidth >= 700)
Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
Expanded(child: cards[0]), const SizedBox(width: 12), Expanded(child: cards[1])])
else ...[cards[0], const SizedBox(height: 12), cards[1]],
]);
});
},
);
/// Heart rate from the band (the Pi's day summaries): the latest day's low – high, the resting rate
/// used for zones / calories, and lowest / highest / resting per day over the period.
Widget? _hr() {
final sm = Summaries(widget.sync.store);
final days = sm.all('day').where((x) => x['hr'] != null).toList();
if (days.isEmpty) return null;
final person = sm.meta('person') ?? {};
final last = days.last, h = (last['hr'] as Map).cast<String, dynamic>();
final from = widget.range.from(parseDay(days.first['_day'] as String), today());
List<(DateTime, double)> pts(String k) => [
for (final x in days)
if ((x['hr'] as Map)[k] != null) (parseDay(x['_day'] as String), ((x['hr'] as Map)[k] as num).toDouble())
];
final lastDay = parseDay(last['_day'] as String);
return Card(
child: Padding(
padding: const EdgeInsets.fromLTRB(14, 10, 8, 10),
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
Row(children: [
const Expanded(child: Text('Heart rate', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold))),
Tooltip(
triggerMode: TooltipTriggerMode.tap,
showDuration: const Duration(seconds: 8),
message: 'From your band (Gadgetbridge → the dashboard). Resting = the median of the last 90 days '
'${person['rest_set'] == true ? '(your setting)' : '(worked out)'}; max ${person['hrmax'] ?? '—'} bpm. '
'Zones and workout calories use both.',
child: const Padding(padding: EdgeInsets.all(6), child: Icon(Icons.info_outline, size: 18, color: muted)),
),
]),
Row(crossAxisAlignment: CrossAxisAlignment.end, children: [
Text('${h['low'] ?? '—'}–${h['high'] ?? '—'}', style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold)),
const Text(' bpm', style: TextStyle(color: muted)),
const Spacer(),
Column(crossAxisAlignment: CrossAxisAlignment.end, children: [
Text('resting ${person['rest'] ?? '—'} bpm', style: const TextStyle(color: good)),
Text(lastDay == today() ? 'today so far' : dm(lastDay), style: const TextStyle(color: muted, fontSize: 12.5)),
]),
const SizedBox(width: 6),
]),
const SizedBox(height: 10),
Padding(
padding: const EdgeInsets.only(right: 6),
child: LineChart(from: from, to: plus(today(), 1), unit: 'bpm', decimals: 0, range: widget.range, series: [
Series('Highest', pts('high'), bad),
Series('Lowest', pts('low'), const Color(0xFF5CC8FF)),
Series('Resting', pts('rest'), good),
]),
),
]),
),
);
}
/// The readings inside the charts' period (the latest is shown on top regardless).
List<Vital> _inPeriod(List<Vital> vs) => vs.where((v) => !day(v.t).isBefore(_from(vs))).toList();
DateTime _from(List<Vital> vs) => widget.range.from(vs.isEmpty ? today() : day(vs.last.t), today());
Widget _bp(List<Vital> vs) {
final last = vs.firstOrNull;
final listed = _inPeriod(vs);
final since = plus(today(), -30);
final month = vs.where((v) => !v.t.isBefore(since)).toList();
final avg = month.isEmpty ? null : (
(month.map((v) => v.sys!).reduce((a, b) => a + b) / month.length).round(),
(month.map((v) => v.dia!).reduce((a, b) => a + b) / month.length).round());
final c = bpClass(last?.sys, last?.dia);
return _VitalCard(
title: 'Blood pressure',
head: last == null ? 'No readings yet' : '${last.sys} / ${last.dia} mmHg',
sub: last == null ? '' : '${c!.$1} · ${dm(last.t)} ${_hm(last.t)}',
subColor: classColor(c?.$2),
extra: avg == null ? null : '30-day average ${avg.$1} / ${avg.$2} (${month.length} reading${month.length != 1 ? 's' : ''})',
info: 'ESC 2024 (office readings): under 120 / 70 non-elevated · 120–139 / 70–89 elevated · 140 / 90+ hypertension · '
'180 / 110+ severe. The higher of the two numbers decides; the average of several readings on different days is what counts.',
chart: vs.isEmpty ? null : LineChart(from: _from(vs), to: plus(today(), 1), unit: 'mmHg', decimals: 0, range: widget.range, series: [
Series('Systolic', vitalSeries(vs, (v) => v.sys?.toDouble()), accent),
Series('Diastolic', vitalSeries(vs, (v) => v.dia?.toDouble()), const Color(0xFF5CC8FF)),
]),
rows: [
if (listed.isEmpty && vs.isNotEmpty) const Padding(padding: EdgeInsets.symmetric(vertical: 6),
child: Text('No readings in this period', style: TextStyle(color: muted))),
for (final v in listed.take(shown['bp']!))
_ReadingRow(v, '${v.sys} / ${v.dia}', classColor(bpClass(v.sys, v.dia)?.$2), () => _edit('bp', v)),
],
more: listed.length - shown['bp']!,
onMore: () => setState(() => shown['bp'] = shown['bp']! + 10),
onAdd: () => _edit('bp', null),
);
}
Widget _ox(List<Vital> vs) {
final last = vs.firstOrNull;
final listed = _inPeriod(vs);
final c = spo2Class(last?.spo2);
return _VitalCard(
title: 'Blood oxygen',
head: last == null ? 'No readings yet' : '${last.spo2!.round()} %',
sub: last == null ? '' : '${c!.$1} · ${dm(last.t)} ${_hm(last.t)}${last.source != null ? ' · ${vitalSources[last.source] ?? last.source}' : ''}',
subColor: classColor(c?.$2),
info: 'At rest: 95–100 % normal · 91–94 % low · 90 % or less very low (see a doctor). Wrist sensors read a couple of % low '
'now and then — a single low spot check isn\'t a verdict.',
chart: vs.isEmpty ? null : LineChart(from: _from(vs), to: plus(today(), 1), unit: '%', decimals: 0, band: (95, 100), limits: (85, 100), range: widget.range,
series: [Series('SpO₂', vitalSeries(vs, (v) => v.spo2), accent)]),
rows: [
if (listed.isEmpty && vs.isNotEmpty) const Padding(padding: EdgeInsets.symmetric(vertical: 6),
child: Text('No readings in this period', style: TextStyle(color: muted))),
for (final v in listed.take(shown['ox']!))
_ReadingRow(v, '${v.spo2!.round()} %', classColor(spo2Class(v.spo2)?.$2), () => _edit('ox', v)),
],
more: listed.length - shown['ox']!,
onMore: () => setState(() => shown['ox'] = shown['ox']! + 10),
onAdd: () => _edit('ox', null),
);
}
Future<void> _edit(String kind, Vital? v) => showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: card,
builder: (_) => VitalSheet(kind: kind, v: v, sync: widget.sync),
);
}
class _VitalCard extends StatelessWidget {
const _VitalCard({required this.title, required this.head, required this.sub, required this.subColor, this.extra,
required this.info, required this.chart, required this.rows, required this.more, required this.onMore, required this.onAdd});
final String title, head, sub, info;
final String? extra;
final Color subColor;
final Widget? chart;
final List<Widget> rows;
final int more;
final VoidCallback onMore, onAdd;
@override
Widget build(BuildContext context) => Card(
child: Padding(
padding: const EdgeInsets.fromLTRB(14, 10, 8, 10),
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
Row(children: [
Expanded(child: Text(title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold))),
Tooltip(triggerMode: TooltipTriggerMode.tap, message: info, showDuration: const Duration(seconds: 8),
child: const Padding(padding: EdgeInsets.all(6), child: Icon(Icons.info_outline, size: 18, color: muted))),
TextButton.icon(onPressed: onAdd, icon: const Icon(Icons.add, size: 18), label: const Text('Add')),
]),
Text(head, style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold)),
if (sub.isNotEmpty) Text(sub, style: TextStyle(color: subColor)),
if (extra != null) Text(extra!, style: const TextStyle(color: muted, fontSize: 13)),
if (chart != null) ...[const SizedBox(height: 10), Padding(padding: const EdgeInsets.only(right: 6), child: chart!)],
...rows,
if (more > 0) TextButton(onPressed: onMore, child: Text('Show more ($more)')),
]),
),
);
}
class _ReadingRow extends StatelessWidget {
const _ReadingRow(this.v, this.value, this.color, this.onTap);
final Vital v;
final String value;
final Color color;
final VoidCallback onTap;
@override
Widget build(BuildContext context) => InkWell(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: Row(children: [
SizedBox(width: 160, child: Text('${v.t.year == today().year ? dm(v.t) : dmy(v.t)} ${_hm(v.t)}', maxLines: 1,
style: const TextStyle(color: muted))),
SizedBox(width: 72, child: Text(value, style: TextStyle(color: color))),
Expanded(child: Text(v.note.isNotEmpty ? v.note : vitalSources[v.source] ?? '', overflow: TextOverflow.ellipsis,
style: const TextStyle(color: muted, fontSize: 13))),
]),
),
);
}
/// Add / edit one reading: date + time, the numbers of its kind, note; Delete = tap twice.
class VitalSheet extends StatefulWidget {
const VitalSheet({super.key, required this.kind, required this.v, required this.sync});
final String kind;
final Vital? v;
final SyncService sync;
@override
State<VitalSheet> createState() => _VitalSheetState();
}
class _VitalSheetState extends State<VitalSheet> {
late DateTime t = widget.v?.t ?? () {
final n = DateTime.now();
return DateTime.utc(n.year, n.month, n.day, n.hour, n.minute);
}();
late final sys = TextEditingController(text: widget.v?.sys?.toString() ?? '');
late final dia = TextEditingController(text: widget.v?.dia?.toString() ?? '');
late final ox = TextEditingController(text: widget.v?.spo2 == null ? '' : widget.v!.spo2!.round().toString());
late final note = TextEditingController(text: widget.v?.note ?? '');
String? error;
bool armed = false;
@override
Widget build(BuildContext context) {
final bp = widget.kind == 'bp';
return Padding(
padding: EdgeInsets.fromLTRB(16, 16, 16, 16 + MediaQuery.of(context).viewInsets.bottom),
child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
Text('${widget.v == null ? 'Add' : 'Edit'} ${bp ? 'blood pressure' : 'blood oxygen'}',
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)),
Row(children: [
TextButton.icon(icon: const Icon(Icons.event, size: 18), label: Text(dmy(t)), onPressed: () async {
final p = await showDatePicker(context: context, initialDate: t, firstDate: DateTime.utc(2000), lastDate: today());
if (p != null) setState(() => t = DateTime.utc(p.year, p.month, p.day, t.hour, t.minute));
}),
TextButton.icon(icon: const Icon(Icons.schedule, size: 18), label: Text(_hm(t)), onPressed: () async {
final p = await showTimePicker(context: context, initialTime: TimeOfDay(hour: t.hour, minute: t.minute));
if (p != null) setState(() => t = DateTime.utc(t.year, t.month, t.day, p.hour, p.minute));
}),
]),
if (bp)
Row(children: [
Expanded(child: TextField(controller: sys, keyboardType: TextInputType.number, autofocus: widget.v == null,
textInputAction: TextInputAction.next,
decoration: const InputDecoration(labelText: 'Systolic (upper)', suffixText: 'mmHg'))),
const SizedBox(width: 12),
Expanded(child: TextField(controller: dia, keyboardType: TextInputType.number,
decoration: const InputDecoration(labelText: 'Diastolic (lower)', suffixText: 'mmHg'))),
])
else
TextField(controller: ox, keyboardType: const TextInputType.numberWithOptions(decimal: true), autofocus: widget.v == null,
decoration: const InputDecoration(labelText: 'Blood oxygen', suffixText: '%')),
TextField(controller: note, maxLength: 500, decoration: const InputDecoration(labelText: 'Note')),
if (error != null) Text(error!, style: const TextStyle(color: bad)),
Row(children: [
if (widget.v != null)
TextButton(
onPressed: () {
if (!armed) return setState(() => armed = true);
widget.sync.store.delete('health.vital', widget.v!.u);
widget.sync.changed();
Navigator.pop(context);
},
child: Text(armed ? 'Tap again to delete' : 'Delete', style: const TextStyle(color: bad)),
),
const Spacer(),
FilledButton(
onPressed: () {
final err = saveVital(widget.sync.store, u: widget.v?.u, kind: widget.kind, t: t,
sys: int.tryParse(sys.text.trim()), dia: int.tryParse(dia.text.trim()),
spo2: double.tryParse(ox.text.trim().replaceAll(',', '.')), note: note.text);
if (err != null) return setState(() => error = err);
widget.sync.changed();
Navigator.pop(context);
},
child: const Text('Save'),
),
]),
]),
);
}
}

View file

@ -0,0 +1,314 @@
// The meal builder (the web page's #fd-meal): a meal = one of My foods made of others. Name,
// ingredients (a food + amount + unit, or an entry's own numbers), the total, "weight when done"
// (soup boils down / takes on water; empty = the ingredients' sum), per 100 g, portions ("whole meal"
// is added by itself), note. Saving works the values out from the ingredients as they are now.
// Ways in: My foods (a meal, or + ▸ New meal) and Food ⋮ ▸ Make a meal (from the day's entries:
// "put them together as one entry" replaces them by one entry of the meal — the day's total stays).
import 'package:flutter/material.dart';
import '../app/sync_service.dart';
import '../app/theme.dart';
import 'food_model.dart';
import 'food_page.dart' show macroDots;
import 'sugar.dart' show fold;
/// Search My foods + the database and pick one (for an ingredient).
Future<Food?> pickFood(BuildContext context, SyncService sync, FoodDb? fdb) => showModalBottomSheet<Food>(
context: context,
isScrollControlled: true,
backgroundColor: card,
builder: (_) => _Picker(sync: sync, fdb: fdb),
);
class _Picker extends StatefulWidget {
const _Picker({required this.sync, required this.fdb});
final SyncService sync;
final FoodDb? fdb;
@override
State<_Picker> createState() => _PickerState();
}
class _PickerState extends State<_Picker> {
final q = TextEditingController();
@override
Widget build(BuildContext context) {
final t = q.text.trim();
final my = t.isEmpty ? <Food>[] : myFoods(widget.sync.store, t);
final kept = t.isEmpty ? <Food>[] : keptProducts(widget.sync.store, t, fold: fold); // picked from the archive before
final db = t.isEmpty ? <Food>[] : [...kept, ...(widget.fdb?.search(t, limit: 12) ?? []).where((f) => !kept.any((k) => k.foodId == f.foodId))];
Widget tile(Food f) => ListTile(
dense: true,
contentPadding: EdgeInsets.zero,
title: Text(f.name),
subtitle: Text([
if (f.kind == 'my') f.isMeal ? 'My meal' : 'My food' else if (f.kind == 'off') f.brand ?? 'product' else f.category,
'${(f.per100['kcal'] ?? 0).round()} kcal / 100 g',
].join(' · '), style: const TextStyle(color: muted)),
onTap: () => Navigator.pop(context, f),
);
return Padding(
padding: EdgeInsets.fromLTRB(16, 14, 16, 12 + MediaQuery.of(context).viewInsets.bottom),
child: ConstrainedBox(
constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.75),
child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
const Text('Add an ingredient', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)),
TextField(controller: q, autofocus: true, onChanged: (_) => setState(() {}),
decoration: const InputDecoration(prefixIcon: Icon(Icons.search), hintText: 'Search foods…')),
Flexible(child: ListView(shrinkWrap: true, children: [
if (my.isNotEmpty) const Padding(padding: EdgeInsets.only(top: 8), child: Text('My foods', style: TextStyle(color: muted, fontSize: 12.5))),
...my.map(tile),
if (db.isNotEmpty) const Padding(padding: EdgeInsets.only(top: 8), child: Text('Food database · products', style: TextStyle(color: muted, fontSize: 12.5))),
...db.map(tile),
])),
]),
),
);
}
}
/// The day's entries to tick for a meal → (picked entries) or null; "from scratch" = [].
Future<List<Entry>?> pickEntries(BuildContext context, List<Entry> es) => showModalBottomSheet<List<Entry>>(
context: context,
isScrollControlled: true,
backgroundColor: card,
builder: (_) => _EntryPicker(es),
);
class _EntryPicker extends StatefulWidget {
const _EntryPicker(this.es);
final List<Entry> es;
@override
State<_EntryPicker> createState() => _EntryPickerState();
}
class _EntryPickerState extends State<_EntryPicker> {
final picked = <String>{};
@override
Widget build(BuildContext context) => Padding(
padding: const EdgeInsets.fromLTRB(16, 14, 16, 12),
child: ConstrainedBox(
constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.75),
child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
const Text('Make a meal', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)),
const Text('Tick what went into it — or start from scratch.', style: TextStyle(color: muted)),
Flexible(child: ListView(shrinkWrap: true, children: [
for (final e in widget.es)
CheckboxListTile(
dense: true,
contentPadding: EdgeInsets.zero,
value: picked.contains(e.u),
onChanged: (x) => setState(() => x! ? picked.add(e.u) : picked.remove(e.u)),
title: Text(e.name),
subtitle: Text('${mealLabels[e.meal]} · ${e.portion.isEmpty ? '' : '${e.portion} · '}${e.kcal.round()} kcal',
style: const TextStyle(color: muted)),
),
])),
Row(children: [
TextButton(onPressed: () => Navigator.pop(context, <Entry>[]), child: const Text('Start from scratch')),
const Spacer(),
FilledButton(
onPressed: picked.isEmpty ? null : () => Navigator.pop(context, widget.es.where((e) => picked.contains(e.u)).toList()),
child: Text('Next (${picked.length})'),
),
]),
]),
),
);
}
class MealBuilder extends StatefulWidget {
/// [row] = the meal being edited; [fromEntries] = entries to build it from (they may be replaced).
const MealBuilder({super.key, required this.sync, required this.fdb, this.row, this.fromEntries = const []});
final SyncService sync;
final FoodDb? fdb;
final Map<String, dynamic>? row;
final List<Entry> fromEntries;
@override
State<MealBuilder> createState() => _MealBuilderState();
}
class _MealBuilderState extends State<MealBuilder> {
late final name = TextEditingController(text: widget.row?['name'] as String? ?? '');
late final note = TextEditingController(text: widget.row?['note'] as String? ?? '');
late final done = TextEditingController(
text: widget.row == null || doneGramsOf(widget.row!) == null ? '' : num1(doneGramsOf(widget.row!)!));
late final List<Ingredient> ings = widget.row != null
? recipeOf(widget.sync.store, widget.fdb, widget.row!)
: [for (final e in widget.fromEntries) _fromEntry(e)];
late final amounts = [for (final i in ings) TextEditingController(text: i.amount == null ? '' : num1(i.amount!))];
late final portions = [
for (final p in (widget.row == null ? <Portion>[] : myFood(widget.row!).portions).where((p) => p.label != 'whole meal'))
(TextEditingController(text: p.label), TextEditingController(text: num1(p.grams)))
];
bool together = true, armed = false;
String? error;
Ingredient _fromEntry(Entry e) {
final f = foodOf(widget.sync.store, widget.fdb, e);
if (f != null && e.amount != null && e.unit != null && f.units.contains(e.unit)) return Ingredient.food(f, e.amount, e.unit);
// its grams when known — an amount in g / ml is its weight
final g = e.n('grams') ?? (e.amount != null && (e.unit == 'g' || e.unit == 'ml') ? e.amount : null);
return Ingredient.fixed({for (final c in foodCols) c: e.n(c)}, e.name, e.amount, e.unit, g);
}
double? _n(TextEditingController c) => double.tryParse(c.text.trim().replaceAll(',', '.'));
Future<void> _add() async {
final f = await pickFood(context, widget.sync, widget.fdb);
if (f == null) return;
setState(() {
final unit = f.portions.isNotEmpty ? f.portions.first.label : 'g';
ings.add(Ingredient.food(f, unit == 'g' ? 100 : 1, unit));
amounts.add(TextEditingController(text: unit == 'g' ? '100' : '1'));
});
}
void _save() {
for (var i = 0; i < ings.length; i++) {
ings[i].amount = _n(amounts[i]);
}
final ps = [for (final (l, g) in portions) if (l.text.trim().isNotEmpty || g.text.trim().isNotEmpty) Portion(l.text, _n(g) ?? 0)];
final store = widget.sync.store;
final (uid, err) = saveMeal(store, uid: widget.row?['_u'] as String?, name: name.text, ings: ings,
doneGrams: _n(done), portions: ps, note: note.text);
if (err != null) return setState(() => error = err);
if (widget.fromEntries.isNotEmpty && together) {
// one entry of the meal (its whole weight) replaces the picked ones: their day, the most common meal
final es = widget.fromEntries;
final counts = <String, int>{};
for (final e in es) {
counts[e.meal] = (counts[e.meal] ?? 0) + 1;
}
final meal = (counts.entries.toList()..sort((a, b) => b.value.compareTo(a.value))).first.key;
saveFromFood(store, day: es.first.day, meal: meal.isEmpty ? 'snack' : meal, food: myFoodByUid(store, uid!)!,
amount: 1, unit: 'whole meal');
for (final e in es) {
store.delete('food.entry', e.u);
}
}
widget.sync.changed();
Navigator.pop(context, uid);
}
@override
Widget build(BuildContext context) {
for (var i = 0; i < ings.length; i++) {
ings[i].amount = _n(amounts[i]);
}
final tot = <String, double>{};
var grams = 0.0;
for (final i in ings) {
i.values.forEach((c, v) {
if (v != null) tot[c] = (tot[c] ?? 0) + v;
});
grams += i.g ?? 0;
}
final weight = _n(done) ?? grams;
return Scaffold(
appBar: AppBar(title: Text(widget.row == null ? 'New meal' : 'Edit meal')),
body: ListView(padding: const EdgeInsets.fromLTRB(16, 8, 16, 24), children: [
TextField(controller: name, decoration: const InputDecoration(labelText: 'Name (e.g. “Cabbage soup (20th Oct 2026)”)')),
const SizedBox(height: 14),
Row(children: [
const Expanded(child: Text('Ingredients', style: TextStyle(fontWeight: FontWeight.bold))),
TextButton.icon(onPressed: _add, icon: const Icon(Icons.add, size: 18), label: const Text('Ingredient')),
]),
for (var i = 0; i < ings.length; i++) _ing(i),
if (ings.isEmpty) const Text('Nothing yet — + Ingredient.', style: TextStyle(color: muted)),
const Divider(color: card2, height: 24),
Row(children: [
const Text('All together ', style: TextStyle(color: muted)),
Text('${(tot['kcal'] ?? 0).round()} kcal · ${num1(grams)} g', style: const TextStyle(fontWeight: FontWeight.bold)),
const SizedBox(width: 8),
macroDots(tot),
]),
TextField(controller: done, keyboardType: const TextInputType.numberWithOptions(decimal: true), onChanged: (_) => setState(() {}),
decoration: InputDecoration(labelText: 'Weight when done (empty = ${num1(grams)} g)', suffixText: 'g')),
if (weight > 0)
Padding(padding: const EdgeInsets.only(top: 6), child: Text(
'Per 100 g: ${((tot['kcal'] ?? 0) * 100 / weight).round()} kcal · '
'P ${num1((tot['protein'] ?? 0) * 100 / weight)} · C ${num1((tot['carbs'] ?? 0) * 100 / weight)} · '
'F ${num1((tot['fat'] ?? 0) * 100 / weight)} g', style: const TextStyle(color: muted))),
const SizedBox(height: 12),
Row(children: [
const Expanded(child: Text('Portions (“whole meal” is added by itself)', style: TextStyle(color: muted, fontSize: 13))),
TextButton.icon(onPressed: () => setState(() => portions.add((TextEditingController(), TextEditingController()))),
icon: const Icon(Icons.add, size: 18), label: const Text('Portion')),
]),
for (var i = 0; i < portions.length; i++)
Row(children: [
Expanded(flex: 3, child: TextField(controller: portions[i].$1, decoration: const InputDecoration(hintText: 'bowl, plate…', isDense: true))),
const SizedBox(width: 10),
Expanded(flex: 2, child: TextField(controller: portions[i].$2, keyboardType: const TextInputType.numberWithOptions(decimal: true),
decoration: const InputDecoration(suffixText: 'g', isDense: true))),
IconButton(onPressed: () => setState(() => portions.removeAt(i)), icon: const Icon(Icons.close, size: 18, color: muted)),
]),
TextField(controller: note, decoration: const InputDecoration(labelText: 'Note')),
if (widget.fromEntries.isNotEmpty)
CheckboxListTile(
contentPadding: EdgeInsets.zero,
value: together,
onChanged: (x) => setState(() => together = x!),
title: Text('Put the ${widget.fromEntries.length} picked entries together in the diary as one entry'),
subtitle: const Text('the day’s total stays the same', style: TextStyle(color: muted)),
),
if (error != null) Padding(padding: const EdgeInsets.only(top: 8), child: Text(error!, style: const TextStyle(color: bad))),
const SizedBox(height: 12),
Row(children: [
if (widget.row != null)
TextButton.icon(
icon: Icon(Icons.delete_outline, color: armed ? Colors.white : bad),
style: TextButton.styleFrom(backgroundColor: armed ? const Color(0xFF8A2B2B) : null),
label: Text(armed ? 'Tap again to delete' : 'Delete', style: TextStyle(color: armed ? Colors.white : bad)),
onPressed: () {
if (!armed) return setState(() => armed = true);
deleteMyFood(widget.sync.store, widget.row!['_u'] as String);
widget.sync.changed();
Navigator.pop(context);
},
),
const Spacer(),
FilledButton(onPressed: _save, child: const Text('Save')),
]),
]),
);
}
Widget _ing(int i) {
final ing = ings[i];
final v = ing.values;
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Row(children: [
Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text(ing.name, maxLines: 2, overflow: TextOverflow.ellipsis),
Text(ing.food == null ? 'its own numbers${ing.grams == null ? ' · no weight' : ' · ${num1(ing.grams!)} g'}'
: '${(v['kcal'] ?? 0).round()} kcal${ing.g == null ? '' : ' · ${num1(ing.g!)} g'}',
style: const TextStyle(color: muted, fontSize: 12.5)),
])),
if (ing.food != null) ...[
SizedBox(width: 64, child: TextField(controller: amounts[i], keyboardType: const TextInputType.numberWithOptions(decimal: true),
onChanged: (_) => setState(() {}), decoration: const InputDecoration(isDense: true))),
const SizedBox(width: 8),
SizedBox(
width: 110,
child: DropdownButton<String>(
value: ing.food!.units.contains(ing.unit) ? ing.unit : 'g',
isExpanded: true,
dropdownColor: card2,
items: [for (final u in ing.food!.units) DropdownMenuItem(value: u, child: Text(u, overflow: TextOverflow.ellipsis))],
onChanged: (u) => setState(() => ing.unit = u),
),
),
] else
Text('${(v['kcal'] ?? 0).round()} kcal', style: const TextStyle(fontWeight: FontWeight.bold)),
IconButton(onPressed: () => setState(() {
ings.removeAt(i);
amounts.removeAt(i);
}), icon: const Icon(Icons.close, size: 18, color: muted)),
]),
);
}
}

View file

@ -0,0 +1,219 @@
// Food ▸ My foods: your own food database (values per 100 g, portions) — the list (tap = edit; a meal
// opens the meal builder), + New food / New meal, and the food editor sheet (also opened from the add
// sheet's "+ New food").
// Delete = hidden (entries made from it keep their numbers), tap twice.
import 'dart:convert';
import 'package:flutter/material.dart';
import '../app/sync_service.dart';
import '../app/theme.dart';
import 'food_model.dart';
import 'meal_builder.dart';
class MyFoodsPage extends StatelessWidget {
const MyFoodsPage({super.key, required this.sync});
final SyncService sync;
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('My foods')),
floatingActionButton: FloatingActionButton(
backgroundColor: accent,
foregroundColor: bg,
tooltip: 'New food',
onPressed: () => showModalBottomSheet(
context: context,
backgroundColor: card,
builder: (c) => SafeArea(child: Column(mainAxisSize: MainAxisSize.min, children: [
ListTile(leading: const Icon(Icons.label_outline), title: const Text('New food'),
subtitle: const Text('from its label', style: TextStyle(color: muted)),
onTap: () {
Navigator.pop(c);
openFoodEditor(context, sync);
}),
ListTile(leading: const Icon(Icons.soup_kitchen_outlined), title: const Text('New meal'),
subtitle: const Text('from its ingredients', style: TextStyle(color: muted)),
onTap: () async {
Navigator.pop(c);
final fdb = await FoodDb.open();
if (context.mounted) {
Navigator.push(context, MaterialPageRoute(builder: (_) => MealBuilder(sync: sync, fdb: fdb)));
}
}),
])),
),
child: const Icon(Icons.add),
),
body: ListenableBuilder(
listenable: sync,
builder: (context, _) {
final all = allMyFoods(sync.store);
if (all.isEmpty) {
return const Center(child: Text('None yet — + to add a food from its label.', style: TextStyle(color: muted)));
}
return ListView(padding: const EdgeInsets.fromLTRB(12, 8, 12, 88), children: [
for (final (r, uses) in all)
Card(
margin: const EdgeInsets.only(bottom: 8),
child: ListTile(
title: Text(r['name'] as String),
subtitle: Text([
'${((r['kcal'] as num?) ?? 0).round()} kcal / 100 g',
if (r['recipe'] != null) 'meal',
...((jsonDecode((r['portions'] as String?) ?? '[]') as List).map((p) => '${p['label']} ${num1((p['grams'] as num).toDouble())} g')),
if (uses > 0) 'used $uses×',
].join(' · '), style: const TextStyle(color: muted)),
onTap: () async {
if (r['recipe'] == null) {
await openFoodEditor(context, sync, row: r);
return;
}
final fdb = await FoodDb.open();
if (context.mounted) {
Navigator.push(context, MaterialPageRoute(builder: (_) => MealBuilder(sync: sync, fdb: fdb, row: r)));
}
},
),
),
]);
},
),
);
}
/// The editor as a bottom sheet; → the saved food's id (null = cancelled / deleted).
Future<String?> openFoodEditor(BuildContext context, SyncService sync, {Map<String, dynamic>? row, String name = ''}) =>
showModalBottomSheet<String>(
context: context,
isScrollControlled: true,
backgroundColor: card,
builder: (_) => FoodEditor(sync: sync, row: row, name: name),
);
class FoodEditor extends StatefulWidget {
const FoodEditor({super.key, required this.sync, this.row, this.name = ''});
final SyncService sync;
final Map<String, dynamic>? row;
final String name;
@override
State<FoodEditor> createState() => _FoodEditorState();
}
class _FoodEditorState extends State<FoodEditor> {
late final name = TextEditingController(text: widget.row?['name'] as String? ?? widget.name);
late final note = TextEditingController(text: widget.row?['note'] as String? ?? '');
late String sugarKind = widget.row?['sugar_kind'] as String? ?? ''; // '' = estimated (sugar.dart)
late final values = {
for (final k in foodFields.keys)
k: TextEditingController(text: widget.row?[k] == null ? '' : num1((widget.row![k] as num).toDouble()))
};
late final portions = [
for (final p in (jsonDecode((widget.row?['portions'] as String?) ?? '[]') as List).cast<Map<String, dynamic>>())
(TextEditingController(text: p['label'] as String), TextEditingController(text: num1((p['grams'] as num).toDouble())))
];
String? error;
bool armed = false;
bool get isMeal => widget.row?['recipe'] != null;
double? _n(TextEditingController c) => double.tryParse(c.text.trim().replaceAll(',', '.'));
void _save() {
final ps = <Portion>[];
for (final (l, g) in portions) {
if (l.text.trim().isEmpty && g.text.trim().isEmpty) continue;
ps.add(Portion(l.text, _n(g) ?? 0));
}
final (uid, err) = saveMyFood(widget.sync.store, uid: widget.row?['_u'] as String?, name: name.text,
per100: isMeal ? {for (final k in foodFields.keys) k: (widget.row![k] as num?)?.toDouble()} : {for (final e in values.entries) e.key: _n(e.value)},
portions: ps, note: note.text, sugarKind: sugarKind);
if (err != null) return setState(() => error = err);
widget.sync.changed();
Navigator.pop(context, uid);
}
@override
Widget build(BuildContext context) => Padding(
padding: EdgeInsets.fromLTRB(16, 16, 16, 12 + MediaQuery.of(context).viewInsets.bottom),
child: SingleChildScrollView(
child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
Text(widget.row == null ? 'New food' : isMeal ? 'Meal' : 'Edit food',
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)),
TextField(controller: name, autofocus: widget.row == null && widget.name.isEmpty,
decoration: const InputDecoration(labelText: 'Name')),
const SizedBox(height: 10),
Text(isMeal ? 'Per 100 g — from its ingredients (change them with the meal builder)' : 'Per 100 g (from the label)',
style: const TextStyle(color: muted, fontSize: 13)),
GridView.count(
crossAxisCount: 2, shrinkWrap: true, physics: const NeverScrollableScrollPhysics(),
crossAxisSpacing: 12, childAspectRatio: 3.2,
children: [
for (final e in foodFields.entries)
TextField(
controller: values[e.key],
enabled: !isMeal,
autofocus: widget.row == null && widget.name.isNotEmpty && e.key == 'kcal',
keyboardType: const TextInputType.numberWithOptions(decimal: true),
textInputAction: TextInputAction.next,
decoration: InputDecoration(labelText: e.value.$1, suffixText: e.value.$2),
),
],
),
const SizedBox(height: 10),
Row(children: [
const Expanded(child: Text('Portions', style: TextStyle(color: muted, fontSize: 13))),
TextButton.icon(
onPressed: () => setState(() => portions.add((TextEditingController(), TextEditingController()))),
icon: const Icon(Icons.add, size: 18), label: const Text('Portion'),
),
]),
for (var i = 0; i < portions.length; i++)
Row(children: [
Expanded(flex: 3, child: TextField(controller: portions[i].$1,
decoration: const InputDecoration(hintText: 'slice, pot, bowl…', isDense: true))),
const SizedBox(width: 10),
Expanded(flex: 2, child: TextField(controller: portions[i].$2,
keyboardType: const TextInputType.numberWithOptions(decimal: true),
decoration: const InputDecoration(suffixText: 'g', isDense: true))),
IconButton(onPressed: () => setState(() => portions.removeAt(i)), icon: const Icon(Icons.close, size: 18, color: muted)),
]),
TextField(controller: note, decoration: const InputDecoration(labelText: 'Note')),
// when the added-sugar estimate gets this one wrong (homemade jam, unsweetened yogurt …)
Row(children: [
const Expanded(child: Text('Sugar counts as', style: TextStyle(color: muted))),
DropdownButton<String>(
value: sugarKind,
underline: const SizedBox(),
dropdownColor: card2,
items: const [
DropdownMenuItem(value: '', child: Text('estimated')),
DropdownMenuItem(value: 'added', child: Text('all added')),
DropdownMenuItem(value: 'dairy', child: Text('milk\'s own, beyond it added')),
DropdownMenuItem(value: 'natural', child: Text('natural (none added)')),
],
onChanged: (v) => setState(() => sugarKind = v ?? ''),
),
]),
if (error != null) Padding(padding: const EdgeInsets.only(top: 8), child: Text(error!, style: const TextStyle(color: bad))),
const SizedBox(height: 10),
Row(children: [
if (widget.row != null)
TextButton.icon(
icon: Icon(Icons.delete_outline, color: armed ? Colors.white : bad),
style: TextButton.styleFrom(backgroundColor: armed ? const Color(0xFF8A2B2B) : null),
label: Text(armed ? 'Tap again to delete' : 'Delete', style: TextStyle(color: armed ? Colors.white : bad)),
onPressed: () {
if (!armed) return setState(() => armed = true);
deleteMyFood(widget.sync.store, widget.row!['_u'] as String);
widget.sync.changed();
Navigator.pop(context);
},
),
const Spacer(),
FilledButton(onPressed: _save, child: const Text('Save')),
]),
]),
),
);
}

View file

@ -0,0 +1,120 @@
// Health ▸ Overview: today at a glance — the food eaten today (the Food page's day card), last night's
// sleep (Sleep's night card, or that it isn't in yet), then steps today | the next period. Each part's
// heading opens its page.
import 'package:flutter/material.dart';
import '../app/sync_service.dart';
import '../app/theme.dart';
import 'activity_page.dart' show thousands;
import 'cycle_model.dart' show CycleSettings, CycleView, Status, iso, parseDay, plus, today;
import 'cycle_page.dart' show cycleStatus;
import 'food_model.dart' show FoodDb;
import 'food_page.dart' show FoodDayCard;
import 'body_page.dart' show dm;
import 'sleep_page.dart' show Night, NightCard;
import 'summaries.dart';
class OverviewPage extends StatefulWidget {
const OverviewPage({super.key, required this.sync, required this.onFood});
final SyncService sync;
final VoidCallback onFood; // → the Food section
@override
State<OverviewPage> createState() => _OverviewPageState();
}
class _OverviewPageState extends State<OverviewPage> {
FoodDb? fdb;
@override
void initState() {
super.initState();
FoodDb.open().then((x) => mounted ? setState(() => fdb = x) : null);
}
void _tab(String name) {
const tabs = ['Overview', 'Cycle', 'Body', 'Sleep', 'Heart', 'Activity'];
DefaultTabController.of(context).animateTo(tabs.indexOf(name));
}
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: widget.sync,
builder: (context, _) {
final sm = Summaries(widget.sync.store);
final now = today();
final nights = [for (final x in sm.all('night', a: iso(plus(now, -400)))) Night(parseDay(x['_day'] as String), x)];
final goal = (((sm.meta('sleep') ?? {})['goal'] as num?) ?? 8).toDouble();
final last = nights.isNotEmpty && nights.last.day == now;
final steps = sm.day(iso(now))?['steps'] as num?;
final week = [for (var k = 1; k <= 7; k++) sm.day(iso(plus(now, -k)))?['steps'] as num?].whereType<num>().toList();
final cv = CycleView(widget.sync.store, const CycleSettings());
var (head, sub) = cycleStatus(cv);
if (cv.status == Status.wait) head = cv.daysToNext == 0 ? 'today' : 'in ${cv.daysToNext} ${cv.daysToNext == 1 ? 'day' : 'days'}';
if (cv.status == Status.period) head = 'day ${cv.cycleDay}';
final wide = MediaQuery.of(context).size.width >= 700;
final food = Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
_heading('Food today', widget.onFood),
FoodDayCard(sync: widget.sync, day: now, fdb: fdb),
]);
final sleep = Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
_heading('Sleep', () => _tab('Sleep')),
if (last)
NightCard(all: nights, i: nights.length - 1, goal: goal)
else
Card(child: Padding(
padding: const EdgeInsets.all(16),
child: Text(
'Last night isn\'t logged yet${nights.isEmpty ? '' : ' — the latest is the night to ${dm(nights.last.day)}'}. '
'It comes from the band once Gadgetbridge has exported and the dashboard has synced.',
style: const TextStyle(color: muted)),
)),
]);
final tiles = Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
Expanded(child: _tile('Steps today', steps == null ? '—' : thousands(steps),
week.isEmpty ? 'nothing from the band yet' : 'last 7 days: ${thousands(week.reduce((a, b) => a + b) / week.length)} a day',
() => _tab('Activity'))),
const SizedBox(width: 10),
Expanded(child: _tile(cv.status == Status.period ? 'Period' : 'Next period', head, sub, () => _tab('Cycle'),
color: cv.status == Status.late ? bad : cv.status == Status.period ? const Color(0xFFFF6B7A) : null)),
]);
return ListView(padding: const EdgeInsets.fromLTRB(12, 4, 12, 24), children: [
if (wide)
Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
Expanded(child: food),
const SizedBox(width: 12),
Expanded(child: Column(children: [sleep, const SizedBox(height: 12), tiles])),
])
else ...[food, const SizedBox(height: 4), sleep, const SizedBox(height: 12), tiles],
]);
},
);
Widget _heading(String title, VoidCallback go) => InkWell(
onTap: go,
child: Padding(
padding: const EdgeInsets.fromLTRB(4, 8, 4, 8),
child: Row(children: [
Text(title, style: const TextStyle(color: muted, fontSize: 13, fontWeight: FontWeight.bold, letterSpacing: .5)),
const Icon(Icons.chevron_right, size: 18, color: muted),
]),
),
);
Widget _tile(String label, String value, String sub, VoidCallback go, {Color? color}) => Card(
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: go,
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text(label.toUpperCase(), style: const TextStyle(color: muted, fontSize: 11.5)),
const SizedBox(height: 2),
Text(value, style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: color)),
const SizedBox(height: 2),
Text(sub, style: const TextStyle(color: muted, fontSize: 12)),
]),
),
),
);
}

27
app/lib/health/range.dart Normal file
View file

@ -0,0 +1,27 @@
// The one time period every Health chart shows (as the web pages' shared range): 1 day … all.
// Any chart's corner chip changes it for all of them; kept on this phone (store meta, not synced).
import 'package:flutter/foundation.dart';
import '../sync/store.dart';
import 'cycle_model.dart' show plus;
const ranges = [('1d', '1 day', 1), ('1w', '1 week', 7), ('1m', '1 month', 30), ('3m', '3 months', 91),
('1y', '1 year', 365), ('all', 'All', 0)];
class HealthRange extends ValueNotifier<String> {
HealthRange(this._store) : super(ranges[(_store.meta('ui_range') == 0 ? 2 : _store.meta('ui_range')) - 1].$1);
final SyncStore _store;
String get label => ranges.firstWhere((r) => r.$1 == value).$2;
void set(String key) {
value = key;
_store.setMeta('ui_range', ranges.indexWhere((r) => r.$1 == key) + 1); // 0 = never set → 1 week
}
/// The first day shown: [days] back including today, or (All) the data's first day.
DateTime from(DateTime first, DateTime now) {
final days = ranges.firstWhere((r) => r.$1 == value).$3;
return days == 0 ? first : plus(now, -(days - 1));
}
}

View file

@ -0,0 +1,620 @@
// Health ▸ Sleep (as on the web page's Sleep tab), from the Pi's summaries: one night on top (score ring —
// breakdown on tap —, numbers, the hypnogram; ‹ › or a bar below picks another), then over the shared
// period: tiles, stages per night (stacked, goal line), bedtime → wake-up, score per night, What stands
// out (the Pi's watch.findings) and by weekday. Per week from 4 months: the average night.
import 'dart:math';
import 'package:flutter/material.dart';
import '../app/sync_service.dart';
import '../app/theme.dart';
import '../widgets/bar_chart.dart' show weeklyFrom;
import '../widgets/line_chart.dart';
import 'activity_page.dart' show hm;
import 'body_page.dart' show dm;
import 'cycle_model.dart' show daysBetween, parseDay, plus, today;
import 'range.dart';
import 'summaries.dart';
const stages = ['deep', 'light', 'rem', 'asleep', 'awake', 'nap']; // stacking order, bottom up (watch.STAGES)
const stageNames = {'deep': 'Deep', 'light': 'Light', 'rem': 'REM', 'asleep': 'Asleep (no stage)', 'awake': 'Awake', 'nap': 'Nap'};
const stageColors = {
'deep': Color(0xFF4F6BED), 'light': Color(0xFF5CC8FF), 'rem': Color(0xFFC792EA),
'asleep': Color(0xFF7A8399), 'awake': Color(0xFFFFB33A), 'nap': Color(0xFFFF8FC8),
};
const _scoreC = Color(0xFF4F6BED);
const _weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
const _mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
/// watch._from_noon: hours since the noon before (21:00 → 9, 07:00 → 19)
double fromNoon(DateTime t) {
final h = t.hour + t.minute / 60;
return h >= 12 ? h - 12 : h + 12;
}
/// watch._wake: wake-up as hours from the noon before the night began (07:00 → 19, 13:00 → 25)
double wakeH(DateTime start, DateTime end) {
final s = DateTime(start.year, start.month, start.day, 12);
final noon = start.hour >= 12 ? s : s.subtract(const Duration(days: 1));
return end.difference(noon).inMinutes / 60;
}
/// watch.clock: hours since noon → "HH:MM"
String clock(double h) {
final m = ((h + 12) * 60).round() % (24 * 60);
return '${(m ~/ 60).toString().padLeft(2, '0')}:${(m % 60).toString().padLeft(2, '0')}';
}
String _t(DateTime d) => d.toIso8601String().substring(11, 16);
class Night {
Night(this.day, this.m) : start = DateTime.parse(m['start'] as String), end = DateTime.parse(m['end'] as String);
final DateTime day; // the wake-up day
final Map<String, dynamic> m;
final DateTime start, end;
num n(String k) => (m[k] as num?) ?? 0;
double get asleep => n('asleep').toDouble();
int get score => n('score').round();
double? get deepPct => (m['deep_pct'] as num?)?.toDouble();
double get bed => fromNoon(start);
double get up => wakeH(start, end);
Map<String, double> get parts => {
'deep': n('deep').toDouble(), 'light': n('light').toDouble(), 'rem': n('rem').toDouble(),
'asleep': n('unstaged').toDouble(), 'awake': n('awake').toDouble(),
};
}
class SleepPage extends StatefulWidget {
const SleepPage({super.key, required this.sync, required this.range});
final SyncService sync;
final HealthRange range;
@override
State<SleepPage> createState() => _SleepPageState();
}
class _SleepPageState extends State<SleepPage> {
DateTime? picked; // the night shown on top (null = the last)
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: Listenable.merge([widget.sync, widget.range]),
builder: (context, _) {
final sm = Summaries(widget.sync.store);
final all = [for (final x in sm.all('night')) Night(parseDay(x['_day'] as String), x)];
if (all.isEmpty) {
return const Center(child: Padding(
padding: EdgeInsets.all(24),
child: Text('No nights from the band yet — they come from the dashboard once it has synced.',
textAlign: TextAlign.center, style: TextStyle(color: muted)),
));
}
final meta = sm.meta('sleep') ?? {};
final goal = ((meta['goal'] as num?) ?? 8).toDouble();
final now = today();
final a = widget.range.from(all.first.day, now);
final ns = all.where((n) => !n.day.isBefore(a)).toList();
final naps = <DateTime, double>{
for (final d in sm.all('day', a: _iso(a)))
if ((d['naps'] as List?)?.isNotEmpty ?? false)
parseDay(d['_day'] as String): (d['naps'] as List).fold<double>(0, (s, p) => s + ((p as Map)['minutes'] as num))
};
var i = picked == null ? all.length - 1 : all.indexWhere((n) => n.day == picked);
if (i < 0) i = all.length - 1;
double? avg(Iterable<double?> xs) {
final v = xs.whereType<double>().toList();
return v.isEmpty ? null : v.reduce((p, q) => p + q) / v.length;
}
final found = ((meta['findings'] as Map?)?[widget.range.value] as List?) ?? const [];
final wide = MediaQuery.of(context).size.width >= 700;
void pick(DateTime d) => setState(() => picked = d);
return ListView(padding: const EdgeInsets.fromLTRB(12, 12, 12, 24), children: [
NightCard(all: all, i: i, goal: goal, onPick: (d) => setState(() => picked = d)),
const SizedBox(height: 12),
GridView.count(
crossAxisCount: wide ? 4 : 2,
shrinkWrap: true, physics: const NeverScrollableScrollPhysics(),
mainAxisSpacing: 10, crossAxisSpacing: 10, childAspectRatio: 1.75,
children: [
_tile('Asleep', hm(avg(ns.map((n) => n.asleep))), 'a night · goal ${goal.toStringAsFixed(goal % 1 == 0 ? 0 : 1)} h',
'The average night of the ${ns.length} in this period'),
_tile('Score', avg(ns.map((n) => n.score.toDouble()))?.round().toString() ?? '—', 'of 100, on average',
'Our own 0–100: duration 50, deep sleep 20, efficiency 15, interruptions 15'),
_tile('Deep', '${avg(ns.map((n) => n.deepPct))?.round() ?? '—'} %', 'of sleep · typical 13–23 %',
'Deep sleep as a share of the staged sleep'),
_tile('Bed → up', ns.isEmpty ? '—' : '${clock(avg(ns.map((n) => n.bed))!)}–${clock(avg(ns.map((n) => n.up))!)}', 'on average',
'Average bedtime and wake-up time'),
],
),
const SizedBox(height: 12),
_card('Stages per night', 'Hours of each stage a night (pink = naps that day), the dashed line = your goal. '
'Tap a night to show it on top.',
_Stacked(nights: ns, naps: naps, from: a, to: now, goal: goal, range: widget.range, onPick: pick)),
const SizedBox(height: 12),
_card('Bedtime → wake-up', 'Each night from going to bed to getting up (evening on top); red = under 7 h asleep.',
_Window(nights: ns, from: a, to: now, onPick: pick)),
const SizedBox(height: 12),
_card('Score per night', 'Our sleep score, 0–100',
LineChart(from: a, to: now, decimals: 0, limits: (0, 100), series: [
Series('Score', [for (final n in ns) (n.day, n.score.toDouble())], _scoreC),
])),
if (found.isNotEmpty) ...[
const SizedBox(height: 12),
Card(child: Padding(
padding: const EdgeInsets.all(14),
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
const Text('What stands out', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
for (final f in found)
Padding(
padding: const EdgeInsets.only(top: 10),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text((f as List)[0] as String, style: const TextStyle(color: accent, fontWeight: FontWeight.bold)),
Text(f[1] as String, style: const TextStyle(height: 1.35)),
]),
),
]),
)),
],
if (ns.length >= 7) ...[const SizedBox(height: 12), _weekdayCard(ns)],
]);
},
);
Widget _weekdayCard(List<Night> ns) {
final by = <int, List<Night>>{};
for (final n in ns) {
by.putIfAbsent(plus(n.day, -1).weekday - 1, () => []).add(n); // the evening you went to bed
}
double? av(List<Night> xs, double Function(Night) f) => xs.isEmpty ? null : xs.map(f).reduce((p, q) => p + q) / xs.length;
final top = [for (var i = 0; i < 7; i++) av(by[i] ?? [], (n) => n.asleep) ?? 0].reduce(max);
return _card('By weekday', 'The night after each weekday evening: average asleep, bedtime and score', Column(children: [
for (var i = 0; i < 7; i++)
Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Row(children: [
SizedBox(width: 38, child: Text(_weekdays[i])),
Expanded(child: ClipRRect(
borderRadius: BorderRadius.circular(3),
child: LinearProgressIndicator(value: top == 0 ? 0 : (av(by[i] ?? [], (n) => n.asleep) ?? 0) / top,
minHeight: 8, color: stageColors['light'], backgroundColor: card2),
)),
SizedBox(width: 150, child: Text(
by[i] == null ? '—' : '${hm(av(by[i]!, (n) => n.asleep))} · ${clock(av(by[i]!, (n) => n.bed)!)} · ${av(by[i]!, (n) => n.score.toDouble())!.round()}',
textAlign: TextAlign.right, style: const TextStyle(fontSize: 12.5))),
]),
),
]));
}
Widget _tile(String label, String value, String sub, String tip) => Tooltip(
triggerMode: TooltipTriggerMode.tap,
showDuration: const Duration(seconds: 6),
message: tip,
child: Card(child: Padding(
padding: const EdgeInsets.all(12),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [
Text(label.toUpperCase(), style: const TextStyle(color: muted, fontSize: 11.5)),
FittedBox(fit: BoxFit.scaleDown, child: Text(value, style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold))),
Text(sub, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: muted, fontSize: 12)),
]),
)),
);
Widget _card(String title, String tip, Widget child) => Card(child: Padding(
padding: const EdgeInsets.fromLTRB(14, 8, 10, 10),
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
Row(children: [
Expanded(child: Text(title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold))),
Tooltip(
triggerMode: TooltipTriggerMode.tap,
showDuration: const Duration(seconds: 8),
message: tip,
child: const Padding(padding: EdgeInsets.all(6), child: Icon(Icons.info_outline, size: 18, color: muted)),
),
]),
child,
]),
));
}
/// One night: ‹ › (with [onPick]), score ring (breakdown on tap), numbers, the hypnogram — Sleep's top card,
/// also on Health ▸ Overview (last night, no arrows).
class NightCard extends StatelessWidget {
const NightCard({super.key, required this.all, required this.i, required this.goal, this.onPick});
final List<Night> all;
final int i;
final double goal;
final void Function(DateTime)? onPick;
@override
Widget build(BuildContext context) {
final n = all[i];
final p = (n.m['parts'] as Map?)?.cast<String, dynamic>() ?? {};
const maxOf = {'Duration': 50, 'Deep sleep': 20, 'Efficiency': 15, 'Interruptions': 15};
final stats = [
('Asleep', hm(n.asleep)),
('In bed', '${_t(n.start)}–${_t(n.end)}'),
('Deep', n.deepPct == null ? '—' : '${hm(n.n('deep'))} · ${n.deepPct!.round()} %'),
('Light', n.n('light') > 0 ? hm(n.n('light')) : '—'),
('Awake', '${hm(n.n('awake'))} · ${n.n('wakeups')}×'),
('Efficiency', '${(n.n('eff') * 100).round()} %'),
];
final night = '${dm(plus(n.day, -1))} → ${dm(n.day)}${n.day.year != today().year ? ' ${n.day.year}' : ''}';
return Card(child: Padding(
padding: EdgeInsets.fromLTRB(6, onPick == null ? 14 : 6, 6, 12),
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
Row(children: [
if (onPick != null) IconButton(onPressed: i > 0 ? () => onPick!(all[i - 1].day) : null, icon: const Icon(Icons.chevron_left)),
Expanded(child: Text(i == all.length - 1 && n.day == today() ? 'Last night · $night' : night,
textAlign: TextAlign.center, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: accent))),
if (onPick != null) IconButton(onPressed: i < all.length - 1 ? () => onPick!(all[i + 1].day) : null, icon: const Icon(Icons.chevron_right)),
]),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Row(children: [
Tooltip(
triggerMode: TooltipTriggerMode.tap,
showDuration: const Duration(seconds: 10),
message: 'Sleep score ${n.score} / 100\n'
'${maxOf.entries.map((e) => '${e.key}: ${p[e.key] ?? '—'} / ${e.value}').join('\n')}\n'
'Duration: full at ${(min(goal, 8) - 0.5).toStringAsFixed(1)} h+; deep: full at 20 %;\n'
'efficiency: asleep ÷ in bed, full at 95 %; interruptions: −4 per wake-up.',
child: SizedBox(
width: 82, height: 82,
child: CustomPaint(
painter: _ScoreRing(n.score / 100),
child: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
Text('${n.score}', style: const TextStyle(fontSize: 26, fontWeight: FontWeight.bold, height: 1)),
const Text('score', style: TextStyle(color: muted, fontSize: 12)),
])),
),
),
),
const SizedBox(width: 16),
Expanded(child: Wrap(runSpacing: 8, children: [
for (final (l, v) in stats)
SizedBox(width: 120, child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text(l.toUpperCase(), style: const TextStyle(color: muted, fontSize: 11)),
Text(v, style: const TextStyle(fontWeight: FontWeight.bold)),
])),
])),
]),
),
const SizedBox(height: 10),
if ((n.m['stages'] as List?)?.isNotEmpty ?? false)
Padding(padding: const EdgeInsets.symmetric(horizontal: 8), child: _Hypnogram(night: n))
else
const Padding(padding: EdgeInsets.all(8), child: Text('No stages recorded for this night', style: TextStyle(color: muted))),
]),
));
}
}
String _iso(DateTime d) => d.toIso8601String().substring(0, 10);
class _ScoreRing extends CustomPainter {
_ScoreRing(this.f);
final double f;
@override
void paint(Canvas c, Size s) {
final r = Rect.fromCircle(center: s.center(Offset.zero), radius: s.width / 2 - 4);
Paint p(Color col) => Paint()..color = col..style = PaintingStyle.stroke..strokeWidth = 6..strokeCap = StrokeCap.round;
c.drawArc(r, 0, 2 * pi, false, p(card2));
if (f > 0) c.drawArc(r, -pi / 2, 2 * pi * f.clamp(0, 1), false, p(_scoreC));
}
@override
bool shouldRepaint(covariant _ScoreRing old) => old.f != f;
}
/// One night's stages: lanes awake / REM / light / deep, a block per run (watch.hypnogram); tap = that run.
class _Hypnogram extends StatefulWidget {
const _Hypnogram({required this.night});
final Night night;
@override
State<_Hypnogram> createState() => _HypnogramState();
}
class _HypnogramState extends State<_Hypnogram> {
int? hit;
@override
void didUpdateWidget(covariant _Hypnogram old) {
super.didUpdateWidget(old);
if (old.night.day != widget.night.day) hit = null;
}
@override
Widget build(BuildContext context) {
final runs = (widget.night.m['stages'] as List).cast<List>();
final n = widget.night;
final h = hit == null ? null : runs[hit!];
String at(num min) => _t(n.start.add(Duration(seconds: (min * 60).round())));
return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
LayoutBuilder(builder: (context, box) {
final painter = _HypPainter(n, runs, hit);
return GestureDetector(
onTapDown: (d) {
final m = painter.minuteAt(d.localPosition.dx, box.maxWidth);
final j = runs.indexWhere((r) => (r[0] as num) <= m && m <= (r[1] as num));
setState(() => hit = j < 0 ? null : j);
},
child: CustomPaint(size: Size(box.maxWidth, 140), painter: painter),
);
}),
SizedBox(
height: 20,
child: Text(
h == null
? 'Tap a block for its times'
: '${stageNames[h[2]] ?? h[2]} · ${at(h[0] as num)} – ${at(h[1] as num)} · ${hm((h[1] as num) - (h[0] as num))}',
textAlign: TextAlign.center,
style: TextStyle(color: h == null ? muted : Colors.white, fontSize: 12.5)),
),
]);
}
}
class _HypPainter extends CustomPainter {
_HypPainter(this.n, this.runs, this.hit);
final Night n;
final List<List> runs;
final int? hit;
static const ml = 46.0, mb = 18.0, pad = 15.0; // minutes either side (as the web's)
double get total => n.end.difference(n.start).inMinutes + 2 * pad;
double x(num min, double w) => ml + (w - ml) * (min + pad) / total;
double minuteAt(double dx, double w) => (dx - ml) / (w - ml) * total - pad;
@override
void paint(Canvas c, Size size) {
const lanes = {'awake': 0, 'rem': 1, 'light': 2, 'asleep': 2, 'deep': 3};
final lh = (size.height - mb) / 4;
final txt = const TextStyle(color: muted, fontSize: 10.5);
void label(String s, Offset o, {bool right = false}) {
final tp = TextPainter(text: TextSpan(text: s, style: txt), textDirection: TextDirection.ltr)..layout();
tp.paint(c, right ? o - Offset(tp.width, tp.height / 2) : o - Offset(tp.width / 2, 0));
}
for (var i = 0; i < 4; i++) {
c.drawLine(Offset(ml, i * lh), Offset(size.width, i * lh), Paint()..color = card2);
label(['Awake', 'REM', 'Light', 'Deep'][i], Offset(ml - 6, i * lh + lh / 2), right: true);
}
for (var i = 0; i < runs.length; i++) {
final r = runs[i];
final lane = lanes[r[2]] ?? 2;
final x0 = x(r[0] as num, size.width), x1 = x(r[1] as num, size.width);
c.drawRRect(RRect.fromRectAndRadius(Rect.fromLTRB(x0, lane * lh + 2, max(x0 + 0.8, x1), (lane + 1) * lh - 2), const Radius.circular(2)),
Paint()..color = hit == i ? Colors.white : stageColors[r[2]] ?? muted);
}
// hour ticks (every 2 h for long nights)
final a = n.start.subtract(const Duration(minutes: 15)), z = n.end.add(const Duration(minutes: 15));
final step = z.difference(a).inHours < 6 ? 1 : 2;
for (var t = DateTime(a.year, a.month, a.day, a.hour + 1); t.isBefore(z); t = t.add(const Duration(hours: 1))) {
if (t.hour % step == 0) label(_t(t), Offset(x(t.difference(n.start).inMinutes, size.width), size.height - mb + 4));
}
}
@override
bool shouldRepaint(covariant _HypPainter old) => true;
}
/// Stages per night, stacked (hours), naps on top, the goal dashed; from [weeklyFrom] days the average
/// night of each week. Tap = its numbers (and that night on top).
class _Stacked extends StatefulWidget {
const _Stacked({required this.nights, required this.naps, required this.from, required this.to, required this.goal,
required this.range, required this.onPick});
final List<Night> nights;
final Map<DateTime, double> naps;
final DateTime from, to;
final double goal;
final HealthRange range;
final void Function(DateTime) onPick;
@override
State<_Stacked> createState() => _StackedState();
}
class _StackedState extends State<_Stacked> {
String? tip;
/// [(first day, {stage: minutes} or null, label, the night's day if one)]
List<(DateTime, Map<String, double>?, String, DateTime?)> _buckets() {
final per = <DateTime, Map<String, double>>{for (final n in widget.nights) n.day: n.parts};
widget.naps.forEach((d, m) => (per[d] ??= {})['nap'] = m);
final n = daysBetween(widget.from, widget.to) + 1;
final out = <(DateTime, Map<String, double>?, String, DateTime?)>[];
if (n >= weeklyFrom) {
for (var s = plus(widget.from, -(widget.from.weekday - 1)); !s.isAfter(widget.to); s = plus(s, 7)) {
final vs = [for (var i = 0; i < 7; i++) per[plus(s, i)]].whereType<Map<String, double>>().toList();
out.add((s, vs.isEmpty ? null : {for (final st in stages) st: vs.fold<double>(0, (a, v) => a + (v[st] ?? 0)) / vs.length},
'Week of ${s.day} ${_mon[s.month - 1]} · the average night (${vs.length})', null));
}
} else {
for (var i = 0; i < n; i++) {
final d = plus(widget.from, i);
out.add((d, per[d], 'Night to ${d.day} ${_mon[d.month - 1]}', per.containsKey(d) ? d : null));
}
}
return out;
}
@override
Widget build(BuildContext context) {
final b = _buckets();
return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
Row(children: [
Expanded(child: Text(tip ?? 'Tap a night for its numbers',
style: TextStyle(color: tip == null ? muted : Colors.white, fontSize: 12.5))),
RangeChip(widget.range),
]),
const SizedBox(height: 6),
LayoutBuilder(builder: (context, box) => GestureDetector(
onTapDown: (d) {
final i = ((d.localPosition.dx - 30) / (box.maxWidth - 30) * b.length).floor().clamp(0, b.length - 1);
final (_, v, label, day) = b[i];
if (v == null) return setState(() => tip = '$label · nothing');
final asleep = ['deep', 'light', 'rem', 'asleep'].fold<double>(0, (s, k) => s + (v[k] ?? 0));
setState(() => tip = '$label · asleep ${hm(asleep)}'
'${(v['deep'] ?? 0) > 0 ? ', deep ${hm(v['deep'])}' : ''}${(v['nap'] ?? 0) > 0 ? ', nap ${hm(v['nap'])}' : ''}');
if (day != null) widget.onPick(day);
},
child: CustomPaint(size: Size(box.maxWidth, 170), painter: _StackPainter(b, widget.goal)),
)),
]);
}
}
class _StackPainter extends CustomPainter {
_StackPainter(this.b, this.goal);
final List<(DateTime, Map<String, double>?, String, DateTime?)> b;
final double goal;
@override
void paint(Canvas c, Size size) {
const ml = 30.0, mb = 16.0, mt = 4.0;
final h = size.height - mb - mt;
final peak = max(goal + 1, [for (final x in b) if (x.$2 != null) x.$2!.values.fold<double>(0, (a, v) => a + v) / 60].fold<double>(0, max));
final top = (peak / 2).ceil() * 2.0;
double y(double hours) => mt + h - h * hours / top;
final txt = const TextStyle(color: muted, fontSize: 10.5);
void label(String s, Offset o, {bool right = false}) {
final tp = TextPainter(text: TextSpan(text: s, style: txt), textDirection: TextDirection.ltr)..layout();
tp.paint(c, right ? o - Offset(tp.width, tp.height / 2) : o - Offset(tp.width / 2, 0));
}
for (var v = 0.0; v <= top; v += top > 10 ? 4 : 2) {
c.drawLine(Offset(ml, y(v)), Offset(size.width, y(v)), Paint()..color = card2);
label('${v.round()}h', Offset(ml - 4, y(v)), right: true);
}
final bw = (size.width - ml) / max(1, b.length), pad = bw > 4 ? bw * 0.18 : 0.0;
final weekly = b.length > 1 && b[1].$1.difference(b[0].$1).inDays == 7;
for (var i = 0; i < b.length; i++) {
final (d, v, _, _) = b[i];
final x0 = ml + i * bw;
if (v != null) {
var base = 0.0;
for (final st in stages) {
final m = (v[st] ?? 0) / 60;
if (m > 0) c.drawRect(Rect.fromLTRB(x0 + pad, y(base + m), x0 + bw - pad, y(base)), Paint()..color = stageColors[st]!);
base += m;
}
}
final l = weekly
? (d.day <= 7 && (b.length <= 30 || d.month % 3 == 1) ? _mon[d.month - 1] : null)
: b.length > 35 ? (d.day == 1 ? _mon[d.month - 1] : null) : (d.weekday == 1 || b.length <= 8 ? '${d.day} ${_mon[d.month - 1]}' : null);
if (l != null) label(l, Offset(x0 + bw / 2, size.height - mb + 3));
}
final gy = y(goal);
for (var x = ml; x < size.width; x += 8) {
c.drawLine(Offset(x, gy), Offset(min(x + 4, size.width), gy), Paint()..color = accent..strokeWidth = 1.2);
}
}
@override
bool shouldRepaint(covariant _StackPainter old) => true;
}
/// Each night as a bar from bedtime to wake-up (watch.window_chart); weekly: the average night.
class _Window extends StatefulWidget {
const _Window({required this.nights, required this.from, required this.to, required this.onPick});
final List<Night> nights;
final DateTime from, to;
final void Function(DateTime) onPick;
@override
State<_Window> createState() => _WindowState();
}
class _WindowState extends State<_Window> {
String? tip;
/// [(first day, bed, up, asleep min, label, night day?)]
List<(DateTime, double, double, double, String, DateTime?)> _bars() {
final n = daysBetween(widget.from, widget.to) + 1;
if (n < weeklyFrom) {
return [
for (final x in widget.nights)
(x.day, x.bed, x.up, x.asleep, 'Night to ${x.day.day} ${_mon[x.day.month - 1]} · ${_t(x.start)} → ${_t(x.end)} · asleep ${hm(x.asleep)}', x.day)
];
}
final wk = <DateTime, List<Night>>{};
for (final x in widget.nights) {
wk.putIfAbsent(plus(x.day, -(x.day.weekday - 1)), () => []).add(x);
}
double av(List<Night> xs, double Function(Night) f) => xs.map(f).reduce((p, q) => p + q) / xs.length;
return [
for (final e in wk.entries)
(e.key, av(e.value, (x) => x.bed), av(e.value, (x) => x.up), av(e.value, (x) => x.asleep),
'Week of ${e.key.day} ${_mon[e.key.month - 1]} · average of ${e.value.length} · '
'${clock(av(e.value, (x) => x.bed))} → ${clock(av(e.value, (x) => x.up))} · asleep ${hm(av(e.value, (x) => x.asleep))}', null)
];
}
@override
Widget build(BuildContext context) {
final bars = _bars();
if (bars.isEmpty) return const SizedBox(height: 40, child: Center(child: Text('No nights in this period', style: TextStyle(color: muted))));
final weekly = daysBetween(widget.from, widget.to) + 1 >= weeklyFrom;
final slots = weekly ? ((daysBetween(widget.from, widget.to) + 7) ~/ 7 + 1) : daysBetween(widget.from, widget.to) + 1;
final a0 = weekly ? plus(widget.from, -(widget.from.weekday - 1)) : widget.from;
return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
Text(tip ?? 'Tap a night for its times', style: TextStyle(color: tip == null ? muted : Colors.white, fontSize: 12.5)),
const SizedBox(height: 6),
LayoutBuilder(builder: (context, box) => GestureDetector(
onTapDown: (d) {
final slot = ((d.localPosition.dx - 40) / (box.maxWidth - 40) * slots).floor();
final hit = bars.where((x) => (daysBetween(a0, x.$1) ~/ (weekly ? 7 : 1)) == slot).toList();
setState(() => tip = hit.isEmpty ? null : hit.first.$5);
if (hit.isNotEmpty && hit.first.$6 != null) widget.onPick(hit.first.$6!);
},
child: CustomPaint(size: Size(box.maxWidth, 180), painter: _WindowPainter(bars, a0, slots, weekly)),
)),
]);
}
}
class _WindowPainter extends CustomPainter {
_WindowPainter(this.bars, this.a0, this.slots, this.weekly);
final List<(DateTime, double, double, double, String, DateTime?)> bars;
final DateTime a0;
final int slots;
final bool weekly;
@override
void paint(Canvas c, Size size) {
const ml = 40.0, mb = 16.0, mt = 4.0;
final top = max(6, bars.map((x) => x.$2).reduce(min).floor() - 1).toDouble();
final bot = min(26, bars.map((x) => x.$3).reduce(max).floor() + 2).toDouble();
double y(double hh) => mt + (size.height - mt - mb) * (hh.clamp(top, bot) - top) / (bot - top);
final txt = const TextStyle(color: muted, fontSize: 10.5);
void label(String s, Offset o, {bool right = false}) {
final tp = TextPainter(text: TextSpan(text: s, style: txt), textDirection: TextDirection.ltr)..layout();
tp.paint(c, right ? o - Offset(tp.width, tp.height / 2) : o - Offset(tp.width / 2, 0));
}
final step = bot - top > 8 ? 2 : 1;
for (var hh = top.toInt(); hh <= bot; hh++) {
if (hh % step != 0) continue;
c.drawLine(Offset(ml, y(hh.toDouble())), Offset(size.width, y(hh.toDouble())), Paint()..color = card2);
label(clock(hh.toDouble()), Offset(ml - 4, y(hh.toDouble())), right: true);
}
final bw = (size.width - ml) / max(1, slots), pad = bw > 4 ? bw * 0.18 : 0.0;
for (final (d, bed, up, asleep, _, _) in bars) {
final i = daysBetween(a0, d) ~/ (weekly ? 7 : 1);
final x0 = ml + i * bw;
c.drawRRect(RRect.fromRectAndRadius(Rect.fromLTRB(x0 + pad, y(bed), x0 + bw - pad, y(up)), const Radius.circular(2)),
Paint()..color = asleep < 7 * 60 ? bad : stageColors['light']!);
}
for (var i = 0; i < slots; i++) {
final d = plus(a0, i * (weekly ? 7 : 1));
final l = weekly
? (d.day <= 7 && (slots <= 30 || d.month % 3 == 1) ? _mon[d.month - 1] : null)
: slots > 35 ? (d.day == 1 ? _mon[d.month - 1] : null) : (d.weekday == 1 || slots <= 8 ? '${d.day} ${_mon[d.month - 1]}' : null);
if (l != null) label(l, Offset(ml + i * bw + bw / 2, size.height - mb + 3));
}
}
@override
bool shouldRepaint(covariant _WindowPainter old) => true;
}

184
app/lib/health/sugar.dart Normal file
View file

@ -0,0 +1,184 @@
// Added sugar, estimated — a port of the dashboard's plugins/food/sugar.py (keep the word lists and
// rules identical): the sugars WHO's limit is about ("free sugars": sugar, honey, syrups added to food,
// plus fruit juice), not the sugar inside whole fruit, vegetables and plain milk. Each food gets a kind
// from its category / name: added (all its sugar counts), dairy (only beyond the milk's own lactose), natural (none).
// Shop products: the label's added-sugar figure, else NOVA 1 / "no added sugar", else their ingredients
// (sugarsIn / dairy, off.py) — see sugar.py's top. Names are matched folded (no diacritics, lower case).
import 'dart:convert';
import 'dart:math';
import '../sync/store.dart';
import 'food_model.dart';
import 'sugar_kinds.g.dart';
const lactose = 5.0; // g per 100 g of milk / yogurt that is the milk's own sugar
// lower-cased letters with diacritics → plain ones (sugar.py's FOLD)
final _foldMap = <String, String>{
for (final (from, to) in [
('áàâäãåāăą', 'a'), ('çčć', 'c'), ('ďđ', 'd'), ('éèêëěęē', 'e'), ('íìîïī', 'i'), ('ľĺł', 'l'), ('ňńñ', 'n'),
('óòôöõőø', 'o'), ('řŕ', 'r'), ('śšşș', 's'), ('ťţț', 't'), ('úùûüůűū', 'u'), ('ýÿ', 'y'), ('žźż', 'z'),
])
for (final c in from.split('')) c: to,
'ß': 'ss', 'æ': 'ae', 'œ': 'oe',
};
/// 'Zahăr Brun' → 'zahar brun' (what the word lists are matched against).
String fold(String s) => s.toLowerCase().split('').map((c) => _foldMap[c] ?? c).join();
final _added = RegExp(
r'juice|nectar(?!ine)|syrup|honey|\bjam\b|jelly|marmalade|candy|candies|chocolate|cocoa|(?<!un)sweetened|frosted|glazed|candied|'
r'\bcake|cookie|biscuit|brownie|\bpie\b|pastr|doughnut|donut|croissant|muffin|waffle|pancake|dessert|pudding|'
r'ice cream|sorbet|gelatin|soda|soft drink|\bcola\b|lemonade|energy drink|sport drink|sports drink|\bpunch\b|'
r'smoothie|milkshake|milk shake|ketchup|bbq|barbecue|sweet and sour|teriyaki|\bsugar\b|sugared|granola|cereal bar|'
r'nutrition bar|protein bar|wafer|caramel|toffee|fudge|marzipan|nutella|'
r'strudel|tart\b|cheesecake|tiramisu|liqueur|cocktail|flavored|flavoured|vanilla|'
r'fruit drink|flavou?r drink|breakfast drink|drink mix|beverage mix|ready.to.drink|carbonated|tonic|ginger ale|limeade|'
r'lemonad|sour mix|creme de|pina colada|daiquiri|shake mix|ovaltine|malted|\bbars?\b|treats|sundae|cobbler|'
r'cinnamon roll|hotcake|french toast|mcgriddle|coleslaw|banana chips|zwieback|\bcran |'
r'schoko|marlenka|sernik|malt loaf|\bbeer|\bbere\b|\bpivo|\bwines?\b|\bcider|\bvin\b|v[ií]no\b|cidru|ciocolat|pr[aă]jitur|\bdulce|zahar|cukor|cukr|'
r'zucker|sucre|zucchero|azucar|acucar|cukier|suiker|sirop|sirup|syrop|sciroppo|honig|\bmiere\b|\bmiel\b|\bmiod|\bmedov|'
r'chocolat|cioccolat|czekolad|cokolad|csokolad|keks|kuchen|torte\b|\btort\b|\bgateau|biscott|gallet|ciastk|susienk|susenk|'
r'oplatk|napolitane\b|\blody\b|zmrzlin|fagylalt|gelato|helado|limonad|saft\b|\bjus\b|succo|\bzumo|\bdzus|\bdzem|'
r'konfit|marmelad|kompot|compot|bonbon|bomboan|pralin|lizak|\bsuc\b|\bsucuri',
caseSensitive: false, unicode: true);
final _dairy = RegExp(
r'\bmilk\b|yogh?urt|jogurt|iaurt|kefir|skyr|quark|tvaroh|buttermilk|cottage|ricotta|cream cheese|\bcream\b|'
r'lapte|mlieko|sm[aâ]nt[aâ]n[aă]|smotana|br[aâ]nz[aă]|\burda\b|chefir|\bsana\b|'
r'\blait\b|milch|\blatte\b|\bleche\b|\bleite\b|\bmlek|\bmlecz|\bmleko|\btej\b|\btejf|\bmelk\b|yaourt|joghurt|'
r'yogur|iogurt|fromage blanc|twarog|\bturo\b|\bsahne|creme fraiche|smietan|smetan|\bnata\b|\bpanna\b|kwark',
caseSensitive: false, unicode: true);
/// The reviewed table's kind for a USDA category (sugar_kinds.g.dart = the dashboard's sugar_kinds.json), or null:
/// by the name. [name]: folded.
String? categoryKind(String category, String name) {
final k = sugarKinds[category.toLowerCase()];
if (k == null) return null;
final (kind, except) = k;
return except != null && RegExp(except).hasMatch(name) ? null : kind;
}
final _notDairy = RegExp(
r'coconut milk|chocolate milk|\b(soy|soya|almond|oat|rice) ?(milk|drink)|(soja|hafer|mandel|reis|kokos)(milch|drink)|'
r'lapte (vegetal|de (soia|migdale|ovaz|cocos|orez))|\bvegan\b',
caseSensitive: false);
final _natural = RegExp(
r'(apple|banana|grape|orange|pear|peach|plum|berr|cherr|melon|mango|pineapple|kiwi|\bfig|\bdate|apricot|raisin|'
r'tomato|onion|carrot|cabbage|potato|pepper|cucumber|lettuce|salad|spinach|broccoli|bean|pea|lentil|corn|squash|'
r'zucchini|pumpkin|beet|garlic|mushroom|rice|oat|bread|pasta|egg|chicken|beef|pork|fish|tuna|salmon|ham|turkey|'
r'cheese|nut|almond|walnut|seed|soup|pickle|clementin|mandarin|grepfruit|grapefruit|\bm[aă]r\b|morcov|sfecl|telin|'
r'ceap|ro[sș]ii|cartof|varz|legume|borsc?h|\bbor[sș]|ciorb|sup[aă]\b|pizza|goulash|gul[aá][sšș]|\bmici\b|congelat)',
caseSensitive: false, unicode: true);
final _flavour = RegExp(r'flavou?red|fruit|vanilla|strawberr|banana', caseSensitive: false);
final _notFlavourDairy = RegExp(r'chocolate|ice cream|shake', caseSensitive: false);
/// A food → "added" / "dairy" / "natural" (sugar.kind). sugarsIn / dairy: off.py's columns (null: not known).
String sugarKind(String name, {String category = '', String source = '', int? nova, String labels = '', String? sugarsIn, int? dairy}) {
name = fold(name);
final ck = categoryKind(category, name);
final isDairy = ((dairy ?? 0) != 0 || ck == 'dairy' || _dairy.hasMatch(name)) && !_notDairy.hasMatch(name);
if (source == 'off') {
if (labels.toLowerCase().contains('no added sugar') || nova == 1) return isDairy ? 'dairy' : 'natural';
if (sugarsIn != null) return isDairy ? 'dairy' : sugarsIn.isNotEmpty ? 'added' : 'natural'; // its ingredients are known
if (isDairy && !_added.hasMatch(name)) return 'dairy';
return 'added';
}
if (ck == 'added' || _added.hasMatch(name)) { // words: the name only ("Fruits and Fruit Juices")
return isDairy && _flavour.hasMatch(name) && !_notFlavourDairy.hasMatch(name) ? 'dairy' : 'added';
}
return isDairy ? 'dairy' : 'natural';
}
double addedPart(String kind, double sugar, double? grams) {
if (sugar == 0) return 0;
if (kind == 'added') return sugar;
if (kind == 'dairy') return max(0, sugar - (grams != null && grams > 0 ? lactose * grams / 100 : sugar));
return 0;
}
bool _says(String name) {
name = fold(name);
return _added.hasMatch(name) || _dairy.hasMatch(name) || _natural.hasMatch(name);
}
String _byName(String name) => _says(name) ? sugarKind(name) : 'added';
String foodKind(Food f) => sugarKind(f.name, category: f.category, source: f.kind == 'off' ? 'off' : f.source, nova: f.nova,
labels: f.labels, sugarsIn: f.sugarsIn, dairy: f.dairy);
/// Added sugar (g) of [sugar] g of a foods.db food (sugar.food_part): the label's own figure when it gives one, else by its kind.
double foodPart(Food f, double sugar, double? grams) {
final s100 = f.per100['sugar'];
// "0 added" yet sugar in the ingredients: a crowd-typed 0, not the label
final a = f.addedSugar == 0 && (f.sugarsIn ?? '').isNotEmpty ? null : f.addedSugar;
if (a != null && s100 != null && s100 > 0) return sugar * min(1.0, a / s100);
return addedPart(foodKind(f), sugar, grams);
}
/// Added sugar of entries (sugar.entry_added), the foods they were made from looked up once.
class AddedSugar {
AddedSugar(this.store, this.fdb);
final SyncStore store;
final FoodDb? fdb;
final _foods = <int, Food?>{};
final _mine = <String, Map<String, dynamic>?>{};
Food? _food(int id) => _foods.putIfAbsent(id, () => fdb?.food(id));
Map<String, dynamic>? _my(String uid) => _mine.putIfAbsent(uid, () => store.row('food.food', uid));
double entry(Entry e) {
final sugar = e.n('sugar') ?? 0;
if (sugar == 0) return 0;
final grams = e.n('grams');
if (e.foodId != null) {
final f = _food(e.foodId!);
if (f != null) return foodPart(f, sugar, grams);
}
if (e.myFoodId != null) {
final m = _my(e.myFoodId!);
if (m != null) return _myAdded(m, sugar, grams, 0);
}
return addedPart(_byName(e.name), sugar, grams);
}
double _myAdded(Map<String, dynamic> m, double sugar, double? grams, int depth) {
final set = m['sugar_kind']; // "Sugar counts as" (My foods): as set, whatever the estimate says
if (set is String && const ['added', 'dairy', 'natural'].contains(set)) return addedPart(set, sugar, grams);
final recipe = m['recipe'] is String ? jsonDecode(m['recipe'] as String) as Map<String, dynamic>? : null;
final ings = (recipe?['ingredients'] as List?)?.cast<Map<String, dynamic>>();
if (ings != null && ings.isNotEmpty) {
var totSugar = 0.0, totAdded = 0.0;
for (final ing in ings) {
final ref = (ing['food'] as String?) ?? '';
final g = (ing['grams'] as num?)?.toDouble();
if (ref.startsWith('usda:') && g != null) {
final f = _food(int.parse(ref.substring(5)));
if (f != null) {
final s = (f.per100['sugar'] ?? 0) * g / 100;
totSugar += s;
totAdded += foodPart(f, s, g);
continue;
}
}
if (ref.startsWith('my:') && g != null && depth < 4) {
final sub = _my(ref.substring(3).replaceFirst('~', '')); // synced refs are "my:~<id>"
if (sub != null) {
final s = ((sub['sugar'] as num?)?.toDouble() ?? 0) * g / 100;
totSugar += s;
totAdded += _myAdded(sub, s, g, depth + 1);
continue;
}
}
final s = (ing['sugar'] as num?)?.toDouble() ?? 0; // a fixed ingredient: its own numbers
if (s > 0) {
totSugar += s;
totAdded += addedPart(_byName((ing['name'] as String?) ?? ''), s, g);
}
}
return totSugar > 0 ? sugar * totAdded / totSugar : 0;
}
final base = (m['based_on'] as num?)?.toInt();
if (base != null) {
final f = _food(base);
if (f != null) return foodPart(f, sugar, grams);
}
return addedPart(_byName((m['name'] as String?) ?? ''), sugar, grams);
}
}

View file

@ -0,0 +1,56 @@
// GENERATED from the dashboard's plugins/food/sugar_kinds.json by `python3 plugins/food/sugar.py --dart <this file>`
// — don't edit; change the table and run it again. USDA category (lower case) → (kind, names going by their name).
const sugarKinds = <String, (String, String?)>{
r'apple juice': (r'added', null),
r'baby food: snacks and sweets': (r'added', null),
r'baby juice': (r'added', null),
r'baked products': (r'added', null),
r'biscuits, muffins, quick breads': (r'added', null),
r'breakfast cereals': (r'added', r'\bplain\b|grits|farina|regular and quick|unsweetened'),
r'cakes and pies': (r'added', null),
r'candy containing chocolate': (r'added', null),
r'candy not containing chocolate': (r'added', null),
r'cereal bars': (r'added', null),
r'cheese': (r'dairy', null),
r'cheese sandwiches': (r'dairy', null),
r'citrus juice': (r'added', null),
r'cookies and brownies': (r'added', null),
r'cottage/ricotta cheese': (r'dairy', null),
r'cream and cream substitutes': (r'dairy', null),
r'cream cheese, sour cream, whipped cream': (r'dairy', null),
r'dairy and egg products': (r'dairy', null),
r'doughnuts, sweet rolls, pastries': (r'added', null),
r'flavored milk, lowfat': (r'added', null),
r'flavored milk, nonfat': (r'added', null),
r'flavored milk, reduced fat': (r'added', null),
r'flavored milk, whole': (r'added', null),
r'fruit drinks': (r'added', null),
r'gelatins, ices, sorbets': (r'added', null),
r'ice cream and frozen dairy desserts': (r'added', null),
r'jams, syrups, toppings': (r'added', null),
r'liquor and cocktails': (r'added', null),
r'milk shakes and other dairy drinks': (r'added', null),
r'milk, lowfat': (r'dairy', null),
r'milk, nonfat': (r'dairy', null),
r'milk, reduced fat': (r'dairy', null),
r'milk, whole': (r'dairy', null),
r'nutrition bars': (r'added', null),
r'nutritional beverages': (r'added', null),
r'other fruit juice': (r'added', null),
r'pancakes, waffles, french toast': (r'added', null),
r'plant-based milk': (r'dairy', null),
r'plant-based yogurt': (r'dairy', null),
r'pudding': (r'added', null),
r'ready-to-eat cereal, higher sugar (>21.2g/100g)': (r'added', null),
r'ready-to-eat cereal, lower sugar (=<21.2g/100g)': (r'added', null),
r'smoothies and grain drinks': (r'added', null),
r'soft drinks': (r'added', null),
r'sport and energy drinks': (r'added', null),
r'sugars and honey': (r'added', null),
r'sweets': (r'added', null),
r'tomato-based condiments': (r'added', null),
r'turnovers and other grain-based items': (r'added', null),
r'vegetable juice': (r'added', null),
r'yogurt, greek': (r'dairy', null),
r'yogurt, regular': (r'dairy', null),
};

View file

@ -0,0 +1,34 @@
// The Pi's Health summaries (dashboard plugins/health/summary.py), synced one way as "health.summary"
// rows: day:<date>, night:<date>, wk:<id>, meta:energy, meta:person — each {k, kind, day, data (JSON)}.
// Read-only here: what the band measured, worked out on the Pi with the Health pages' own functions.
import 'dart:convert';
import '../sync/store.dart';
class Summaries {
Summaries(this.store);
final SyncStore store;
Map<String, dynamic>? _get(String k) {
final r = store.row('health.summary', k);
return r == null ? null : jsonDecode(r['data'] as String) as Map<String, dynamic>;
}
Map<String, dynamic>? day(String iso) => _get('day:$iso');
Map<String, dynamic>? night(String iso) => _get('night:$iso');
Map<String, dynamic>? meta(String name) => _get('meta:$name');
/// Every row of a kind (day / night / workout) in [a, z] (ISO days; null = all), by day.
List<Map<String, dynamic>> all(String kind, {String? a, String? z}) {
final rs = store.rows('health.summary', where: "json_extract(data, '\$.kind') = ?", args: [kind]);
final out = <Map<String, dynamic>>[];
for (final r in rs) {
final d = r['day'] as String?;
if (a != null && d != null && d.compareTo(a) < 0) continue;
if (z != null && d != null && d.compareTo(z) > 0) continue;
out.add({'_day': d, ...jsonDecode(r['data'] as String) as Map<String, dynamic>});
}
out.sort((x, y) => ((x['_day'] as String?) ?? '').compareTo((y['_day'] as String?) ?? ''));
return out;
}
}

176
app/lib/main.dart Normal file
View file

@ -0,0 +1,176 @@
// dashPi companion app: Health (with Cycle + Food), Work, Weather — works offline, keeps its own
// copy of the data and syncs it through your dash-sync mailbox (server/) with the dashboard.
// First start: Connect (device token + passphrase); then the app (app/shell.dart).
//
// A build may prefill the server: --dart-define=DEV_SERVER=https://sync.example.com (tool/publish.env);
// dev runs also DEV_TOKEN=… DEV_PASS=… (only ever with a local test mailbox).
import 'dart:io';
import 'package:flutter/foundation.dart' show kDebugMode;
import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart' show Format;
import 'app/background.dart';
import 'app/scanner.dart';
import 'app/shell.dart';
import 'app/sync_service.dart';
import 'app/theme.dart';
import 'health/food_model.dart' show FoodDb;
import 'sync/client.dart';
import 'sync/store.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(const DashApp());
}
class DashApp extends StatelessWidget {
const DashApp({super.key});
@override
Widget build(BuildContext context) =>
MaterialApp(title: 'dashPi', debugShowCheckedModeBanner: false, theme: appTheme(), home: const Start());
}
/// Connected → the app, else the connect form.
class Start extends StatefulWidget {
const Start({super.key});
@override
State<Start> createState() => _StartState();
}
class _StartState extends State<Start> {
SyncService? sync;
bool loading = true;
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
final s = await SyncSettings.load();
if (s != null) {
sync = SyncService(s, SyncStore(await dataPath(), s.device));
FoodDb.store = sync!.store; // products kept from the archive (food_model.dart)
scheduleBackground();
}
setState(() => loading = false);
}
Future<void> _connected(SyncSettings s) async {
await s.save();
final st = SyncStore(await dataPath(), s.device);
FoodDb.store = st;
setState(() => sync = SyncService(s, st));
scheduleBackground();
}
/// Disconnect: the settings are gone already; drop this phone's copy of the data too.
Future<void> _forget() async {
final old = sync;
await stopBackground();
setState(() => sync = null);
old?.store.db.close();
old?.dispose();
final p = await dataPath();
for (final f in [p, '$p-wal', '$p-shm']) {
if (File(f).existsSync()) File(f).deleteSync();
}
}
@override
Widget build(BuildContext context) {
if (loading) return const Scaffold(body: Center(child: CircularProgressIndicator()));
if (sync == null) return ConnectPage(onConnected: _connected);
return Shell(sync: sync!, onForget: _forget);
}
}
class ConnectPage extends StatefulWidget {
const ConnectPage({super.key, required this.onConnected});
final Future<void> Function(SyncSettings) onConnected;
@override
State<ConnectPage> createState() => _ConnectPageState();
}
class _ConnectPageState extends State<ConnectPage> {
final server = TextEditingController(text: const String.fromEnvironment('DEV_SERVER'));
final token = TextEditingController(text: const String.fromEnvironment('DEV_TOKEN'));
final pass = TextEditingController(text: const String.fromEnvironment('DEV_PASS'));
final recovery = TextEditingController();
bool busy = false, useRecovery = false;
String? error;
/// The QR code from the dashboard's Settings ▸ General ▸ Add a device: dashpi://connect?server=…&token=…
bool _takeLink(String text) {
final u = Uri.tryParse(text.trim());
if (u == null || u.scheme != 'dashpi' || u.host != 'connect') return false;
final s = u.queryParameters['server'], t = u.queryParameters['token'];
if (s == null || t == null || s.isEmpty || t.isEmpty) return false;
setState(() {
server.text = s;
token.text = t;
error = null;
});
return true;
}
Future<void> _scan() async {
final v = await scanCode(context, title: 'Scan the code from the dashboard', format: Format.qrCode,
accept: (v) => v.startsWith('dashpi://connect?'));
if (v != null && !_takeLink(v)) setState(() => error = "That's not a code from the dashboard.");
}
Future<void> _go() async {
if (_takeLink(token.text) || _takeLink(server.text)) return; // the link pasted into a field
setState(() {
busy = true;
error = null;
});
try {
if (!kDebugMode && !server.text.trim().startsWith('https://')) {
throw 'The server needs an https:// address (the token travels with every request).';
}
final s = await join(server.text.trim(), token.text.trim(),
passphrase: pass.text, recovery: useRecovery ? recovery.text : null);
await widget.onConnected(s);
} catch (e) {
setState(() => error = '$e');
} finally {
if (mounted) setState(() => busy = false);
}
}
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('Connect to your dashboard')),
body: ListView(padding: const EdgeInsets.all(16), children: [
const Text('On the dashboard: Settings ▸ General ▸ Devices ▸ Add a device shows a code — scan it, then type '
'the passphrase you chose when you set up sync there.', style: TextStyle(color: muted)),
const SizedBox(height: 12),
OutlinedButton.icon(onPressed: busy ? null : _scan, icon: const Icon(Icons.qr_code_scanner),
label: const Text('Scan the code from the dashboard')),
const SizedBox(height: 8),
TextField(controller: server, keyboardType: TextInputType.url,
decoration: const InputDecoration(labelText: 'Server', hintText: 'https://sync.example.com')),
TextField(controller: token, obscureText: true, decoration: const InputDecoration(labelText: 'Device token')),
if (!useRecovery)
TextField(controller: pass, obscureText: true, decoration: const InputDecoration(labelText: 'Sync passphrase'))
else
TextField(controller: recovery, decoration: const InputDecoration(labelText: 'Recovery key (ABCD-EFGH-…)')),
TextButton(
onPressed: () => setState(() => useRecovery = !useRecovery),
child: Text(useRecovery ? 'Use the passphrase instead' : 'Forgot it? Use the recovery key')),
const SizedBox(height: 12),
if (error != null) Text(error!, style: const TextStyle(color: bad)),
const SizedBox(height: 12),
FilledButton(
onPressed: busy ? null : _go,
child: busy
? const SizedBox(height: 18, width: 18, child: CircularProgressIndicator(strokeWidth: 2))
: const Text('Connect')),
]),
);
}

284
app/lib/notes/markdown.dart Normal file
View file

@ -0,0 +1,284 @@
// Markdown → widgets for the notes' preview: the same reading as the web page's (notes.js md):
// headings, paragraphs (a line break is a break), - / 1. lists (nested by indent), - [ ] tasks
// (tappable: onTask(n) with n counted like toggleTask), > quotes, ``` code, tables, --- rules;
// inline **bold**, *italic*, ~~strike~~, ==mark==, `code`, [links](https://…), bare URLs, #tags.
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../app/theme.dart';
const _cool = Color(0xFF5CC8FF), _dim = Color(0xFF5D6472), _codeBg = Color(0xFF10131A);
const mono = TextStyle(fontFamily: 'monospace', fontSize: 13.5);
final _fence = RegExp(r'^\s*(```|~~~)'), _head = RegExp(r'^(#{1,6})\s+(.*)$'), _hr = RegExp(r'^\s*([-*_])(\s*\1){2,}\s*$');
final _quote = RegExp(r'^\s*>'), _item = RegExp(r'^(\s*)([-*+]|\d+[.)])\s+(.*)$');
final _tsep = RegExp(r'^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$');
final _taskLine = RegExp(r'^(\s*(?:>\s*)*(?:[-*+]|\d+[.)])\s+\[)([ xX])(\].*)$');
final tagRe = RegExp(r'(^|\s)#(\p{L}[\p{L}\p{N}_/-]*)', unicode: true);
final _inline = RegExp(
r'`([^`]+)`' // 1 code
r'|\[([^\]]+)\]\(([^)\s]+)\)' // 2, 3 link
r'''|(https?://[^\s<>()]+[^\s<>().,;:!?'"])''' // 4 bare URL
r'|\*\*(.+?)\*\*|__(.+?)__' // 5, 6 bold
r'|(?<![*\w])\*(?!\s)(.+?)\*(?!\w)' // 7 italic
r'|(?<![_\w])_(?!\s)(.+?)_(?!\w)' // 8 italic
r'|~~(.+?)~~' // 9 strike
r'|==(.+?)==' // 10 mark
r'|(?<=^|\s)#(\p{L}[\p{L}\p{N}_/-]*)', // 11 tag
unicode: true);
/// Tick / untick the n-th checkbox in the text (counted outside code blocks, like the preview).
String toggleTask(String src, int n) {
final lines = src.split('\n');
var k = 0;
String? fence;
for (var i = 0; i < lines.length; i++) {
final f = _fence.firstMatch(lines[i]);
if (fence != null) {
if (lines[i].trim().startsWith(fence)) fence = null;
continue;
}
if (f != null) {
fence = f[1];
continue;
}
final m = _taskLine.firstMatch(lines[i]);
if (m != null && k++ == n) {
lines[i] = '${m[1]}${m[2] == ' ' ? 'x' : ' '}${m[3]}';
break;
}
}
return lines.join('\n');
}
class MarkdownView extends StatefulWidget {
const MarkdownView(this.text, {super.key, this.onTask, this.onTag});
final String text;
final void Function(int n)? onTask;
final void Function(String tag)? onTag;
@override
State<MarkdownView> createState() => _MarkdownViewState();
}
class _MarkdownViewState extends State<MarkdownView> {
final _taps = <TapGestureRecognizer>[];
int _task = 0;
@override
void dispose() {
for (final t in _taps) {
t.dispose();
}
super.dispose();
}
TapGestureRecognizer _tap(VoidCallback fn) {
final t = TapGestureRecognizer()..onTap = fn;
_taps.add(t);
return t;
}
void _openLink(String url) {
Clipboard.setData(ClipboardData(text: url));
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Link copied: $url')));
}
// ---- inline ------------------------------------------------------------------------------
List<InlineSpan> _spans(String s, TextStyle st) {
final out = <InlineSpan>[];
var at = 0;
for (final m in _inline.allMatches(s)) {
if (m.start > at) out.add(TextSpan(text: s.substring(at, m.start), style: st));
at = m.end;
if (m[1] != null) {
out.add(TextSpan(text: m[1], style: st.merge(mono).copyWith(backgroundColor: _codeBg)));
} else if (m[2] != null || m[4] != null) {
final url = m[3] ?? m[4]!;
if (!RegExp(r'^(https?:|mailto:)', caseSensitive: false).hasMatch(url)) {
out.add(TextSpan(text: m[0], style: st));
continue;
}
out.add(TextSpan(text: m[2] ?? url, style: st.copyWith(color: _cool, decoration: TextDecoration.underline,
decorationColor: _cool), recognizer: _tap(() => _openLink(url))));
} else if (m[5] != null || m[6] != null) {
out.addAll(_spans(m[5] ?? m[6]!, st.copyWith(fontWeight: FontWeight.bold)));
} else if (m[7] != null || m[8] != null) {
out.addAll(_spans(m[7] ?? m[8]!, st.copyWith(fontStyle: FontStyle.italic)));
} else if (m[9] != null) {
out.addAll(_spans(m[9]!, st.copyWith(color: _dim, decoration: TextDecoration.lineThrough)));
} else if (m[10] != null) {
out.addAll(_spans(m[10]!, st.copyWith(backgroundColor: const Color(0xFF4A3B1E))));
} else if (m[11] != null) {
final tag = m[11]!;
out.add(TextSpan(text: '#$tag', style: st.copyWith(color: _cool),
recognizer: widget.onTag == null ? null : _tap(() => widget.onTag!(tag.toLowerCase()))));
}
}
if (at < s.length) out.add(TextSpan(text: s.substring(at), style: st));
return out;
}
Widget _text(String s, TextStyle st) => Text.rich(TextSpan(children: _spans(s, st)));
// ---- blocks ------------------------------------------------------------------------------
List<Widget> _blocks(String src, TextStyle base) {
final lines = src.replaceAll('\r\n', '\n').split('\n');
final out = <Widget>[];
bool starts(String l) =>
_fence.hasMatch(l) || _head.hasMatch(l) || _hr.hasMatch(l) || _quote.hasMatch(l) || _item.hasMatch(l);
var i = 0;
while (i < lines.length) {
final l = lines[i];
if (l.trim().isEmpty) {
i++;
continue;
}
RegExpMatch? m;
if ((m = _fence.firstMatch(l)) != null) {
final code = <String>[];
for (i++; i < lines.length && !lines[i].trim().startsWith(m![1]!); i++) {
code.add(lines[i]);
}
i++;
out.add(Container(
width: double.infinity,
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(color: _codeBg, borderRadius: BorderRadius.circular(10)),
child: SingleChildScrollView(scrollDirection: Axis.horizontal, child: Text(code.join('\n'), style: mono)),
));
} else if ((m = _head.firstMatch(l)) != null) {
final n = m![1]!.length;
final size = const [24.0, 20.0, 17.5, 15.5, 15.0, 15.0][n - 1];
out.add(Padding(
padding: const EdgeInsets.only(top: 6),
child: _text(m[2]!.replaceAll(RegExp(r'\s#+\s*$'), ''), base.copyWith(fontSize: size,
fontWeight: FontWeight.bold, color: n == 1 ? accent : n >= 4 ? muted : null)),
));
i++;
} else if (_hr.hasMatch(l)) {
out.add(const Divider(color: card2, height: 20));
i++;
} else if (_quote.hasMatch(l)) {
final q = <String>[];
for (; i < lines.length && _quote.hasMatch(lines[i]); i++) {
q.add(lines[i].replaceFirst(RegExp(r'^\s*>\s?'), ''));
}
out.add(Container(
padding: const EdgeInsets.only(left: 12),
decoration: const BoxDecoration(border: Border(left: BorderSide(color: Color(0xFF3A4253), width: 3))),
child: _column(_blocks(q.join('\n'), base.copyWith(color: muted))),
));
} else if (l.contains('|') && i + 1 < lines.length && _tsep.hasMatch(lines[i + 1])) {
List<String> cells(String x) => x.trim().replaceAll(RegExp(r'^\||\|$'), '').split('|').map((c) => c.trim()).toList();
final rows = [cells(l)];
for (i += 2; i < lines.length && lines[i].contains('|') && lines[i].trim().isNotEmpty; i++) {
rows.add(cells(lines[i]));
}
final w = rows.map((r) => r.length).reduce((a, b) => a > b ? a : b);
out.add(SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Table(
defaultColumnWidth: const IntrinsicColumnWidth(),
border: TableBorder.all(color: card2),
children: [
for (final (k, r) in rows.indexed)
TableRow(
decoration: k == 0 ? const BoxDecoration(color: _codeBg) : null,
children: [
for (var c = 0; c < w; c++)
Padding(padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
child: _text(c < r.length ? r[c] : '', k == 0 ? base.copyWith(fontWeight: FontWeight.bold) : base)),
],
),
],
),
));
} else if (_item.hasMatch(l)) {
final items = <(int, bool, String)>[];
while (i < lines.length) {
final x = lines[i];
final im = _item.firstMatch(x);
if (im != null) {
items.add((im[1]!.replaceAll('\t', ' ').length, RegExp(r'\d').hasMatch(im[2]!), im[3]!));
} else if (x.trim().isNotEmpty && RegExp(r'^\s').hasMatch(x) && items.isNotEmpty) {
final (a, b, t) = items.removeLast(); // a wrapped line of the item above
items.add((a, b, '$t\n${x.trim()}'));
} else {
break;
}
i++;
}
out.add(_list(items, base));
} else {
final p = <String>[];
for (; i < lines.length && lines[i].trim().isNotEmpty && !(p.isNotEmpty && starts(lines[i])); i++) {
p.add(lines[i]);
}
out.add(_text(p.join('\n'), base));
}
}
return out;
}
/// One row per item, indented by its depth (the indents seen so far, like nested lists).
Widget _list(List<(int, bool, String)> items, TextStyle base) {
final stack = <int>[], numbers = <int>[];
final rows = <Widget>[];
for (final (ind, ordered, text) in items) {
while (stack.isNotEmpty && ind < stack.last) {
stack.removeLast();
numbers.removeLast();
}
if (stack.isEmpty || ind > stack.last) {
stack.add(ind);
numbers.add(0);
}
numbers[numbers.length - 1]++;
final depth = stack.length - 1;
final t = RegExp(r'^\[([ xX])\](\s+|$)([\s\S]*)$').firstMatch(text);
Widget lead;
Widget body;
if (t != null) {
final n = _task++, done = t[1] != ' ';
lead = InkWell(
onTap: widget.onTask == null ? null : () => widget.onTask!(n),
child: Padding(
padding: const EdgeInsets.only(right: 6),
child: Icon(done ? Icons.check_box : Icons.check_box_outline_blank, size: 21, color: done ? accent : muted),
),
);
body = _text(t[3]!, done ? base.copyWith(color: _dim, decoration: TextDecoration.lineThrough) : base);
} else {
lead = SizedBox(
width: 22,
child: Text(ordered ? '${numbers.last}.' : depth.isEven ? '•' : '◦', style: base.copyWith(color: muted)),
);
body = _text(text, base);
}
rows.add(Padding(
padding: EdgeInsets.only(left: 4 + depth * 20.0, top: 2, bottom: 2),
child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [lead, Expanded(child: body)]),
));
}
return _column(rows, gap: 0);
}
Widget _column(List<Widget> ws, {double gap = 8}) => Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
for (final (k, w) in ws.indexed) ...[if (k > 0) SizedBox(height: gap), w],
],
);
@override
Widget build(BuildContext context) {
for (final t in _taps) {
t.dispose();
}
_taps.clear();
_task = 0;
final base = DefaultTextStyle.of(context).style.copyWith(fontSize: 15.5, height: 1.45);
return _column(_blocks(widget.text, base), gap: 10);
}
}

View file

@ -0,0 +1,346 @@
// One note: Preview (markdown.dart — tap a checkbox to tick it, a #tag to list its notes) or Edit
// (the markdown text, a toolbar above the keyboard; Enter in a list item starts the next one).
// Saves a second after the last key and on leaving; when a sync changed the note meanwhile, the
// text is kept as a copy beside it (notes_model.saveNote). A change arriving while nothing is typed
// here just shows up.
import 'dart:async';
import 'package:flutter/material.dart';
import '../app/sync_service.dart';
import '../app/theme.dart';
import 'markdown.dart';
import 'notes_model.dart';
import 'notes_page.dart' show askFolder;
class NoteEditor extends StatefulWidget {
const NoteEditor({super.key, required this.sync, this.id, this.folder = '', this.pinned = false, this.startText = '',
this.onTag});
final SyncService sync;
final String? id; // null = a new note (saved once there's text)
final String folder, startText;
final bool pinned;
final void Function(String tag)? onTag;
@override
State<NoteEditor> createState() => _NoteEditorState();
}
final _itemRe = RegExp(r'^(\s*)([-*+]|\d+[.)])(\s+)(\[[ xX]\]\s+)?(.*)$');
class _NoteEditorState extends State<NoteEditor> {
late String? id = widget.id;
late final Note? first = id == null ? null : getNote(widget.sync.store, id!);
late final text = TextEditingController(text: first?.body ?? widget.startText);
late String? base = first?.rev;
late String folder = first?.folder ?? widget.folder;
late bool pinned = first?.pinned ?? widget.pinned;
late bool editing = first == null || first!.body.trim().isEmpty;
late String last = text.text;
bool dirty = false;
Timer? timer;
final focus = FocusNode();
SyncService get sync => widget.sync;
Note? get note => id == null ? null : getNote(sync.store, id!);
@override
void initState() {
super.initState();
sync.addListener(_synced);
if (first == null) text.selection = const TextSelection.collapsed(offset: 0);
}
@override
void dispose() {
_save(later: true);
sync.removeListener(_synced);
timer?.cancel();
text.dispose();
focus.dispose();
super.dispose();
}
/// Data arrived / changed: the note changed elsewhere and nothing's typed here → show it.
void _synced() {
if (id == null || !mounted) return;
final n = note;
if (n == null) { // deleted on another device
if (dirty) {
id = null; // what's typed becomes a new note
_save(later: true);
} else {
Navigator.of(context).maybePop();
}
return;
}
if (n.rev != base && !dirty) {
setState(() {
base = n.rev;
text.text = last = n.body;
});
}
if (n.folder != folder || n.pinned != pinned) {
setState(() {
folder = n.folder;
pinned = n.pinned;
});
}
}
/// later: from dispose / a sync callback — the pages hear about it after this frame.
void _save({bool later = false}) {
timer?.cancel();
if (!dirty) return;
dirty = false;
if (id == null && text.text.trim().isEmpty) return; // an empty new note: nothing to keep
final (nid, conflict) = saveNote(sync.store, id: id, body: text.text, base: base, folder: folder, pinned: pinned);
id = nid;
base = note?.rev;
if (later) {
scheduleMicrotask(sync.changed);
return;
}
sync.changed();
if (conflict && mounted) {
setState(() {});
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('This note changed on another device meanwhile — your text is kept as a separate copy.')));
}
}
void _changed(String v) {
// Enter at the end of a list item: the next item (an empty item ends the list)
final p = text.selection.baseOffset;
if (v.length == last.length + 1 && p > 0 && text.selection.isCollapsed && v[p - 1] == '\n' &&
v.substring(0, p - 1) + v.substring(p) == last) {
final s = v.lastIndexOf('\n', p - 2) + 1;
final m = _itemRe.firstMatch(v.substring(s, p - 1));
if (m != null) {
if (m[5]!.trim().isEmpty) {
_set(v.substring(0, s) + v.substring(p), s);
} else {
final n = RegExp(r'^(\d+)([.)])$').firstMatch(m[2]!);
final mark = '${m[1]}${n == null ? m[2] : '${int.parse(n[1]!) + 1}${n[2]}'}${m[3]}${m[4] != null ? '[ ] ' : ''}';
_set(v.substring(0, p) + mark + v.substring(p), p + mark.length);
}
return;
}
}
last = v;
_dirty();
}
void _set(String v, int cursor) {
text.value = TextEditingValue(text: v, selection: TextSelection.collapsed(offset: cursor));
last = v;
_dirty();
}
void _dirty() {
dirty = true;
timer?.cancel();
timer = Timer(const Duration(seconds: 1), _save);
}
// ---- toolbar -------------------------------------------------------------------------------
void _wrap(String a, [String? b, String ph = 'text']) {
b ??= a;
final v = text.text, sel = text.selection.isValid ? text.selection : TextSelection.collapsed(offset: v.length);
final inner = sel.isCollapsed ? ph : sel.textInside(v);
_set(v.replaceRange(sel.start, sel.end, '$a$inner$b'), sel.start + a.length + inner.length);
text.selection = TextSelection(baseOffset: sel.start + a.length, extentOffset: sel.start + a.length + inner.length);
focus.requestFocus();
}
void _lines(String Function(String) fn) {
final v = text.text, sel = text.selection.isValid ? text.selection : TextSelection.collapsed(offset: v.length);
final s = sel.start == 0 ? 0 : v.lastIndexOf('\n', sel.start - 1) + 1;
var e = v.indexOf('\n', sel.end);
if (e < 0) e = v.length;
final block = v.substring(s, e).split('\n').map(fn).join('\n');
_set(v.replaceRange(s, e, block), s + block.length);
focus.requestFocus();
}
late final tools = <(Widget, String, VoidCallback)>[
(const Text('H', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 17)), 'Heading', () => _lines((l) =>
RegExp(r'^#{1,5}\s').hasMatch(l) ? '#$l' : RegExp(r'^#{6}\s').hasMatch(l) ? l.replaceFirst(RegExp(r'^#+\s'), '') : '# $l')),
(const Icon(Icons.format_bold), 'Bold', () => _wrap('**')),
(const Icon(Icons.format_italic), 'Italic', () => _wrap('*')),
(const Icon(Icons.format_strikethrough), 'Strikethrough', () => _wrap('~~')),
(const Icon(Icons.format_list_bulleted), 'List', () => _lines((l) => RegExp(r'^\s*[-*+]\s').hasMatch(l)
? l.replaceFirst(RegExp(r'^(\s*)[-*+]\s+(\[[ xX]\]\s+)?'), '') : '- $l')),
(const Icon(Icons.check_box_outlined), 'Checklist', () => _lines((l) => RegExp(r'^\s*[-*+]\s\[[ xX]\]').hasMatch(l)
? l.replaceFirst(RegExp(r'^\s*[-*+]\s\[[ xX]\]\s?'), '') : l.replaceFirst(RegExp(r'^\s*(?:[-*+]\s+)?'), '- [ ] '))),
(const Icon(Icons.format_quote), 'Quote', () => _lines((l) => l.startsWith('>') ? l.replaceFirst(RegExp(r'^>\s?'), '') : '> $l')),
(const Icon(Icons.code), 'Code', () => _wrap('`', '`', 'code')),
(const Icon(Icons.link), 'Link', () => _wrap('[', '](https://)', 'link')),
(const Icon(Icons.tag), 'Tag', () => _wrap('#', '', 'tag')),
];
// ---- the menu ------------------------------------------------------------------------------
Future<void> _move() async {
final f = await askFolder(context, sync, folder);
if (f == null) return;
setState(() => folder = cleanFolder(f));
if (id != null) {
_save();
setNote(sync.store, id!, {'folder': folder});
sync.changed();
}
}
void _pin() {
setState(() => pinned = !pinned);
if (id != null) {
_save();
setNote(sync.store, id!, {'pinned': pinned ? 1 : 0});
sync.changed();
}
}
void _trash() {
_save();
if (id != null) {
trashNote(sync.store, id!, true);
sync.changed();
}
dirty = false;
Navigator.pop(context);
}
@override
Widget build(BuildContext context) {
final n = note;
final trashed = n?.trashed != null;
final showEdit = editing && !trashed;
return Scaffold(
appBar: AppBar(
titleSpacing: 0,
title: InkWell(
onTap: trashed ? null : _move,
child: Row(mainAxisSize: MainAxisSize.min, children: [
Icon(folder.isEmpty ? Icons.folder_off_outlined : Icons.folder_outlined, size: 18, color: muted),
const SizedBox(width: 6),
Flexible(child: Text(folder.isEmpty ? 'No folder' : folder, overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 15, color: muted))),
]),
),
actions: [
if (!trashed) ...[
IconButton(
tooltip: editing ? 'Preview' : 'Edit',
icon: Icon(editing ? Icons.visibility_outlined : Icons.edit_outlined),
onPressed: () {
_save();
setState(() => editing = !editing);
if (editing) focus.requestFocus();
},
),
IconButton(
tooltip: pinned ? 'Unpin' : 'Pin to the top',
icon: Icon(pinned ? Icons.push_pin : Icons.push_pin_outlined, color: pinned ? accent : null),
onPressed: _pin,
),
],
PopupMenuButton<String>(
icon: const Icon(Icons.more_vert),
color: card2,
onSelected: (k) {
switch (k) {
case 'move':
_move();
case 'trash':
_trash();
case 'restore':
trashNote(sync.store, id!, false);
sync.changed();
case 'purge':
deleteNote(sync.store, id!);
sync.changed();
Navigator.pop(context);
}
},
itemBuilder: (_) => trashed
? const [
PopupMenuItem(value: 'restore', child: Text('Restore')),
PopupMenuItem(value: 'purge', child: Text('Delete for good', style: TextStyle(color: bad))),
]
: const [
PopupMenuItem(value: 'move', child: Text('Move to folder…')),
PopupMenuItem(value: 'trash', child: Text('Move to the trash')),
],
),
],
),
body: SafeArea(
top: false,
child: Column(children: [
if (trashed)
_banner('In the trash — restore it to edit.', null)
else if (n?.origin != null)
_banner('Conflicted copy: this note was changed on two devices at once, and this is the version that didn\'t '
'win — the other one kept the original. Take what you need, then keep it or move it to the trash.',
TextButton(onPressed: () {
setNote(sync.store, id!, {'origin': null});
sync.changed();
}, child: const Text('Keep as a normal note'))),
Expanded(
child: showEdit
? Padding(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 0),
child: TextField(
controller: text,
focusNode: focus,
autofocus: first == null,
expands: true,
maxLines: null,
keyboardType: TextInputType.multiline,
textCapitalization: TextCapitalization.sentences,
style: const TextStyle(fontFamily: 'monospace', fontSize: 15, height: 1.45),
decoration: const InputDecoration(border: InputBorder.none,
hintText: 'Write in markdown: # heading, **bold**, - [ ] a task, #tag …'),
onChanged: _changed,
),
)
: ListView(padding: const EdgeInsets.fromLTRB(18, 10, 18, 40), children: [
if (text.text.trim().isEmpty)
const Text('Empty — tap ✎ to write.', style: TextStyle(color: muted))
else
MarkdownView(
text.text,
onTask: trashed ? null : (i) => setState(() {
_set(toggleTask(text.text, i), 0);
_save();
}),
onTag: widget.onTag == null ? null : (t) {
widget.onTag!(t);
Navigator.pop(context);
},
),
]),
),
if (showEdit)
Container(
color: card,
height: 46,
child: ListView(scrollDirection: Axis.horizontal, children: [
for (final (icon, tip, fn) in tools) IconButton(tooltip: tip, icon: icon, onPressed: fn),
]),
),
]),
),
);
}
Widget _banner(String msg, Widget? action) => Container(
width: double.infinity,
margin: const EdgeInsets.fromLTRB(12, 8, 12, 0),
padding: const EdgeInsets.fromLTRB(12, 10, 12, 4),
decoration: BoxDecoration(color: const Color(0xFF3A2A17), borderRadius: BorderRadius.circular(10)),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text(msg, style: const TextStyle(color: Color(0xFFF4D6A8), fontSize: 13.5)),
if (action != null) Align(alignment: Alignment.centerRight, child: action) else const SizedBox(height: 6),
]),
);
}

View file

@ -0,0 +1,136 @@
// Notes: the dashboard's notes plugin (plugins/notes/db.py) on the phone — one synced row per note
// in "notes.note": folder ("Work/Acme", '' = none), body (markdown), pinned, created / updated
// (UTC), rev / revs (versions, for the sync's "keep both copies" — SyncStore.forks), origin (a
// conflicted copy: the rev it keeps), trashed (in the trash since). Title = the first line, tags =
// the #words — worked out on read, like the web page.
import 'dart:math';
import '../sync/store.dart';
import 'markdown.dart' show tagRe;
const noteTable = 'notes.note';
const _revs = 200; // versions remembered per note (db.REVS)
String nowIso() => '${DateTime.now().toUtc().toIso8601String().substring(0, 19)}Z';
String newRev() {
final r = Random.secure();
return List.generate(6, (_) => r.nextInt(256).toRadixString(16).padLeft(2, '0')).join();
}
String noteTitle(String body) {
for (final l in body.split('\n')) {
final s = l.trim().replaceFirst(RegExp(r'^#+'), '').trim();
if (s.isNotEmpty) return s.length > 120 ? s.substring(0, 120) : s;
}
return 'Untitled';
}
List<String> noteTags(String body) {
final plain = body.replaceAll(RegExp(r'```[\s\S]*?(```|$)'), '').replaceAll(RegExp(r'`[^`\n]*`'), '');
return {for (final m in tagRe.allMatches(plain)) m[2]!.toLowerCase()}.toList();
}
String noteSnippet(String body) {
final lines = body.split('\n');
final first = lines.indexWhere((l) => l.trim().isNotEmpty);
final text = lines.skip(first + 1).map((l) => l.replaceFirst(RegExp(r'^\s*(?:[-*+]|\d+[.)])\s+(?:\[[ xX]\]\s+)?'), '')).join(' ')
.replaceAll(RegExp(r'[#>*_`~=\[\]]|\(http[^)]*\)'), '').replaceAll(RegExp(r'\s+'), ' ').trim();
return text.length > 160 ? text.substring(0, 160) : text;
}
/// " Work / Acme/ " → "Work/Acme".
String cleanFolder(String f) => f.replaceAll('\\', '/').split('/').map((p) => p.trim()).where((p) => p.isNotEmpty).join('/');
/// Lower case without accents, for search.
String fold(String s) {
const from = 'áäàâãåčćďéěëèêíïìîľĺňñóöòôõőřŕšśťúůüùûűýÿžźżłąęß';
const to = 'aaaaaaccdeeeeeiiiillnnoooooorrssstuuuuuuyyzzzlaes';
final out = StringBuffer();
for (final c in s.toLowerCase().split('')) {
final i = from.indexOf(c);
out.write(i < 0 ? c : to[i]);
}
return out.toString();
}
class Note {
Note(this.r);
final Map<String, dynamic> r;
String get id => r['_u'] as String;
String get body => (r['body'] as String?) ?? '';
String get folder => (r['folder'] as String?) ?? '';
bool get pinned => (r['pinned'] as num? ?? 0) != 0;
String get updated => (r['updated'] as String?) ?? '';
String get rev => (r['rev'] as String?) ?? '';
String? get origin => r['origin'] as String?;
String? get trashed => r['trashed'] as String?;
String get title => noteTitle(body);
List<String> get tags => noteTags(body);
}
List<Note> allNotes(SyncStore s) => [for (final r in s.rows(noteTable)) Note(r)];
Note? getNote(SyncStore s, String id) {
final r = s.row(noteTable, id);
return r == null ? null : Note(r);
}
/// Save the text typed on version [base] → (the note's id, conflict). A new note: no id. When the
/// note changed meanwhile (a sync came in), the text becomes a copy beside it (db.save).
(String, bool) saveNote(SyncStore s, {String? id, required String body, String? base, String folder = '', bool pinned = false}) {
final t = nowIso();
final cur = id == null ? null : s.row(noteTable, id);
if (cur == null || (base != null && base != cur['rev'] && body != cur['body'])) {
final rev = newRev(), nid = SyncStore.randomId();
final copy = cur != null;
s.put(noteTable, nid, {
'folder': copy ? cur['folder'] : cleanFolder(folder), 'body': body, 'pinned': copy ? 0 : (pinned ? 1 : 0),
'created': t, 'updated': t, 'rev': rev, 'revs': rev, 'origin': copy ? rev : null, 'trashed': null,
});
return (nid, copy);
}
if (body == cur['body']) return (id!, false);
final row = {...cur, 'body': body, 'updated': t};
if (s.known(noteTable, id!)) { // seen elsewhere: a new version (else typing goes on in this one)
final rev = newRev();
final revs = [...((cur['revs'] as String?) ?? '').split(' ').where((x) => x.isNotEmpty), rev];
row['rev'] = rev;
row['revs'] = revs.skip(max(0, revs.length - _revs)).join(' ');
}
s.put(noteTable, id, row);
return (id, false);
}
/// Pinned, folder, trashed, origin — no new version.
void setNote(SyncStore s, String id, Map<String, dynamic> fields) {
final cur = s.row(noteTable, id);
if (cur != null) s.put(noteTable, id, {...cur, ...fields});
}
void trashNote(SyncStore s, String id, bool on) => setNote(s, id, {'trashed': on ? nowIso() : null});
/// For good (from the trash).
void deleteNote(SyncStore s, String id) => s.delete(noteTable, id);
int emptyTrash(SyncStore s) {
final gone = allNotes(s).where((n) => n.trashed != null).toList();
for (final n in gone) {
s.delete(noteTable, n.id);
}
return gone.length;
}
/// Every note in [from] and its sub-folders moves to [to] (same sub-paths).
int renameFolder(SyncStore s, String from, String to) {
from = cleanFolder(from);
to = cleanFolder(to);
var n = 0;
for (final x in allNotes(s)) {
if (x.folder == from || x.folder.startsWith('$from/')) {
setNote(s, x.id, {'folder': cleanFolder(to + x.folder.substring(from.length))});
n++;
}
}
return n;
}

View file

@ -0,0 +1,437 @@
// Notes: the list — search box, where you are in the title (tap: All / Pinned / conflicted copies /
// folders / tags / Trash), pinned first, newest change first; + = a new note there; tap = the note
// (note_editor.dart), long-press = pin, move, trash. ⋮: rename the folder, empty the trash.
import 'package:flutter/material.dart';
import '../app/sync_service.dart';
import '../app/theme.dart';
import 'note_editor.dart';
import 'notes_model.dart';
/// Where the list is: all, pinned, conflicts, folder (value), tag (value), trash.
typedef NoteFilter = ({String kind, String? value});
class NotesPage extends StatefulWidget {
const NotesPage({super.key, required this.sync, this.actions = const []});
final SyncService sync;
final List<Widget> actions;
@override
State<NotesPage> createState() => _NotesPageState();
}
class _NotesPageState extends State<NotesPage> {
NoteFilter filter = (kind: 'all', value: null);
final search = TextEditingController();
String get label => switch (filter.kind) {
'pinned' => 'Pinned',
'conflicts' => 'Conflicted copies',
'folder' => filter.value!.split('/').last,
'tag' => '#${filter.value}',
'trash' => 'Trash',
_ => 'Notes',
};
List<Note> shown(List<Note> all) {
var l = filter.kind == 'trash' ? all.where((n) => n.trashed != null) : all.where((n) => n.trashed == null);
l = switch (filter.kind) {
'pinned' => l.where((n) => n.pinned),
'conflicts' => l.where((n) => n.origin != null),
'folder' => l.where((n) => n.folder == filter.value || n.folder.startsWith('${filter.value}/')),
'tag' => l.where((n) => n.tags.contains(filter.value)),
_ => l,
};
final words = fold(search.text).split(RegExp(r'\s+')).where((w) => w.isNotEmpty).toList();
if (words.isNotEmpty) {
l = l.where((n) {
final t = fold('${n.body} ${n.folder}');
return words.every(t.contains);
});
}
final out = l.toList()
..sort((a, b) {
if (filter.kind != 'trash' && a.pinned != b.pinned) return a.pinned ? -1 : 1;
return (b.trashed ?? b.updated).compareTo(a.trashed ?? a.updated);
});
return out;
}
void _open(Note? n) => Navigator.push(context, MaterialPageRoute(builder: (_) => NoteEditor(
sync: widget.sync,
id: n?.id,
folder: filter.kind == 'folder' ? filter.value! : '',
pinned: filter.kind == 'pinned',
startText: filter.kind == 'tag' ? '\n\n#${filter.value}' : '',
onTag: (t) => setState(() => filter = (kind: 'tag', value: t)),
)));
/// The sheet behind the title: where to look.
void _where(List<Note> all) {
final live = all.where((n) => n.trashed == null).toList();
final folders = <String, int>{};
for (final n in live) {
if (n.folder.isEmpty) continue;
final parts = n.folder.split('/');
for (var i = 1; i <= parts.length; i++) {
final p = parts.take(i).join('/');
folders[p] = (folders[p] ?? 0) + 1;
}
}
final tags = <String, int>{};
for (final n in live) {
for (final t in n.tags) {
tags[t] = (tags[t] ?? 0) + 1;
}
}
final pinned = live.where((n) => n.pinned).length, copies = live.where((n) => n.origin != null).length;
showModalBottomSheet(
context: context,
backgroundColor: card,
isScrollControlled: true,
builder: (c) {
Widget item(NoteFilter f, Widget icon, String text, int n, {int depth = 0}) => ListTile(
dense: true,
contentPadding: EdgeInsets.only(left: 16 + depth * 18.0, right: 16),
leading: icon,
title: Text(text, overflow: TextOverflow.ellipsis),
trailing: n > 0 ? Text('$n', style: const TextStyle(color: muted)) : null,
selected: f == filter,
selectedColor: accent,
onTap: () {
Navigator.pop(c);
setState(() => filter = f);
},
);
final names = folders.keys.toList()..sort();
final tagNames = tags.keys.toList()..sort();
return DraggableScrollableSheet(
expand: false,
initialChildSize: .6,
maxChildSize: .92,
builder: (_, scroll) => ListView(controller: scroll, children: [
item((kind: 'all', value: null), const Icon(Icons.notes), 'All notes', live.length),
if (pinned > 0) item((kind: 'pinned', value: null), const Icon(Icons.push_pin_outlined), 'Pinned', pinned),
if (copies > 0)
item((kind: 'conflicts', value: null), const Icon(Icons.warning_amber, color: Color(0xFFFF9A4D)),
'Conflicted copies', copies),
if (names.isNotEmpty) const _Cap('Folders'),
for (final f in names)
item((kind: 'folder', value: f), const Icon(Icons.folder_outlined, size: 20), f.split('/').last, folders[f]!,
depth: '/'.allMatches(f).length),
if (tagNames.isNotEmpty) ...[
const _Cap('Tags'),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 14),
child: Wrap(spacing: 6, runSpacing: 6, children: [
for (final t in tagNames)
ChoiceChip(
label: Text('#$t ${tags[t]}'),
selected: filter == (kind: 'tag', value: t),
onSelected: (_) {
Navigator.pop(c);
setState(() => filter = (kind: 'tag', value: t));
},
),
]),
),
],
const Divider(color: card2),
item((kind: 'trash', value: null), const Icon(Icons.delete_outline), 'Trash', all.length - live.length),
const SizedBox(height: 12),
]),
);
},
);
}
/// Long-press: pin, move, trash (or, in the trash: restore, delete for good).
void _actions(Note n) {
final s = widget.sync.store;
showModalBottomSheet(
context: context,
backgroundColor: card,
builder: (c) => SafeArea(child: Column(mainAxisSize: MainAxisSize.min, children: [
ListTile(title: Text(n.title, style: const TextStyle(fontWeight: FontWeight.bold), overflow: TextOverflow.ellipsis)),
if (n.trashed == null) ...[
ListTile(
leading: Icon(n.pinned ? Icons.push_pin : Icons.push_pin_outlined),
title: Text(n.pinned ? 'Unpin' : 'Pin to the top'),
onTap: () {
Navigator.pop(c);
setNote(s, n.id, {'pinned': n.pinned ? 0 : 1});
widget.sync.changed();
},
),
ListTile(
leading: const Icon(Icons.drive_file_move_outlined),
title: const Text('Move to folder…'),
onTap: () async {
Navigator.pop(c);
final f = await askFolder(context, widget.sync, n.folder);
if (f != null) {
setNote(s, n.id, {'folder': cleanFolder(f)});
widget.sync.changed();
}
},
),
ListTile(
leading: const Icon(Icons.delete_outline),
title: const Text('Move to the trash'),
onTap: () {
Navigator.pop(c);
trashNote(s, n.id, true);
widget.sync.changed();
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: const Text('Moved to the trash'),
persist: false, // with an action Flutter keeps it up until tapped
action: SnackBarAction(label: 'Undo', onPressed: () {
trashNote(s, n.id, false);
widget.sync.changed();
}),
));
},
),
] else ...[
ListTile(
leading: const Icon(Icons.restore),
title: const Text('Restore'),
onTap: () {
Navigator.pop(c);
trashNote(s, n.id, false);
widget.sync.changed();
},
),
ListTile(
leading: const Icon(Icons.delete_forever, color: bad),
title: const Text('Delete for good', style: TextStyle(color: bad)),
onTap: () {
Navigator.pop(c);
deleteNote(s, n.id);
widget.sync.changed();
},
),
],
])),
);
}
Future<void> _renameFolder() async {
final old = filter.value!;
final to = await askText(context, 'Rename folder', old, hint: 'a/b for a sub-folder');
if (to == null || cleanFolder(to).isEmpty || cleanFolder(to) == old) return;
renameFolder(widget.sync.store, old, to);
widget.sync.changed();
setState(() => filter = (kind: 'folder', value: cleanFolder(to)));
}
void _emptyTrash() => showDialog(
context: context,
builder: (d) => AlertDialog(
title: const Text('Empty the trash?'),
content: const Text('The notes in it are deleted on every device.'),
actions: [
TextButton(onPressed: () => Navigator.pop(d), child: const Text('Cancel')),
TextButton(onPressed: () {
Navigator.pop(d);
emptyTrash(widget.sync.store);
widget.sync.changed();
}, child: const Text('Delete them', style: TextStyle(color: bad))),
],
),
);
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: widget.sync,
builder: (context, _) {
final all = allNotes(widget.sync.store);
final list = shown(all);
return Scaffold(
appBar: AppBar(
title: InkWell(
onTap: () => _where(all),
child: Row(mainAxisSize: MainAxisSize.min, children: [
Flexible(child: Text(label, overflow: TextOverflow.ellipsis)),
const Icon(Icons.arrow_drop_down),
]),
),
actions: [
...widget.actions,
if (filter.kind == 'folder' || filter.kind == 'trash')
PopupMenuButton<String>(
icon: const Icon(Icons.more_vert),
color: card2,
onSelected: (k) => k == 'rename' ? _renameFolder() : _emptyTrash(),
itemBuilder: (_) => [
if (filter.kind == 'folder') const PopupMenuItem(value: 'rename', child: Text('Rename folder')),
if (filter.kind == 'trash') const PopupMenuItem(value: 'empty', child: Text('Empty the trash')),
],
),
],
),
floatingActionButton: filter.kind == 'trash'
? null
: FloatingActionButton(
backgroundColor: accent,
foregroundColor: bg,
tooltip: 'New note',
onPressed: () => _open(null),
child: const Icon(Icons.add),
),
body: Column(children: [
Padding(
padding: const EdgeInsets.fromLTRB(12, 4, 12, 6),
child: TextField(
controller: search,
onChanged: (_) => setState(() {}),
decoration: InputDecoration(
isDense: true,
hintText: 'Search notes',
prefixIcon: const Icon(Icons.search, size: 20),
suffixIcon: search.text.isEmpty ? null : IconButton(
icon: const Icon(Icons.close, size: 18),
onPressed: () => setState(search.clear),
),
filled: true,
fillColor: card,
border: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide.none),
),
),
),
Expanded(
child: list.isEmpty
? Center(child: Text(
search.text.isNotEmpty ? 'Nothing matches.'
: filter.kind == 'trash' ? 'The trash is empty.' : 'No notes here yet — + to write one.',
style: const TextStyle(color: muted)))
: ListView.builder(
padding: const EdgeInsets.fromLTRB(12, 0, 12, 88),
itemCount: list.length,
itemBuilder: (_, i) => _tile(list[i]),
),
),
]),
);
},
);
Widget _tile(Note n) {
final snip = noteSnippet(n.body), tags = n.tags.take(4).toList();
final showFolder = filter.kind != 'folder' && n.folder.isNotEmpty;
return Card(
margin: const EdgeInsets.only(bottom: 8),
child: InkWell(
borderRadius: BorderRadius.circular(12),
onTap: () => _open(n),
onLongPress: () => _actions(n),
child: Padding(
padding: const EdgeInsets.fromLTRB(14, 10, 14, 10),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Row(children: [
if (n.pinned && filter.kind != 'trash')
const Padding(padding: EdgeInsets.only(right: 4), child: Icon(Icons.push_pin, size: 15, color: accent)),
if (n.origin != null)
const Padding(padding: EdgeInsets.only(right: 4),
child: Icon(Icons.warning_amber, size: 16, color: Color(0xFFFF9A4D))),
Expanded(child: Text(n.title, maxLines: 1, overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold))),
const SizedBox(width: 8),
Text(when(n.trashed ?? n.updated), style: const TextStyle(color: muted, fontSize: 12)),
]),
if (snip.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 3),
child: Text(snip, maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle(color: muted, fontSize: 13.5)),
),
if (showFolder || tags.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 5),
child: Wrap(spacing: 10, children: [
if (showFolder) Text('▸ ${n.folder}', style: const TextStyle(color: Color(0xFF5D6472), fontSize: 12)),
for (final t in tags) Text('#$t', style: const TextStyle(color: Color(0xFF5CC8FF), fontSize: 12)),
]),
),
]),
),
),
);
}
}
class _Cap extends StatelessWidget {
const _Cap(this.text);
final String text;
@override
Widget build(BuildContext context) => Padding(
padding: const EdgeInsets.fromLTRB(16, 14, 16, 4),
child: Text(text.toUpperCase(), style: const TextStyle(color: muted, fontSize: 12, fontWeight: FontWeight.bold)),
);
}
/// "14:05" today, "3 Oct" this year, else "3 Oct 2025".
String when(String iso) {
final d = DateTime.tryParse(iso)?.toLocal();
if (d == null) return '';
final now = DateTime.now();
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
if (d.year == now.year && d.month == now.month && d.day == now.day) {
return '${d.hour.toString().padLeft(2, '0')}:${d.minute.toString().padLeft(2, '0')}';
}
return '${d.day} ${months[d.month - 1]}${d.year == now.year ? '' : ' ${d.year}'}';
}
/// A one-line text dialog → the text, or null when cancelled.
Future<String?> askText(BuildContext context, String title, String value, {String? hint}) {
final c = TextEditingController(text: value);
return showDialog<String>(
context: context,
builder: (d) => AlertDialog(
title: Text(title),
content: TextField(controller: c, autofocus: true, decoration: InputDecoration(hintText: hint),
onSubmitted: (v) => Navigator.pop(d, v)),
actions: [
TextButton(onPressed: () => Navigator.pop(d), child: const Text('Cancel')),
TextButton(onPressed: () => Navigator.pop(d, c.text), child: const Text('OK')),
],
),
);
}
/// Pick a folder (the ones there are, or type a new one; '' = none) → null when cancelled.
Future<String?> askFolder(BuildContext context, SyncService sync, String current) {
final names = {for (final n in allNotes(sync.store)) if (n.trashed == null && n.folder.isNotEmpty) n.folder}.toList()..sort();
return showModalBottomSheet<String>(
context: context,
backgroundColor: card,
isScrollControlled: true,
builder: (c) => SafeArea(child: ConstrainedBox(
constraints: BoxConstraints(maxHeight: MediaQuery.of(c).size.height * .7),
child: ListView(shrinkWrap: true, children: [
const ListTile(title: Text('Move to folder', style: TextStyle(fontWeight: FontWeight.bold))),
ListTile(
leading: const Icon(Icons.create_new_folder_outlined),
title: const Text('New folder…'),
onTap: () async {
final f = await askText(c, 'New folder', current, hint: 'a/b for a sub-folder');
if (c.mounted) Navigator.pop(c, f);
},
),
ListTile(
leading: const Icon(Icons.folder_off_outlined),
title: const Text('No folder'),
selected: current.isEmpty,
selectedColor: accent,
onTap: () => Navigator.pop(c, ''),
),
for (final f in names)
ListTile(
leading: const Icon(Icons.folder_outlined),
title: Text(f),
selected: f == current,
selectedColor: accent,
onTap: () => Navigator.pop(c, f),
),
]),
)),
);
}

122
app/lib/sync/client.dart Normal file
View file

@ -0,0 +1,122 @@
// Talking to the dash-sync mailbox (PROTOCOL.md "HTTP"): join with a device token + the
// passphrase, then pull everyone else's batches and push ours — what the dashboard's
// sync.py does every 5 minutes. The token and the data key live in Android's secure storage
// (Keystore-backed); the rest (clock, how far we've read) in the store.
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:http/http.dart' as http;
import 'crypto.dart';
import 'store.dart';
const chunk = 2000; // changes per batch, like sync.py
class SyncSettings {
SyncSettings({required this.server, required this.token, required this.account, required this.name,
required this.device, required this.key});
final String server, token, account, name, device;
final Uint8List key;
static const _storage = FlutterSecureStorage();
static Future<SyncSettings?> load() async {
final j = await _storage.read(key: 'sync');
if (j == null) return null;
final m = jsonDecode(j) as Map<String, dynamic>;
return SyncSettings(server: m['server'], token: m['token'], account: m['account'], name: m['name'],
device: m['device'], key: base64Decode(m['key']));
}
Future<void> save() => _storage.write(
key: 'sync',
value: jsonEncode({'server': server, 'token': token, 'account': account, 'name': name,
'device': device, 'key': base64Encode(key)}));
static Future<void> forget() => _storage.delete(key: 'sync');
}
class SyncError implements Exception {
SyncError(this.message);
final String message;
@override
String toString() => message;
}
Future<Map<String, dynamic>> _call(String server, String token, String method, String path,
{Uint8List? body}) async {
final uri = Uri.parse(server.replaceAll(RegExp(r'/+$'), '') + path);
final headers = {'Authorization': 'Bearer $token', 'Accept': 'application/json'};
late http.Response r;
try {
r = method == 'POST'
? await http.post(uri, headers: {...headers, 'Content-Type': 'application/octet-stream'}, body: body)
: await http.get(uri, headers: headers);
} catch (e) {
throw SyncError("Can't reach the server ($e)");
}
final j = r.body.isEmpty ? <String, dynamic>{} : jsonDecode(r.body) as Map<String, dynamic>;
if (r.statusCode >= 400) throw SyncError('Server: ${r.statusCode} ${j['error'] ?? r.body}');
return j;
}
/// First start: check the token, fetch the wrapped key, unlock it with the passphrase (or take
/// the recovery key). The server must already have a key — the dashboard makes it (sync.py setup).
Future<SyncSettings> join(String server, String token, {String? passphrase, String? recovery}) async {
final hello = await _call(server, token, 'GET', '/v1/hello');
final Uint8List key;
if (recovery != null && recovery.trim().isNotEmpty) {
key = SyncCrypto.fromRecovery(recovery);
} else {
final Map<String, dynamic> wrapped;
try {
wrapped = await _call(server, token, 'GET', '/v1/key');
} on SyncError catch (e) {
if (e.message.contains('404')) throw SyncError('No key on the server yet — set up the dashboard first.');
rethrow;
}
key = await SyncCrypto.unwrap(wrapped, passphrase ?? '');
}
return SyncSettings(server: server, token: token, account: hello['account'], name: hello['device'],
device: SyncStore.randomId().substring(0, 12), key: key);
}
class SyncResult {
int batches = 0, applied = 0, skipped = 0, pushed = 0;
@override
String toString() => '$batches batches in ($applied applied, $skipped skipped), $pushed changes out';
}
/// Pull everyone else's batches since the last one read, then push ours.
Future<SyncResult> runSync(SyncSettings s, SyncStore store, SyncCrypto crypto) async {
final res = SyncResult();
while (true) {
final j = await _call(s.server, s.token, 'GET', '/v1/batches?after=${store.meta('pulled')}&limit=50');
final batches = (j['batches'] as List).cast<Map<String, dynamic>>();
if (batches.isEmpty) break;
for (final b in batches) {
if (b['device'] != s.name) {
final batch = crypto.openBatch(s.key, base64Decode(b['blob'] as String), s.account);
if (batch['dev'] != s.device) {
final st = store.apply(batch['changes'] as List);
res.applied += st['applied']!;
res.skipped += st['skipped']!;
}
res.batches++;
}
store.setMeta('pulled', b['seq'] as int); // only after the batch is in (applying again is harmless)
}
}
final (items, mark) = store.changes();
for (var i = 0; i < items.length; i += chunk) {
final part = items.sublist(i, i + chunk > items.length ? items.length : i + chunk);
final blob = crypto.sealBatch(s.key,
{'v': 1, 'dev': s.device, 'made': DateTime.now().millisecondsSinceEpoch, 'changes': part}, s.account);
await _call(s.server, s.token, 'POST', '/v1/batches', body: blob);
res.pushed += part.length;
}
if (items.isNotEmpty) store.markPushed(mark);
return res;
}

117
app/lib/sync/crypto.dart Normal file
View file

@ -0,0 +1,117 @@
// Encryption for dash-sync (PROTOCOL.md "Keys" + "A batch"), byte for byte what the dashboard's
// sync.py does with PyNaCl: a batch = "DS1\0" + 24-byte nonce + XChaCha20-Poly1305-IETF(data key,
// nonce, zlib(JSON), ad = "dash-sync/1/<account>"); the data key sits on the server wrapped with
// Argon2id(passphrase). Argon2id with 64 MB takes a second or two, so it runs in its own isolate.
import 'dart:convert';
import 'dart:io';
import 'dart:isolate';
import 'dart:typed_data';
import 'package:sodium/sodium_sumo.dart';
const _magic = [0x44, 0x53, 0x31, 0x00]; // "DS1\0"
const _keyAd = 'dash-sync/key/1';
class SyncCrypto {
SyncCrypto._(this._sodium);
static Future<SyncCrypto> create() async => SyncCrypto._(await SodiumSumoInit.init());
final SodiumSumo _sodium;
Aead get _aead => _sodium.crypto.aeadXChaCha20Poly1305IETF;
Uint8List _ad(String account) => utf8.encode('dash-sync/1/$account');
/// JSON → zlib → sealed batch, ready to POST.
Uint8List sealBatch(Uint8List key, Map<String, dynamic> batch, String account) {
final plain = Uint8List.fromList(ZLibCodec(level: 6).encode(utf8.encode(jsonEncode(batch))));
final nonce = _sodium.randombytes.buf(24);
final k = SecureKey.fromList(_sodium, key);
try {
final box = _aead.encrypt(message: plain, nonce: nonce, key: k, additionalData: _ad(account));
return Uint8List.fromList([..._magic, ...nonce, ...box]);
} finally {
k.dispose();
}
}
/// A sealed batch → its JSON. Throws on a wrong key / account or a damaged batch.
Map<String, dynamic> openBatch(Uint8List key, Uint8List blob, String account) {
if (blob.length < 28 + 16 || !_listEq(blob.sublist(0, 4), _magic)) {
throw const FormatException('not a sync batch');
}
final k = SecureKey.fromList(_sodium, key);
try {
final plain = _aead.decrypt(
cipherText: blob.sublist(28), nonce: blob.sublist(4, 28), key: k, additionalData: _ad(account));
return jsonDecode(utf8.decode(ZLibCodec().decode(plain))) as Map<String, dynamic>;
} finally {
k.dispose();
}
}
/// The data key from the server's wrapped key + the passphrase (in a background isolate).
/// Throws [WrongPassphrase].
static Future<Uint8List> unwrap(Map<String, dynamic> w, String passphrase) =>
Isolate.run(() async => _unwrap(await SodiumSumoInit.init(), w, passphrase));
static Uint8List _unwrap(SodiumSumo s, Map<String, dynamic> w, String passphrase) {
if (w['kdf'] != 'argon2id13') throw FormatException('unknown kdf ${w['kdf']}');
final kek = s.crypto.pwhash(
outLen: 32,
password: Int8List.fromList(utf8.encode(passphrase)),
salt: base64Decode(w['salt'] as String),
opsLimit: w['ops'] as int,
memLimit: w['mem'] as int,
alg: CryptoPwhashAlgorithm.argon2id13,
);
try {
// a copy: what libsodium returns is a view on native memory that's freed with the isolate
return Uint8List.fromList(s.crypto.aeadXChaCha20Poly1305IETF.decrypt(
cipherText: base64Decode(w['box'] as String),
nonce: base64Decode(w['nonce'] as String),
key: kek,
additionalData: utf8.encode(_keyAd),
));
} on SodiumException {
throw const WrongPassphrase();
} finally {
kek.dispose();
}
}
/// The recovery key ("ABCD-EFGH-…", base32 of the data key) → the data key.
static Uint8List fromRecovery(String code) {
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
final s = code.replaceAll(RegExp(r'[\s-]'), '').toUpperCase();
final out = <int>[];
var buf = 0, bits = 0;
for (final ch in s.split('')) {
final v = alphabet.indexOf(ch);
if (v < 0) throw const FormatException("that's not a recovery key");
buf = (buf << 5) | v;
bits += 5;
if (bits >= 8) {
bits -= 8;
out.add((buf >> bits) & 0xff);
}
}
if (out.length != 32) throw const FormatException("that's not a recovery key");
return Uint8List.fromList(out);
}
static bool _listEq(List<int> a, List<int> b) {
if (a.length != b.length) return false;
for (var i = 0; i < a.length; i++) {
if (a[i] != b[i]) return false;
}
return true;
}
}
class WrongPassphrase implements Exception {
const WrongPassphrase();
@override
String toString() => 'Wrong passphrase';
}

145
app/lib/sync/gb_relay.dart Normal file
View file

@ -0,0 +1,145 @@
// The band's data from Gadgetbridge to the dashboard, through the sync (no Syncthing): Gadgetbridge's
// database export on this phone (Gadgetbridge ▸ Settings ▸ Automations ▸ Auto export), picked once,
// is read at every sync (the app's and the background task's, background.dart) when it changed; the new rows of the six tables the dashboard's gb.py reads
// (only those columns) go into the store as health.<TABLE> rows — ids = the band's timestamps, as
// gb.RELAY_SYNC — and travel like any change. The Pi imports them (gb.import_relay).
//
// Incremental like gb.py: rows from the newest relayed minute minus OVERLAP (the band hands over
// sleep and late minutes after the fact); an unchanged row isn't put again. Rows older than KEEP
// days that were sent are dropped here without a delete marker — the Pi keeps them.
// With them goes the phone's time zone (health.RELAY_INFO "tz"): the dashboard reads the band's times in it
// unless Settings ▸ Health sets one.
import 'dart:io';
import 'package:gb_export/gb_export.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqlite3/sqlite3.dart';
import 'store.dart';
const overlapS = 2 * 86400;
const keepDays = 14;
/// table → (id prefix, timestamp column, timestamp in ms?, columns sent) — gb.RELAY_SCHEMA / RELAY_SYNC
const relayTables = {
'XIAOMI_ACTIVITY_SAMPLE': ('a', 'TIMESTAMP', false, ['TIMESTAMP', 'HEART_RATE', 'STEPS', 'DISTANCE_CM']),
'XIAOMI_DAILY_SUMMARY_SAMPLE': ('d', 'TIMESTAMP', true, ['TIMESTAMP', 'HR_RESTING']),
'XIAOMI_SLEEP_STAGE_SAMPLE': ('s', 'TIMESTAMP', true, ['TIMESTAMP', 'STAGE']),
'XIAOMI_SLEEP_TIME_SAMPLE': ('t', 'TIMESTAMP', true, ['TIMESTAMP', 'WAKEUP_TIME']),
'BASE_ACTIVITY_SUMMARY': ('w', 'START_TIME', true, ['START_TIME', 'END_TIME', 'ACTIVITY_KIND', 'OVERRIDE_ACTIVITY_KIND']),
'XIAOMI_MANUAL_SAMPLE': ('m', 'TIMESTAMP', true, ['TIMESTAMP', 'TYPE', 'VALUE']),
};
class GbRelay {
GbRelay(this.store);
final SyncStore store;
String? get uri => store.metaText('gb_uri');
String? get lastResult => store.metaText('gb_result');
int get lastRun => store.meta('gb_run'); // ms
/// The system file picker → remember the export (null = cancelled).
Future<bool> pick() async {
final u = await pickExport();
if (u == null) return false;
store.setMetaText('gb_uri', u);
store.setMetaText('gb_stamp', null); // read it at the next sync
return true;
}
void forget() {
store.setMetaText('gb_uri', null);
store.setMetaText('gb_stamp', null);
}
/// Read the export if it changed → rows put (0 = nothing new; null = no export picked).
Future<int?> run() async {
final u = uri;
if (u == null) return null;
final info = await exportInfo(u);
if (info == null) {
_done('can\'t open the export — choose it again');
return 0;
}
await _zone();
final stamp = '${info['size']}:${info['modified']}';
var put = 0;
if (stamp != store.metaText('gb_stamp')) {
final tmp = '${(await getTemporaryDirectory()).path}/gb_export.db';
if (!await copyExport(u, tmp)) {
_done('can\'t read the export');
return 0;
}
try {
put = _read(tmp);
store.setMetaText('gb_stamp', stamp);
_done('$put new or changed rows from the export of ${_when(info['modified']!)}');
} catch (e) {
_done('the export couldn\'t be read: $e');
} finally {
for (final f in [tmp, '$tmp-wal', '$tmp-shm', '$tmp-journal']) {
final x = File(f);
if (x.existsSync()) x.deleteSync();
}
}
}
_trim();
return put;
}
int _read(String path) {
final gb = sqlite3.open(path, mode: OpenMode.readOnly);
var put = 0, newest = store.meta('gb_last');
final since = newest == 0 ? 0 : newest - overlapS;
try {
store.db.execute('BEGIN');
for (final MapEntry(key: t, value: (prefix, ts, ms, cols)) in relayTables.entries) {
final have = gb.select("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?", [t]);
if (have.isEmpty) continue;
for (final r in gb.select('SELECT ${cols.join(', ')} FROM $t WHERE $ts >= ? ORDER BY $ts', [ms ? since * 1000 : since])) {
final data = {for (final c in cols) c: r[c]};
final id = t == 'XIAOMI_MANUAL_SAMPLE' ? '$prefix:${r['TIMESTAMP']}:${r['TYPE']}' : '$prefix:${r[ts]}';
final old = store.row('health.$t', id);
if (old != null && cols.every((c) => old[c] == data[c])) continue;
store.put('health.$t', id, data);
put++;
if (t == 'XIAOMI_ACTIVITY_SAMPLE' && (r[ts] as int) > newest) newest = r[ts] as int;
}
}
store.setMeta('gb_last', newest);
store.db.execute('COMMIT');
} catch (_) {
store.db.execute('ROLLBACK');
rethrow;
} finally {
gb.close();
}
return put;
}
/// The phone's time zone → health.RELAY_INFO (only when it changed: a trip abroad, the clocks moved by hand).
Future<void> _zone() async {
final z = await timeZone();
if (z == null || z.isEmpty || store.row('health.RELAY_INFO', 'i:tz')?['v'] == z) return;
store.put('health.RELAY_INFO', 'i:tz', {'k': 'tz', 'v': z});
}
/// Drop rows older than keepDays that were already sent — here only (no delete marker).
void _trim() {
final cut = DateTime.now().millisecondsSinceEpoch ~/ 1000 - keepDays * 86400, pushed = store.meta('pushed');
for (final MapEntry(key: t, value: (_, ts, ms, _)) in relayTables.entries) {
store.db.execute("DELETE FROM rec WHERE t = ? AND h <= ? AND json_extract(data, '\$.$ts') < ?",
['health.$t', pushed, ms ? cut * 1000 : cut]);
}
}
void _done(String result) {
store.setMetaText('gb_result', result);
store.setMeta('gb_run', DateTime.now().millisecondsSinceEpoch);
}
static String _when(int ms) {
final d = DateTime.fromMillisecondsSinceEpoch(ms);
return '${d.day}.${d.month}. ${d.hour.toString().padLeft(2, '0')}:${d.minute.toString().padLeft(2, '0')}';
}
}

39
app/lib/sync/kick.dart Normal file
View file

@ -0,0 +1,39 @@
// "Sync now" to the dashboard over the home network (the dashboard's sync.kick): right after the
// band's rows went out, the Pi pulls them, imports them, rewrites the Health summaries and pushes
// them at once — then the app pulls again. Away from home the Pi doesn't answer and nothing changes
// (the usual 5-minute / hourly rhythm). The message is sealed with the data key, so only a device
// of this account can send one.
import 'dart:convert';
import 'dart:io';
import 'package:http/io_client.dart';
import 'client.dart';
import 'crypto.dart';
import 'store.dart';
/// The dashboard on the home network, e.g. http://192.168.1.50:8080: the Sync page (store meta pi_url),
/// else the build's --dart-define=PI_URL=… (tool/publish.env); empty = no "sync now", the usual rhythm only.
String piUrl(SyncStore store) =>
(store.metaText('pi_url') ?? const String.fromEnvironment('PI_URL')).trim().replaceAll(RegExp(r'/+$'), '');
const _connect = Duration(seconds: 3); // not home → give up quickly
const _answer = Duration(minutes: 3); // the Pi 3: import + summaries ≈ 1 min
/// → true when the Pi sent something back (pull now).
Future<bool> kickPi(SyncSettings s, SyncStore store, SyncCrypto crypto) async {
final pi = piUrl(store);
if (pi.isEmpty) return false;
final blob = crypto.sealBatch(s.key, {'kick': DateTime.now().millisecondsSinceEpoch}, s.account);
final client = IOClient(HttpClient()..connectionTimeout = _connect);
try {
final r = await client
.post(Uri.parse('$pi/api/sync/kick'), headers: {'Content-Type': 'application/octet-stream'}, body: blob)
.timeout(_answer);
if (r.statusCode != 200) return false;
return ((jsonDecode(r.body) as Map<String, dynamic>)['pushed'] ?? 0) > 0;
} catch (_) {
return false;
} finally {
client.close();
}
}

225
app/lib/sync/store.dart Normal file
View file

@ -0,0 +1,225 @@
// The phone's copy of the synced data, kept in the wire format of PROTOCOL.md: one row per
// (table, id) with its stamp, device and the columns as JSON — references are already ids there,
// so nothing is translated (the dashboard's syncdb.py turns them into its integer keys; we don't
// need to). The merge rules are syncdb.apply's: the later (stamp, device) wins per row, deletes
// leave a marker, a change older than a marker is skipped, the clock only moves forward.
//
// rec (t "food.entry", u id, h stamp, d device, data JSON)
// tomb (t, u, h, d) a delete marker
// meta (k, v) clock, pushed (my newest stamp sent), pulled (server seq)
import 'dart:convert';
import 'dart:math';
import 'package:sqlite3/sqlite3.dart';
class SyncStore {
SyncStore(String path, this.device) : db = sqlite3.open(path) {
db.execute('PRAGMA journal_mode = WAL');
db.execute('PRAGMA busy_timeout = 10000'); // the app and the background sync share the file
db.execute('''
CREATE TABLE IF NOT EXISTS rec (t TEXT NOT NULL, u TEXT NOT NULL, h INTEGER NOT NULL, d TEXT NOT NULL,
data TEXT NOT NULL, PRIMARY KEY (t, u)) WITHOUT ROWID;
CREATE TABLE IF NOT EXISTS tomb (t TEXT NOT NULL, u TEXT NOT NULL, h INTEGER NOT NULL, d TEXT NOT NULL,
PRIMARY KEY (t, u)) WITHOUT ROWID;
CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v) WITHOUT ROWID;
CREATE INDEX IF NOT EXISTS rec_mine ON rec (d, h);
CREATE INDEX IF NOT EXISTS tomb_mine ON tomb (d, h);
''');
}
final Database db;
final String device; // this device's id (12 hex), in every change it makes
int meta(String k) => (db.select('SELECT v FROM meta WHERE k = ?', [k]).firstOrNull?['v'] as int?) ?? 0;
void setMeta(String k, int v) => db.execute('INSERT OR REPLACE INTO meta VALUES (?, ?)', [k, v]);
String? metaText(String k) => db.select('SELECT v FROM meta WHERE k = ?', [k]).firstOrNull?['v'] as String?;
void setMetaText(String k, String? v) =>
v == null ? db.execute('DELETE FROM meta WHERE k = ?', [k]) : db.execute('INSERT OR REPLACE INTO meta VALUES (?, ?)', [k, v]);
/// Tables whose rows are documents (syncdb.py "fork"): their text columns, versioned by rev / revs.
/// Two versions written at the same time are both kept — the loser as "copy:" + its rev.
static const forks = {'notes.note': ['body', 'updated']};
/// Tables the phone never reads — the dashboards' raw ActivityWatch data (every window, every minute of
/// typing): not kept. What the app shows of it comes as the Pi's blocks (workload.act).
static const skip = ['activity.'];
static bool newer(int h, String d, int? lh, String? ld) =>
h != (lh ?? 0) ? h > (lh ?? 0) : d.compareTo(ld ?? '') > 0;
/// A new local stamp: never below the last one + 1 (PROTOCOL.md "Stamps").
int _tick() {
final h = max(meta('clock') + 1, DateTime.now().millisecondsSinceEpoch);
setMeta('clock', h);
return h;
}
// ---- reading -----------------------------------------------------------------------------
/// Every live row of a table ("food.entry") as {_u, _h (its change stamp), …columns}.
List<Map<String, dynamic>> rows(String t, {String? where, List<Object?> args = const []}) => [
for (final r in db.select(
'SELECT u, h, data FROM rec WHERE t = ?${where == null ? '' : ' AND ($where)'}', [t, ...args]))
{'_u': r['u'], '_h': r['h'], ...jsonDecode(r['data'] as String) as Map<String, dynamic>}
];
Map<String, dynamic>? row(String t, String u) {
final r = db.select('SELECT data FROM rec WHERE t = ? AND u = ?', [t, u]).firstOrNull;
return r == null ? null : {'_u': u, ...jsonDecode(r['data'] as String) as Map<String, dynamic>};
}
Map<String, int> counts() => {
for (final r in db.select('SELECT t, count(*) AS n FROM rec GROUP BY t ORDER BY t'))
r['t'] as String: r['n'] as int
};
// ---- writing here ------------------------------------------------------------------------
/// Save a row made / changed on this device (the whole row: columns we don't show are kept
/// by passing the row as read). `u` = its id: a natural one ("day:2026-10-20") or random.
void put(String t, String u, Map<String, dynamic> data) {
final clean = Map<String, dynamic>.of(data)
..remove('_u')
..remove('_h');
db.execute('INSERT OR REPLACE INTO rec VALUES (?, ?, ?, ?, ?)', [t, u, _tick(), device, jsonEncode(clean)]);
}
/// Has another device seen this row as it is (it came from one, or went out)?
bool known(String t, String u) {
final r = db.select('SELECT h, d FROM rec WHERE t = ? AND u = ?', [t, u]).firstOrNull;
return r == null || r['d'] != device || (r['h'] as int) <= meta('pushed');
}
void delete(String t, String u) {
final h = _tick();
db.execute('DELETE FROM rec WHERE t = ? AND u = ?', [t, u]);
db.execute('INSERT OR REPLACE INTO tomb VALUES (?, ?, ?, ?)', [t, u, h, device]);
}
/// Drop rows of [t] whose JSON [field] is below [before] — here only, no delete marker (the other side
/// keeps them): only rows another device made, or ours already sent.
void dropOld(String t, String field, num before) => db.execute(
"DELETE FROM rec WHERE t = ? AND json_extract(data, '\$.$field') < ? AND (d != ? OR h <= ?)",
[t, before, device, meta('pushed')]);
static String randomId() {
final r = Random.secure();
return List.generate(16, (_) => r.nextInt(256).toRadixString(16).padLeft(2, '0')).join();
}
// ---- sync ---------------------------------------------------------------------------------
/// This device's changes since the last push: (changes, mark) — markPushed(mark) once sent.
(List<Map<String, dynamic>>, int) changes() {
final since = meta('pushed');
var mark = since;
final out = <Map<String, dynamic>>[];
final items = <(int, Map<String, dynamic>)>[];
for (final r in db.select('SELECT t, u, h, d, data FROM rec WHERE d = ? AND h > ?', [device, since])) {
items.add((r['h'] as int,
{'t': r['t'], 'u': r['u'], 'h': r['h'], 'd': r['d'], 'row': jsonDecode(r['data'] as String)}));
}
for (final r in db.select('SELECT t, u, h, d FROM tomb WHERE d = ? AND h > ?', [device, since])) {
items.add((r['h'] as int, {'t': r['t'], 'u': r['u'], 'h': r['h'], 'd': r['d'], 'del': true}));
}
items.sort((a, b) => a.$1.compareTo(b.$1));
for (final (h, c) in items) {
out.add(c);
mark = max(mark, h);
}
return (out, mark);
}
void markPushed(int mark) => setMeta('pushed', max(meta('pushed'), mark));
/// Another device's changes → {applied, skipped}. Rows first, then the deletes (like syncdb).
Map<String, int> apply(List<dynamic> changes) {
final stats = {'applied': 0, 'skipped': 0};
if (changes.isEmpty) return stats;
db.execute('BEGIN IMMEDIATE');
try {
var top = meta('clock');
for (final c in changes.cast<Map<String, dynamic>>()) {
top = max(top, c['h'] as int);
}
setMeta('clock', top); // the clock moves past what arrives
for (final pass in [false, true]) {
for (final c in changes.cast<Map<String, dynamic>>()) {
if ((c['del'] == true) != pass) continue;
final t = c['t'] as String, u = c['u'] as String, h = c['h'] as int, d = c['d'] as String;
if (skip.any(t.startsWith)) {
stats['skipped'] = stats['skipped']! + 1;
continue;
}
final cur = db.select('SELECT h, d, data FROM rec WHERE t = ? AND u = ?', [t, u]).firstOrNull;
final tomb = db.select('SELECT h, d FROM tomb WHERE t = ? AND u = ?', [t, u]).firstOrNull;
if (pass) {
if (tomb == null || newer(h, d, tomb['h'] as int, tomb['d'] as String)) {
db.execute('INSERT OR REPLACE INTO tomb VALUES (?, ?, ?, ?)', [t, u, h, d]);
}
if (cur != null && newer(h, d, cur['h'] as int, cur['d'] as String)) {
db.execute('DELETE FROM rec WHERE t = ? AND u = ?', [t, u]);
stats['applied'] = stats['applied']! + 1;
} else {
stats['skipped'] = stats['skipped']! + 1;
}
} else {
if (cur != null && forks.containsKey(t) &&
(tomb == null || newer(h, d, tomb['h'] as int, tomb['d'] as String)) &&
_fork(t, u, h, d, (c['row'] as Map).cast<String, dynamic>(), cur)) {
stats['applied'] = stats['applied']! + 1;
continue;
}
final beaten = (tomb != null && !newer(h, d, tomb['h'] as int, tomb['d'] as String)) ||
(cur != null && !newer(h, d, cur['h'] as int, cur['d'] as String));
if (beaten) {
stats['skipped'] = stats['skipped']! + 1;
} else {
db.execute('INSERT OR REPLACE INTO rec VALUES (?, ?, ?, ?, ?)', [t, u, h, d, jsonEncode(c['row'])]);
stats['applied'] = stats['applied']! + 1;
}
}
}
}
db.execute('COMMIT');
} catch (_) {
db.execute('ROLLBACK');
rethrow;
}
return stats;
}
/// syncdb._fork: a document row meeting another version of itself → true when settled here,
/// false = go on with the plain last-change-wins (after keeping the loser as a copy).
bool _fork(String t, String u, int h, String d, Map<String, dynamic> row, Row cur) {
final loc = jsonDecode(cur['data'] as String) as Map<String, dynamic>;
final mine = loc['rev'] as String?, theirs = row['rev'] as String?;
if (mine == null || theirs == null || mine == theirs) return false; // the same text: only the rest differs
final win = newer(h, d, cur['h'] as int, cur['d'] as String);
final text = [...forks[t]!, 'rev', 'revs'];
List<String> revs(Map<String, dynamic> m) => ((m['revs'] as String?) ?? '').split(' ');
if (revs(row).contains(mine)) { // written on top of ours: its text
if (win) return false;
final merged = {...loc, for (final k in text) if (row.containsKey(k)) k: row[k]};
db.execute('UPDATE rec SET data = ? WHERE t = ? AND u = ?', [jsonEncode(merged), t, u]);
return true;
}
if (revs(loc).contains(theirs)) { // ours was written on top of it: our text, their pin / folder —
if (!win) return false; // stamped here, so it goes out (with their stamp our text never would)
final merged = {...row, for (final k in text) if (loc.containsKey(k)) k: loc[k]};
db.execute('UPDATE rec SET h = ?, d = ?, data = ? WHERE t = ? AND u = ?', [_tick(), device, jsonEncode(merged), t, u]);
return true;
}
// both written at the same time: the later one stays, the other becomes a copy (the same one on every device)
final (lost, lh, ld) = win ? (loc, cur['h'] as int, cur['d'] as String) : (row, h, d);
final cu = 'copy:${lost['rev']}';
if (db.select('SELECT 1 FROM rec WHERE t = ? AND u = ?', [t, cu]).isEmpty &&
db.select('SELECT 1 FROM tomb WHERE t = ? AND u = ?', [t, cu]).isEmpty) {
db.execute('INSERT INTO rec VALUES (?, ?, ?, ?, ?)', [t, cu, lh, ld, jsonEncode({...lost, 'origin': lost['rev']})]);
}
return false;
}
}

View file

@ -0,0 +1,115 @@
// At home: the dashboard's measurement stations (termix sensors), from Weather's home button — each sensor's
// latest values, then temperature and humidity by the hour (24 h / 7 days / 30 days). Synced one way from
// the Pi (plugins/stations: tables now + hourly, db.phone_*), so it shows offline too; the phone keeps
// stationDays of hours.
import 'package:flutter/material.dart';
import '../app/sync_service.dart';
import '../app/theme.dart';
import '../widgets/line_chart.dart';
import 'weather_page.dart' show tempColour;
const stationDays = 30;
const _colors = [Color(0xFF5CC8FF), Color(0xFFFFB33A), Color(0xFF7FD6A3), Color(0xFFC792EA), Color(0xFFFF8FC8), Color(0xFFFF9A9A)];
/// A now row's sensor: its id ("now:2") — device_id is the Pi table's integer key, which the sync leaves out.
int _dev(Map<String, dynamic> r) => (r['device_id'] as int?) ?? int.parse((r['_u'] as String).split(':')[1]);
/// Local time in the form the charts use (their day / hour ticks are UTC dates).
DateTime _chartTime(DateTime t) {
final l = t.toLocal();
return DateTime.utc(l.year, l.month, l.day, l.hour, l.minute);
}
class StationsPage extends StatefulWidget {
const StationsPage({super.key, required this.sync});
final SyncService sync;
@override
State<StationsPage> createState() => _StationsPageState();
}
class _StationsPageState extends State<StationsPage> {
int days = 1;
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('At home')),
body: ListenableBuilder(listenable: widget.sync, builder: (context, _) => _body()),
);
Widget _body() {
final store = widget.sync.store;
final now = store.rows('stations.now')..sort((a, b) => _dev(a).compareTo(_dev(b)));
if (now.isEmpty) {
return const Center(child: Padding(
padding: EdgeInsets.all(24),
child: Text('No sensors yet — they come from the dashboard once it has synced.', textAlign: TextAlign.center,
style: TextStyle(color: muted)),
));
}
final nowS = DateTime.now().millisecondsSinceEpoch ~/ 1000;
final from = DateTime.now().subtract(Duration(days: days));
final hours = store.rows('stations.hourly', where: "json_extract(data, '\$.t') >= ?", args: [from.millisecondsSinceEpoch ~/ 1000]);
String ago(int t) {
final m = (nowS - t) ~/ 60;
return m < 2 ? 'now' : m < 60 ? '$m min ago' : m < 1440 ? '${m ~/ 60} h ago' : '${m ~/ 1440} d ago';
}
List<Series> series(String k) => [
for (var i = 0; i < now.length; i++)
Series(now[i]['name'] as String? ?? '', [
for (final h in hours.where((h) => h['device_id'] == _dev(now[i])))
if (h[k] != null) (_chartTime(DateTime.fromMillisecondsSinceEpoch((h['t'] as int) * 1000 + 1800000)), (h[k] as num).toDouble())
]..sort((a, b) => a.$1.compareTo(b.$1)), _colors[i % _colors.length]),
];
Widget chart(String title, String k, String unit, int decimals) => Card(child: Padding(
padding: const EdgeInsets.fromLTRB(14, 10, 10, 10),
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
Text(title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
const SizedBox(height: 8),
LineChart(height: 170, from: _chartTime(from), to: _chartTime(DateTime.now()), unit: unit, decimals: decimals, series: series(k)),
]),
));
return ListView(padding: const EdgeInsets.fromLTRB(12, 8, 12, 24), children: [
Card(child: Padding(
padding: const EdgeInsets.fromLTRB(14, 8, 14, 8),
child: Column(children: [
for (var i = 0; i < now.length; i++)
Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: Row(children: [
Container(width: 9, height: 9, decoration: BoxDecoration(color: _colors[i % _colors.length], shape: BoxShape.circle)),
const SizedBox(width: 10),
Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text(now[i]['name'] as String? ?? '', style: const TextStyle(fontSize: 15)),
Text(ago(now[i]['t'] as int), style: const TextStyle(color: muted, fontSize: 12)),
])),
if (now[i]['temp'] != null)
Text('${(now[i]['temp'] as num).toStringAsFixed(1)}°',
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: tempColour(now[i]['temp'] as num))),
if (now[i]['hum'] != null)
SizedBox(width: 74, child: Row(mainAxisAlignment: MainAxisAlignment.end, children: [
const Icon(Icons.water_drop_outlined, size: 16, color: Color(0xFF5CC8FF)),
Text(' ${(now[i]['hum'] as num).round()}%', style: const TextStyle(fontSize: 15)),
])),
]),
),
]),
)),
const SizedBox(height: 8),
Row(children: [
for (final (d, l) in [(1, '24 h'), (7, '7 days'), (30, '30 days')])
Padding(
padding: const EdgeInsets.only(right: 8),
child: ChoiceChip(label: Text(l), selected: days == d, showCheckmark: false,
labelStyle: TextStyle(color: days == d ? accent : Colors.white), onSelected: (_) => setState(() => days = d)),
),
]),
const SizedBox(height: 8),
chart('Temperature', 'temp', '°C', 1),
const SizedBox(height: 12),
chart('Humidity', 'hum', '%', 0),
]);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,132 @@
// Bars over dates for the health pages (steps, energy …): one per day, or from [weeklyFrom] days one
// per week = the average day of the days with data (as the web's weekly grouping). Tap or drag = that
// bar's numbers above the chart; [range] = the shared Health period as a chip in the corner.
import 'dart:math';
import 'package:flutter/material.dart';
import '../app/theme.dart';
import '../health/cycle_model.dart' show daysBetween, plus;
import '../health/range.dart';
import 'line_chart.dart' show RangeChip;
const weeklyFrom = 120;
const _mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
class BarChart extends StatefulWidget {
const BarChart({super.key, required this.points, required this.from, required this.to, required this.color,
this.fmt, this.goal, this.height = 160, this.range});
final List<(DateTime, double)> points; // one per day
final DateTime from, to;
final Color color;
final String Function(double)? fmt; // the tip's value
final double? goal; // a dashed line (per day)
final double height;
final HealthRange? range;
@override
State<BarChart> createState() => _BarChartState();
}
class _BarChartState extends State<BarChart> {
int? hit;
/// [(first day, value or null, label)]
List<(DateTime, double?, String)> _buckets() {
final byDay = {for (final p in widget.points) p.$1: p.$2};
final n = daysBetween(widget.from, widget.to) + 1;
final out = <(DateTime, double?, String)>[];
if (n >= weeklyFrom) {
for (var s = plus(widget.from, -(widget.from.weekday - 1)); !s.isAfter(widget.to); s = plus(s, 7)) {
final vs = [for (var i = 0; i < 7; i++) byDay[plus(s, i)]].whereType<double>().toList();
out.add((s, vs.isEmpty ? null : vs.reduce((a, b) => a + b) / vs.length,
'Week of ${s.day} ${_mon[s.month - 1]} ${s.year} · a day'));
}
} else {
for (var i = 0; i < n; i++) {
final d = plus(widget.from, i);
out.add((d, byDay[d], '${d.day} ${_mon[d.month - 1]} ${d.year}'));
}
}
return out;
}
@override
Widget build(BuildContext context) {
final b = _buckets();
final fmt = widget.fmt ?? (double v) => v.round().toString();
final h = hit != null && hit! < b.length ? b[hit!] : null;
return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
Row(children: [
Expanded(
child: Text(h == null ? 'Tap a bar for its numbers' : '${h.$3}: ${h.$2 == null ? 'nothing' : fmt(h.$2!)}',
style: TextStyle(color: h == null ? muted : Colors.white, fontSize: 12.5)),
),
if (widget.range != null) RangeChip(widget.range!),
]),
const SizedBox(height: 6),
LayoutBuilder(builder: (context, box) {
void pick(Offset o) =>
setState(() => hit = ((o.dx - 34) / (box.maxWidth - 34) * b.length).floor().clamp(0, b.length - 1));
return GestureDetector(
onTapDown: (d) => pick(d.localPosition),
onHorizontalDragUpdate: (d) => pick(d.localPosition),
child: CustomPaint(size: Size(box.maxWidth, widget.height), painter: _Painter(b, widget, hit)),
);
}),
]);
}
}
class _Painter extends CustomPainter {
_Painter(this.b, this.w, this.hit);
final List<(DateTime, double?, String)> b;
final BarChart w;
final int? hit;
static double _nice(double x) {
final e = pow(10, (log(x) / ln10).floor()).toDouble(), f = x / e;
return (f <= 1 ? 1 : f <= 2 ? 2 : f <= 5 ? 5 : 10) * e;
}
@override
void paint(Canvas c, Size size) {
const ml = 34.0, mb = 16.0, mt = 4.0;
final h = size.height - mb - mt;
final peak = max(1.0, [w.goal ?? 0, for (final x in b) x.$2 ?? 0].reduce(max));
final step = _nice(peak / 3), top = (peak / step).ceil() * step;
double y(double v) => mt + h - h * v / top;
final txt = const TextStyle(color: muted, fontSize: 10.5);
void label(String s, Offset o, {bool right = false}) {
final tp = TextPainter(text: TextSpan(text: s, style: txt), textDirection: TextDirection.ltr)..layout();
tp.paint(c, right ? o - Offset(tp.width, tp.height / 2) : o - Offset(tp.width / 2, 0));
}
for (var v = 0.0; v <= top + 0.001; v += step) {
c.drawLine(Offset(ml, y(v)), Offset(size.width, y(v)), Paint()..color = card2);
label(v >= 1000 ? '${(v / 1000).toStringAsFixed(v % 1000 == 0 ? 0 : 1)}k' : v.round().toString(), Offset(ml - 4, y(v)), right: true);
}
final bw = (size.width - ml) / max(1, b.length), pad = bw > 4 ? bw * 0.18 : 0.0;
final weekly = b.length > 1 && b[1].$1.difference(b[0].$1).inDays == 7;
for (var i = 0; i < b.length; i++) {
final (d, v, _) = b[i];
final x0 = ml + i * bw;
if (v != null && v > 0) {
c.drawRect(Rect.fromLTRB(x0 + pad, y(v), x0 + bw - pad, y(0)),
Paint()..color = hit == i ? Colors.white : w.color.withValues(alpha: hit == null ? 1 : .75));
}
final l = weekly
? (d.day <= 7 && (b.length <= 30 || d.month % 3 == 1) ? _mon[d.month - 1] : null)
: b.length > 35 ? (d.day == 1 ? _mon[d.month - 1] : null) : (d.weekday == 1 || b.length <= 8 ? '${d.day} ${_mon[d.month - 1]}' : null);
if (l != null) label(l, Offset(x0 + bw / 2, size.height - mb + 3));
}
if (w.goal != null) {
final gy = y(w.goal!);
for (var x = ml; x < size.width; x += 8) {
c.drawLine(Offset(x, gy), Offset(min(x + 4, size.width), gy), Paint()..color = accent..strokeWidth = 1.2);
}
}
}
@override
bool shouldRepaint(covariant _Painter old) => true;
}

View file

@ -0,0 +1,212 @@
// A small time chart for the health pages: lines (or dots) over dates, an optional band (the
// healthy range), hour / day / month ticks to suit the span, a few value ticks; tap or drag shows
// the nearest point. With [range]: the shared Health period as a chip in the corner (tap = change
// it for every Health chart).
import 'dart:math';
import 'package:flutter/material.dart';
import '../app/theme.dart';
import '../health/range.dart';
class Series {
const Series(this.name, this.points, this.color);
final String name;
final List<(DateTime, double)> points;
final Color color;
}
class LineChart extends StatefulWidget {
const LineChart({super.key, required this.series, required this.from, required this.to, this.unit = '',
this.band, this.limits, this.height = 190, this.decimals = 1, this.range});
final List<Series> series;
final DateTime from, to;
final String unit;
final (double, double)? band;
final (double, double)? limits; // a fixed scale (stretched if a value falls outside), e.g. 85–100 % for SpO₂
final double height;
final int decimals;
final HealthRange? range;
@override
State<LineChart> createState() => _LineChartState();
}
class _LineChartState extends State<LineChart> {
(Series, (DateTime, double))? hit;
@override
Widget build(BuildContext context) {
final chart = _chart(context);
if (widget.range == null) return chart;
return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [Align(alignment: Alignment.centerRight, child: RangeChip(widget.range!)), const SizedBox(height: 4), chart]);
}
Widget _chart(BuildContext context) {
final pts = [for (final s in widget.series) for (final p in s.points) if (!p.$1.isBefore(widget.from)) p];
if (pts.isEmpty) {
return SizedBox(height: 60, child: Center(child: Text('Nothing measured in this period', style: TextStyle(color: muted.withValues(alpha: .8)))));
}
return LayoutBuilder(builder: (context, box) {
final painter = _Painter(widget, hit);
void pick(Offset o) {
(Series, (DateTime, double))? best;
var bd = double.infinity;
for (final s in widget.series) {
for (final p in s.points) {
if (p.$1.isBefore(widget.from)) continue;
final d = (painter.pos(p, box.maxWidth) - o).distance;
if (d < bd) {
bd = d;
best = (s, p);
}
}
}
setState(() => hit = bd < 60 ? best : null);
}
return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
GestureDetector(
onTapDown: (d) => pick(d.localPosition),
onHorizontalDragUpdate: (d) => pick(d.localPosition),
child: CustomPaint(size: Size(box.maxWidth, widget.height), painter: painter),
),
SizedBox(
height: 20,
child: hit == null
? null
: Text('${hit!.$1.name}: ${hit!.$2.$2.toStringAsFixed(widget.decimals)} ${widget.unit} · '
'${hit!.$2.$1.day}.${hit!.$2.$1.month}.${hit!.$2.$1.year}'
'${hit!.$2.$1.hour + hit!.$2.$1.minute > 0 ? ' ${hit!.$2.$1.toIso8601String().substring(11, 16)}' : ''}',
textAlign: TextAlign.center, style: TextStyle(color: hit!.$1.color, fontSize: 13)),
),
]);
});
}
}
class _Painter extends CustomPainter {
_Painter(this.w, this.hit) {
final vs = [for (final s in w.series) for (final p in s.points) if (!p.$1.isBefore(w.from)) p.$2];
var lo = vs.reduce(min), hi = vs.reduce(max);
if (w.band != null && w.band!.$1 < hi && w.band!.$2 > lo) { // the band only stretches the scale where it meets the data
lo = min(lo, w.band!.$1);
hi = max(hi, w.band!.$2);
}
if (w.limits != null) {
lo = min(lo, w.limits!.$1);
hi = max(hi, w.limits!.$2);
} else {
final pad = max((hi - lo) * 0.1, 0.5);
lo -= pad;
hi += pad;
}
step = _nice((hi - lo) / 4);
this.lo = (lo / step).floorToDouble() * step;
this.hi = (hi / step).ceilToDouble() * step;
}
final LineChart w;
final (Series, (DateTime, double))? hit;
late final double lo, hi, step;
static const ml = 40.0, mb = 18.0, mt = 6.0;
static double _nice(double x) {
final e = pow(10, (log(x) / ln10).floor()).toDouble();
final f = x / e;
return (f <= 1 ? 1 : f <= 2 ? 2 : f <= 5 ? 5 : 10) * e;
}
double get span => max(1, w.to.difference(w.from).inHours / 24);
Offset pos((DateTime, double) p, double width) {
final x = ml + (p.$1.difference(w.from).inHours / 24) / span * (width - ml - 8);
final y = mt + (1 - (p.$2 - lo) / (hi - lo)) * (w.height - mt - mb);
return Offset(x, y);
}
@override
void paint(Canvas c, Size size) {
final grid = Paint()..color = card2..strokeWidth = 1;
final txt = TextStyle(color: muted, fontSize: 10.5);
void label(String s, Offset at, {bool right = false, bool center = false}) {
final tp = TextPainter(text: TextSpan(text: s, style: txt), textDirection: TextDirection.ltr)..layout();
tp.paint(c, at - Offset(right ? tp.width : center ? tp.width / 2 : 0, tp.height / 2));
}
if (w.band != null) {
final top = max(mt, pos((w.from, w.band!.$2), size.width).dy), bottom = min(w.height - mb, pos((w.to, w.band!.$1), size.width).dy);
if (bottom > top) c.drawRect(Rect.fromLTRB(ml, top, size.width - 8, bottom), Paint()..color = good.withValues(alpha: 0.08));
}
for (var v = lo; v <= hi + step / 2; v += step) {
final y = pos((w.from, v), size.width).dy;
c.drawLine(Offset(ml, y), Offset(size.width - 8, y), grid);
label(v.toStringAsFixed(step < 1 ? 1 : 0), Offset(ml - 6, y), right: true);
}
// x ticks to suit the span: hours (≤ 2 days), days (≤ 45), months
final days = span;
const mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
void tick(DateTime d, String text) {
if (d.isBefore(w.from) || d.isAfter(w.to)) return;
label(text, Offset(pos((d, lo), size.width).dx, w.height - mb / 2 + 2), center: true);
}
if (days <= 2) {
for (var d = DateTime.utc(w.from.year, w.from.month, w.from.day); !d.isAfter(w.to); d = d.add(const Duration(hours: 4))) {
tick(d, d.hour == 0 ? '${d.day} ${mon[d.month - 1]}' : '${d.hour.toString().padLeft(2, '0')}:00');
}
} else if (days <= 45) {
final every = (days / 7).ceil();
for (var d = DateTime.utc(w.from.year, w.from.month, w.from.day), i = 0; !d.isAfter(w.to); d = d.add(const Duration(days: 1)), i++) {
if (i % every == 0) tick(d, '${d.day} ${mon[d.month - 1]}');
}
} else {
final every = days > 800 ? 6 : days > 400 ? 3 : 1;
for (var d = DateTime.utc(w.from.year, w.from.month, 1); !d.isAfter(w.to); d = DateTime.utc(d.year, d.month + 1, 1)) {
if ((d.month - 1) % every == 0) tick(d, d.month == 1 ? '${d.year}' : mon[d.month - 1]);
}
}
for (final s in w.series) {
final ps = [for (final p in s.points) if (!p.$1.isBefore(w.from)) pos(p, size.width)];
final line = Paint()..color = s.color..strokeWidth = 2..style = PaintingStyle.stroke;
if (ps.length > 1) {
final path = Path()..moveTo(ps.first.dx, ps.first.dy);
for (final p in ps.skip(1)) {
path.lineTo(p.dx, p.dy);
}
c.drawPath(path, line);
}
for (final p in ps) {
c.drawCircle(p, ps.length > 40 ? 1.8 : 3, Paint()..color = s.color);
}
}
if (hit != null) {
final p = pos(hit!.$2, size.width);
c.drawCircle(p, 6, Paint()..color = hit!.$1.color.withValues(alpha: .35));
c.drawLine(Offset(p.dx, mt), Offset(p.dx, w.height - mb), Paint()..color = muted.withValues(alpha: .4));
}
}
@override
bool shouldRepaint(covariant _Painter old) => true;
}
/// The shared Health period as a small chip (tap = change it for every Health chart).
class RangeChip extends StatelessWidget {
const RangeChip(this.r, {super.key});
final HealthRange r;
@override
Widget build(BuildContext context) => PopupMenuButton<String>(
tooltip: 'Time period (every Health chart)',
color: card2,
initialValue: r.value,
onSelected: r.set,
itemBuilder: (_) => [for (final (k, l, _) in ranges) PopupMenuItem(value: k, child: Text(l))],
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
decoration: BoxDecoration(color: card2, borderRadius: BorderRadius.circular(8)),
child: Row(mainAxisSize: MainAxisSize.min, children: [
Text(r.label, style: const TextStyle(color: accent, fontSize: 13)),
const Icon(Icons.arrow_drop_down, color: accent, size: 18),
]),
),
);
}

View file

@ -0,0 +1,406 @@
// Customers (the web's Settings ▸ Work): the tree — customers, sub-customers, projects, tasks —
// with this month's hours and the rate in force today; tap one = its editor: name, where it sits,
// colour (customers always have one; below them "same as above" = inherit), billable (inherit /
// yes / no), currency, the rate history (from a day, or always), notes, archived. Nodes with time
// booked can't be deleted (archive them); a node's + adds a sub-customer / project / task under it.
import 'package:flutter/material.dart';
import '../app/sync_service.dart';
import '../app/theme.dart';
import 'entry_sheet.dart' show NodePicker, hexColor;
import 'work_model.dart';
IconData kindIcon(Node n) => n.kind == 'task'
? Icons.check_box_outline_blank
: n.kind == 'project'
? Icons.folder_outlined
: Icons.business;
class CustomersPage extends StatefulWidget {
const CustomersPage({super.key, required this.sync, this.s = const WorkSettings()});
final SyncService sync;
final WorkSettings s;
@override
State<CustomersPage> createState() => _CustomersPageState();
}
class _CustomersPageState extends State<CustomersPage> {
bool showArchived = false;
void _edit({String? id, String kind = 'client', String? parent}) => Navigator.push(
context,
MaterialPageRoute(
builder: (_) => NodeEditor(sync: widget.sync, s: widget.s, nodeId: id, kind: kind, parent: parent),
),
);
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: widget.sync,
builder: (context, _) {
final store = widget.sync.store;
final t = Tree(store, widget.s);
final now = DateTime.now(), first = DateTime.utc(now.year, now.month);
final month = <String, double>{};
for (final e in entriesBetween(store, first, now.add(const Duration(days: 1)))) {
for (final n in t.chain(e.node)) {
month[n.id] = (month[n.id] ?? 0) + e.minutes;
}
}
final todayIso = fmtDay(now);
final archivedCount = t.nodes.values.where((n) => n.archived).length;
final rows = t.walk(archived: showArchived).toList();
return Scaffold(
appBar: AppBar(
title: const Text('Customers'),
actions: [
if (archivedCount > 0)
TextButton(
onPressed: () => setState(() => showArchived = !showArchived),
child: Text(showArchived ? 'Hide archived' : 'Archived ($archivedCount)'),
),
],
),
floatingActionButton: FloatingActionButton.extended(
onPressed: () => _edit(),
icon: const Icon(Icons.add),
label: const Text('Customer'),
),
body: rows.isEmpty
? const Center(
child: Text('No customers yet', style: TextStyle(color: muted)),
)
: ListView(
padding: const EdgeInsets.only(bottom: 90),
children: [
for (final (n, d) in rows)
ListTile(
contentPadding: EdgeInsets.only(left: 16.0 + d * 20, right: 8),
leading: Icon(kindIcon(n), color: hexColor(t.colour(n.id))),
title: Text(n.name, style: TextStyle(color: t.archived(n.id) ? muted : null)),
subtitle: Text(
[
Tree.kindLabel(n),
'${num0(t.rate(n.id, todayIso).$1)} ${t.currency(n.id)}/h${t.rates[n.id]?.isNotEmpty == true ? '' : ' (inherited)'}',
if (!t.billable(n.id).$1) 'not billable',
if (month[n.id] != null) '${hm(month[n.id]!)} this month',
if (t.archived(n.id)) 'archived',
].join(' · '),
style: const TextStyle(color: muted, fontSize: 12.5),
),
trailing: n.kind == 'task' ? null : _addMenu(n),
onTap: () => _edit(id: n.id),
),
],
),
);
},
);
Widget _addMenu(Node n) => PopupMenuButton<String>(
icon: const Icon(Icons.add, color: muted),
tooltip: 'Add under ${n.name}',
color: card2,
onSelected: (k) => _edit(kind: k == 'sub' ? 'client' : k, parent: n.id),
itemBuilder: (_) => [
if (n.kind == 'client') const PopupMenuItem(value: 'sub', child: Text('Sub-customer')),
if (n.kind == 'client') const PopupMenuItem(value: 'project', child: Text('Project')),
const PopupMenuItem(value: 'task', child: Text('Task')),
],
);
}
/// One node's editor (new when [nodeId] is null: a [kind] under [parent]).
class NodeEditor extends StatefulWidget {
const NodeEditor({super.key, required this.sync, this.s = const WorkSettings(), this.nodeId, this.kind = 'client', this.parent});
final SyncService sync;
final WorkSettings s;
final String? nodeId, kind, parent;
@override
State<NodeEditor> createState() => _NodeEditorState();
}
class _NodeEditorState extends State<NodeEditor> {
late Tree t = Tree(widget.sync.store, widget.s);
late NodeForm f = widget.nodeId != null && t.nodes.containsKey(widget.nodeId)
? NodeForm.of(t, t.nodes[widget.nodeId]!)
: NodeForm(kind: widget.kind ?? 'client', parent: widget.parent);
late final name = TextEditingController(text: f.name),
currency = TextEditingController(text: f.currency),
notes = TextEditingController(text: f.notes);
late final rateCtl = [for (final r in f.rates) TextEditingController(text: r.$2)];
late final sinceList = [for (final r in f.rates) r.$1];
String? error, errorField;
bool armed = false;
bool get isNew => f.id == null;
bool get topLevel => f.kind == 'client' && f.parent == null;
void _save() {
f
..name = name.text
..currency = currency.text
..notes = notes.text
..rates = [for (var i = 0; i < rateCtl.length; i++) (sinceList[i], rateCtl[i].text)];
try {
saveNode(widget.sync.store, t, f);
widget.sync.changed();
Navigator.pop(context);
} on Invalid catch (e) {
setState(() {
error = e.message;
errorField = e.field;
});
}
}
void _delete() {
if (!armed) {
setState(() => armed = true);
return;
}
if (!deleteNode(widget.sync.store, t, f.id!)) {
setState(() {
armed = false;
error = 'Time is booked on it — archive it instead.';
});
return;
}
widget.sync.changed();
Navigator.pop(context);
}
Future<void> _parent() async {
final allowed = parentsOf[f.kind]!;
final mine = f.id == null ? <String>{} : t.subtree(f.id!);
final nid = await showModalBottomSheet<String>(
context: context,
isScrollControlled: true,
backgroundColor: card,
builder: (_) =>
NodePicker(tree: t, recent: const [], current: f.parent, only: (n) => allowed.contains(n.kind) && !mine.contains(n.id)),
);
if (nid != null) setState(() => f.parent = nid);
}
Future<void> _since(int i) async {
final cur = DateTime.tryParse(sinceList[i]);
final p = await showDatePicker(
context: context,
initialDate: cur ?? DateTime.now(),
firstDate: DateTime(2000),
lastDate: DateTime(2100),
helpText: 'Rate from this day',
);
if (p != null) setState(() => sinceList[i] = fmtDay(p));
}
@override
Widget build(BuildContext context) {
final todayIso = fmtDay(DateTime.now());
final parentId = f.parent;
final (pRate, pRsrc) = parentId != null ? t.rate(parentId, todayIso) : (widget.s.defaultRate, null);
final (pBill, pBsrc) = parentId != null ? t.billable(parentId) : (true, null);
final pCur = parentId != null ? t.currency(parentId) : widget.s.currency;
final booked = f.id == null ? 0.0 : t.subtree(f.id!).fold(0.0, (m, i) => m + (bookedMinutes(widget.sync.store)[i] ?? 0));
final kindName = f.kind == 'client'
? (topLevel ? 'Customer' : 'Sub-customer')
: f.kind == 'project'
? 'Project'
: 'Task';
return Scaffold(
appBar: AppBar(
title: Text(isNew ? 'New ${kindName.toLowerCase()}' : kindName),
actions: [TextButton(onPressed: _save, child: const Text('Save'))],
),
body: ListView(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 32),
children: [
TextField(
controller: name,
autofocus: isNew,
textCapitalization: TextCapitalization.sentences,
decoration: InputDecoration(
labelText: 'Name',
border: const OutlineInputBorder(),
errorText: errorField == 'name' ? error : null,
),
),
const SizedBox(height: 12),
// where it sits (customers are top level; a sub-customer can move under another customer)
if (!topLevel || !isNew)
ListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Under'),
subtitle: Text(
parentId == null ? '— top level (a customer)' : t.path(parentId),
style: TextStyle(color: errorField == 'parent_id' ? bad : muted),
),
trailing: f.kind == 'client' && parentId != null
? TextButton(onPressed: () => setState(() => f.parent = null), child: const Text('Make top level'))
: null,
onTap: _parent,
),
if (errorField == 'parent_id') Text(error!, style: const TextStyle(color: bad)),
const SizedBox(height: 6),
const Text('Colour', style: TextStyle(color: muted)),
const SizedBox(height: 6),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
if (!topLevel)
ChoiceChip(
label: const Text('Same as above'),
avatar: Icon(Icons.circle, size: 14, color: hexColor(t.colour(parentId))),
selected: f.colour == null,
onSelected: (_) => setState(() => f.colour = null),
),
for (final c in [
if (f.colour != null && !palette.contains(f.colour)) f.colour!,
...palette,
]) // a custom one (set on the web) first
GestureDetector(
onTap: () => setState(() => f.colour = c),
child: Container(
width: 32,
height: 32,
decoration: BoxDecoration(
color: hexColor(c),
shape: BoxShape.circle,
border: Border.all(color: f.colour == c ? Colors.white : Colors.transparent, width: 2.5),
),
),
),
],
),
const SizedBox(height: 16),
const Text('New entries are', style: TextStyle(color: muted)),
const SizedBox(height: 6),
SegmentedButton<int?>(
segments: [
ButtonSegment(value: null, label: Text(pBill ? 'Inherit (billable)' : 'Inherit (not)')),
const ButtonSegment(value: 1, label: Text('Billable')),
const ButtonSegment(value: 0, label: Text('Not billable')),
],
selected: {f.billable},
showSelectedIcon: false,
onSelectionChanged: (v) => setState(() => f.billable = v.first),
),
if (f.billable == null)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(pBsrc != null ? 'from ${pBsrc.name}' : 'the default', style: const TextStyle(color: muted, fontSize: 12.5)),
),
const SizedBox(height: 16),
TextField(
controller: currency,
maxLength: 3,
textCapitalization: TextCapitalization.characters,
decoration: InputDecoration(
labelText: 'Currency',
hintText: '$pCur (inherited)',
border: const OutlineInputBorder(),
errorText: errorField == 'currency' ? error : null,
counterText: '',
),
),
const SizedBox(height: 16),
Row(
children: [
const Expanded(
child: Text('Hourly rate', style: TextStyle(color: muted)),
),
TextButton.icon(
onPressed: () => setState(() {
rateCtl.add(TextEditingController());
sinceList.add(rateCtl.length == 1 ? '' : todayIso);
}),
icon: const Icon(Icons.add),
label: Text(rateCtl.isEmpty ? 'Own rate' : 'New rate from a day'),
),
],
),
if (rateCtl.isEmpty)
Text('${num0(pRate)} $pCur/h — ${pRsrc != null ? 'from ${pRsrc.name}' : 'the default'}', style: const TextStyle(color: muted)),
for (var i = 0; i < rateCtl.length; i++)
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Row(
children: [
Expanded(
child: OutlinedButton(
onPressed: () => _since(i),
onLongPress: () => setState(() => sinceList[i] = ''),
child: Text(sinceList[i].isEmpty ? 'Always' : 'From ${sinceList[i]}'),
),
),
const SizedBox(width: 8),
SizedBox(
width: 110,
child: TextField(
controller: rateCtl[i],
keyboardType: const TextInputType.numberWithOptions(decimal: true),
decoration: InputDecoration(
isDense: true,
border: const OutlineInputBorder(),
suffixText: '/h',
errorText: errorField == 'rates.$i.rate' || errorField == 'rates.$i.since' ? '!' : null,
),
),
),
IconButton(
onPressed: () => setState(() {
rateCtl.removeAt(i);
sinceList.removeAt(i);
}),
icon: const Icon(Icons.close, color: muted),
),
],
),
),
if (errorField?.startsWith('rates.') == true) Text(error!, style: const TextStyle(color: bad)),
if (rateCtl.isNotEmpty)
const Text(
'A rate counts from its day on; earlier work keeps the rate it had. Long-press a day = always.',
style: TextStyle(color: muted, fontSize: 12),
),
const SizedBox(height: 16),
TextField(
controller: notes,
minLines: 2,
maxLines: 8,
decoration: const InputDecoration(labelText: 'Notes', border: OutlineInputBorder()),
),
const SizedBox(height: 8),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Archived'),
subtitle: const Text('Hidden from the picker; its time stays in reports', style: TextStyle(color: muted)),
value: f.archived,
onChanged: (v) => setState(() => f.archived = v),
),
if (error != null && errorField == null) Text(error!, style: const TextStyle(color: bad)),
const SizedBox(height: 12),
Row(
children: [
if (!isNew)
booked > 0
? Text('${hm(booked)} booked — archive instead of deleting', style: const TextStyle(color: muted, fontSize: 12.5))
: TextButton.icon(
onPressed: _delete,
icon: Icon(Icons.delete_outline, color: armed ? bad : muted),
label: Text(
armed ? 'Tap again to delete (with everything under it)' : 'Delete',
style: TextStyle(color: armed ? bad : muted),
),
),
const Spacer(),
FilledButton(onPressed: _save, child: const Text('Save')),
],
),
],
),
);
}
}

View file

@ -0,0 +1,432 @@
// Booking time (the web page's entry form as a bottom sheet): what it was for — one picker for the
// whole tree + the recent ones as chips —, the day, start and end (an end at or before the start
// = the next day), billable (the tree's default + where it comes from), the rate and amount it
// comes to on that day, a note. Delete = tap twice. The last thing booked is remembered.
import 'package:flutter/material.dart';
import '../app/sync_service.dart';
import '../app/theme.dart';
import 'work_model.dart';
Color hexColor(String hex) => Color(int.parse('ff${hex.substring(1)}', radix: 16));
String hhmm(int minutes) => '${two(minutes ~/ 60 % 24)}:${two(minutes % 60)}';
const _dow = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
const _mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
String dayLabel(DateTime d) => '${_dow[d.weekday - 1]} ${d.day} ${_mon[d.month - 1]}${d.year != DateTime.now().year ? ' ${d.year}' : ''}';
/// A new entry at [day] from [startMin] (default: now, rounded down to 15 minutes), or [entry] to edit.
Future<void> openEntry(
BuildContext context,
SyncService sync, {
WorkEntry? entry,
DateTime? day,
int? startMin,
int? endMin,
String? node,
String note = '',
WorkSettings s = const WorkSettings(),
}) => showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: card,
builder: (_) => EntrySheet(sync: sync, entry: entry, day: day, startMin: startMin, endMin: endMin, node: node, note: note, s: s),
);
class EntrySheet extends StatefulWidget {
const EntrySheet({
super.key,
required this.sync,
this.entry,
this.day,
this.startMin,
this.endMin,
this.node,
this.note = '',
required this.s,
});
final SyncService sync;
final WorkEntry? entry;
final DateTime? day;
final int? startMin, endMin;
final String? node; // a guess (an Activity block's customer); the last one booked otherwise
final String note; // a calendar event's title, an Activity block's items
final WorkSettings s;
@override
State<EntrySheet> createState() => _EntrySheetState();
}
class _EntrySheetState extends State<EntrySheet> {
late Tree t = Tree(widget.sync.store, widget.s);
late EntryForm f;
late final note = TextEditingController(text: f.note);
bool billableTouched = false, armed = false;
String? error, errorField;
@override
void initState() {
super.initState();
final e = widget.entry;
if (e != null) {
final d0 = dayOf(e.s);
f = EntryForm(
id: e.id,
node: e.node,
day: d0,
startMin: e.s.difference(d0).inMinutes,
endMin: e.e.difference(dayOf(e.e)).inMinutes,
endDay: e.e.difference(d0).inDays > 1 ? dayOf(e.e) : null,
billable: e.billable,
note: e.note,
);
billableTouched = true; // an entry's own billable stays as it is
} else {
final now = DateTime.now();
final start = widget.startMin ?? (now.hour * 60 + now.minute) ~/ 15 * 15;
var last = widget.node != null && t.nodes.containsKey(widget.node) ? widget.node : widget.sync.store.metaText('work_last');
if (last != null && (!t.nodes.containsKey(last) || t.archived(last))) last = null;
last ??= recent(widget.sync.store, t, 1).firstOrNull;
f = EntryForm(
node: last,
day: widget.day ?? dayOf(now),
startMin: start,
endMin: widget.endMin ?? start + widget.s.defaultMinutes,
billable: t.billable(last).$1,
note: widget.note,
);
}
}
void _pick(String nid) => setState(() {
f.node = nid;
if (!billableTouched) f.billable = t.billable(nid).$1;
if (errorField == 'node_id') error = errorField = null;
});
Future<void> _chooseNode() async {
final nid = await showModalBottomSheet<String>(
context: context,
isScrollControlled: true,
backgroundColor: card,
builder: (_) => NodePicker(tree: t, recent: recent(widget.sync.store, t), current: f.node),
);
if (nid != null) _pick(nid);
}
Future<void> _time(bool start) async {
final m = start ? f.startMin : f.endMin;
final p = await showTimePicker(
context: context,
initialTime: TimeOfDay(hour: m ~/ 60 % 24, minute: m % 60),
builder: (c, child) => MediaQuery(data: MediaQuery.of(c).copyWith(alwaysUse24HourFormat: true), child: child!),
);
if (p == null) return;
setState(() {
final v = p.hour * 60 + p.minute;
if (start) {
final dur = f.endMin - f.startMin; // moving the start keeps the length
f.startMin = v;
if (f.endDay == null) f.endMin = v + (dur > 0 ? dur : widget.s.defaultMinutes);
} else {
f.endMin = v;
}
});
}
Future<void> _date() async {
final p = await showDatePicker(context: context, initialDate: f.day, firstDate: DateTime(2000), lastDate: DateTime(2100));
if (p != null) setState(() => f.day = dayOf(p));
}
void _save() {
f.note = note.text; // an end past 24:00 (start + length, the + chips) is the next day's time: span() adds it to the day
try {
final id = saveEntry(widget.sync.store, t, f);
widget.sync.store.setMetaText('work_last', f.node);
widget.sync.changed();
Navigator.pop(context, id);
} on Invalid catch (e) {
setState(() {
error = e.message;
errorField = e.field;
});
}
}
void _delete() {
if (!armed) {
setState(() => armed = true);
return;
}
deleteEntry(widget.sync.store, f.id!);
widget.sync.changed();
Navigator.pop(context);
}
@override
Widget build(BuildContext context) {
final (a, b) = f.span();
final dur = b.difference(a).inMinutes;
final nid = f.node;
final (rate, rsrc) = t.rate(nid, fmtDay(f.day));
final cur = t.currency(nid);
final (defB, bsrc) = t.billable(nid);
final rec = recent(widget.sync.store, t).where((i) => i != nid).take(4).toList();
return Padding(
padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
child: SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(16, 14, 16, 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
Text(
f.id == null ? 'Book time' : 'Edit entry',
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent),
),
const SizedBox(height: 10),
if (t.isEmpty)
const Padding(
padding: EdgeInsets.only(bottom: 8),
child: Text('No customers yet — add one under ⋮ ▸ Customers first.', style: TextStyle(color: bad)),
),
// what for
InkWell(
borderRadius: BorderRadius.circular(10),
onTap: t.isEmpty ? null : _chooseNode,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
decoration: BoxDecoration(
color: card2,
borderRadius: BorderRadius.circular(10),
border: errorField == 'node_id' ? Border.all(color: bad) : null,
),
child: Row(
children: [
Icon(Icons.circle, size: 12, color: nid == null ? muted : hexColor(t.colour(nid))),
const SizedBox(width: 10),
Expanded(
child: Text(
nid == null ? 'What did you work on?' : t.path(nid),
style: TextStyle(fontSize: 15.5, color: nid == null ? muted : Colors.white),
),
),
const Icon(Icons.unfold_more, color: muted),
],
),
),
),
if (rec.isNotEmpty) ...[
const SizedBox(height: 6),
Wrap(
spacing: 6,
runSpacing: 4,
children: [
for (final r in rec)
ActionChip(
avatar: Icon(Icons.circle, size: 10, color: hexColor(t.colour(r))),
label: Text(t.nodes[r]!.name),
onPressed: () => _pick(r),
),
],
),
],
const SizedBox(height: 12),
// when
Row(
children: [
Expanded(flex: 5, child: _field(Icons.event, dayLabel(f.day), _date)),
const SizedBox(width: 6),
Expanded(flex: 3, child: _field(null, hhmm(f.startMin), () => _time(true))),
const Padding(
padding: EdgeInsets.symmetric(horizontal: 4),
child: Text('–', style: TextStyle(color: muted)),
),
Expanded(flex: 3, child: _field(null, hhmm(f.endMin), () => _time(false), bad: errorField == 'end')),
],
),
const SizedBox(height: 4),
Text(
[hm(dur > 0 ? dur : 0), if (!dayOf(b).isAtSameMomentAs(f.day) && dur > 0) 'ends ${dayLabel(dayOf(b))}'].join(' · '),
style: const TextStyle(color: muted),
),
const SizedBox(height: 4),
Wrap(
spacing: 6,
children: [
for (final m in const [15, 30, 60, 120])
ActionChip(label: Text(m < 60 ? '+$m min' : '+${m ~/ 60} h'), onPressed: () => setState(() => f.endMin += m)),
],
),
const SizedBox(height: 6),
// billable + money
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Billable'),
subtitle: Text(
nid == null ? '' : 'Default: ${defB ? 'billable' : 'not billable'}${bsrc != null ? ' (from ${bsrc.name})' : ''}',
style: const TextStyle(color: muted),
),
value: f.billable,
onChanged: (v) => setState(() {
f.billable = v;
billableTouched = true;
}),
),
if (nid != null && f.billable)
Text(
'${num0(rate)} $cur/h${rsrc != null ? ' from ${rsrc.name}' : ' (default)'} = ${money(dur > 0 ? dur / 60 * rate : 0, cur)}',
style: const TextStyle(color: muted),
),
const SizedBox(height: 10),
TextField(
controller: note,
minLines: 1,
maxLines: 5,
decoration: const InputDecoration(labelText: 'Note', border: OutlineInputBorder()),
),
if (error != null)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(error!, style: const TextStyle(color: bad)),
),
const SizedBox(height: 12),
Row(
children: [
if (f.id != null)
TextButton.icon(
onPressed: _delete,
icon: Icon(Icons.delete_outline, color: armed ? bad : muted),
label: Text(armed ? 'Tap again to delete' : 'Delete', style: TextStyle(color: armed ? bad : muted)),
),
const Spacer(),
TextButton(onPressed: () => Navigator.pop(context), child: const Text('Cancel')),
const SizedBox(width: 6),
FilledButton(onPressed: t.isEmpty ? null : _save, child: const Text('Save')),
],
),
],
),
),
);
}
Widget _field(IconData? icon, String text, VoidCallback onTap, {bool bad = false}) => InkWell(
borderRadius: BorderRadius.circular(10),
onTap: onTap,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 12),
decoration: BoxDecoration(
color: card2,
borderRadius: BorderRadius.circular(10),
border: bad ? Border.all(color: const Color(0xFFFF9A9A)) : null,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (icon != null) ...[Icon(icon, size: 16, color: muted), const SizedBox(width: 6)],
Flexible(
child: Text(text, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 15.5)),
),
],
),
),
);
}
/// The whole tree to pick from (the form's picker): a search box, the recent ones, then every live
/// node indented under its parent. Archived ones only when searching (or the current one).
class NodePicker extends StatefulWidget {
const NodePicker({super.key, required this.tree, required this.recent, this.current, this.only});
final Tree tree;
final List<String> recent;
final String? current;
final bool Function(Node)? only; // e.g. parents allowed for a kind
@override
State<NodePicker> createState() => _NodePickerState();
}
class _NodePickerState extends State<NodePicker> {
String q = '';
@override
Widget build(BuildContext context) {
final t = widget.tree;
final words = q.toLowerCase().split(RegExp(r'\s+')).where((w) => w.isNotEmpty).toList();
final rows = [
for (final (n, d) in t.walk(archived: true))
if ((widget.only?.call(n) ?? true) &&
(words.isEmpty ? (!t.archived(n.id) || n.id == widget.current) : words.every(t.path(n.id).toLowerCase().contains)))
(n, d),
];
return SizedBox(
height: MediaQuery.of(context).size.height * .75,
child: Padding(
padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
child: Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(12, 12, 12, 6),
child: TextField(
autofocus: false,
decoration: const InputDecoration(
prefixIcon: Icon(Icons.search),
hintText: 'Customer, project, task…',
border: OutlineInputBorder(),
),
onChanged: (v) => setState(() => q = v),
),
),
if (words.isEmpty && widget.recent.isNotEmpty && widget.only == null)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Wrap(
spacing: 6,
children: [
for (final r in widget.recent)
ActionChip(
avatar: Icon(Icons.history, size: 15, color: hexColor(t.colour(r))),
label: Text(t.nodes[r]!.name),
onPressed: () => Navigator.pop(context, r),
),
],
),
),
Expanded(
child: rows.isEmpty
? const Center(
child: Text('Nothing matches', style: TextStyle(color: muted)),
)
: ListView(
children: [
for (final (n, d) in rows)
ListTile(
dense: true,
selected: n.id == widget.current,
contentPadding: EdgeInsets.only(left: 16.0 + (words.isEmpty ? d * 18 : 0), right: 12),
leading: Icon(
n.kind == 'task'
? Icons.check_box_outline_blank
: n.kind == 'project'
? Icons.folder_outlined
: Icons.business,
size: 18,
color: hexColor(t.colour(n.id)),
),
title: Text(
words.isEmpty ? n.name : t.path(n.id),
style: TextStyle(fontSize: 15, color: t.archived(n.id) ? muted : null),
),
subtitle: t.archived(n.id) ? const Text('archived', style: TextStyle(color: muted)) : null,
onTap: () => Navigator.pop(context, n.id),
),
],
),
),
],
),
),
);
}
}

View file

@ -0,0 +1,239 @@
// Report (the web's /work/report): a range — this / last week, month, year, or any days — and
// optionally one customer; the totals, the tree with hours / billable / money per node, and every
// entry (tap = edit). "Copy CSV" puts the entries on the clipboard in the Pi's CSV columns.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../app/sync_service.dart';
import '../app/theme.dart';
import 'entry_sheet.dart';
import 'work_model.dart';
class ReportPage extends StatefulWidget {
const ReportPage({super.key, required this.sync, this.s = const WorkSettings()});
final SyncService sync;
final WorkSettings s;
@override
State<ReportPage> createState() => _ReportPageState();
}
class _ReportPageState extends State<ReportPage> {
String preset = 'month';
late (DateTime, DateTime) range = presetRange('month')!;
String? client;
String _amounts(Agg a) =>
(a.amounts.entries.toList()..sort((x, y) => x.key.compareTo(y.key))).map((e) => money(e.value, e.key)).join(' · ');
Future<void> _custom() async {
final p = await showDateRangePicker(
context: context,
firstDate: DateTime(2000),
lastDate: DateTime(2100),
initialDateRange: DateTimeRange(start: range.$1, end: range.$2),
);
if (p != null) {
setState(() {
preset = 'custom';
range = (dayOf(p.start), dayOf(p.end));
});
}
}
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: widget.sync,
builder: (context, _) {
final store = widget.sync.store;
final t = Tree(store, widget.s);
final r = report(store, t, range.$1, range.$2, client: client);
final clients = [
for (final (n, d) in t.walk(archived: true))
if (n.kind == 'client') (n, d),
];
return Scaffold(
appBar: AppBar(
title: const Text('Report'),
actions: [
IconButton(
tooltip: 'Copy as CSV',
icon: const Icon(Icons.copy_all),
onPressed: r.items.isEmpty
? null
: () async {
await Clipboard.setData(ClipboardData(text: reportCsv(r, t)));
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('${r.items.length} entries copied as CSV')));
}
},
),
],
),
body: ListView(
padding: const EdgeInsets.fromLTRB(12, 6, 12, 24),
children: [
Wrap(
spacing: 6,
runSpacing: 4,
children: [
for (final (k, label) in presets)
ChoiceChip(
label: Text(label),
selected: preset == k,
onSelected: (_) => setState(() {
preset = k;
range = presetRange(k)!;
}),
),
ChoiceChip(
label: Text(preset == 'custom' ? '${dayLabel(range.$1)} – ${dayLabel(range.$2)}' : 'Days…'),
selected: preset == 'custom',
onSelected: (_) => _custom(),
),
],
),
const SizedBox(height: 8),
DropdownButtonFormField<String?>(
initialValue: client,
isExpanded: true,
decoration: const InputDecoration(labelText: 'Customer', border: OutlineInputBorder(), isDense: true),
items: [
const DropdownMenuItem(value: null, child: Text('Everyone')),
for (final (n, d) in clients) DropdownMenuItem(value: n.id, child: Text('${' ' * d}${n.name}')),
],
onChanged: (v) => setState(() => client = v),
),
const SizedBox(height: 10),
Card(
child: Padding(
padding: const EdgeInsets.all(14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('${dayLabel(range.$1)} – ${dayLabel(range.$2)}', style: const TextStyle(color: muted)),
const SizedBox(height: 4),
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(hm(r.total.m), style: const TextStyle(fontSize: 26, fontWeight: FontWeight.bold)),
const SizedBox(width: 8),
Text('${(r.total.m / 60).toStringAsFixed(2)} h', style: const TextStyle(color: muted)),
const Spacer(),
Text(_amounts(r.total), style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
],
),
Text.rich(
TextSpan(
children: [
TextSpan(
text: '${hm(r.total.bm)} billable',
style: const TextStyle(color: good),
),
TextSpan(
text: ' · ${hm(r.total.m - r.total.bm)} not billable',
style: const TextStyle(color: muted),
),
],
),
),
],
),
),
),
if (r.rows.isEmpty)
const Padding(
padding: EdgeInsets.all(24),
child: Center(
child: Text('Nothing booked in this range', style: TextStyle(color: muted)),
),
),
if (r.rows.isNotEmpty) ...[
const SizedBox(height: 10),
Card(
child: Column(
children: [
for (final row in r.rows)
ListTile(
dense: true,
contentPadding: EdgeInsets.only(left: 12.0 + row.depth * 18, right: 12),
leading: Icon(Icons.circle, size: 11, color: hexColor(t.colour(row.node.id))),
minLeadingWidth: 10,
title: Text(row.node.name, style: TextStyle(fontWeight: row.depth == 0 ? FontWeight.bold : null)),
subtitle: Text(
'${hm(row.agg.bm)} billable${row.agg.m > row.agg.bm ? ' · ${hm(row.agg.m - row.agg.bm)} not' : ''}',
style: const TextStyle(color: muted, fontSize: 12),
),
trailing: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(hm(row.agg.m), style: const TextStyle(fontWeight: FontWeight.w600)),
if (row.agg.amounts.isNotEmpty) Text(_amounts(row.agg), style: const TextStyle(fontSize: 12, color: muted)),
],
),
onTap: row.node.kind == 'client' ? () => setState(() => client = row.node.id) : null,
),
],
),
),
const SizedBox(height: 14),
Text(
'Entries (${r.items.length})',
style: const TextStyle(color: muted, fontWeight: FontWeight.w600),
),
const SizedBox(height: 4),
..._entries(t, r),
],
],
),
);
},
);
List<Widget> _entries(Tree t, Report r) {
final out = <Widget>[];
String? lastDay;
for (final i in r.items) {
final e = i.e, d = e.start.substring(0, 10);
if (d != lastDay) {
out.add(
Padding(
padding: const EdgeInsets.fromLTRB(4, 10, 4, 2),
child: Text(
dayLabel(dayOf(e.s)),
style: const TextStyle(color: accent, fontWeight: FontWeight.w600),
),
),
);
lastDay = d;
}
out.add(
Card(
margin: const EdgeInsets.only(bottom: 4),
child: ListTile(
dense: true,
leading: Container(width: 4, height: 36, color: hexColor(t.colour(e.node))),
minLeadingWidth: 4,
title: Text(t.path(e.node)),
subtitle: Text(
['${e.start.substring(11)}–${e.end.substring(11)}', if (e.note.isNotEmpty) e.note.split('\n').first].join(' · '),
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(color: muted),
),
trailing: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(hm(e.minutes), style: const TextStyle(fontWeight: FontWeight.w600)),
Text(e.billable ? money(i.amount, i.currency) : 'not billable', style: const TextStyle(fontSize: 12, color: muted)),
],
),
onTap: () => openEntry(context, widget.sync, entry: e, s: widget.s),
),
),
);
}
return out;
}
}

View file

@ -0,0 +1,799 @@
// The workload tracker — a port of the dashboard's plugins/workload: db.py (the tree, inheritance,
// rate history, what an entry is) and views.py (week totals, the report). Keep them in step.
//
// Synced rows (workload.db, ids = the Pi's _uid; references are those ids):
// "workload.node" {kind client|project|task, parent_id, name, colour, billable 0/1/null, currency,
// notes, archived 0/1, created}
// "workload.rate" {node_id, since 'YYYY-MM-DD' | '0000-01-01' = always, rate} id = '<node id>:<since>'
// "workload.entry" {node_id, start, end 'YYYY-MM-DD HH:MM' local, billable 0/1, note, created, updated}
import 'dart:convert';
import '../sync/store.dart';
const kinds = ['client', 'project', 'task'];
const parentsOf = {
'client': [null, 'client'],
'project': ['client'],
'task': ['client', 'project'],
};
const palette = ['#ffb33a', '#5cc8ff', '#7fd6a3', '#ff6b7a', '#c792ea', '#ff9d5c', '#82aaff', '#f78c6c', '#c3e88d', '#89ddff'];
const epoch = '0000-01-01'; // a rate "since" this applies to all work
const tNode = 'workload.node', tRate = 'workload.rate', tEntry = 'workload.entry';
/// Until settings sync: the dashboard's Settings ▸ Work defaults.
class WorkSettings {
const WorkSettings({
this.currency = 'EUR',
this.defaultRate = 0,
this.dayStart = 7,
this.dayEnd = 19,
this.defaultMinutes = 60,
this.weekTarget = 40,
});
final String currency;
final double defaultRate;
final int dayStart, dayEnd, defaultMinutes;
final double weekTarget;
}
class Invalid implements Exception {
Invalid(this.field, this.message);
final String field, message;
@override
String toString() => message;
}
// ---- times -------------------------------------------------------------------------------
String two(int n) => n.toString().padLeft(2, '0');
String fmtDay(DateTime d) => '${d.year}-${two(d.month)}-${two(d.day)}';
String fmtMin(DateTime d) => '${fmtDay(d)} ${two(d.hour)}:${two(d.minute)}';
String fmtSec(DateTime d) => '${fmtMin(d)}:${two(d.second)}';
// Wall-clock time, like the Pi (naive datetimes): every date here is a UTC DateTime holding the local
// fields, so a day is always 24 h and a week 7 × 24 h — summer time never shifts a block or a week number.
DateTime parseMin(String s) => DateTime.parse('${s.replaceFirst(' ', 'T')}Z');
DateTime dayOf(DateTime d) => DateTime.utc(d.year, d.month, d.day);
/// Monday 00:00 of the week [offset] weeks from this one (views.week_start).
DateTime weekStart(int offset, [DateTime? now]) {
final t = dayOf(now ?? DateTime.now());
return DateTime.utc(t.year, t.month, t.day - (t.weekday - 1) + 7 * offset);
}
/// The ISO week number of a week's Monday (Python's isocalendar()[1]).
int isoWeek(DateTime monday) {
final thu = DateTime.utc(monday.year, monday.month, monday.day + 3);
return thu.difference(DateTime.utc(thu.year, 1, 1)).inDays ~/ 7 + 1;
}
/// 90 → '1:30' (views.hm).
String hm(num minutes) {
final m = minutes.round();
return '${m ~/ 60}:${two(m % 60)}';
}
/// 1234.5 → '1 234.50 EUR' (views.money).
String money(double amount, String currency) {
final s = amount.toStringAsFixed(2), dot = s.indexOf('.');
final neg = s.startsWith('-');
final digits = s.substring(neg ? 1 : 0, dot);
final b = StringBuffer(neg ? '-' : '');
for (var i = 0; i < digits.length; i++) {
if (i > 0 && (digits.length - i) % 3 == 0) b.write(' ');
b.write(digits[i]);
}
return '$b${s.substring(dot)} $currency';
}
/// A rate as the Pi's f"{rate:g}" would print it (20.0 → '20', 22.5 → '22.5').
String num0(double v) => v == v.roundToDouble() ? v.round().toString() : v.toString();
// ---- rows --------------------------------------------------------------------------------
class Node {
Node(this.r);
final Map<String, dynamic> r;
String get id => r['_u'] as String;
String get kind => r['kind'] as String;
String? get parent => r['parent_id'] as String?;
String get name => r['name'] as String? ?? '?';
String? get colour => r['colour'] as String?;
int? get billable => (r['billable'] as num?)?.toInt();
String? get currency => r['currency'] as String?;
String get notes => r['notes'] as String? ?? '';
bool get archived => (r['archived'] as num? ?? 0) != 0;
bool get isSub => kind == 'client' && parent != null;
}
class Rate {
Rate(this.since, this.rate);
final String since;
final double rate;
}
class WorkEntry {
WorkEntry(this.r) : s = parseMin(r['start'] as String), e = parseMin(r['end'] as String);
final Map<String, dynamic> r;
final DateTime s, e;
String get id => r['_u'] as String;
String get node => r['node_id'] as String;
String get start => r['start'] as String;
String get end => r['end'] as String;
bool get billable => (r['billable'] as num? ?? 0) != 0;
String get note => r['note'] as String? ?? '';
double get minutes => e.difference(s).inSeconds / 60;
}
// ---- the tree ----------------------------------------------------------------------------
/// All nodes + rates in memory (db.Tree): inheritance, paths, the picker list.
class Tree {
Tree(SyncStore store, [this.s = const WorkSettings()]) {
final ns = store.rows(tNode).map(Node.new).toList()..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
for (final n in ns) {
nodes[n.id] = n;
}
for (final r in store.rows(tRate)) {
final nid = r['node_id'] as String?;
if (nid == null) continue;
rates.putIfAbsent(nid, () => []).add(Rate(r['since'] as String, (r['rate'] as num).toDouble()));
}
for (final l in rates.values) {
l.sort((a, b) => a.since.compareTo(b.since));
}
for (final n in nodes.values) {
// a parent that isn't here (yet) → shown at the top until it arrives
children.putIfAbsent(nodes.containsKey(n.parent) ? n.parent : null, () => []).add(n.id);
}
}
final WorkSettings s;
final nodes = <String, Node>{};
final rates = <String, List<Rate>>{};
final children = <String?, List<String>>{};
bool get isEmpty => nodes.isEmpty;
/// The node and its ancestors, nearest first.
List<Node> chain(String? nid) {
final out = <Node>[], seen = <String>{};
while (nid != null && nodes.containsKey(nid) && seen.add(nid)) {
out.add(nodes[nid]!);
nid = nodes[nid]!.parent;
}
return out;
}
String path(String nid, [String sep = ' › ']) => chain(nid).reversed.map((n) => n.name).join(sep);
/// The top-level customer a node belongs to.
Node? clientOf(String nid) {
final c = chain(nid);
return c.isEmpty ? null : c.last;
}
(T, Node?) _inherit<T>(String? nid, T? Function(Node) key, T def) {
for (final n in chain(nid)) {
final v = key(n);
if (v != null) return (v, n);
}
return (def, null);
}
String colour(String? nid) => _inherit(nid, (n) => n.colour, palette[0]).$1;
String currency(String? nid) => _inherit(nid, (n) => n.currency, s.currency).$1;
/// (default billable for new entries, the node it comes from or null = default yes).
(bool, Node?) billable(String? nid) {
final (v, src) = _inherit(nid, (n) => n.billable, 1);
return (v != 0, src);
}
/// (hourly rate on [day] 'YYYY-MM-DD', the node it comes from or null = the default rate):
/// the nearest node with a rate in force that day wins.
(double, Node?) rate(String? nid, String day) {
for (final n in chain(nid)) {
Rate? best;
for (final r in rates[n.id] ?? const <Rate>[]) {
if (r.since.compareTo(day) <= 0) best = r;
}
if (best != null) return (best.rate, n);
}
return (s.defaultRate, null);
}
bool archived(String nid) => chain(nid).any((n) => n.archived);
/// Depth-first (node, depth): under each node its sub-customers, then projects, then tasks.
Iterable<(Node, int)> walk({String? parent, int depth = 0, bool archived = false}) sync* {
const order = {'client': 0, 'project': 1, 'task': 2};
final kids = [...?children[parent]]
..sort((a, b) {
final x = nodes[a]!, y = nodes[b]!;
final k = order[x.kind]!.compareTo(order[y.kind]!);
return k != 0 ? k : x.name.toLowerCase().compareTo(y.name.toLowerCase());
});
for (final i in kids) {
final n = nodes[i]!;
if (n.archived && !archived) continue;
yield (n, depth);
yield* walk(parent: i, depth: depth + 1, archived: archived);
}
}
Set<String> subtree(String nid) {
final out = <String>{}, todo = [nid];
while (todo.isNotEmpty) {
final i = todo.removeLast();
if (out.add(i)) todo.addAll(children[i] ?? const []);
}
return out;
}
/// One entry → (minutes, amount, currency); unbillable work is worth 0 (views._amount).
(double, double, String) amount(WorkEntry e) {
final cur = currency(e.node);
if (!e.billable) return (e.minutes, 0, cur);
return (e.minutes, e.minutes / 60 * rate(e.node, e.start.substring(0, 10)).$1, cur);
}
/// "A sub-customer" / "A project" … for labels.
static String kindLabel(Node n) => n.isSub ? 'Sub-customer' : const {'client': 'Customer', 'project': 'Project', 'task': 'Task'}[n.kind]!;
}
// ---- entries -----------------------------------------------------------------------------
/// Entries overlapping [start, end) (entries_between); [keep] = node ids to keep.
List<WorkEntry> entriesBetween(SyncStore store, DateTime start, DateTime end, {Set<String>? keep}) {
final out = [
for (final r in store.rows(
tEntry,
where: "json_extract(data, '\$.start') < ? AND json_extract(data, '\$.end') > ?",
args: [fmtMin(end), fmtMin(start)],
))
WorkEntry(r),
]..sort((a, b) => a.start.compareTo(b.start));
return keep == null ? out : out.where((e) => keep.contains(e.node)).toList();
}
/// The last few distinct nodes worked on (the form's chips), live ones only (db.recent).
List<String> recent(SyncStore store, Tree t, [int n = 5]) {
final last = <String, String>{};
for (final r in store.rows(tEntry)) {
final nid = r['node_id'] as String?, u = r['updated'] as String? ?? '';
if (nid != null && u.compareTo(last[nid] ?? '') > 0) last[nid] = u;
}
final ids = last.keys.toList()..sort((a, b) => last[b]!.compareTo(last[a]!));
return ids.where((i) => t.nodes.containsKey(i) && !t.archived(i)).take(n).toList();
}
/// What the entry form submits (db.clean_entry): times as picked; an end at or before the start
/// on the same day means it ends the next day (23:00 – 01:00).
class EntryForm {
EntryForm({
this.id,
this.node,
required this.day,
required this.startMin,
required this.endMin,
this.endDay,
required this.billable,
this.note = '',
});
String? id, node;
DateTime day; // the start's day
int startMin, endMin; // minutes after midnight
DateTime? endDay; // only when it was set on purpose (else: same day, or the next one)
bool billable;
String note;
(DateTime, DateTime) span() {
final a = day.add(Duration(minutes: startMin));
var b = (endDay ?? day).add(Duration(minutes: endMin));
if (!b.isAfter(a) && endDay == null) b = b.add(const Duration(days: 1));
return (a, b);
}
}
Map<String, dynamic> cleanEntry(EntryForm f, Tree t) {
if (f.node == null || !t.nodes.containsKey(f.node)) throw Invalid('node_id', 'Choose what you worked on.');
final (a, b) = f.span();
if (!b.isAfter(a)) throw Invalid('end', 'The end must be after the start.');
if (b.difference(a).inSeconds > 24 * 3600) throw Invalid('end', 'At most 24 hours in one entry.');
final note = f.note.trim();
return {
'node_id': f.node,
'start': fmtMin(a),
'end': fmtMin(b),
'billable': f.billable ? 1 : 0,
'note': note.length > 2000 ? note.substring(0, 2000) : note,
};
}
/// Create or update an entry → its id.
String saveEntry(SyncStore store, Tree t, EntryForm f) {
final v = cleanEntry(f, t), now = fmtSec(DateTime.now());
if (f.id == null) {
final id = SyncStore.randomId();
store.put(tEntry, id, {...v, 'created': now, 'updated': now});
return id;
}
final old = store.row(tEntry, f.id!);
if (old == null) throw Invalid('node_id', 'This entry was deleted meanwhile.');
store.put(tEntry, f.id!, {...old, ...v, 'updated': now});
return f.id!;
}
void deleteEntry(SyncStore store, String id) => store.delete(tEntry, id);
// ---- nodes -------------------------------------------------------------------------------
class NodeForm {
NodeForm({
this.id,
required this.kind,
this.parent,
this.name = '',
this.colour,
this.billable,
this.currency = '',
this.notes = '',
this.archived = false,
List<(String, String)>? rates,
}) : rates = rates ?? [];
String? id, parent, colour;
String kind, name, currency, notes;
int? billable; // null = inherit
bool archived;
List<(String, String)> rates; // (since '' = always, rate as typed)
factory NodeForm.of(Tree t, Node n) => NodeForm(
id: n.id,
kind: n.kind,
parent: n.parent,
name: n.name,
colour: n.colour,
billable: n.billable,
currency: n.currency ?? '',
notes: n.notes,
archived: n.archived,
rates: [for (final r in t.rates[n.id] ?? const <Rate>[]) (r.since == epoch ? '' : r.since, num0(r.rate))],
);
}
/// db._clean_node + _save_rates → (row, rates {since: rate}).
(Map<String, dynamic>, Map<String, double>) cleanNode(NodeForm f, Tree t) {
final name = f.name.trim();
if (name.isEmpty) throw Invalid('name', 'Give it a name.');
if (name.length > 80) throw Invalid('name', 'At most 80 characters.');
final kind = f.id == null ? f.kind : t.nodes[f.id]!.kind;
if (!kinds.contains(kind)) throw Invalid('kind', 'Unknown kind.');
final parent = f.parent;
if (parent != null && !t.nodes.containsKey(parent)) throw Invalid('parent_id', 'That parent no longer exists.');
final pkind = parent == null ? null : t.nodes[parent]!.kind;
if (!parentsOf[kind]!.contains(pkind)) {
throw Invalid(
'parent_id',
const {
'client': 'A sub-customer goes under a customer.',
'project': 'A project goes under a customer.',
'task': 'A task goes under a customer or a project.',
}[kind]!,
);
}
if (f.id != null && parent != null && t.subtree(f.id!).contains(parent)) throw Invalid('parent_id', "It can't go under itself.");
var colour = f.colour;
if (colour != null && !RegExp(r'^#[0-9a-fA-F]{6}$').hasMatch(colour)) throw Invalid('colour', 'A colour like #ffb33a.');
if (kind == 'client' && parent == null && colour == null) {
// customers always have one
final used = {
for (final n in t.nodes.values)
if (n.parent == null && n.id != f.id) n.colour,
};
colour = palette.firstWhere((c) => !used.contains(c), orElse: () => palette[used.length % palette.length]);
}
final currency = f.currency.trim().toUpperCase();
if (currency.isNotEmpty && !RegExp(r'^[A-Z]{3}$').hasMatch(currency)) throw Invalid('currency', 'A 3-letter code like EUR or RON.');
final rates = <String, double>{};
for (var i = 0; i < f.rates.length; i++) {
final (sinceRaw, rateRaw) = f.rates[i];
final raw = rateRaw.trim().replaceAll(',', '.');
if (raw.isEmpty) continue;
final rate = double.tryParse(raw);
if (rate == null) throw Invalid('rates.$i.rate', 'The rate must be a number.');
if (rate < 0 || rate > 100000) throw Invalid('rates.$i.rate', 'Between 0 and 100000.');
final since = sinceRaw.trim().isEmpty ? epoch : sinceRaw.trim();
if (since != epoch && (DateTime.tryParse(since) == null || !RegExp(r'^\d{4}-\d\d-\d\d$').hasMatch(since))) {
throw Invalid('rates.$i.since', 'A date, or empty for always.');
}
if (rates.containsKey(since)) throw Invalid('rates.$i.since', 'Two rates from the same day.');
rates[since] = rate;
}
final notes = f.notes.length > 4000 ? f.notes.substring(0, 4000) : f.notes;
return (
{
'kind': kind,
'parent_id': parent,
'name': name,
'colour': colour,
'billable': f.billable,
'currency': currency.isEmpty ? null : currency,
'notes': notes,
'archived': f.archived ? 1 : 0,
},
rates,
);
}
/// Create (no id) or update a node and replace its rate history → its id.
String saveNode(SyncStore store, Tree t, NodeForm f) {
final (v, rates) = cleanNode(f, t);
final String id;
if (f.id == null) {
id = SyncStore.randomId();
store.put(tNode, id, {...v, 'created': fmtSec(DateTime.now())});
} else {
id = f.id!;
final old = store.row(tNode, id);
if (old == null) throw Invalid('name', 'It was deleted meanwhile.');
store.put(tNode, id, {...old, ...v});
}
// rates: ids are '<node>:<since>' (the Pi's key) — unchanged rows aren't touched
final have = {for (final r in t.rates[id] ?? const <Rate>[]) r.since: r.rate};
for (final since in have.keys) {
if (!rates.containsKey(since)) store.delete(tRate, '$id:$since');
}
for (final MapEntry(key: since, value: rate) in rates.entries) {
if (have[since] != rate) store.put(tRate, '$id:$since', {'node_id': id, 'since': since, 'rate': rate});
}
return id;
}
/// Delete a node and everything under it — only when no time is booked there (archive it
/// instead). → false when refused.
bool deleteNode(SyncStore store, Tree t, String nid) {
final ids = t.subtree(nid);
if (store.rows(tEntry).any((r) => ids.contains(r['node_id']))) return false;
final order = ids.toList()..sort((a, b) => t.chain(b).length.compareTo(t.chain(a).length)); // leaves first
for (final i in order) {
for (final r in t.rates[i] ?? const <Rate>[]) {
store.delete(tRate, '$i:${r.since}');
}
store.delete(tNode, i);
}
return true;
}
/// node id → minutes ever booked directly on it.
Map<String, double> bookedMinutes(SyncStore store) {
final out = <String, double>{};
for (final r in store.rows(tEntry)) {
final e = WorkEntry(r);
out[e.node] = (out[e.node] ?? 0) + e.minutes;
}
return out;
}
// ---- the week ----------------------------------------------------------------------------
class Block {
Block(this.e, this.a, this.b, this.contBefore, this.contAfter);
final WorkEntry e;
final double a, b; // minutes after the day's midnight
final bool contBefore, contAfter;
int lane = 0, lanes = 1;
}
class DayCol {
DayCol(this.day, this.blocks, this.minutes, this.billableMinutes);
final DateTime day;
final List<Block> blocks;
final double minutes, billableMinutes;
}
class CustomerWeek {
CustomerWeek(this.node, this.minutes, this.amounts, this.rate);
final Node node;
final double minutes;
final Map<String, double> amounts;
final String rate;
}
class WeekView {
WeekView(this.monday, this.days, this.minutes, this.billableMinutes, this.amounts, this.customers);
final DateTime monday;
final List<DayCol> days;
final double minutes, billableMinutes;
final Map<String, double> amounts;
final List<CustomerWeek> customers;
}
/// Overlap layout: lane + lanes per cluster of overlapping blocks (views._lanes).
void lanes(List<Block> items) {
final cluster = <Block>[];
double? end;
void flush() {
final n = cluster.fold(0, (m, i) => i.lane > m ? i.lane : m) + 1;
for (final i in cluster) {
i.lanes = n;
}
}
items.sort((x, y) => x.a != y.a ? x.a.compareTo(y.a) : y.b.compareTo(x.b));
for (final it in items) {
if (cluster.isNotEmpty && it.a >= end!) {
flush();
cluster.clear();
end = null;
}
final used = {
for (final c in cluster)
if (c.b > it.a) c.lane,
};
var l = 0;
while (used.contains(l)) {
l++;
}
it.lane = l;
cluster.add(it);
end = end == null ? it.b : (it.b > end ? it.b : end);
}
if (cluster.isNotEmpty) flush();
}
WeekView week(SyncStore store, Tree t, int offset, [DateTime? now]) {
final ws = weekStart(offset, now), we = DateTime.utc(ws.year, ws.month, ws.day + 7);
final entries = entriesBetween(store, ws, we);
final days = <DayCol>[];
var tot = 0.0, totB = 0.0;
for (var d = 0; d < 7; d++) {
final d0 = DateTime.utc(ws.year, ws.month, ws.day + d), d1 = DateTime.utc(ws.year, ws.month, ws.day + d + 1);
final blocks = <Block>[];
var m = 0.0, bm = 0.0;
for (final e in entries) {
final a = e.s.isAfter(d0) ? e.s : d0, b = e.e.isBefore(d1) ? e.e : d1;
if (!b.isAfter(a)) continue;
final am = a.difference(d0).inSeconds / 60, bmin = b.difference(d0).inSeconds / 60;
m += bmin - am;
if (e.billable) bm += bmin - am;
blocks.add(Block(e, am, bmin, e.s.isBefore(d0), e.e.isAfter(d1)));
}
lanes(blocks);
days.add(DayCol(d0, blocks, m, bm));
tot += m;
totB += bm;
}
final amounts = <String, double>{};
final per = <String, (double, Map<String, double>)>{};
for (final e in entries) {
// money by the entry's own date + rate
final (minutes, amt, cur) = t.amount(e);
if (e.billable) amounts[cur] = (amounts[cur] ?? 0) + amt;
final top = t.clientOf(e.node);
if (top != null) {
final p = per[top.id] ?? (0.0, <String, double>{});
if (e.billable) p.$2[cur] = (p.$2[cur] ?? 0) + amt;
per[top.id] = (p.$1 + minutes, p.$2);
}
}
final todayIso = fmtDay(now ?? DateTime.now());
final customers = [
for (final (n, _) in t.walk())
if (n.parent == null)
CustomerWeek(n, per[n.id]?.$1 ?? 0, per[n.id]?.$2 ?? {}, '${num0(t.rate(n.id, todayIso).$1)} ${t.currency(n.id)}/h'),
]..sort((a, b) => b.minutes.compareTo(a.minutes));
return WeekView(ws, days, tot, totB, amounts, customers);
}
// ---- the report --------------------------------------------------------------------------
const presets = [
('week', 'This week'),
('lastweek', 'Last week'),
('month', 'This month'),
('lastmonth', 'Last month'),
('year', 'This year'),
('lastyear', 'Last year'),
];
/// (from, to) inclusive days of a preset (views.preset_range), or null.
(DateTime, DateTime)? presetRange(String name, [DateTime? now]) {
final t = dayOf(now ?? DateTime.now());
final mon = DateTime.utc(t.year, t.month, t.day - (t.weekday - 1));
switch (name) {
case 'week':
return (mon, DateTime.utc(mon.year, mon.month, mon.day + 6));
case 'lastweek':
return (DateTime.utc(mon.year, mon.month, mon.day - 7), DateTime.utc(mon.year, mon.month, mon.day - 1));
case 'month':
return (DateTime.utc(t.year, t.month, 1), DateTime.utc(t.year, t.month + 1, 0));
case 'lastmonth':
return (DateTime.utc(t.year, t.month - 1, 1), DateTime.utc(t.year, t.month, 0));
case 'year':
return (DateTime.utc(t.year, 1, 1), DateTime.utc(t.year, 12, 31));
case 'lastyear':
return (DateTime.utc(t.year - 1, 1, 1), DateTime.utc(t.year - 1, 12, 31));
}
return null;
}
class Agg {
double m = 0, bm = 0;
final amounts = <String, double>{};
void add(double minutes, bool billable, double amt, String cur) {
m += minutes;
if (billable) {
bm += minutes;
amounts[cur] = (amounts[cur] ?? 0) + amt;
}
}
}
class ReportRow {
ReportRow(this.node, this.depth, this.agg);
final Node node;
final int depth;
final Agg agg;
}
class ReportItem {
ReportItem(this.e, this.rate, this.amount, this.currency);
final WorkEntry e;
final double rate, amount;
final String currency;
}
class Report {
Report(this.rows, this.items, this.total);
final List<ReportRow> rows;
final List<ReportItem> items;
final Agg total;
}
/// Hours + money in [from, to] (inclusive days) as a tree; [client] limits it to one node's
/// subtree. Entries count on the day they start (views.report).
Report report(SyncStore store, Tree t, DateTime from, DateTime to, {String? client}) {
final keep = client != null && t.nodes.containsKey(client) ? t.subtree(client) : null;
final start = dayOf(from), end = DateTime.utc(to.year, to.month, to.day + 1);
final rows = entriesBetween(
store,
start.subtract(const Duration(days: 1)),
end,
keep: keep,
).where((e) => !e.s.isBefore(start) && e.s.isBefore(end)).toList();
final agg = <String, Agg>{}, total = Agg(), items = <ReportItem>[];
for (final e in rows) {
final (minutes, amt, cur) = t.amount(e);
for (final n in t.chain(e.node)) {
agg.putIfAbsent(n.id, Agg.new).add(minutes, e.billable, amt, cur);
}
total.add(minutes, e.billable, amt, cur);
items.add(ReportItem(e, e.billable ? t.rate(e.node, e.start.substring(0, 10)).$1 : 0, amt, cur));
}
return Report(
[
for (final (n, d) in t.walk(archived: true))
if (agg[n.id] != null) ReportRow(n, d, agg[n.id]!),
],
items,
total,
);
}
/// The report's entries as CSV (the Pi's /work/report.csv).
String reportCsv(Report r, Tree t) {
String q(String s) => RegExp(r'[",\n\r]').hasMatch(s) ? '"${s.replaceAll('"', '""')}"' : s;
final b = StringBuffer('date,start,end,hours,customer / project / task,billable,rate,amount,currency,note\r\n');
for (final i in r.items) {
final e = i.e;
b.write(
[
e.start.substring(0, 10),
e.start.substring(11),
e.end.substring(11),
(e.minutes / 60).toStringAsFixed(2),
q(t.path(e.node)),
e.billable ? 'yes' : 'no',
e.billable ? num0(i.rate) : '',
e.billable ? i.amount.toStringAsFixed(2) : '',
i.currency,
q(e.note),
].join(','),
);
b.write('\r\n');
}
return b.toString();
}
// ---- what the Pi adds to the week (plugins/workload/phone.py) -----------------------------
// "workload.cal" — the calendar's timed events (drawn faintly behind; tap = book them);
// "workload.act" — Activity's blocks for the lane beside the bookings (tap = book with the customer guessed).
const tCal = 'workload.cal', tAct = 'workload.act';
class Ghost {
Ghost(this.title, this.calendar, this.colour, this.a, this.b, this.s, this.e);
final String title, calendar, colour;
final double a, b; // minutes after the day's midnight
final DateTime s, e; // the part inside this day
}
class ActBlock {
ActBlock(this.r) : a = (r['a'] as num).toDouble(), b = (r['b'] as num).toDouble();
final Map<String, dynamic> r;
final double a, b;
String get day => r['day'] as String;
String get start => r['start'] as String;
String get end => r['end'] as String;
String get colour => r['colour'] as String? ?? '#8b929e';
String get path => r['path'] as String? ?? '';
String get name => r['name'] as String? ?? '';
String get what => r['what'] as String? ?? '';
String get dur => r['dur'] as String? ?? '';
List<String> get names => ((jsonDecodeSafe(r['names'] as String?) as List?) ?? const []).cast<String>();
}
Object? jsonDecodeSafe(String? s) {
if (s == null || s.isEmpty) return null;
try {
return jsonDecode(s);
} catch (_) {
return null;
}
}
/// The calendar events inside each day of the week from [monday] (all-day ones aren't sent).
List<List<Ghost>> ghosts(SyncStore store, DateTime monday) {
final end = DateTime.utc(monday.year, monday.month, monday.day + 7);
final rows = store.rows(
tCal,
where: "json_extract(data, '\$.start') < ? AND json_extract(data, '\$.end') > ?",
args: [fmtMin(end), fmtMin(monday)],
);
return [
for (var d = 0; d < 7; d++)
() {
final d0 = DateTime.utc(monday.year, monday.month, monday.day + d),
d1 = DateTime.utc(monday.year, monday.month, monday.day + d + 1);
final out = <Ghost>[];
for (final r in rows) {
final s = parseMin(r['start'] as String), e = parseMin(r['end'] as String);
final a = s.isAfter(d0) ? s : d0, b = e.isBefore(d1) ? e : d1;
if (!b.isAfter(a)) continue;
out.add(
Ghost(
r['title'] as String? ?? '',
r['calendar'] as String? ?? '',
r['colour'] as String? ?? '#8b929e',
a.difference(d0).inSeconds / 60,
b.difference(d0).inSeconds / 60,
a,
b,
),
);
}
out.sort((x, y) => x.a.compareTo(y.a));
return out;
}(),
];
}
/// Activity's blocks per day of the week from [monday].
List<List<ActBlock>> actBlocks(SyncStore store, DateTime monday) {
final days = [for (var d = 0; d < 7; d++) fmtDay(DateTime.utc(monday.year, monday.month, monday.day + d))];
final rows = store.rows(tAct, where: "json_extract(data, '\$.day') BETWEEN ? AND ?", args: [days.first, days.last]);
return [for (final d in days) (rows.where((r) => r['day'] == d).map(ActBlock.new).toList()..sort((x, y) => x.a.compareTo(y.a)))];
}
/// The customer / project an Activity block is probably for: the first of its category names
/// (nearest first: "Rocket", "Acme", "Customer", "Work") that's a live node's name (views._guess).
String? guessNode(Tree t, List<String> names) {
final byName = <String, String>{};
for (final (n, _) in t.walk()) {
byName.putIfAbsent(n.name.trim().toLowerCase(), () => n.id);
}
for (final x in names) {
final id = byName[x.trim().toLowerCase()];
if (id != null) return id;
}
return null;
}

1054
app/lib/work/work_page.dart Normal file

File diff suppressed because it is too large Load diff

33
app/packages/gb_export/.gitignore vendored Normal file
View file

@ -0,0 +1,33 @@
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.build/
.buildlog/
.history
.svn/
.swiftpm/
migrate_working_dir/
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/
# Flutter/Dart/Pub related
# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock.
/pubspec.lock
**/doc/api/
.dart_tool/
.flutter-plugins-dependencies
/build/
/coverage/

Some files were not shown because too many files have changed in this diff Show more