Settings sync between the dashboard and the app
- Dashboard (settingsync.py): the plugins' settings go into a synced settings.db, one row per setting (the row id is the setting's key, so the phone and the dashboard edit the same row; the later change wins) plus each field as the plugin declares it. Fields marked "local" (addresses, paths on one machine) and the plugins' on / off stay out. Values set on another device are checked as the Settings page does before they're saved; a refused one is written back with the dashboard's value. - App 1.1.7: a Settings page (the gear on every tab) built from those fields, synced both ways. Food targets, the cycle, the work day and the body profile read the synced values; with a dashboard that doesn't sync settings yet, they still come from its Health summaries. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
98b110dd56
commit
820aca7d92
25 changed files with 606 additions and 41 deletions
|
|
@ -13,6 +13,12 @@ What changed in each published build of the app. `tool/publish.sh` shows the ent
|
|||
- The band's data goes with the phone's time zone, so the dashboard reads its times right without a
|
||||
setting.
|
||||
|
||||
## 1.1.7 — 2026-10-26
|
||||
|
||||
- Settings (the gear at the top): the dashboard's Health, Cycle, Food and Work settings, synced both ways —
|
||||
change them here or on the dashboard. Food's targets, the cycle's lengths, Work's day and the body
|
||||
profile now follow them instead of fixed values in the app. A value the dashboard can't take is put back.
|
||||
|
||||
## 1.1.6 — 2026-10-26
|
||||
|
||||
- Food: the arrows at the top go a week back / ahead; swiping sideways goes a day. The dashboard's arrows go
|
||||
|
|
|
|||
111
app/lib/app/prefs.dart
Normal file
111
app/lib/app/prefs.dart
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
// The dashboard's settings, synced both ways (the dashboard's settingsync.py): "settings.setting" rows
|
||||
// {k "food.goal_rate", v JSON}, one per setting (the row id is k, so the phone and the dashboard edit the
|
||||
// same row; the later change wins), and "settings.field" rows {k, plugin, title, pos, spec JSON} — each
|
||||
// setting as the plugin declares it (label, type, options, min / max, help), so the Settings page needs no
|
||||
// list of its own. The dashboard checks what arrives as its Settings page does; a value it refuses is
|
||||
// written back with its own, which comes back here at the next sync.
|
||||
import 'dart:convert';
|
||||
|
||||
import '../sync/store.dart';
|
||||
|
||||
const tSetting = 'settings.setting', tField = 'settings.field';
|
||||
|
||||
class Prefs {
|
||||
Prefs(this.store);
|
||||
final SyncStore store;
|
||||
|
||||
/// The value of "plugin.key", or [d] while it hasn't come from the dashboard yet.
|
||||
T get<T>(String k, T d) {
|
||||
final r = store.row(tSetting, k);
|
||||
if (r == null) return d;
|
||||
try {
|
||||
final v = jsonDecode(r['v'] as String);
|
||||
if (v is T) return v;
|
||||
if (d is double && v is num) return v.toDouble() as T;
|
||||
if (d is int && v is num) return v.round() as T;
|
||||
} catch (_) {}
|
||||
return d;
|
||||
}
|
||||
|
||||
num number(String k, num d) => get<num>(k, d);
|
||||
|
||||
void set(String k, Object? v) {
|
||||
final r = store.row(tSetting, k);
|
||||
final enc = jsonEncode(v);
|
||||
if (r != null && r['v'] == enc) return; // unchanged: nothing to send
|
||||
store.put(tSetting, k, {'k': k, 'v': enc});
|
||||
}
|
||||
|
||||
/// The fields the dashboard shares, by plugin (in its order).
|
||||
List<(String, String, List<Field>)> sections() {
|
||||
final fs = [for (final r in store.rows(tField)) Field.of(r)]..sort((a, b) => a.pos.compareTo(b.pos));
|
||||
final out = <(String, String, List<Field>)>[];
|
||||
for (final f in fs) {
|
||||
if (out.isEmpty || out.last.$1 != f.plugin) out.add((f.plugin, f.title, []));
|
||||
out.last.$3.add(f);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
/// One setting as the plugin declares it (pluginhost: META["settings"]).
|
||||
class Field {
|
||||
Field(this.k, this.plugin, this.title, this.pos, this.spec);
|
||||
factory Field.of(Map<String, dynamic> r) {
|
||||
Map<String, dynamic> spec;
|
||||
try {
|
||||
spec = jsonDecode(r['spec'] as String) as Map<String, dynamic>;
|
||||
} catch (_) {
|
||||
spec = {};
|
||||
}
|
||||
return Field(r['k'] as String, (r['plugin'] as String?) ?? '', (r['title'] as String?) ?? '', (r['pos'] as num?)?.toInt() ?? 0, spec);
|
||||
}
|
||||
final String k, plugin, title;
|
||||
final int pos;
|
||||
final Map<String, dynamic> spec;
|
||||
|
||||
String get key => spec['key'] as String? ?? k.split('.').last;
|
||||
String get type => spec['type'] as String? ?? 'text';
|
||||
String get label => spec['label'] as String? ?? key;
|
||||
String? get help => spec['help'] as String?;
|
||||
Object? get def => spec['default'];
|
||||
num? get min => spec['min'] as num?;
|
||||
num? get max => spec['max'] as num?;
|
||||
bool get integer => spec['integer'] == true;
|
||||
|
||||
/// [(value, label)] of a select.
|
||||
List<(Object?, String)> get options => [
|
||||
for (final o in (spec['options'] as List?) ?? const [])
|
||||
o is List ? (o.first, '${o.length > 1 ? o[1] : o.first}') : (o, '$o'),
|
||||
];
|
||||
|
||||
/// The value checked as the dashboard will (pluginhost._value) → (value, null) or (null, why not).
|
||||
(Object?, String?) check(Object? v) {
|
||||
switch (type) {
|
||||
case 'bool':
|
||||
return (v == true, null);
|
||||
case 'number':
|
||||
final n = v is num ? v : num.tryParse('${v ?? ''}'.trim().replaceAll(',', '.'));
|
||||
if (n == null) return (null, 'Must be a number.');
|
||||
final lo = min ?? double.negativeInfinity, hi = max ?? double.infinity;
|
||||
if (n < lo || n > hi) return (null, 'Must be between ${_g(lo)} and ${_g(hi)}.');
|
||||
return (integer ? n.toInt() : n.toDouble(), null); // int() on the dashboard: cut, not rounded
|
||||
case 'select':
|
||||
for (final (o, _) in options) {
|
||||
if ('$o' == '$v') return (o, null);
|
||||
}
|
||||
return (null, 'Pick one of the options.');
|
||||
default:
|
||||
final s = '${v ?? ''}'.trim();
|
||||
final mx = (spec['max'] as num?)?.toInt() ?? 200;
|
||||
if (s.length > mx) return (null, 'At most $mx characters.');
|
||||
final p = spec['pattern'] as String?;
|
||||
if (p != null && s.isNotEmpty && !RegExp('^(?:$p)\$').hasMatch(s)) {
|
||||
return (null, spec['pattern_help'] as String? ?? 'Not a valid value.');
|
||||
}
|
||||
return (s, null);
|
||||
}
|
||||
}
|
||||
|
||||
static String _g(num n) => n == n.roundToDouble() ? n.round().toString() : '$n';
|
||||
}
|
||||
167
app/lib/app/settings_page.dart
Normal file
167
app/lib/app/settings_page.dart
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
// Settings: the dashboard's plugin settings (Health, Cycle, Food, Work …), built from the fields it shares
|
||||
// (prefs.dart) and synced both ways. A switch or a pick is saved at once; a number or text opens a small
|
||||
// editor that checks it as the dashboard will. Food's custom protein / carbs / fat are edited together
|
||||
// (they must make 100 %) and only show with the "Custom" split.
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'prefs.dart';
|
||||
import 'sync_service.dart';
|
||||
import 'theme.dart';
|
||||
|
||||
const _split = ['food.custom_protein', 'food.custom_carbs', 'food.custom_fat'];
|
||||
|
||||
class SettingsPage extends StatelessWidget {
|
||||
const SettingsPage({super.key, required this.sync});
|
||||
final SyncService sync;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Scaffold(
|
||||
appBar: AppBar(title: const Text('Settings')),
|
||||
body: ListenableBuilder(
|
||||
listenable: sync,
|
||||
builder: (context, _) {
|
||||
final p = Prefs(sync.store);
|
||||
final secs = p.sections();
|
||||
if (secs.isEmpty) {
|
||||
return const Padding(padding: EdgeInsets.all(16),
|
||||
child: Text('The settings come from the dashboard with the next sync.', style: TextStyle(color: muted)));
|
||||
}
|
||||
return ListView(padding: const EdgeInsets.only(bottom: 24), children: [
|
||||
for (final (_, title, fields) in secs) ...[
|
||||
Padding(padding: const EdgeInsets.fromLTRB(16, 18, 16, 4),
|
||||
child: Text(title, style: const TextStyle(color: accent, fontWeight: FontWeight.bold, fontSize: 15))),
|
||||
for (final f in fields)
|
||||
if (!_split.contains(f.k)) _tile(context, p, f)
|
||||
else if (f.k == _split.first && p.get<String>('food.macro_preset', '') == 'custom') _splitTile(context, p, fields),
|
||||
],
|
||||
]);
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
void _set(Prefs p, String k, Object? v) {
|
||||
p.set(k, v);
|
||||
sync.changed(); // goes out with the next sync
|
||||
}
|
||||
|
||||
Widget? _info(Field f) => f.help == null
|
||||
? null
|
||||
: Tooltip(message: f.help!, triggerMode: TooltipTriggerMode.tap, showDuration: const Duration(seconds: 8),
|
||||
child: const Padding(padding: EdgeInsets.all(8), child: Icon(Icons.info_outline, size: 18, color: muted)));
|
||||
|
||||
Widget _tile(BuildContext context, Prefs p, Field f) {
|
||||
final v = p.get<Object?>(f.k, f.def);
|
||||
switch (f.type) {
|
||||
case 'bool':
|
||||
return SwitchListTile(
|
||||
title: Row(children: [Flexible(child: Text(f.label)), ?_info(f)]),
|
||||
value: v == true,
|
||||
onChanged: (x) => _set(p, f.k, x),
|
||||
);
|
||||
case 'select':
|
||||
final opts = f.options;
|
||||
final cur = opts.where((o) => '${o.$1}' == '$v').firstOrNull;
|
||||
return ListTile(
|
||||
title: Row(children: [Flexible(child: Text(f.label)), ?_info(f)]),
|
||||
subtitle: DropdownButton<int>(
|
||||
isExpanded: true,
|
||||
value: cur == null ? null : opts.indexOf(cur),
|
||||
underline: const SizedBox(),
|
||||
dropdownColor: card2,
|
||||
items: [for (var i = 0; i < opts.length; i++) DropdownMenuItem(value: i, child: Text(opts[i].$2))],
|
||||
onChanged: (i) => i == null ? null : _set(p, f.k, opts[i].$1),
|
||||
),
|
||||
);
|
||||
default:
|
||||
final shown = v == null || '$v'.isEmpty ? '—' : f.type == 'number' && v is num && v == v.roundToDouble() ? '${v.round()}' : '$v';
|
||||
return ListTile(
|
||||
title: Row(children: [Flexible(child: Text(f.label)), ?_info(f)]),
|
||||
subtitle: Text(shown, style: const TextStyle(color: muted)),
|
||||
trailing: const Icon(Icons.edit_outlined, size: 18, color: muted),
|
||||
onTap: () => _edit(context, p, [f]),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Widget _splitTile(BuildContext context, Prefs p, List<Field> fields) {
|
||||
final fs = [for (final k in _split) fields.firstWhere((f) => f.k == k)];
|
||||
final vs = [for (final f in fs) p.number(f.k, (f.def as num?) ?? 0).round()];
|
||||
return ListTile(
|
||||
title: const Text('Custom split: protein / carbs / fat'),
|
||||
subtitle: Text('${vs[0]} / ${vs[1]} / ${vs[2]} % of the energy', style: const TextStyle(color: muted)),
|
||||
trailing: const Icon(Icons.edit_outlined, size: 18, color: muted),
|
||||
onTap: () => _edit(context, p, fs, total: 100),
|
||||
);
|
||||
}
|
||||
|
||||
/// A number / text editor for one field, or several edited together ([total]: they must add up to it).
|
||||
Future<void> _edit(BuildContext context, Prefs p, List<Field> fs, {num? total}) => showModalBottomSheet(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
backgroundColor: card,
|
||||
builder: (_) => _Editor(fields: fs, values: [for (final f in fs) p.get<Object?>(f.k, f.def)], total: total,
|
||||
onSave: (vs) {
|
||||
for (var i = 0; i < fs.length; i++) {
|
||||
_set(p, fs[i].k, vs[i]);
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
class _Editor extends StatefulWidget {
|
||||
const _Editor({required this.fields, required this.values, required this.onSave, this.total});
|
||||
final List<Field> fields;
|
||||
final List<Object?> values;
|
||||
final num? total;
|
||||
final void Function(List<Object?>) onSave;
|
||||
@override
|
||||
State<_Editor> createState() => _EditorState();
|
||||
}
|
||||
|
||||
class _EditorState extends State<_Editor> {
|
||||
late final ctl = [
|
||||
for (final v in widget.values) TextEditingController(text: v == null ? '' : v is num && v == v.roundToDouble() ? '${v.round()}' : '$v'),
|
||||
];
|
||||
String? error;
|
||||
|
||||
void _save() {
|
||||
final out = <Object?>[];
|
||||
for (var i = 0; i < widget.fields.length; i++) {
|
||||
final (v, err) = widget.fields[i].check(ctl[i].text);
|
||||
if (err != null) return setState(() => error = '${widget.fields[i].label}: $err');
|
||||
out.add(v);
|
||||
}
|
||||
final t = widget.total;
|
||||
if (t != null) {
|
||||
final sum = out.fold<num>(0, (a, v) => a + (v as num));
|
||||
if (sum != t) return setState(() => error = 'They make ${sum.round()} %, not ${t.round()}.');
|
||||
}
|
||||
widget.onSave(out);
|
||||
Navigator.pop(context);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Padding(
|
||||
padding: EdgeInsets.fromLTRB(16, 16, 16, 16 + MediaQuery.of(context).viewInsets.bottom),
|
||||
child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
for (var i = 0; i < widget.fields.length; i++)
|
||||
TextField(
|
||||
controller: ctl[i],
|
||||
autofocus: i == 0,
|
||||
keyboardType: widget.fields[i].type == 'number' ? const TextInputType.numberWithOptions(decimal: true, signed: true) : null,
|
||||
decoration: InputDecoration(labelText: widget.fields[i].label, helperText: _range(widget.fields[i])),
|
||||
onSubmitted: (_) => _save(),
|
||||
),
|
||||
if (error != null) Padding(padding: const EdgeInsets.only(top: 8), child: Text(error!, style: const TextStyle(color: bad))),
|
||||
const SizedBox(height: 12),
|
||||
FilledButton(onPressed: _save, child: const Text('Save')),
|
||||
]),
|
||||
);
|
||||
|
||||
static String? _range(Field f) {
|
||||
if (f.type != 'number' || (f.min == null && f.max == null)) return null;
|
||||
String g(num n) => n == n.roundToDouble() ? '${n.round()}' : '$n';
|
||||
return '${f.min == null ? '' : g(f.min!)} – ${f.max == null ? '' : g(f.max!)}';
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -23,6 +23,7 @@ import '../health/range.dart';
|
|||
import '../health/sleep_page.dart';
|
||||
import '../sync/client.dart';
|
||||
import '../sync/kick.dart' show piUrl;
|
||||
import 'settings_page.dart';
|
||||
import 'sync_service.dart';
|
||||
import 'updater.dart';
|
||||
import 'theme.dart';
|
||||
|
|
@ -71,7 +72,7 @@ class _ShellState extends State<Shell> {
|
|||
color: card2,
|
||||
onSelected: (k) {
|
||||
if (k == 'doctor') {
|
||||
Navigator.push(context, MaterialPageRoute(builder: (_) => DoctorPage(sync: widget.sync, settings: const CycleSettings())));
|
||||
Navigator.push(context, MaterialPageRoute(builder: (_) => DoctorPage(sync: widget.sync, settings: CycleSettings.of(widget.sync.store))));
|
||||
}
|
||||
},
|
||||
itemBuilder: (_) => const [PopupMenuItem(value: 'doctor', child: Text('For your doctor'))],
|
||||
|
|
@ -96,6 +97,12 @@ class _ShellState extends State<Shell> {
|
|||
),
|
||||
);
|
||||
|
||||
Widget _settingsIcon() => IconButton(
|
||||
tooltip: 'Settings',
|
||||
onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (_) => SettingsPage(sync: widget.sync))),
|
||||
icon: const Icon(Icons.settings_outlined),
|
||||
);
|
||||
|
||||
static const sections = [
|
||||
(Icons.favorite_border, Icons.favorite, 'Health'),
|
||||
(Icons.restaurant_outlined, Icons.restaurant, 'Food'),
|
||||
|
|
@ -115,8 +122,8 @@ class _ShellState extends State<Shell> {
|
|||
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),
|
||||
? AppBar(titleSpacing: 0, title: tabs, actions: [_syncIcon(), _settingsIcon(), _healthMenu()])
|
||||
: AppBar(title: const Text('Health'), actions: [_syncIcon(), _settingsIcon(), _healthMenu()], bottom: tabs),
|
||||
body: TabBarView(children: [
|
||||
OverviewPage(sync: widget.sync, onFood: () => setState(() => section = 1)),
|
||||
CyclePage(sync: widget.sync),
|
||||
|
|
@ -127,10 +134,10 @@ class _ShellState extends State<Shell> {
|
|||
]),
|
||||
),
|
||||
),
|
||||
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
|
||||
1 => Scaffold(appBar: AppBar(title: const Text('Food'), actions: [_syncIcon(), _settingsIcon(), _foodMenu()]), body: FoodPage(sync: widget.sync)),
|
||||
2 => WorkPage(sync: widget.sync, actions: [_syncIcon(), _settingsIcon(), _workMenu()]), // its own bar: in landscape the week's ‹ CW › is in it
|
||||
3 => NotesPage(sync: widget.sync, actions: [_syncIcon(), _settingsIcon()]), // its own bar: the title picks folder / tag
|
||||
_ => WeatherPage(sync: widget.sync, actions: [_syncIcon(), _settingsIcon()]), // its own bar: the place is the title's dropdown
|
||||
};
|
||||
void go(int i) => setState(() => section = i);
|
||||
if (wide) {
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@
|
|||
// note, source} — imported ones have id "vital:<t>", ones typed here a random id.
|
||||
import 'dart:math';
|
||||
|
||||
import '../app/prefs.dart';
|
||||
import '../sync/store.dart';
|
||||
import 'cycle_model.dart' show iso, parseDay, daysBetween, today;
|
||||
import 'summaries.dart';
|
||||
|
|
@ -27,9 +28,18 @@ const fields = {
|
|||
};
|
||||
const fatDayFields = {'weight', 'waist', 'hip', 'neck', 'fat_scale'};
|
||||
|
||||
/// The values set on the dashboard (Settings ▸ Health), from its person summary (profileOf).
|
||||
/// The dashboard's Settings ▸ Health (synced: prefs.dart); until they've come, its person summary (profileOf).
|
||||
class Profile {
|
||||
const Profile({this.sex = female, this.birth, this.height});
|
||||
|
||||
static Profile of(SyncStore store) {
|
||||
final p = Prefs(store), s = profileOf(store);
|
||||
final b = DateTime.tryParse(p.get<String>('health.birth_date', ''));
|
||||
final h = p.number('health.height', 0).toDouble();
|
||||
return Profile(sex: p.get<String>('health.sex', s.sex), birth: b == null ? s.birth : DateTime.utc(b.year, b.month, b.day),
|
||||
height: h > 0 ? h : s.height);
|
||||
}
|
||||
|
||||
final String sex;
|
||||
final DateTime? birth;
|
||||
final double? height;
|
||||
|
|
|
|||
|
|
@ -47,13 +47,13 @@ class _BodyPageState extends State<BodyPage> {
|
|||
backgroundColor: accent,
|
||||
foregroundColor: bg,
|
||||
tooltip: 'Add measurements',
|
||||
onPressed: () => _edit(BodyView(widget.sync.store, profileOf(widget.sync.store)), null),
|
||||
onPressed: () => _edit(BodyView(widget.sync.store, Profile.of(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));
|
||||
final v = BodyView(widget.sync.store, Profile.of(widget.sync.store));
|
||||
if (v.rows.isEmpty) {
|
||||
return const Center(child: Text('No measurements yet — + to add the first.', style: TextStyle(color: muted)));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@
|
|||
// pain_len, tags "a,b", note, source, updated}. Days are UTC dates here (no DST surprises).
|
||||
import 'dart:math';
|
||||
|
||||
import '../app/prefs.dart';
|
||||
import '../sync/store.dart';
|
||||
|
||||
const history = 12; // cycles averaged (at most)
|
||||
|
|
@ -58,10 +59,17 @@ 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));
|
||||
|
||||
/// The dashboard's Settings ▸ Cycle (synced: prefs.dart); its defaults until they've come.
|
||||
class CycleSettings {
|
||||
const CycleSettings({this.cycleLength = 28, this.periodLength = 5, this.showFertile = true});
|
||||
const CycleSettings({this.cycleLength = 28, this.periodLength = 5, this.showFertile = false});
|
||||
final int cycleLength, periodLength;
|
||||
final bool showFertile;
|
||||
|
||||
static CycleSettings of(SyncStore store) {
|
||||
final p = Prefs(store);
|
||||
return CycleSettings(cycleLength: p.number('cycle.cycle_length', 28).round(),
|
||||
periodLength: p.number('cycle.period_length', 5).round(), showFertile: p.get<bool>('cycle.show_fertile', false));
|
||||
}
|
||||
}
|
||||
|
||||
class DayLog {
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ class CyclePage extends StatefulWidget {
|
|||
|
||||
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)
|
||||
CycleSettings get settings => CycleSettings.of(widget.sync.store); // the dashboard's, synced
|
||||
|
||||
void _save(DateTime d, Map<String, dynamic> fields) {
|
||||
saveDay(widget.sync.store, d, fields);
|
||||
|
|
|
|||
|
|
@ -18,8 +18,9 @@ import 'package:flutter/services.dart';
|
|||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:sqlite3/sqlite3.dart';
|
||||
|
||||
import '../app/prefs.dart';
|
||||
import '../sync/store.dart';
|
||||
import 'body_model.dart' show BodyView, bmrMifflin, female, profileOf;
|
||||
import 'body_model.dart' show BodyView, Profile, bmrMifflin, female;
|
||||
import 'cycle_model.dart' show iso;
|
||||
import 'sugar.dart' show fold;
|
||||
import 'summaries.dart';
|
||||
|
|
@ -33,7 +34,10 @@ const foodCols = ['kcal', 'protein', 'carbs', 'sugar', 'fiber', 'fat', 'sat_fat'
|
|||
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.
|
||||
/// Macro presets: % of the energy from protein / carbs / fat (views.PRESETS; "custom" = the custom fields).
|
||||
const macroPresets = {'balanced': (20, 50, 30), 'high_protein': (30, 40, 30), 'mediterranean': (20, 45, 35), 'lower_carb': (30, 25, 45)};
|
||||
|
||||
/// The dashboard's Settings ▸ Food (synced: prefs.dart); its defaults until they've come.
|
||||
class FoodSettings {
|
||||
const FoodSettings({this.goalRate = 0, this.split = (20, 50, 30), this.kcalTarget = 0, this.fiberMin = 25,
|
||||
this.sugarMax = 50, this.sodiumMax = 2000});
|
||||
|
|
@ -41,7 +45,21 @@ class FoodSettings {
|
|||
final (int, int, int) split; // protein / carbs / fat % of the energy
|
||||
final int kcalTarget, fiberMin, sugarMax, sodiumMax;
|
||||
|
||||
/// views.split: the preset's split, or the custom one.
|
||||
static FoodSettings of(SyncStore store) {
|
||||
if (store.row(tSetting, 'food.macro_preset') == null) return _summary(store); // a dashboard without settings sync
|
||||
final p = Prefs(store);
|
||||
int n(String k, int d) => p.number('food.$k', d).round();
|
||||
final preset = p.get<String>('food.macro_preset', 'balanced');
|
||||
final split = preset == 'custom'
|
||||
? (n('custom_protein', 20), n('custom_carbs', 50), n('custom_fat', 30))
|
||||
: macroPresets[preset] ?? macroPresets['balanced']!;
|
||||
return FoodSettings(goalRate: p.number('food.goal_rate', 0).toDouble(), split: split, kcalTarget: n('kcal_target', 0),
|
||||
fiberMin: n('fiber_min', 25), sugarMax: n('sugar_max', 50), sodiumMax: n('sodium_max', 2000));
|
||||
}
|
||||
|
||||
/// Older dashboards: Settings ▸ Food as its Health summary brings it (meta:food).
|
||||
static FoodSettings _summary(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();
|
||||
|
|
@ -494,7 +512,7 @@ class Plan {
|
|||
/// 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 b = BodyView(store, Profile.of(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);
|
||||
|
|
|
|||
|
|
@ -40,7 +40,7 @@ class FoodPage extends StatefulWidget {
|
|||
class _FoodPageState extends State<FoodPage> {
|
||||
DateTime d = today();
|
||||
FoodDb? fdb;
|
||||
FoodSettings get s => FoodSettings.of(widget.sync.store); // Settings ▸ Food on the dashboard
|
||||
FoodSettings get s => FoodSettings.of(widget.sync.store); // the dashboard's, synced
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
|
|
|
|||
|
|
@ -47,7 +47,7 @@ class _OverviewPageState extends State<OverviewPage> {
|
|||
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());
|
||||
final cv = CycleView(widget.sync.store, CycleSettings.of(widget.sync.store));
|
||||
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}';
|
||||
|
|
|
|||
|
|
@ -17,9 +17,9 @@ IconData kindIcon(Node n) => n.kind == 'task'
|
|||
: Icons.business;
|
||||
|
||||
class CustomersPage extends StatefulWidget {
|
||||
const CustomersPage({super.key, required this.sync, this.s = const WorkSettings()});
|
||||
const CustomersPage({super.key, required this.sync});
|
||||
final SyncService sync;
|
||||
final WorkSettings s;
|
||||
WorkSettings get s => WorkSettings.of(sync.store); // the dashboard's, synced
|
||||
@override
|
||||
State<CustomersPage> createState() => _CustomersPageState();
|
||||
}
|
||||
|
|
@ -30,7 +30,7 @@ class _CustomersPageState extends State<CustomersPage> {
|
|||
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),
|
||||
builder: (_) => NodeEditor(sync: widget.sync, nodeId: id, kind: kind, parent: parent),
|
||||
),
|
||||
);
|
||||
|
||||
|
|
@ -112,9 +112,9 @@ class _CustomersPageState extends State<CustomersPage> {
|
|||
|
||||
/// 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});
|
||||
const NodeEditor({super.key, required this.sync, this.nodeId, this.kind = 'client', this.parent});
|
||||
final SyncService sync;
|
||||
final WorkSettings s;
|
||||
WorkSettings get s => WorkSettings.of(sync.store); // the dashboard's, synced
|
||||
final String? nodeId, kind, parent;
|
||||
@override
|
||||
State<NodeEditor> createState() => _NodeEditorState();
|
||||
|
|
|
|||
|
|
@ -26,12 +26,12 @@ Future<void> openEntry(
|
|||
int? endMin,
|
||||
String? node,
|
||||
String note = '',
|
||||
WorkSettings s = const WorkSettings(),
|
||||
WorkSettings? s,
|
||||
}) => 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),
|
||||
builder: (_) => EntrySheet(sync: sync, entry: entry, day: day, startMin: startMin, endMin: endMin, node: node, note: note, s: s ?? WorkSettings.of(sync.store)),
|
||||
);
|
||||
|
||||
class EntrySheet extends StatefulWidget {
|
||||
|
|
|
|||
|
|
@ -10,9 +10,9 @@ import 'entry_sheet.dart';
|
|||
import 'work_model.dart';
|
||||
|
||||
class ReportPage extends StatefulWidget {
|
||||
const ReportPage({super.key, required this.sync, this.s = const WorkSettings()});
|
||||
const ReportPage({super.key, required this.sync});
|
||||
final SyncService sync;
|
||||
final WorkSettings s;
|
||||
WorkSettings get s => WorkSettings.of(sync.store); // the dashboard's, synced
|
||||
@override
|
||||
State<ReportPage> createState() => _ReportPageState();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@
|
|||
// "workload.entry" {node_id, start, end 'YYYY-MM-DD HH:MM' local, billable 0/1, note, created, updated}
|
||||
import 'dart:convert';
|
||||
|
||||
import '../app/prefs.dart';
|
||||
import '../sync/store.dart';
|
||||
|
||||
const kinds = ['client', 'project', 'task'];
|
||||
|
|
@ -20,7 +21,7 @@ const palette = ['#ffb33a', '#5cc8ff', '#7fd6a3', '#ff6b7a', '#c792ea', '#ff9d5c
|
|||
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.
|
||||
/// The dashboard's Settings ▸ Work (synced: prefs.dart); its defaults until they've come.
|
||||
class WorkSettings {
|
||||
const WorkSettings({
|
||||
this.currency = 'EUR',
|
||||
|
|
@ -34,6 +35,13 @@ class WorkSettings {
|
|||
final double defaultRate;
|
||||
final int dayStart, dayEnd, defaultMinutes;
|
||||
final double weekTarget;
|
||||
|
||||
static WorkSettings of(SyncStore store) {
|
||||
final p = Prefs(store);
|
||||
return WorkSettings(currency: p.get<String>('workload.currency', 'EUR'), defaultRate: p.number('workload.default_rate', 0).toDouble(),
|
||||
dayStart: p.number('workload.day_start', 7).round(), dayEnd: p.number('workload.day_end', 19).round(),
|
||||
defaultMinutes: p.number('workload.default_minutes', 60).round(), weekTarget: p.number('workload.week_target', 40).toDouble());
|
||||
}
|
||||
}
|
||||
|
||||
class Invalid implements Exception {
|
||||
|
|
|
|||
|
|
@ -54,9 +54,9 @@ Widget _hold({
|
|||
);
|
||||
|
||||
class WorkPage extends StatefulWidget {
|
||||
const WorkPage({super.key, required this.sync, this.s = const WorkSettings(), this.actions = const []});
|
||||
const WorkPage({super.key, required this.sync, this.actions = const []});
|
||||
final SyncService sync;
|
||||
final WorkSettings s;
|
||||
WorkSettings get s => WorkSettings.of(sync.store); // the dashboard's, synced
|
||||
final List<Widget> actions; // the shell's (sync icon, ⋮) — Work has its own bar: in landscape the week's ‹ CW › sits in it
|
||||
@override
|
||||
State<WorkPage> createState() => _WorkPageState();
|
||||
|
|
@ -202,7 +202,7 @@ class _WorkPageState extends State<WorkPage> {
|
|||
onPressed: () => Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (_) => NodeEditor(sync: widget.sync, s: widget.s, nodeId: c.node.id),
|
||||
builder: (_) => NodeEditor(sync: widget.sync, nodeId: c.node.id),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
|
@ -299,7 +299,7 @@ class _WorkPageState extends State<WorkPage> {
|
|||
onPressed: () => Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (_) => CustomersPage(sync: widget.sync, s: widget.s),
|
||||
builder: (_) => CustomersPage(sync: widget.sync),
|
||||
),
|
||||
),
|
||||
icon: const Icon(Icons.add),
|
||||
|
|
@ -407,7 +407,7 @@ class _WorkPageState extends State<WorkPage> {
|
|||
onPressed: () => Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (_) => NodeEditor(sync: widget.sync, s: widget.s, nodeId: c.node.id),
|
||||
builder: (_) => NodeEditor(sync: widget.sync, nodeId: c.node.id),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
|
|||
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
||||
# In Windows, build-name is used as the major, minor, and patch parts
|
||||
# of the product and file versions while build-number is used as the build suffix.
|
||||
version: 1.1.6+10
|
||||
version: 1.1.7+11
|
||||
|
||||
environment:
|
||||
sdk: ^3.12.2
|
||||
|
|
|
|||
66
app/test/prefs_test.dart
Normal file
66
app/test/prefs_test.dart
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
// The dashboard's settings as they sync (prefs.dart = settingsync.py): values read with the dashboard's
|
||||
// defaults until they've come, the food split from its preset or the custom fields, the fields' checks.
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:dash_app/app/prefs.dart';
|
||||
import 'package:dash_app/health/cycle_model.dart';
|
||||
import 'package:dash_app/health/food_model.dart';
|
||||
import 'package:dash_app/sync/store.dart';
|
||||
import 'package:dash_app/work/work_model.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
final store = SyncStore('${Directory.systemTemp.createTempSync('prefs').path}/d.db', 'test00000000');
|
||||
void fromDashboard(String k, Object? v) => store.put(tSetting, k, {'k': k, 'v': jsonEncode(v)});
|
||||
|
||||
test('defaults until the dashboard\'s values come', () {
|
||||
final f = FoodSettings.of(store);
|
||||
expect(f.split, (20, 50, 30));
|
||||
expect(f.goalRate, 0);
|
||||
expect(CycleSettings.of(store).cycleLength, 28);
|
||||
expect(WorkSettings.of(store).dayStart, 7);
|
||||
});
|
||||
|
||||
test('the dashboard\'s values: presets, the custom split, numbers as stored', () {
|
||||
fromDashboard('food.macro_preset', 'high_protein');
|
||||
fromDashboard('food.goal_rate', 0.25);
|
||||
fromDashboard('cycle.cycle_length', 30.0);
|
||||
fromDashboard('workload.currency', 'RON');
|
||||
expect(FoodSettings.of(store).split, (30, 40, 30));
|
||||
expect(FoodSettings.of(store).goalRate, 0.25);
|
||||
expect(CycleSettings.of(store).cycleLength, 30);
|
||||
expect(WorkSettings.of(store).currency, 'RON');
|
||||
fromDashboard('food.macro_preset', 'custom');
|
||||
fromDashboard('food.custom_protein', 35);
|
||||
fromDashboard('food.custom_carbs', 35);
|
||||
fromDashboard('food.custom_fat', 30);
|
||||
expect(FoodSettings.of(store).split, (35, 35, 30));
|
||||
});
|
||||
|
||||
test('set writes only a change', () {
|
||||
final p = Prefs(store);
|
||||
p.set('food.sugar_max', 40);
|
||||
final h = store.rows(tSetting).firstWhere((r) => r['_u'] == 'food.sugar_max')['_h'];
|
||||
p.set('food.sugar_max', 40);
|
||||
expect(store.rows(tSetting).firstWhere((r) => r['_u'] == 'food.sugar_max')['_h'], h);
|
||||
expect(FoodSettings.of(store).sugarMax, 40);
|
||||
});
|
||||
|
||||
test('fields: sections in order, checks as the dashboard', () {
|
||||
void field(String k, int pos, Map<String, Object?> spec) =>
|
||||
store.put(tField, k, {'k': k, 'plugin': k.split('.').first, 'title': k.split('.').first, 'pos': pos, 'spec': jsonEncode(spec)});
|
||||
field('cycle.cycle_length', 0, {'key': 'cycle_length', 'type': 'number', 'min': 15, 'max': 60, 'integer': true});
|
||||
field('food.goal_rate', 1, {'key': 'goal_rate', 'type': 'select', 'options': [[0.0, 'Keep'], [0.25, 'Lose 0.25 %']]});
|
||||
field('workload.currency', 2, {'key': 'currency', 'type': 'text', 'max': 3, 'pattern': '[A-Za-z]{3}'});
|
||||
final secs = Prefs(store).sections();
|
||||
expect([for (final s in secs) s.$1], ['cycle', 'food', 'workload']);
|
||||
final cl = secs[0].$3.single, gr = secs[1].$3.single, cur = secs[2].$3.single;
|
||||
expect(cl.check('29.6'), (29, null));
|
||||
expect(cl.check('80').$2, 'Must be between 15 and 60.');
|
||||
expect(gr.check(0.25), (0.25, null));
|
||||
expect(gr.check('1').$2, 'Pick one of the options.');
|
||||
expect(cur.check('eu1').$2, isNotNull);
|
||||
expect(cur.check('EUR'), ('EUR', null));
|
||||
});
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue