From 62e06d63a438e2818c19608683efd717ff056f9f Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 7 Aug 2026 22:05:48 +0200 Subject: [PATCH] Share the quick steppers and the date-time pair --- lib/core/widgets/datetime_input.dart | 70 +++++++++ lib/core/widgets/decimal_input.dart | 108 ++++++++++++- lib/features/measurements/widgets/forms.dart | 55 +------ .../measurements/widgets/weight_form.dart | 143 ++---------------- test/core/widgets/datetime_input_test.dart | 34 +++++ test/core/widgets/decimal_input_test.dart | 83 ++++++++++ .../widgets/weight_form_test.dart | 10 +- 7 files changed, 312 insertions(+), 191 deletions(-) diff --git a/lib/core/widgets/datetime_input.dart b/lib/core/widgets/datetime_input.dart index 1dab063dc..e2f3aa745 100644 --- a/lib/core/widgets/datetime_input.dart +++ b/lib/core/widgets/datetime_input.dart @@ -18,6 +18,7 @@ import 'package:flutter/material.dart'; import 'package:wger/core/formatting/formatting.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; /// Read-only field that opens a time picker on tap. /// @@ -221,3 +222,72 @@ class _DateInputWidgetState extends State { ); } } + +/// The two halves of one [DateTime]: a date field above a time field, each +/// reporting the whole moment through [onChanged]. +/// +/// For the entries that are stamped with a single point in time. Where date +/// and time are stored apart (a meal has a time and no date), the two fields +/// are used on their own instead. +class DateTimeInputWidget extends StatefulWidget { + const DateTimeInputWidget({ + required this.value, + required this.onChanged, + this.firstDate, + this.lastDate, + super.key, + }); + + /// The moment both fields show, and the one edits are applied to. + final DateTime value; + + /// Called with the full moment after either half was picked. + final ValueChanged onChanged; + + /// Earliest selectable date, ten years back by default. + final DateTime? firstDate; + + /// Latest selectable date, today by default. + final DateTime? lastDate; + + @override + State createState() => _DateTimeInputWidgetState(); +} + +class _DateTimeInputWidgetState extends State { + /// The moment as far as it has been edited. Kept here because the callers + /// collect what they build without rebuilding, so the value passed in would + /// still be the one the form started with when the second half is picked. + late DateTime _value = widget.value; + + void _report(DateTime value) { + setState(() => _value = value); + widget.onChanged(value); + } + + @override + Widget build(BuildContext context) { + final i18n = AppLocalizations.of(context); + + return Column( + children: [ + DateInputWidget( + value: _value, + labelText: i18n.date, + firstDate: widget.firstDate ?? DateTime(DateTime.now().year - 10), + lastDate: widget.lastDate ?? DateTime.now(), + onChanged: (date) => _report( + _value.copyWith(year: date.year, month: date.month, day: date.day), + ), + ), + TimeInputWidget( + value: TimeOfDay.fromDateTime(_value), + labelText: i18n.time, + onChanged: (time) => _report( + _value.copyWith(hour: time.hour, minute: time.minute, second: 0), + ), + ), + ], + ); + } +} diff --git a/lib/core/widgets/decimal_input.dart b/lib/core/widgets/decimal_input.dart index 625806b08..6a144c2b9 100644 --- a/lib/core/widgets/decimal_input.dart +++ b/lib/core/widgets/decimal_input.dart @@ -17,6 +17,7 @@ */ import 'package:flutter/material.dart'; +import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:wger/core/consts.dart'; import 'package:wger/core/formatting/formatting.dart'; import 'package:wger/core/number_input.dart'; @@ -28,7 +29,10 @@ import 'package:wger/l10n/generated/app_localizations.dart'; /// through [onChanged] as a parsed [num], or null when the field is empty. /// Display and parsing always go through the same NumberFormat, so a value can /// never be mis-read because of a decimal-separator mismatch between locales. -class DecimalInputWidget extends StatelessWidget { +/// +/// [value] seeds the field, later changes to it are ignored: what the user +/// typed is what stands. +class DecimalInputWidget extends StatefulWidget { const DecimalInputWidget({ required this.value, required this.onChanged, @@ -37,6 +41,7 @@ class DecimalInputWidget extends StatelessWidget { this.isRequired = false, this.min, this.max, + this.steppers = const [], super.key, }); @@ -61,31 +66,120 @@ class DecimalInputWidget extends StatelessWidget { /// Optional inclusive upper bound. See [min]. final num? max; + /// Step sizes for the quick +/- buttons around the field, biggest first. + /// Empty for a plain field. + final List steppers; + + @override + State createState() => _DecimalInputWidgetState(); +} + +class _DecimalInputWidgetState extends State { + /// Controller rather than `initialValue`, because the steppers write into + /// the field. Seeded in didChangeDependencies, which is where the locale + /// that formats the value is available. + final _controller = TextEditingController(); + bool _seeded = false; + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + if (!_seeded) { + _seeded = true; + final value = widget.value; + if (value != null) { + _controller.text = localizedNumberFormat(context).format(value); + } + } + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + /// Adds [delta] to what the field currently holds, unless that leaves the + /// valid range or the field holds nothing to add to. + void _step(num delta) { + final numberFormat = localizedNumberFormat(context); + final parsed = numberFormat.tryParse(_controller.text); + if (parsed == null) { + return; + } + + final stepped = parsed + delta; + if ((widget.min != null && stepped < widget.min!) || + (widget.max != null && stepped > widget.max!)) { + return; + } + + _controller.text = numberFormat.format(stepped); + // Setting the text does not run the field's onChanged + widget.onChanged(stepped); + } + + /// The quick-change buttons of one side, biggest step outermost. The biggest + /// one is drawn as a circled icon, so the two sizes stay apart at a glance. + List _stepperButtons({required bool plus}) => [ + for (final (index, step) in widget.steppers.indexed) + IconButton( + key: Key('stepper-${plus ? 'plus' : 'minus'}-$index'), + icon: FaIcon( + switch ((index, plus)) { + (0, false) => FontAwesomeIcons.circleMinus, + (0, true) => FontAwesomeIcons.circlePlus, + (_, false) => FontAwesomeIcons.minus, + (_, true) => FontAwesomeIcons.plus, + }, + ), + onPressed: () => _step(plus ? step : -step), + ), + ]; + @override Widget build(BuildContext context) { final i18n = AppLocalizations.of(context); final numberFormat = localizedNumberFormat(context); + final hasSteppers = widget.steppers.isNotEmpty; return TextFormField( - initialValue: value == null ? '' : numberFormat.format(value), - decoration: InputDecoration(labelText: labelText, suffixText: suffixText), + controller: _controller, + decoration: InputDecoration( + labelText: widget.labelText, + suffixText: widget.suffixText, + prefix: hasSteppers + ? Row( + mainAxisSize: MainAxisSize.min, + children: _stepperButtons(plus: false), + ) + : null, + suffix: hasSteppers + ? Row( + mainAxisSize: MainAxisSize.min, + children: _stepperButtons(plus: true).reversed.toList(), + ) + : null, + ), keyboardType: textInputTypeDecimal, inputFormatters: [LocalizedDecimalInputFormatter(numberFormat.symbols.DECIMAL_SEP)], onChanged: (text) { final trimmed = text.trim(); - onChanged(trimmed.isEmpty ? null : numberFormat.tryParse(trimmed)); + widget.onChanged(trimmed.isEmpty ? null : numberFormat.tryParse(trimmed)); }, validator: (text) { final trimmed = text?.trim() ?? ''; if (trimmed.isEmpty) { - return isRequired ? i18n.enterValue : null; + return widget.isRequired ? i18n.enterValue : null; } final parsed = numberFormat.tryParse(trimmed); if (parsed == null) { return i18n.enterValidNumber; } - if (min != null && max != null && (parsed < min! || parsed > max!)) { - return i18n.formMinMaxValues(min!.toInt(), max!.toInt()); + if (widget.min != null && + widget.max != null && + (parsed < widget.min! || parsed > widget.max!)) { + return i18n.formMinMaxValues(widget.min!.toInt(), widget.max!.toInt()); } return null; }, diff --git a/lib/features/measurements/widgets/forms.dart b/lib/features/measurements/widgets/forms.dart index 428176abf..dec23dfb9 100644 --- a/lib/features/measurements/widgets/forms.dart +++ b/lib/features/measurements/widgets/forms.dart @@ -336,36 +336,9 @@ class _MeasurementEntryFormState extends ConsumerState { key: _form, child: Column( children: [ - // Date - DateInputWidget( + DateTimeInputWidget( value: _draft.date, - labelText: AppLocalizations.of(context).date, - firstDate: DateTime(DateTime.now().year - 10), - lastDate: DateTime.now(), - onChanged: (date) { - _draft = _draft.copyWith( - date: _draft.date.copyWith( - year: date.year, - month: date.month, - day: date.day, - ), - ); - }, - ), - - // Time - TimeInputWidget( - value: TimeOfDay.fromDateTime(_draft.date), - labelText: AppLocalizations.of(context).time, - onChanged: (time) { - _draft = _draft.copyWith( - date: _draft.date.copyWith( - hour: time.hour, - minute: time.minute, - second: 0, - ), - ); - }, + onChanged: (date) => _draft = _draft.copyWith(date: date), ), // Value @@ -456,29 +429,9 @@ class _GroupMeasurementEntryFormState extends ConsumerState _date = date, ), // One value field per component, each bounded by its own type: diff --git a/lib/features/measurements/widgets/weight_form.dart b/lib/features/measurements/widgets/weight_form.dart index 5aa45c2b7..3713d2148 100644 --- a/lib/features/measurements/widgets/weight_form.dart +++ b/lib/features/measurements/widgets/weight_form.dart @@ -18,11 +18,9 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart' as riverpod; -import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:wger/core/consts.dart'; -import 'package:wger/core/formatting/formatting.dart'; -import 'package:wger/core/number_input.dart'; import 'package:wger/core/widgets/datetime_input.dart'; +import 'package:wger/core/widgets/decimal_input.dart'; import 'package:wger/core/widgets/form_submit_button.dart'; import 'package:wger/features/account/providers/user_profile_notifier.dart'; import 'package:wger/features/measurements/models/measurement_category.dart'; @@ -54,20 +52,15 @@ class WeightForm extends riverpod.ConsumerStatefulWidget { class _WeightFormState extends riverpod.ConsumerState { final _form = GlobalKey(); - // Controller instead of initialValue because the quick +/- buttons write - // into the field. Seeded in didChangeDependencies (needs the locale). - final _weightController = TextEditingController(); - bool _seeded = false; - late DateTime _date; - num _weight = 0; + num? _weight; late String _unit; @override void initState() { super.initState(); _date = widget._entry?.date ?? DateTime.now(); - _weight = widget._entry?.value ?? 0; + _weight = widget._entry?.value; // Existing entries keep their stored unit (the value is shown exactly as // entered); new entries default to the profile unit @@ -77,137 +70,31 @@ class _WeightFormState extends riverpod.ConsumerState { : weightDisplayUnit(ref.read(userProfileProvider).value?.isMetric ?? true); } - @override - void didChangeDependencies() { - super.didChangeDependencies(); - if (!_seeded) { - _seeded = true; - if (widget._entry != null) { - _weightController.text = localizedNumberFormat(context).format(widget._entry!.value); - } - } - } - - @override - void dispose() { - _weightController.dispose(); - super.dispose(); - } - /// The bounds of the unit the value is currently entered in MetricLimits get _limits => MetricType.bodyWeight.limits(_unit); - /// `true` when [value] (in the currently selected unit) is plausible - bool _isInRange(num value) => _limits.contains(value); - - /// Adds [delta] to the field's current value, clamped to the valid range - void _step(num delta) { - final numberFormat = localizedNumberFormat(context); - final parsed = numberFormat.tryParse(_weightController.text); - if (parsed == null) { - return; - } - final newValue = parsed + delta; - if (!_isInRange(newValue)) { - return; - } - _weightController.text = numberFormat.format(newValue); - } - @override Widget build(BuildContext context) { - final numberFormat = localizedNumberFormat(context); - return Form( key: _form, child: Column( children: [ - DateInputWidget( - key: const Key('dateInput'), + DateTimeInputWidget( + key: const Key('dateTimeInput'), value: _date, - labelText: AppLocalizations.of(context).date, - firstDate: DateTime(DateTime.now().year - 10), - lastDate: DateTime.now(), - onChanged: (date) { - _date = _date.copyWith( - year: date.year, - month: date.month, - day: date.day, - ); - }, - ), - TimeInputWidget( - key: const Key('timeInput'), - value: TimeOfDay.fromDateTime(_date), - labelText: AppLocalizations.of(context).time, - onChanged: (time) { - _date = _date.copyWith( - hour: time.hour, - minute: time.minute, - second: 0, - ); - }, + onChanged: (value) => _date = value, ), // Weight - TextFormField( + DecimalInputWidget( key: const Key('weightInput'), - decoration: InputDecoration( - labelText: AppLocalizations.of(context).weight, - prefix: Row( - mainAxisSize: MainAxisSize.min, - children: [ - IconButton( - key: const Key('quickMinus'), - icon: const FaIcon(FontAwesomeIcons.circleMinus), - onPressed: () => _step(-_stepperBig), - ), - IconButton( - key: const Key('quickMinusSmall'), - icon: const FaIcon(FontAwesomeIcons.minus), - onPressed: () => _step(-_stepperSmall), - ), - ], - ), - suffix: Row( - mainAxisSize: MainAxisSize.min, - children: [ - IconButton( - key: const Key('quickPlusSmall'), - icon: const FaIcon(FontAwesomeIcons.plus), - onPressed: () => _step(_stepperSmall), - ), - IconButton( - key: const Key('quickPlus'), - icon: const FaIcon(FontAwesomeIcons.circlePlus), - onPressed: () => _step(_stepperBig), - ), - ], - ), - ), - controller: _weightController, - keyboardType: textInputTypeDecimal, - inputFormatters: [LocalizedDecimalInputFormatter(numberFormat.symbols.DECIMAL_SEP)], - onSaved: (newValue) { - _weight = numberFormat.parse(newValue!); - }, - validator: (value) { - final i18n = AppLocalizations.of(context); - if (value!.isEmpty) { - return i18n.enterValue; - } - final parsed = numberFormat.tryParse(value); - if (parsed == null) { - return i18n.enterValidNumber; - } - if (!_isInRange(parsed)) { - return i18n.formMinMaxValues( - _limits.min.toInt(), - _limits.max.toInt(), - ); - } - return null; - }, + value: _weight, + labelText: AppLocalizations.of(context).weight, + isRequired: true, + min: _limits.min, + max: _limits.max, + steppers: const [_stepperBig, _stepperSmall], + onChanged: (value) => _weight = value, ), // Unit the value is entered in, stamped onto the entry when saving @@ -241,7 +128,7 @@ class _WeightFormState extends riverpod.ConsumerState { id: widget._entry?.id, categoryId: widget._category.id!, date: _date, - value: _weight, + value: _weight!, notes: widget._entry?.notes ?? '', source: widget._entry?.source ?? 'user', externalId: widget._entry?.externalId, diff --git a/test/core/widgets/datetime_input_test.dart b/test/core/widgets/datetime_input_test.dart index 2a48bdef0..4c779e8c9 100644 --- a/test/core/widgets/datetime_input_test.dart +++ b/test/core/widgets/datetime_input_test.dart @@ -177,4 +177,38 @@ void main() { expect(find.text('1/5/2021'), findsOneWidget); }); }); + + group('DateTimeInputWidget', () { + testWidgets('reports the whole moment, keeping the half picked before', ( + WidgetTester tester, + ) async { + // The forms collect what they are told without rebuilding, so the + // second pick must not be applied to the moment they started with + DateTime? reported; + await tester.pumpWidget( + wrap( + DateTimeInputWidget( + value: DateTime(2021, 1, 1, 15, 30), + onChanged: (value) => reported = value, + ), + ), + ); + await tester.pumpAndSettle(); + + // Straight through the two halves, whose own pickers are covered above + tester.widget(find.byType(DateInputWidget)).onChanged(DateTime(2021, 1, 5)); + await tester.pumpAndSettle(); + expect(reported, DateTime(2021, 1, 5, 15, 30)); + + tester + .widget(find.byType(TimeInputWidget)) + .onChanged(const TimeOfDay(hour: 9, minute: 45)); + await tester.pumpAndSettle(); + + // The day of the first pick, the time of the second + expect(reported, DateTime(2021, 1, 5, 9, 45)); + expect(find.text('1/5/2021'), findsOneWidget); + expect(find.text('9:45 AM'), findsOneWidget); + }); + }); } diff --git a/test/core/widgets/decimal_input_test.dart b/test/core/widgets/decimal_input_test.dart index 02c57ac97..1a8ee2149 100644 --- a/test/core/widgets/decimal_input_test.dart +++ b/test/core/widgets/decimal_input_test.dart @@ -142,4 +142,87 @@ void main() { expect(formKey.currentState!.validate(), isTrue); }); + + group('steppers', () { + Widget wrapStepped({ + num? value = 80, + String locale = 'en', + num? min, + num? max, + required ValueChanged onChanged, + }) => wrap( + DecimalInputWidget( + value: value, + labelText: 'X', + min: min, + max: max, + steppers: const [1, 0.1], + onChanged: onChanged, + ), + locale: locale, + ); + + testWidgets('a field without them has no buttons', (WidgetTester tester) async { + await tester.pumpWidget( + wrap(DecimalInputWidget(value: 80, labelText: 'X', onChanged: (_) {})), + ); + await tester.pumpAndSettle(); + + expect(find.byType(IconButton), findsNothing); + }); + + testWidgets('each button steps the field by its size and reports it', ( + WidgetTester tester, + ) async { + num? captured; + await tester.pumpWidget(wrapStepped(onChanged: (value) => captured = value)); + await tester.pumpAndSettle(); + + await tester.tap(find.byKey(const Key('stepper-minus-0'))); + await tester.pumpAndSettle(); + expect(find.text('79'), findsOneWidget); + expect(captured, 79); + + await tester.tap(find.byKey(const Key('stepper-plus-1'))); + await tester.pumpAndSettle(); + expect(find.text('79.1'), findsOneWidget); + expect(captured, 79.1); + }); + + testWidgets('steps in the format of the active locale', (WidgetTester tester) async { + await tester.pumpWidget(wrapStepped(locale: 'de', onChanged: (_) {})); + await tester.pumpAndSettle(); + + await tester.tap(find.byKey(const Key('stepper-minus-1'))); + await tester.pumpAndSettle(); + + expect(find.text('79,9'), findsOneWidget); + }); + + testWidgets('a step out of the valid range is ignored', (WidgetTester tester) async { + num? captured; + await tester.pumpWidget( + wrapStepped(value: 80, min: 80, max: 80.5, onChanged: (value) => captured = value), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.byKey(const Key('stepper-minus-0'))); + await tester.tap(find.byKey(const Key('stepper-plus-0'))); + await tester.pumpAndSettle(); + + expect(find.text('80'), findsOneWidget); + expect(captured, isNull); + }); + + testWidgets('an empty field has nothing to step', (WidgetTester tester) async { + await tester.pumpWidget(wrapStepped(value: null, onChanged: (_) {})); + await tester.pumpAndSettle(); + + await tester.tap(find.byKey(const Key('stepper-plus-0'))); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + expect(find.text('1'), findsNothing); + }); + }); } diff --git a/test/features/measurements/widgets/weight_form_test.dart b/test/features/measurements/widgets/weight_form_test.dart index 1f1ae42b9..bf3de3e1d 100644 --- a/test/features/measurements/widgets/weight_form_test.dart +++ b/test/features/measurements/widgets/weight_form_test.dart @@ -95,16 +95,16 @@ void main() { await tester.pumpWidget(createWeightForm(entry: testWeightEntry1)); await tester.pumpAndSettle(); - await tester.tap(find.byKey(const Key('quickMinus'))); + await tester.tap(find.byKey(const Key('stepper-minus-0'))); expect(find.text('79'), findsOneWidget); - await tester.tap(find.byKey(const Key('quickMinusSmall'))); + await tester.tap(find.byKey(const Key('stepper-minus-1'))); expect(find.text('78.9'), findsOneWidget); - await tester.tap(find.byKey(const Key('quickPlus'))); + await tester.tap(find.byKey(const Key('stepper-plus-0'))); expect(find.text('79.9'), findsOneWidget); - await tester.tap(find.byKey(const Key('quickPlusSmall'))); + await tester.tap(find.byKey(const Key('stepper-plus-1'))); expect(find.text('80'), findsOneWidget); }); @@ -117,7 +117,7 @@ void main() { expect(find.text('shiba inu'), findsNothing); // Quick-change still works on the now-empty field - await tester.tap(find.byKey(const Key('quickMinus'))); + await tester.tap(find.byKey(const Key('stepper-minus-0'))); await tester.pumpAndSettle(); expect(find.text('shiba inu'), findsNothing); });