dashboard/app/lib/health/cycle_page.dart
bashynx 820aca7d92 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>
2026-10-26 16:30:00 +02:00

351 lines
16 KiB
Dart
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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
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);
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'),
),
]),
),
);
}