Skip to content

Offline gym log for Android. No account, no ads, no internet.

Custom body measurements with a reminder

InlitXf525c57f7563
diff --git a/lib/models/measure.dart b/lib/models/measure.dart
index 65c36e1..7cbf78e 100644
--- a/lib/models/measure.dart
+++ b/lib/models/measure.dart
@@ -26,3 +26,21 @@ class BodyMeasure {
((j['v'] ?? 0) as num).toDouble(),
);
}
+
+class CustomMeasure {
+ CustomMeasure(this.id, this.name, {this.unit = '', this.length = true});
+
+ final String id;
+ String name;
+ String unit;
+ bool length;
+
+ Map<String, dynamic> toJson() => {'id': id, 'n': name, if (unit.isNotEmpty) 'u': unit, if (!length) 'l': false};
+
+ static CustomMeasure? fromJson(Map<String, dynamic> j) {
+ final id = j['id'] as String? ?? '';
+ final name = (j['n'] as String? ?? '').trim();
+ if (!id.startsWith('c') || name.isEmpty) return null;
+ return CustomMeasure(id, name, unit: j['u'] as String? ?? '', length: j['l'] as bool? ?? true);
+ }
+}
diff --git a/lib/screens/measures_screen.dart b/lib/screens/measures_screen.dart
index 8600e44..932e9a9 100644
--- a/lib/screens/measures_screen.dart
+++ b/lib/screens/measures_screen.dart
@@ -1,6 +1,7 @@
import 'dart:math' as math;
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import 'package:phosphoricons_flutter/phosphoricons_flutter.dart';
import '../l10n/l10n.dart';
@@ -38,8 +39,16 @@ class MeasuresScreen extends StatelessWidget {
),
const SizedBox(height: 14),
Text(t.measuresHint, style: AppTheme.s(13, color: gc.textSecondary, height: 1.5)),
+ const SizedBox(height: 18),
+ const _MeasureReminder(),
const SizedBox(height: 20),
- for (final key in kMeasureKeys) _MeasureRow(measureKey: key),
+ for (final key in fit.allMeasureKeys) _MeasureRow(key: ValueKey(key), measureKey: key),
+ const SizedBox(height: 4),
+ GhostButton(
+ label: t.newMeasure,
+ icon: PhosphorIconsBold.plus,
+ onTap: () => showNewMeasureSheet(context),
+ ),
],
),
),
@@ -47,8 +56,83 @@ class MeasuresScreen extends StatelessWidget {
}
}
+const List<int> _kMeasureEvery = [0, 7, 14, 30];
+
+class _MeasureReminder extends StatelessWidget {
+ const _MeasureReminder();
+
+ Future<void> _custom(BuildContext context) async {
+ final current = fit.measureEveryDays;
+ final days = await askNumber(context,
+ title: t.measureEvery, initial: '${current > 0 ? current : 21}', decimal: false);
+ if (days != null) fit.setMeasureEvery(days.round());
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final gc = context.gc;
+ final current = fit.measureEveryDays;
+ final custom = current > 0 && !_kMeasureEvery.contains(current);
+ final left = fit.daysUntilMeasure;
+ final due = left != null && left <= 0;
+ Widget tab(String label, bool on, VoidCallback onTap) => Expanded(
+ child: Semantics(
+ button: true,
+ selected: on,
+ label: label,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: () {
+ HapticFeedback.selectionClick();
+ onTap();
+ },
+ child: AnimatedContainer(
+ duration: const Duration(milliseconds: 180),
+ height: 36,
+ alignment: Alignment.center,
+ decoration: BoxDecoration(
+ color: on ? gc.ember : Colors.transparent,
+ borderRadius: BorderRadius.circular(100),
+ ),
+ child: FittedBox(
+ fit: BoxFit.scaleDown,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 6),
+ child: Text(label,
+ maxLines: 1,
+ style: AppTheme.f(13, weight: FontWeight.w600, color: on ? gc.onEmber : gc.textSecondary)),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Row(children: [
+ Expanded(
+ child: Text('${t.measureEvery} · ${t.intervalDays}'.toUpperCase(),
+ style: AppTheme.f(10.5, weight: FontWeight.w700, color: gc.textTertiary, letterSpacing: 1.4)),
+ ),
+ if (left != null)
+ Text(due ? t.measureDueNow : t.measureNextIn(left),
+ style: AppTheme.f(12, weight: FontWeight.w600, color: due ? gc.accent : gc.textTertiary)),
+ ]),
+ const SizedBox(height: 10),
+ Container(
+ padding: const EdgeInsets.all(4),
+ decoration: BoxDecoration(color: gc.bgRaised, borderRadius: BorderRadius.circular(100)),
+ child: Row(children: [
+ for (final days in _kMeasureEvery)
+ tab(days <= 0 ? t.photoEveryOff : '$days', current == days, () => fit.setMeasureEvery(days)),
+ tab(custom ? '$current' : t.custom, custom, () => _custom(context)),
+ ]),
+ ),
+ ]);
+ }
+}
+
class _MeasureRow extends StatelessWidget {
- const _MeasureRow({required this.measureKey});
+ const _MeasureRow({super.key, required this.measureKey});
final String measureKey;
@@ -65,7 +149,7 @@ class _MeasureRow extends StatelessWidget {
behavior: HitTestBehavior.opaque,
onTap: () => showMeasureSheet(context, measureKey),
child: SoftCard(
- radius: 18,
+ radius: 16,
padding: const EdgeInsets.fromLTRB(18, 16, 18, 16),
child: Row(
children: [
@@ -73,7 +157,9 @@ class _MeasureRow extends StatelessWidget {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- Text(t.measureName(measureKey),
+ Text(fit.measureTitle(measureKey),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
style: AppTheme.s(12,
weight: FontWeight.w600, color: gc.textSecondary, letterSpacing: 1)),
const SizedBox(height: 6),
@@ -160,34 +246,65 @@ class _MeasureSheetState extends State<_MeasureSheet> {
String get _key => widget.measureKey;
bool get _pct => fit.isPercent(_key);
- double get _step => _pct ? 0.5 : (fit.isInches ? 0.25 : 0.5);
- int get _major => _pct ? 10 : (fit.isInches ? 4 : 10);
+ bool get _free => fit.isFreeMeasure(_key);
+ double get _step => _free ? _freeStep : (_pct ? 0.5 : (fit.isInches ? 0.25 : 0.5));
+ int get _major => _free ? 10 : (_pct ? 10 : (fit.isInches ? 4 : 10));
+
+ late final double _freeStep = () {
+ final latest = fit.latestMeasure(_key)?.value ?? 0;
+ return latest > 0 && latest < 20 ? 0.1 : 0.5;
+ }();
(double, double) get _baseRange {
+ if (_free) return (0, 100);
if (_pct) return (3, 60);
final r = _rangesCm[_key] ?? (10.0, 200.0, 50.0);
return (_snap(fit.toDisplayCm(r.$1)), _snap(fit.toDisplayCm(r.$2)));
}
- (double, double) _around(double v) {
- final (lo, hi) = _baseRange;
- return (math.min(lo, v), math.max(hi, v));
- }
-
late (double, double) _range = _around(_value);
- double get _typedMax => _pct ? 100 : _snap(fit.toDisplayCm(400));
+ double get _typedMax => _free ? 99999 : (_pct ? 100 : _snap(fit.toDisplayCm(400)));
double _snap(double v) => (v / _step).round() * _step;
late double _value = () {
final latest = fit.latestMeasure(_key);
if (latest != null) return _snap(fit.toDisplayMeasure(_key, latest.value));
+ if (_free) return 50.0;
if (_pct) return 20.0;
return _snap(fit.toDisplayCm((_rangesCm[_key] ?? (10.0, 200.0, 50.0)).$3));
}();
- String _show(double v) => decimalText(v.toStringAsFixed(_step < 0.5 ? 2 : 1));
+ String _show(double v) => decimalText(v.toStringAsFixed(_step < 0.25 ? 1 : (_step < 0.5 ? 2 : 1)));
+
+ (double, double) _around(double v) {
+ final (lo, hi) = _baseRange;
+ if (_free) {
+ final top = math.max(hi, (v * 1.6 / 10).ceil() * 10.0);
+ return (0, top);
+ }
+ return (math.min(lo, v), math.max(hi, v));
+ }
+
+ Future<void> _rename() async {
+ final c = fit.customMeasure(_key);
+ if (c == null) return;
+ final name = await askText(context, title: t.measureRename, initial: c.name, hint: t.measureNameHint);
+ if (name == null || name.trim().isEmpty || !mounted) return;
+ fit.editCustomMeasure(_key, name: name);
+ setState(() {});
+ }
+
+ Future<void> _delete() async {
+ final c = fit.customMeasure(_key);
+ if (c == null) return;
+ final ok = await askConfirm(context,
+ title: t.measureDeleteTitle(c.name), body: t.measureDeleteBody, confirmLabel: t.delete, danger: true);
+ if (!ok || !mounted) return;
+ Navigator.of(context).pop();
+ fit.deleteCustomMeasure(_key);
+ }
void _save() {
if (_value <= 0) return;
@@ -196,7 +313,7 @@ class _MeasureSheetState extends State<_MeasureSheet> {
}
Future<void> _type() async {
- final typed = await askNumber(context, title: t.measureName(_key), initial: _show(_value), decimal: true);
+ final typed = await askNumber(context, title: fit.measureTitle(_key), initial: _show(_value), decimal: true);
if (typed == null || !mounted) return;
if (typed <= 0) return;
final v = math.max(_step, _snap(typed.clamp(_step, _typedMax)));
@@ -213,18 +330,14 @@ class _MeasureSheetState extends State<_MeasureSheet> {
final (lo, hi) = _range;
return Container(
- decoration: BoxDecoration(
- color: gc.bg,
- border: Border.all(color: gc.border),
- borderRadius: const BorderRadius.vertical(top: Radius.circular(26)),
- ),
+ decoration: sheetDecoration(gc),
clipBehavior: Clip.antiAlias,
child: SafeArea(
top: false,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
- SheetHandle(color: gc.border, margin: const EdgeInsets.symmetric(vertical: 12)),
+ SheetHandle(margin: const EdgeInsets.symmetric(vertical: 12)),
Padding(
padding: const EdgeInsets.fromLTRB(20, 4, 20, 20),
child: Column(
@@ -232,12 +345,27 @@ class _MeasureSheetState extends State<_MeasureSheet> {
children: [
Row(children: [
Expanded(
- child: Text(t.measureName(_key),
+ child: Text(fit.measureTitle(_key),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
style: AppTheme.f(17, weight: FontWeight.w800, color: gc.text)),
),
+ if (fit.isCustomMeasure(_key))
+ Semantics(
+ button: true,
+ label: t.measureRename,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: _rename,
+ child: Padding(
+ padding: const EdgeInsets.all(8),
+ child: Icon(PhosphorIconsRegular.pencilSimple, size: 19, color: gc.textSecondary),
+ ),
+ ),
+ ),
Semantics(
button: true,
- label: t.measureName(_key),
+ label: fit.measureTitle(_key),
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: _type,
@@ -274,7 +402,7 @@ class _MeasureSheetState extends State<_MeasureSheet> {
onChanged: (v) => setState(() => _value = v),
),
const SizedBox(height: 18),
- PrimaryButton(label: t.save, onTap: _save, height: 54),
+ PrimaryButton(label: t.save, onTap: _save, height: 52),
if (history.isNotEmpty) ...[
const SizedBox(height: 22),
Text(t.measureHistory,
@@ -283,6 +411,21 @@ class _MeasureSheetState extends State<_MeasureSheet> {
const SizedBox(height: 10),
for (final m in history.take(6)) _historyRow(gc, m),
],
+ if (fit.isCustomMeasure(_key)) ...[
+ const SizedBox(height: 10),
+ GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: _delete,
+ child: SizedBox(
+ height: 44,
+ child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
+ Icon(PhosphorIconsRegular.trash, size: 16, color: gc.danger),
+ const SizedBox(width: 8),
+ Text(t.measureDelete, style: AppTheme.f(14, weight: FontWeight.w600, color: gc.danger)),
+ ]),
+ ),
+ ),
+ ],
],
),
),
@@ -321,3 +464,147 @@ class _MeasureSheetState extends State<_MeasureSheet> {
),
);
}
+
+Future<void> showNewMeasureSheet(BuildContext context) async {
+ final id = await showAppSheet<String>(
+ context: context,
+ isScrollControlled: true,
+ backgroundColor: Colors.transparent,
+ builder: (_) => const _NewMeasureSheet(),
+ );
+ if (id != null && id.isNotEmpty && context.mounted) showMeasureSheet(context, id);
+}
+
+class _NewMeasureSheet extends StatefulWidget {
+ const _NewMeasureSheet();
+
+ @override
+ State<_NewMeasureSheet> createState() => _NewMeasureSheetState();
+}
+
+class _NewMeasureSheetState extends State<_NewMeasureSheet> {
+ final _name = TextEditingController();
+ final _unit = TextEditingController();
+ bool _length = true;
+
+ @override
+ void dispose() {
+ _name.dispose();
+ _unit.dispose();
+ super.dispose();
+ }
+
+ void _save() {
+ if (_name.text.trim().isEmpty) {
+ HapticFeedback.heavyImpact();
+ return;
+ }
+ final id = fit.addCustomMeasure(_name.text, unit: _unit.text, length: _length);
+ Navigator.of(context).pop(id);
+ }
+
+ Widget _field(GymColors gc, TextEditingController c, String hint, {bool autofocus = false, int max = 40}) =>
+ Container(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 2),
+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(16)),
+ child: TextField(
+ controller: c,
+ autofocus: autofocus,
+ maxLength: max,
+ textCapitalization: TextCapitalization.sentences,
+ cursorColor: gc.accent,
+ onChanged: (_) => setState(() {}),
+ onSubmitted: (_) => _save(),
+ style: AppTheme.f(15, weight: FontWeight.w600, color: gc.text),
+ decoration: InputDecoration(
+ border: InputBorder.none,
+ hintText: hint,
+ hintStyle: AppTheme.f(15, weight: FontWeight.w500, color: gc.textTertiary),
+ counterText: '',
+ ),
+ ),
+ );
+
+ Widget _kind(GymColors gc, bool length, String title, String hint) {
+ final on = _length == length;
+ return Expanded(
+ child: Semantics(
+ button: true,
+ selected: on,
+ label: title,
+ child: Pressable(
+ scale: 0.97,
+ onTap: () {
+ HapticFeedback.selectionClick();
+ setState(() => _length = length);
+ },
+ child: AnimatedContainer(
+ duration: const Duration(milliseconds: 180),
+ padding: const EdgeInsets.fromLTRB(14, 12, 14, 12),
+ decoration: BoxDecoration(
+ color: on ? gc.accent.withValues(alpha: 0.12) : gc.bgRaised2,
+ borderRadius: BorderRadius.circular(16),
+ border: Border.all(color: on ? gc.accent : Colors.transparent, width: 1.5),
+ ),
+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text(title, style: AppTheme.f(14, weight: FontWeight.w700, color: gc.text)),
+ const SizedBox(height: 3),
+ Text(hint, style: AppTheme.f(11.5, weight: FontWeight.w500, color: gc.textSecondary, height: 1.3)),
+ ]),
+ ),
+ ),
+ ),
+ );
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final gc = context.gc;
+ final ready = _name.text.trim().isNotEmpty;
+ return Padding(
+ padding: EdgeInsets.only(bottom: MediaQuery.viewInsetsOf(context).bottom),
+ child: Container(
+ padding: sheetPad(context),
+ decoration: sheetDecoration(gc),
+ child: SingleChildScrollView(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ const SheetHandle(),
+ const SizedBox(height: 16),
+ SheetTitle(t.newMeasure, subtitle: t.newMeasureHint),
+ const SizedBox(height: 18),
+ _field(gc, _name, t.measureNameHint, autofocus: true),
+ const SizedBox(height: 12),
+ IntrinsicHeight(
+ child: Row(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
+ _kind(gc, true, t.measureKindLength, t.measureKindLengthHint),
+ const SizedBox(width: 8),
+ _kind(gc, false, t.measureKindOther, t.measureKindOtherHint),
+ ]),
+ ),
+ AnimatedSize(
+ duration: const Duration(milliseconds: 220),
+ curve: Curves.easeOutCubic,
+ alignment: Alignment.topCenter,
+ child: _length
+ ? const SizedBox(width: double.infinity)
+ : Padding(
+ padding: const EdgeInsets.only(top: 12),
+ child: _field(gc, _unit, '${t.measureUnit} · ${t.measureUnitHint}', max: 8),
+ ),
+ ),
+ const SizedBox(height: 18),
+ AnimatedOpacity(
+ duration: const Duration(milliseconds: 160),
+ opacity: ready ? 1 : 0.45,
+ child: PrimaryButton(label: t.save, onTap: _save, height: 52),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/services/progress_reminder.dart b/lib/services/progress_reminder.dart
index 6755e04..3e4d485 100644
--- a/lib/services/progress_reminder.dart
+++ b/lib/services/progress_reminder.dart
@@ -10,6 +10,7 @@ class ProgressReminder {
static final ProgressReminder instance = ProgressReminder._();
static const _id = 1002;
+ static const _measureId = 1003;
final _plugin = FlutterLocalNotificationsPlugin();
bool enabled = true;
@@ -51,6 +52,97 @@ class ProgressReminder {
}
}
+ Future<void> scheduleMeasure(DateTime day, int intervalDays) async {
+ if (!enabled) return;
+ await cancelMeasure();
+ if (intervalDays <= 0) return;
+ try {
+ final when = atLocal(DateTime(day.year, day.month, day.day, 10, 30));
+ if (!when.isAfter(tz.TZDateTime.now(tz.local))) return;
+ await _plugin.zonedSchedule(
+ id: _measureId,
+ title: t.notifMeasureTitle,
+ body: t.notifMeasureBody(intervalDays),
+ scheduledDate: when,
+ notificationDetails: NotificationDetails(
+ android: AndroidNotificationDetails(
+ 'measures',
+ t.notifMeasureChannel,
+ channelDescription: t.notifMeasureChannelWhy,
+ importance: Importance.defaultImportance,
+ priority: Priority.defaultPriority,
+ playSound: true,
+ ),
+ iOS: _darwin,
+ ),
+ androidScheduleMode: await reminderMode(_plugin),
+ );
+ } catch (e) {
+ debugPrint('No se pudo programar el recordatorio de medidas: $e');
+ }
+ }
+
+ static const _fastId = 1004;
+ static const _fastDoneId = 1005;
+
+ AndroidNotificationDetails _fastAndroid({required bool live, DateTime? end}) => AndroidNotificationDetails(
+ live ? 'fasting_live' : 'fasting',
+ live ? t.notifFastLiveChannel : t.notifFastChannel,
+ channelDescription: live ? t.notifFastLiveChannelWhy : t.notifFastChannelWhy,
+ importance: live ? Importance.low : Importance.defaultImportance,
+ priority: live ? Priority.low : Priority.defaultPriority,
+ playSound: !live,
+ enableVibration: !live,
+ ongoing: live,
+ autoCancel: !live,
+ onlyAlertOnce: live,
+ showWhen: live,
+ when: live ? end?.millisecondsSinceEpoch : null,
+ usesChronometer: live,
+ chronometerCountDown: live,
+ category: live ? AndroidNotificationCategory.stopwatch : AndroidNotificationCategory.reminder,
+ );
+
+ Future<void> showFast(DateTime start, DateTime end) async {
+ if (!enabled) return;
+ await cancelFast();
+ try {
+ if (end.isAfter(DateTime.now())) {
+ await _plugin.show(
+ id: _fastId,
+ title: t.notifFastLiveTitle,
+ body: t.notifFastLiveBody(t.clockTime(end)),
+ notificationDetails: NotificationDetails(android: _fastAndroid(live: true, end: end)),
+ );
+ await _plugin.zonedSchedule(
+ id: _fastDoneId,
+ title: t.notifFastDoneTitle,
+ body: t.notifFastDoneBody(end.difference(start).inHours),
+ scheduledDate: tz.TZDateTime.from(end, tz.local),
+ notificationDetails: NotificationDetails(android: _fastAndroid(live: false), iOS: _darwin),
+ androidScheduleMode: await reminderMode(_plugin),
+ );
+ }
+ } catch (e) {
+ debugPrint('No se pudo programar el aviso del ayuno: $e');
+ }
+ }
+
+ Future<void> cancelFast() async {
+ if (!enabled) return;
+ try {
+ await _plugin.cancel(id: _fastId);
+ await _plugin.cancel(id: _fastDoneId);
+ } catch (_) {}
+ }
+
+ Future<void> cancelMeasure() async {
+ if (!enabled) return;
+ try {
+ await _plugin.cancel(id: _measureId);
+ } catch (_) {}
+ }
+
Future<void> cancel() async {
if (!enabled) return;
try {
diff --git a/lib/state/measures_state.dart b/lib/state/measures_state.dart
index 6338e1c..a0c5de8 100644
--- a/lib/state/measures_state.dart
+++ b/lib/state/measures_state.dart
@@ -3,17 +3,35 @@ part of 'fit_state.dart';
const double _cmPerInch = 2.54;
mixin MeasuresState on FitCore {
+ final List<CustomMeasure> customMeasures = [];
+ int measureEveryDays = 0;
+
bool get isInches => units == 'lb';
String get lengthUnit => isInches ? 'in' : 'cm';
+ List<String> get allMeasureKeys => [...kMeasureKeys, for (final c in customMeasures) c.id];
+
+ CustomMeasure? customMeasure(String key) {
+ for (final c in customMeasures) {
+ if (c.id == key) return c;
+ }
+ return null;
+ }
+
+ bool isCustomMeasure(String key) => customMeasure(key) != null;
+
+ bool isFreeMeasure(String key) => customMeasure(key)?.length == false;
+
+ String measureTitle(String key) => customMeasure(key)?.name ?? t.measureName(key);
+
bool isPercent(String key) => key == 'bodyfat';
double toDisplayMeasure(String key, double raw) =>
- isPercent(key) || !isInches ? raw : raw / _cmPerInch;
+ isPercent(key) || isFreeMeasure(key) || !isInches ? raw : raw / _cmPerInch;
double fromDisplayMeasure(String key, double shown) =>
- isPercent(key) || !isInches ? shown : shown * _cmPerInch;
+ isPercent(key) || isFreeMeasure(key) || !isInches ? shown : shown * _cmPerInch;
double toDisplayCm(double cm) => isInches ? cm / _cmPerInch : cm;
@@ -33,11 +51,19 @@ mixin MeasuresState on FitCore {
double get girthStep => isInches ? _cmPerInch / 4 : 0.5;
- String measureUnit(String key) => isPercent(key) ? '%' : lengthUnit;
+ String measureUnit(String key) {
+ if (isPercent(key)) return '%';
+ final c = customMeasure(key);
+ if (c != null && !c.length) return c.unit;
+ return lengthUnit;
+ }
String measureValue(String key, double raw) => fmt(_round1(toDisplayMeasure(key, raw)));
- String measureLabel(String key, double raw) => '${measureValue(key, raw)} ${measureUnit(key)}';
+ String measureLabel(String key, double raw) {
+ final unit = measureUnit(key);
+ return unit.isEmpty ? measureValue(key, raw) : '${measureValue(key, raw)} $unit';
+ }
List<BodyMeasure> measureHistory(String key) {
final out = measures.where((m) => m.key == key).toList()
@@ -60,26 +86,115 @@ mixin MeasuresState on FitCore {
measureHistory(key).reversed.map((m) => toDisplayMeasure(key, m.value)).toList();
List<String> get trackedMeasures =>
- kMeasureKeys.where((k) => latestMeasure(k) != null).toList();
+ allMeasureKeys.where((k) => latestMeasure(k) != null).toList();
bool get hasMeasures => measures.isNotEmpty;
void addMeasure(String key, double shown, {DateTime? date}) {
- if (!kMeasureKeys.contains(key) || shown <= 0) return;
+ if (!allMeasureKeys.contains(key) || shown <= 0) return;
final when = date ?? DateTime.now();
- final raw = _round1(fromDisplayMeasure(key, shown));
+ final raw = isFreeMeasure(key) ? (shown * 100).round() / 100 : _round1(fromDisplayMeasure(key, shown));
measures.removeWhere((m) => m.key == key && _dayKey(m.date) == _dayKey(when));
measures.add(BodyMeasure(when, key, raw));
+ _syncMeasureReminder();
_persist();
notifyListeners();
}
void deleteMeasure(BodyMeasure m) {
measures.remove(m);
+ _syncMeasureReminder();
+ _persist();
+ notifyListeners();
+ }
+
+ String addCustomMeasure(String name, {String unit = '', bool length = true}) {
+ final clean = name.trim();
+ if (clean.isEmpty) return '';
+ var id = 'c${DateTime.now().microsecondsSinceEpoch.toRadixString(36)}';
+ while (customMeasure(id) != null) {
+ id = '${id}x';
+ }
+ customMeasures.add(CustomMeasure(id, _cut(clean, 40), unit: _cut(unit.trim(), 8), length: length));
+ _persist();
+ notifyListeners();
+ return id;
+ }
+
+ void editCustomMeasure(String id, {String? name, String? unit}) {
+ final c = customMeasure(id);
+ if (c == null) return;
+ if (name != null && name.trim().isNotEmpty) c.name = _cut(name.trim(), 40);
+ if (unit != null && !c.length) c.unit = _cut(unit.trim(), 8);
+ _persist();
+ notifyListeners();
+ }
+
+ void deleteCustomMeasure(String id) {
+ customMeasures.removeWhere((c) => c.id == id);
+ measures.removeWhere((m) => m.key == id);
+ _syncMeasureReminder();
_persist();
notifyListeners();
}
+ String _cut(String v, int max) => v.length > max ? v.substring(0, max) : v;
+
+ DateTime? get lastMeasureDay {
+ DateTime? last;
+ for (final m in measures) {
+ if (last == null || m.date.isAfter(last)) last = m.date;
+ }
+ return last == null ? null : DateTime(last.year, last.month, last.day);
+ }
+
+ DateTime? get nextMeasureDue {
+ if (measureEveryDays <= 0) return null;
+ final last = lastMeasureDay;
+ if (last == null) return null;
+ return DateTime(last.year, last.month, last.day + measureEveryDays);
+ }
+
+ int? get daysUntilMeasure {
+ final due = nextMeasureDue;
+ if (due == null) return null;
+ final now = DateTime.now();
+ return due.difference(DateTime(now.year, now.month, now.day)).inDays;
+ }
+
+ void setMeasureEvery(int days) {
+ measureEveryDays = days <= 0 ? 0 : days.clamp(1, 365);
+ _syncMeasureReminder();
+ _persist();
+ notifyListeners();
+ }
+
+ void syncMeasureReminder() => _syncMeasureReminder();
+
+ void _syncMeasureReminder() {
+ final due = nextMeasureDue;
+ if (due == null) {
+ ProgressReminder.instance.cancelMeasure();
+ return;
+ }
+ ProgressReminder.instance.scheduleMeasure(due, measureEveryDays);
+ }
+
+ void loadCustomMeasures(Map<String, dynamic> data) {
+ customMeasures
+ ..clear()
+ ..addAll([
+ for (final e in (data['customMeasures'] as List?) ?? const [])
+ if (e is Map) ?CustomMeasure.fromJson(e.cast<String, dynamic>()),
+ ]);
+ measureEveryDays = ((data['measureEvery'] as num?)?.toInt() ?? 0).clamp(0, 365);
+ }
+
+ Map<String, dynamic> customMeasuresJson() => {
+ if (customMeasures.isNotEmpty) 'customMeasures': customMeasures.map((c) => c.toJson()).toList(),
+ if (measureEveryDays > 0) 'measureEvery': measureEveryDays,
+ };
+
void goMeasures() => pushRoute('measures');
void backFromMeasures() => popRoute(fallback: 'progress');
diff --git a/test/measures_test.dart b/test/measures_test.dart
index 981ebf1..43db96c 100644
--- a/test/measures_test.dart
+++ b/test/measures_test.dart
@@ -82,4 +82,56 @@ void main() {
fit.resetAllData();
expect(fit.measures, isEmpty);
});
+
+ test('a custom length follows the unit setting like the built-in ones', () {
+ final id = fit.addCustomMeasure('Wrist');
+ fit.addMeasure(id, 17);
+ expect(fit.measureTitle(id), 'Wrist');
+ expect(fit.measureLabel(id, 17), '17 cm');
+ fit.setUnits('lb');
+ expect(fit.measureUnit(id), 'in');
+ expect(fit.latestMeasure(id)!.value, closeTo(17, 0.001));
+ });
+
+ test('a custom measure with its own unit is never converted', () {
+ final id = fit.addCustomMeasure('Resting pulse', unit: 'bpm', length: false);
+ fit.setUnits('lb');
+ fit.addMeasure(id, 58);
+ expect(fit.latestMeasure(id)!.value, 58);
+ expect(fit.measureLabel(id, 58), '58 bpm');
+ expect(fit.trackedMeasures, contains(id));
+ });
+
+ test('a blank name makes nothing and a deleted measure takes its values with it', () {
+ expect(fit.addCustomMeasure(' '), isEmpty);
+ expect(fit.customMeasures, isEmpty);
+ final id = fit.addCustomMeasure('Wrist');
+ fit.addMeasure(id, 17);
+ fit.addMeasure('waist', 80);
+ fit.deleteCustomMeasure(id);
+ expect(fit.customMeasures, isEmpty);
+ expect(fit.measures.map((m) => m.key), ['waist']);
+ });
+
+ test('custom measures and the reminder survive a reload', () {
+ final id = fit.addCustomMeasure('Body water', unit: '%', length: false);
+ fit.addMeasure(id, 55.5);
+ fit.setMeasureEvery(14);
+ fit.persistNow();
+ fit.loadFromStore();
+ expect(fit.measureTitle(id), 'Body water');
+ expect(fit.isFreeMeasure(id), isTrue);
+ expect(fit.latestMeasure(id)!.value, closeTo(55.5, 0.001));
+ expect(fit.measureEveryDays, 14);
+ });
+
+ test('the reminder counts from the last reading of any measure', () {
+ expect(fit.nextMeasureDue, isNull);
+ fit.setMeasureEvery(7);
+ expect(fit.nextMeasureDue, isNull, reason: 'sin medidas no hay desde cuándo contar');
+ fit.addMeasure('waist', 80, date: DateTime.now().subtract(const Duration(days: 3)));
+ expect(fit.daysUntilMeasure, 4);
+ fit.setMeasureEvery(0);
+ expect(fit.nextMeasureDue, isNull);
+ });
}