diff --git a/app/lib/screens/log_meal_future_mixin.dart b/app/lib/screens/log_meal_future_mixin.dart index a839d3f..c151b3f 100644 --- a/app/lib/screens/log_meal_future_mixin.dart +++ b/app/lib/screens/log_meal_future_mixin.dart @@ -16,6 +16,7 @@ import 'package:diet_guard_app/models/slot.dart'; import 'package:diet_guard_app/services/log_storage_service.dart'; import 'package:diet_guard_app/services/meal_schedule_service.dart'; import 'package:diet_guard_app/ui/theme.dart'; +import 'package:diet_guard_app/widgets/pickers/pickers.dart'; import 'package:diet_guard_app/widgets/slot_selector_row.dart'; import 'package:flutter/material.dart'; @@ -51,7 +52,7 @@ mixin LogMealFutureMixin on State { Future _pickFutureDate() async { final today = DateTime.now(); final tomorrow = DateTime(today.year, today.month, today.day + 1); - final picked = await showDatePicker( + final picked = await pickDate( context: context, firstDate: tomorrow, lastDate: tomorrow.add(const Duration(days: 365)), diff --git a/app/lib/ui/theme.dart b/app/lib/ui/theme.dart index da5bad7..b0c395b 100644 --- a/app/lib/ui/theme.dart +++ b/app/lib/ui/theme.dart @@ -195,6 +195,9 @@ abstract final class AppWidth { /// value reads as a layout error rather than an affordance. static const double field = 420; + /// 440px — cap for a date/time picker dialog (7 day columns + year wheel). + static const double picker = 440; + /// Viewport height below which the layout should switch to its compact form. /// /// 700px, i.e. 768 minus typical window chrome: the supported floor is a diff --git a/app/lib/widgets/body/dated_value_card.dart b/app/lib/widgets/body/dated_value_card.dart index 8085c22..6cd512e 100644 --- a/app/lib/widgets/body/dated_value_card.dart +++ b/app/lib/widgets/body/dated_value_card.dart @@ -7,6 +7,7 @@ import 'package:diet_guard_app/ui/cues.dart'; import 'package:diet_guard_app/ui/theme.dart'; import 'package:diet_guard_app/widgets/body/body_section.dart'; import 'package:diet_guard_app/widgets/body/weight_chart.dart'; +import 'package:diet_guard_app/widgets/pickers/pickers.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -80,7 +81,7 @@ class _DatedValueCardState extends State { String _fmt(double value) => '${oneDecimal(value)} ${widget.unit}'; Future _pickDay() async { - final picked = await showDatePicker( + final picked = await pickDate( context: context, firstDate: DateTime(2000), lastDate: DateTime.now(), diff --git a/app/lib/widgets/body/profile_card.dart b/app/lib/widgets/body/profile_card.dart index d97b140..1e644af 100644 --- a/app/lib/widgets/body/profile_card.dart +++ b/app/lib/widgets/body/profile_card.dart @@ -6,6 +6,7 @@ import 'package:diet_guard_app/services/body_service.dart'; import 'package:diet_guard_app/ui/cues.dart'; import 'package:diet_guard_app/ui/theme.dart'; import 'package:diet_guard_app/widgets/body/body_section.dart'; +import 'package:diet_guard_app/widgets/pickers/pickers.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -46,7 +47,7 @@ class _ProfileCardState extends State { Future _pickBirth() async { final now = DateTime.now(); final initial = DateTime.tryParse(_birth ?? '') ?? DateTime(now.year - 30); - final picked = await showDatePicker( + final picked = await pickDate( context: context, firstDate: DateTime(1900), lastDate: now, diff --git a/app/lib/widgets/history/history_filter_sheet.dart b/app/lib/widgets/history/history_filter_sheet.dart index ea29ef8..14eda3e 100644 --- a/app/lib/widgets/history/history_filter_sheet.dart +++ b/app/lib/widgets/history/history_filter_sheet.dart @@ -9,6 +9,7 @@ import 'package:diet_guard_app/widgets/filters/filter_fields.dart'; import 'package:diet_guard_app/widgets/history/history_filter.dart'; import 'package:diet_guard_app/widgets/history/history_filter_sort.dart'; import 'package:diet_guard_app/widgets/history/history_grouping.dart'; +import 'package:diet_guard_app/widgets/pickers/pickers.dart'; import 'package:flutter/material.dart'; /// The draggable bottom sheet that edits the history filter and sort order. @@ -111,7 +112,7 @@ class FilterSheet extends StatelessWidget { ], ), onPressed: () async { - final picked = await showDateRangePicker( + final picked = await pickDateRange( context: context, firstDate: DateTime(2020), lastDate: DateTime.now().add(const Duration(days: 1)), diff --git a/app/lib/widgets/meal_time_dropdown.dart b/app/lib/widgets/meal_time_dropdown.dart index ae7ba85..8c7e7f3 100644 --- a/app/lib/widgets/meal_time_dropdown.dart +++ b/app/lib/widgets/meal_time_dropdown.dart @@ -6,6 +6,7 @@ import 'dart:async'; import 'package:diet_guard_app/models/meal_schedule.dart'; import 'package:diet_guard_app/models/slot.dart'; import 'package:diet_guard_app/ui/theme.dart'; +import 'package:diet_guard_app/widgets/pickers/pickers.dart'; import 'package:flutter/material.dart'; /// Picks a minute of day, offering the 15-minute grid within @@ -56,8 +57,8 @@ class MealTimeDropdown extends StatelessWidget { /// while the clock button may go to 23:44). Defaults to [maxMinute]. final int? gridMaxMinute; - /// Called with the chosen minute, already clamped into - /// [minMinute]..[maxMinute]. Not called when the picker is dismissed. + /// Called with the chosen minute, always within [minMinute]..[maxMinute] + /// (the time picker cannot pick outside it). Not called when dismissed. final ValueChanged onChanged; /// The minutes listed, ascending: the grid marks in range plus [value]. @@ -77,28 +78,15 @@ class MealTimeDropdown extends StatelessWidget { }.toList()..sort(); } - int _clampToRange(int minute) => minute < minMinute - ? minMinute - : (minute > maxMinute ? maxMinute : minute); - Future _pickExact(BuildContext context) async { - final picked = await showTimePicker( + final picked = await pickTime( context: context, initialTime: TimeOfDay(hour: value ~/ 60, minute: value % 60), - // Empty so the picker does not print its own heading over the clock. - helpText: '', - // The rest of the app writes times as HH:MM; an AM/PM dial here would - // be the one place that reads differently. - builder: (context, child) => MediaQuery( - data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true), - child: child!, - ), + minMinute: minMinute, + maxMinute: maxMinute, ); if (picked == null) return; - // Clamped rather than rejected: the picker cannot be told the range, and - // the nearest legal minute is what `MealSchedule.normalized` would - // produce anyway -- doing it here keeps the dropdown's own contract. - onChanged(_clampToRange(picked.hour * 60 + picked.minute)); + onChanged(picked.hour * 60 + picked.minute); } @override diff --git a/app/lib/widgets/pickers/date_dialog.dart b/app/lib/widgets/pickers/date_dialog.dart new file mode 100644 index 0000000..56b720f --- /dev/null +++ b/app/lib/widgets/pickers/date_dialog.dart @@ -0,0 +1,127 @@ +/// The date and date-range dialog: month chips above, the day grid with the +/// year wheel beside it, check and close icons below. +library; + +import 'package:diet_guard_app/ui/theme.dart'; +import 'package:diet_guard_app/widgets/pickers/date_grid.dart'; +import 'package:diet_guard_app/widgets/pickers/date_selection.dart'; +import 'package:diet_guard_app/widgets/pickers/month_chips.dart'; +import 'package:diet_guard_app/widgets/pickers/picker_frame.dart'; +import 'package:diet_guard_app/widgets/pickers/year_wheel.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +/// Width of the year wheel beside the grid. +const double kYearWheelWidth = 64; + +/// Pops a `DateTime` (single mode) or a `DateTimeRange` (range mode). +/// +/// Keyboard: arrows move the grid cursor by a day or a week, Space taps the +/// cursor day in range mode, Enter confirms, Esc cancels. +class DateDialog extends StatefulWidget { + /// Creates a [DateDialog] over [selection]. + const DateDialog({ + required this.selection, + this.startOnYear = false, + this.today, + super.key, + }); + + /// The selection to edit; its mode decides the popped type. + final DateSelection selection; + + /// Focus the year wheel first (the birth-date flow) instead of the grid. + final bool startOnYear; + + /// The day to ring; now when null (a seam for tests). + final DateTime? today; + + @override + State createState() => _DateDialogState(); +} + +class _DateDialogState extends State { + DateSelection get _sel => widget.selection; + bool _gridFocused = false; + + void _confirm() => Navigator.of( + context, + ).pop(_sel.range ? _sel.dateRange : _sel.start); + + KeyEventResult _key(FocusNode _, KeyEvent event) { + if (event is! KeyDownEvent && event is! KeyRepeatEvent) { + return KeyEventResult.ignored; + } + final step = switch (event.logicalKey) { + LogicalKeyboardKey.arrowLeft => -1, + LogicalKeyboardKey.arrowRight => 1, + LogicalKeyboardKey.arrowUp => -7, + LogicalKeyboardKey.arrowDown => 7, + _ => 0, + }; + if (step != 0) { + setState(() => _sel.moveCursor(step)); + return KeyEventResult.handled; + } + if (_sel.range && event.logicalKey == LogicalKeyboardKey.space) { + setState(() => _sel.tap(_sel.cursor)); + return KeyEventResult.handled; + } + return KeyEventResult.ignored; + } + + @override + Widget build(BuildContext context) => PickerFrame( + canConfirm: _sel.canConfirm, + onConfirm: _confirm, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + MonthChips( + year: _sel.year, + selected: _sel.month, + allowed: (m) => _sel.monthAllowed(_sel.year, m), + onTap: (m) => setState(() => _sel.showMonth(m)), + ), + const SizedBox(height: AppSpacing.sm), + LayoutBuilder( + builder: (context, constraints) { + final gridWidth = + constraints.maxWidth - kYearWheelWidth - AppSpacing.sm; + return SizedBox( + height: gridWidth / 7 * (kGridCells ~/ 7), + child: Row( + spacing: AppSpacing.sm, + children: [ + Expanded( + child: Focus( + autofocus: !widget.startOnYear, + onKeyEvent: _key, + onFocusChange: (f) => setState(() => _gridFocused = f), + child: DateGrid( + selection: _sel, + today: widget.today ?? DateTime.now(), + showCursor: _gridFocused, + onTap: (day) => setState(() => _sel.tap(day)), + ), + ), + ), + SizedBox( + width: kYearWheelWidth, + child: YearWheel( + firstYear: _sel.first.year, + lastYear: _sel.last.year, + value: _sel.year, + autofocus: widget.startOnYear, + onChanged: (y) => setState(() => _sel.showYear(y)), + ), + ), + ], + ), + ); + }, + ), + ], + ), + ); +} diff --git a/app/lib/widgets/pickers/date_grid.dart b/app/lib/widgets/pickers/date_grid.dart new file mode 100644 index 0000000..e038084 --- /dev/null +++ b/app/lib/widgets/pickers/date_grid.dart @@ -0,0 +1,74 @@ +/// The day grid: one month of numerals, Monday first, with no weekday header. +/// +/// One widget serves the single-date and the range picker; the mode lives in +/// [DateSelection], so the range picker is a mode of this grid, not a copy. +library; + +import 'package:diet_guard_app/widgets/pickers/date_selection.dart'; +import 'package:diet_guard_app/widgets/pickers/numeral_cell.dart'; +import 'package:flutter/material.dart'; + +/// Six rows of seven: every month fits, and the dialog never changes height. +const int kGridCells = 42; + +/// The shown month of [selection] as a numeral grid. +/// +/// Today has a ring; weekends are dimmed with a dot; out-of-range days are +/// dimmed further and inert. The chosen day, or both range ends, are filled; +/// the days of a range are shaded. +class DateGrid extends StatelessWidget { + /// Creates a [DateGrid]. + const DateGrid({ + required this.selection, + required this.today, + required this.onTap, + this.showCursor = false, + super.key, + }); + + /// The selection being edited (read only here). + final DateSelection selection; + + /// Today's date, ringed. + final DateTime today; + + /// Called with a tapped in-range day. + final ValueChanged onTap; + + /// Whether to outline the keyboard cursor (the grid has focus). + final bool showCursor; + + bool _inBand(DateTime day) { + final start = selection.start; + final end = selection.end; + if (start == null || end == null || start == end) return false; + return !day.isBefore(start) && !day.isAfter(end); + } + + @override + Widget build(BuildContext context) { + final l10n = MaterialLocalizations.of(context); + final year = selection.year; + final month = selection.month; + final lead = DateTime(year, month).weekday - DateTime.monday; + final days = DateUtils.getDaysInMonth(year, month); + return numeralRows(7, [ + for (var i = 0; i < lead; i++) const SizedBox.shrink(), + for (var d = 1; d <= days; d++) _cell(DateTime(year, month, d), l10n), + for (var i = lead + days; i < kGridCells; i++) const SizedBox.shrink(), + ]); + } + + Widget _cell(DateTime day, MaterialLocalizations l10n) => NumeralCell( + key: ValueKey(day), + label: '${day.day}', + semanticLabel: l10n.formatFullDate(day), + onTap: () => onTap(day), + enabled: selection.allows(day), + selected: day == selection.start || day == selection.end, + band: _inBand(day), + ring: DateUtils.isSameDay(day, today), + dot: day.weekday >= DateTime.saturday, + focused: showCursor && day == selection.cursor, + ); +} diff --git a/app/lib/widgets/pickers/date_selection.dart b/app/lib/widgets/pickers/date_selection.dart new file mode 100644 index 0000000..1729104 --- /dev/null +++ b/app/lib/widgets/pickers/date_selection.dart @@ -0,0 +1,140 @@ +/// The date picker's selection rules, kept free of widgets so each rule is a +/// plain unit test: bounds clamp, the two-tap range, the month/year day clamp. +library; + +import 'dart:math' as math; + +import 'package:flutter/material.dart' show DateTimeRange, DateUtils; + +/// What the date picker has chosen, and which month it is showing. +/// +/// Every date is date-only (midnight local); days are stepped with +/// `DateTime(y, m, d + n)`, never a `Duration`, so DST cannot shift a day. +class DateSelection { + /// A single-date selection starting on [initial], clamped into bounds. + DateSelection.single({ + required DateTime first, + required DateTime last, + DateTime? initial, + }) : first = DateUtils.dateOnly(first), + last = DateUtils.dateOnly(last), + range = false { + start = _clamp(initial ?? DateTime.now()); + _init(start!); + } + + /// A two-tap range selection. A preset [initial] range counts as both taps + /// done, so it can be confirmed at once. + DateSelection.range({ + required DateTime first, + required DateTime last, + DateTimeRange? initial, + }) : first = DateUtils.dateOnly(first), + last = DateUtils.dateOnly(last), + range = true { + if (initial != null) { + start = _clamp(initial.start); + end = _clamp(initial.end); + } + _init(start ?? _clamp(DateTime.now())); + } + + /// Earliest selectable day. + final DateTime first; + + /// Latest selectable day. + final DateTime last; + + /// Whether this is the two-tap range mode. + final bool range; + + /// The chosen day (single mode) or the range start. + DateTime? start; + + /// The range end; null until the second tap. + DateTime? end; + + /// The keyboard cursor; equals [start] in single mode. + late DateTime cursor; + + /// Shown year. + late int year; + + /// Shown month, 1-12. + late int month; + + void _init(DateTime at) { + cursor = at; + year = at.year; + month = at.month; + } + + DateTime _clamp(DateTime day) { + final d = DateUtils.dateOnly(day); + if (d.isBefore(first)) return first; + return d.isAfter(last) ? last : d; + } + + /// Whether [day] lies within the bounds. + bool allows(DateTime day) => !day.isBefore(first) && !day.isAfter(last); + + /// Whether any day of month [m] of year [y] lies within the bounds. + bool monthAllowed(int y, int m) => + !DateTime(y, m + 1, 0).isBefore(first) && !DateTime(y, m).isAfter(last); + + /// Whether the check may be pressed: always in single mode, after both + /// taps in range mode. + bool get canConfirm => !range || end != null; + + /// The range chosen so far, once both ends are set. + DateTimeRange? get dateRange => + end == null ? null : DateTimeRange(start: start!, end: end!); + + /// A tap on [day]. Out-of-range days are inert. In range mode: the first + /// tap sets the start, the second the end (in either order), a third + /// restarts from [day]. + void tap(DateTime day) { + if (!allows(day)) return; + cursor = day; + if (!range) { + start = day; + } else if (start == null || end != null) { + start = day; + end = null; + } else if (day.isBefore(start!)) { + end = start; + start = day; + } else { + end = day; + } + } + + /// Moves the cursor by [days], following it into another month. Stops at + /// the bounds. In single mode the selection moves with it. + void moveCursor(int days) { + final day = DateTime(cursor.year, cursor.month, cursor.day + days); + if (!allows(day)) return; + _init(day); + if (!range) start = day; + } + + /// Shows month [m] of the shown year. + void showMonth(int m) => _show(year, m); + + /// Shows year [y], keeping the month where the bounds allow. + void showYear(int y) => _show(y, month); + + /// Shows ([y], [m]), pulling the month into bounds and the cursor day to + /// the new month's last day where it is shorter. A range's chosen ends + /// never move. + void _show(int y, int m) { + var shown = m; + if (y == first.year && shown < first.month) shown = first.month; + if (y == last.year && shown > last.month) shown = last.month; + final day = math.min(cursor.day, DateUtils.getDaysInMonth(y, shown)); + year = y; + month = shown; + cursor = _clamp(DateTime(y, shown, day)); + if (!range) start = cursor; + } +} diff --git a/app/lib/widgets/pickers/loop_wheel_delegate.dart b/app/lib/widgets/pickers/loop_wheel_delegate.dart new file mode 100644 index 0000000..f253b7b --- /dev/null +++ b/app/lib/widgets/pickers/loop_wheel_delegate.dart @@ -0,0 +1,30 @@ +/// The endless child delegate of the looping time wheels. +library; + +import 'package:flutter/widgets.dart'; + +/// An endless delegate that passes the absolute index to its builder, so a +/// tapped item knows which of its many copies it is (the framework's +/// looping delegate only hands out the wrapped child). +class LoopWheelDelegate extends ListWheelChildDelegate { + /// Creates a delegate looping over [count] values. + LoopWheelDelegate(this.count, this.builder); + + /// Number of distinct values before the wheel wraps. + final int count; + + /// Builds the item at an absolute (unwrapped) index. + final Widget Function(int index) builder; + + @override + Widget? build(BuildContext context, int index) => builder(index); + + @override + int? get estimatedChildCount => null; + + @override + int trueIndexOf(int index) => index % count; + + @override + bool shouldRebuild(covariant ListWheelChildDelegate oldDelegate) => true; +} diff --git a/app/lib/widgets/pickers/month_chips.dart b/app/lib/widgets/pickers/month_chips.dart new file mode 100644 index 0000000..b5bf5e1 --- /dev/null +++ b/app/lib/widgets/pickers/month_chips.dart @@ -0,0 +1,46 @@ +/// The month row of the date picker: numerals 1-12 instead of month names. +library; + +import 'package:diet_guard_app/widgets/pickers/numeral_cell.dart'; +import 'package:flutter/material.dart'; + +/// Twelve numeral chips in two rows of six; months wholly outside the bounds +/// are dimmed and inert. +class MonthChips extends StatelessWidget { + /// Creates a [MonthChips]. + const MonthChips({ + required this.year, + required this.selected, + required this.allowed, + required this.onTap, + super.key, + }); + + /// The shown year (for the spoken month names). + final int year; + + /// The shown month, 1-12. + final int selected; + + /// Whether month 1-12 has any day within the bounds. + final bool Function(int month) allowed; + + /// Called with a tapped allowed month. + final ValueChanged onTap; + + @override + Widget build(BuildContext context) { + final l10n = MaterialLocalizations.of(context); + return numeralRows(6, aspectRatio: 1.6, [ + for (var m = 1; m <= 12; m++) + NumeralCell( + key: ValueKey('month-$m'), + label: '$m', + semanticLabel: l10n.formatMonthYear(DateTime(year, m)), + onTap: () => onTap(m), + enabled: allowed(m), + selected: m == selected, + ), + ]); + } +} diff --git a/app/lib/widgets/pickers/numeral_cell.dart b/app/lib/widgets/pickers/numeral_cell.dart new file mode 100644 index 0000000..d596fba --- /dev/null +++ b/app/lib/widgets/pickers/numeral_cell.dart @@ -0,0 +1,153 @@ +/// One tappable numeral of the pickers' grids (a day, a month), plus the +/// equal-width row layout both grids use. +library; + +import 'package:flutter/material.dart'; + +/// Alpha of a weekend numeral: dimmed, with a dot as the second channel. +const double kWeekendAlpha = 0.6; + +/// Alpha of an out-of-range numeral: far below [kWeekendAlpha], so an +/// out-of-range weekend never reads like an in-range one. +const double kDisabledAlpha = 0.25; + +/// Alpha of the shaded band between two range ends. +const double kBandAlpha = 0.3; + +/// A numeral in a stadium. Every visual state is a field, so tests assert +/// state rather than colours. +class NumeralCell extends StatelessWidget { + /// Creates a [NumeralCell]. + const NumeralCell({ + required this.label, + required this.semanticLabel, + required this.onTap, + this.enabled = true, + this.selected = false, + this.band = false, + this.ring = false, + this.dot = false, + this.focused = false, + super.key, + }); + + /// The painted numeral. + final String label; + + /// The spoken name (a full date, a month); never painted. + final String semanticLabel; + + /// Called on tap when [enabled]. + final VoidCallback onTap; + + /// Out-of-range cells are dimmed and inert. + final bool enabled; + + /// Filled: the chosen value (a range end is a filled cap). + final bool selected; + + /// Shaded background: inside a chosen range. + final bool band; + + /// Outlined: today. + final bool ring; + + /// Dimmed with a dot below: a weekend. + final bool dot; + + /// The keyboard cursor. + final bool focused; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final alpha = !enabled ? kDisabledAlpha : (dot ? kWeekendAlpha : 1.0); + final fg = selected + ? scheme.onPrimary + : scheme.onSurface.withValues(alpha: alpha); + final edge = ring || focused + ? BorderSide(color: focused ? scheme.outline : scheme.primary, width: 2) + : BorderSide.none; + final shape = StadiumBorder(side: edge); + return Semantics( + label: semanticLabel, + button: true, + selected: selected, + enabled: enabled, + // excludeSemantics drops the InkWell's own tap action, so the node + // offers it here or a screen reader cannot pick a day. + onTap: enabled ? onTap : null, + excludeSemantics: true, + child: ColoredBox( + // Translucent, not primaryContainer: in this theme that equals + // primary, which hid the filled range ends inside the band. + color: band + ? scheme.primary.withValues(alpha: kBandAlpha) + : Colors.transparent, + child: Padding( + padding: const EdgeInsets.all(2), + child: Material( + type: MaterialType.transparency, + child: InkWell( + customBorder: shape, + canRequestFocus: false, + onTap: enabled ? onTap : null, + child: Ink( + decoration: ShapeDecoration( + shape: shape, + color: selected ? scheme.primary : null, + ), + child: Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + label, + style: TextStyle( + color: fg, + fontWeight: selected ? FontWeight.bold : null, + ), + ), + if (dot) + Container( + width: 4, + height: 4, + decoration: BoxDecoration( + color: fg, + shape: BoxShape.circle, + ), + ), + ], + ), + ), + ), + ), + ), + ), + ), + ); + } +} + +/// Lays [cells] out in rows of [columns] equal-width cells, each +/// [aspectRatio] wide per unit of height; a short last row is padded. +Widget numeralRows(int columns, List cells, {double aspectRatio = 1}) => + Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (var r = 0; r < cells.length; r += columns) + Row( + children: [ + for (var c = r; c < r + columns; c++) + Expanded( + child: AspectRatio( + aspectRatio: aspectRatio, + child: c < cells.length + ? cells[c] + : const SizedBox.shrink(), + ), + ), + ], + ), + ], + ); diff --git a/app/lib/widgets/pickers/numeral_wheel.dart b/app/lib/widgets/pickers/numeral_wheel.dart new file mode 100644 index 0000000..8716ca6 --- /dev/null +++ b/app/lib/widgets/pickers/numeral_wheel.dart @@ -0,0 +1,238 @@ +/// A controlled numeral wheel: the year wheel and both time wheels. +library; + +import 'package:diet_guard_app/ui/theme.dart'; +import 'package:diet_guard_app/widgets/pickers/loop_wheel_delegate.dart'; +import 'package:diet_guard_app/widgets/pickers/numeral_cell.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +/// Height of one wheel item. +const double kWheelItemExtent = 40; + +/// A wheel of the values `offset .. offset + count - 1`, optionally looping. +/// +/// Controlled: [value] is the truth and the wheel animates to it when the +/// parent changes it. Mouse drag scrolls (web excludes the mouse from drag by +/// default), a tap on any item selects it, arrow keys step by one. Values +/// failing [enabled] are dimmed and inert: [onChanged] never reports them and +/// a wheel that settles on one springs back to [value]. +class NumeralWheel extends StatefulWidget { + /// Creates a [NumeralWheel]. + const NumeralWheel({ + required this.count, + required this.value, + required this.onChanged, + required this.semanticLabel, + this.offset = 0, + this.loop = false, + this.digits = 1, + this.enabled, + this.autofocus = false, + super.key, + }); + + /// Number of values. + final int count; + + /// The value at index 0. + final int offset; + + /// The current value. + final int value; + + /// Called with each newly centred allowed value. + final ValueChanged onChanged; + + /// The spoken name of the wheel ("Year"); never painted. + final String semanticLabel; + + /// Whether the last value wraps to the first. + final bool loop; + + /// Zero-padded width of each numeral (2 for `05`). + final int digits; + + /// Which values may be picked; all when null. + final bool Function(int value)? enabled; + + /// Whether the wheel takes keyboard focus when it appears. + final bool autofocus; + + @override + State createState() => _NumeralWheelState(); +} + +class _NumeralWheelState extends State { + late final FixedExtentScrollController _controller = + FixedExtentScrollController(initialItem: widget.value - widget.offset); + late int _centred = widget.value - widget.offset; + bool _focused = false; + + int _valueAt(int index) => + widget.offset + (widget.loop ? index % widget.count : index); + + bool _ok(int value) => widget.enabled?.call(value) ?? true; + + /// The index nearest the centre that shows [value] (a loop has many). + int _indexOf(int value) { + final target = value - widget.offset; + if (!widget.loop) return target; + final n = widget.count; + final delta = (target - _centred) % n; + return delta > n ~/ 2 ? _centred + delta - n : _centred + delta; + } + + void _goTo(int index) => _controller.animateToItem( + index, + duration: AppDuration.fast, + curve: AppCurve.standard, + ); + + bool get _scrolling => + _controller.hasClients && _controller.position.isScrollingNotifier.value; + + @override + void didUpdateWidget(NumeralWheel old) { + super.didUpdateWidget(old); + // Not mid-drag: the parent echoing an intermediate value must not yank + // the wheel out from under the pointer. + if (widget.value != _valueAt(_centred) && !_scrolling) { + _afterFrame(() => _goTo(_indexOf(widget.value))); + } + } + + void _afterFrame(VoidCallback action) => + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) action(); + }); + + /// The allowed value nearest [value], by value and never across the wrap + /// (08:00 out of range means 08:15, not 08:59). A fast drag can skip every + /// allowed value on its way past an end, so the last reported value is no + /// anchor. + int _nearestAllowed(int value) { + final last = widget.offset + widget.count - 1; + for (var d = 1; d < widget.count; d++) { + for (final v in [value - d, value + d]) { + if (v >= widget.offset && v <= last && _ok(v)) return v; + } + } + return widget.value; + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + void _centre(int index) { + setState(() => _centred = index); + final value = _valueAt(index); + if (_ok(value) && value != widget.value) widget.onChanged(value); + } + + KeyEventResult _key(FocusNode _, KeyEvent event) { + if (event is! KeyDownEvent && event is! KeyRepeatEvent) { + return KeyEventResult.ignored; + } + final step = switch (event.logicalKey) { + LogicalKeyboardKey.arrowUp => -1, + LogicalKeyboardKey.arrowDown => 1, + _ => 0, + }; + if (step == 0) return KeyEventResult.ignored; + final next = _centred + step; + final inList = widget.loop || (next >= 0 && next < widget.count); + if (inList && _ok(_valueAt(next))) _goTo(next); + return KeyEventResult.handled; + } + + Widget _item(BuildContext context, int index) { + final value = _valueAt(index); + final ok = _ok(value); + final scheme = Theme.of(context).colorScheme; + final centred = index == _centred; + return GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: ok ? () => _goTo(index) : null, + child: Center( + child: Text( + '$value'.padLeft(widget.digits, '0'), + key: ValueKey('wheel-$value'), + style: TextStyle( + fontSize: centred ? AppTextSize.title : AppTextSize.subtitle, + fontWeight: centred ? FontWeight.bold : null, + color: scheme.onSurface.withValues(alpha: ok ? 1 : kDisabledAlpha), + ), + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final behavior = ScrollConfiguration.of(context).copyWith( + dragDevices: PointerDeviceKind.values.toSet(), + scrollbars: false, + ); + return Semantics( + label: widget.semanticLabel, + container: true, + child: Focus( + autofocus: widget.autofocus, + onKeyEvent: _key, + onFocusChange: (f) => setState(() => _focused = f), + child: Stack( + alignment: Alignment.center, + children: [ + Container( + height: kWheelItemExtent, + decoration: BoxDecoration( + color: scheme.primaryContainer, + border: _focused + ? Border.all(color: scheme.outline, width: 2) + : null, + borderRadius: BorderRadius.circular(AppRadius.sm), + ), + ), + NotificationListener( + onNotification: (_) { + if (!_ok(_valueAt(_centred))) { + _afterFrame( + () => _goTo(_indexOf(_nearestAllowed(_valueAt(_centred)))), + ); + } else if (_valueAt(_centred) != widget.value) { + _afterFrame(() => _goTo(_indexOf(widget.value))); + } + return false; + }, + child: ScrollConfiguration( + behavior: behavior, + child: ListWheelScrollView.useDelegate( + controller: _controller, + itemExtent: kWheelItemExtent, + physics: const FixedExtentScrollPhysics(), + diameterRatio: 1.6, + onSelectedItemChanged: _centre, + childDelegate: widget.loop + ? LoopWheelDelegate( + widget.count, + (i) => _item(context, i), + ) + : ListWheelChildBuilderDelegate( + childCount: widget.count, + builder: _item, + ), + ), + ), + ), + ], + ), + ), + ); + } +} diff --git a/app/lib/widgets/pickers/picker_frame.dart b/app/lib/widgets/pickers/picker_frame.dart new file mode 100644 index 0000000..57437ad --- /dev/null +++ b/app/lib/widgets/pickers/picker_frame.dart @@ -0,0 +1,75 @@ +/// The shared dialog around every picker: a centred, width-capped [Dialog] +/// with a close icon (cancel) and a check icon (confirm), no words. +library; + +import 'package:diet_guard_app/ui/theme.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +/// Picker chrome. Outside tap and Esc cancel (the dialog route's own +/// dismiss); Enter confirms when [canConfirm]. +/// +/// The icons carry spoken-only `semanticLabel`s and no `tooltip:`, which +/// would paint the word on long-press. +class PickerFrame extends StatelessWidget { + /// Creates a [PickerFrame]. + const PickerFrame({ + required this.child, + required this.canConfirm, + required this.onConfirm, + super.key, + }); + + /// The picker body. + final Widget child; + + /// Whether the check is enabled (a half-chosen range is not). + final bool canConfirm; + + /// Pops the dialog with the chosen value. + final VoidCallback onConfirm; + + void _enter() { + if (canConfirm) onConfirm(); + } + + @override + Widget build(BuildContext context) => Dialog( + insetPadding: const EdgeInsets.all(AppSpacing.md), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: AppWidth.picker), + child: SingleChildScrollView( + padding: const EdgeInsets.all(AppSpacing.md), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + // Around the body only: Enter on a focused close icon must + // reach that button (cancel), not bubble up into a confirm. + CallbackShortcuts( + bindings: { + const SingleActivator(LogicalKeyboardKey.enter): _enter, + const SingleActivator(LogicalKeyboardKey.numpadEnter): _enter, + }, + child: child, + ), + const SizedBox(height: AppSpacing.sm), + Row( + mainAxisAlignment: MainAxisAlignment.end, + spacing: AppSpacing.sm, + children: [ + IconButton( + onPressed: () => Navigator.of(context).pop(), + icon: const Icon(Icons.close, semanticLabel: 'Cancel'), + ), + IconButton.filled( + onPressed: canConfirm ? onConfirm : null, + icon: const Icon(Icons.check, semanticLabel: 'Confirm'), + ), + ], + ), + ], + ), + ), + ), + ); +} diff --git a/app/lib/widgets/pickers/pickers.dart b/app/lib/widgets/pickers/pickers.dart new file mode 100644 index 0000000..55008df --- /dev/null +++ b/app/lib/widgets/pickers/pickers.dart @@ -0,0 +1,67 @@ +/// Icon-only replacements for `showDatePicker`, `showDateRangePicker` and +/// `showTimePicker`, which paint "Select date", "Cancel", "OK" and tooltips. +/// +/// Same arguments as the framework calls, so a call site changes by one +/// function name. Dropped on purpose: the weekday header, month names and +/// both text-entry modes (see the textgate rework report). +library; + +import 'package:diet_guard_app/widgets/pickers/date_dialog.dart'; +import 'package:diet_guard_app/widgets/pickers/date_selection.dart'; +import 'package:diet_guard_app/widgets/pickers/time_dialog.dart'; +import 'package:flutter/material.dart'; + +/// Picks one day in [firstDate]..[lastDate]; null when cancelled. +/// +/// [initialDatePickerMode] `year` focuses the year wheel first. +Future pickDate({ + required BuildContext context, + required DateTime firstDate, + required DateTime lastDate, + DateTime? initialDate, + DatePickerMode initialDatePickerMode = DatePickerMode.day, +}) => showDialog( + context: context, + builder: (_) => DateDialog( + selection: DateSelection.single( + first: firstDate, + last: lastDate, + initial: initialDate, + ), + startOnYear: initialDatePickerMode == DatePickerMode.year, + ), +); + +/// Picks a range of days in [firstDate]..[lastDate] by two taps; null when +/// cancelled. +Future pickDateRange({ + required BuildContext context, + required DateTime firstDate, + required DateTime lastDate, + DateTimeRange? initialDateRange, +}) => showDialog( + context: context, + builder: (_) => DateDialog( + selection: DateSelection.range( + first: firstDate, + last: lastDate, + initial: initialDateRange, + ), + ), +); + +/// Picks a 24 h time whose minute of day lies in [minMinute]..[maxMinute]; +/// null when cancelled. +Future pickTime({ + required BuildContext context, + required TimeOfDay initialTime, + int minMinute = 0, + int maxMinute = 24 * 60 - 1, +}) => showDialog( + context: context, + builder: (_) => TimeDialog( + initialMinute: initialTime.hour * 60 + initialTime.minute, + minMinute: minMinute, + maxMinute: maxMinute, + ), +); diff --git a/app/lib/widgets/pickers/time_dialog.dart b/app/lib/widgets/pickers/time_dialog.dart new file mode 100644 index 0000000..078f527 --- /dev/null +++ b/app/lib/widgets/pickers/time_dialog.dart @@ -0,0 +1,52 @@ +/// The time dialog: hour and minute wheels between check and close icons. +library; + +import 'package:diet_guard_app/widgets/pickers/picker_frame.dart'; +import 'package:diet_guard_app/widgets/pickers/time_wheels.dart'; +import 'package:flutter/material.dart'; + +/// Pops the chosen [TimeOfDay], always within [minMinute]..[maxMinute]. +class TimeDialog extends StatefulWidget { + /// Creates a [TimeDialog]; [initialMinute] is clamped into range, since a + /// value written by another device may lie outside it. + const TimeDialog({ + required this.initialMinute, + required this.minMinute, + required this.maxMinute, + super.key, + }); + + /// The starting minute of day. + final int initialMinute; + + /// Earliest allowed minute of day. + final int minMinute; + + /// Latest allowed minute of day. + final int maxMinute; + + @override + State createState() => _TimeDialogState(); +} + +class _TimeDialogState extends State { + late int _minute = clampMinute( + widget.initialMinute, + widget.minMinute, + widget.maxMinute, + ); + + @override + Widget build(BuildContext context) => PickerFrame( + canConfirm: true, + onConfirm: () => Navigator.of( + context, + ).pop(TimeOfDay(hour: _minute ~/ 60, minute: _minute % 60)), + child: TimeWheels( + minute: _minute, + minMinute: widget.minMinute, + maxMinute: widget.maxMinute, + onChanged: (m) => setState(() => _minute = m), + ), + ); +} diff --git a/app/lib/widgets/pickers/time_wheels.dart b/app/lib/widgets/pickers/time_wheels.dart new file mode 100644 index 0000000..4d3e403 --- /dev/null +++ b/app/lib/widgets/pickers/time_wheels.dart @@ -0,0 +1,91 @@ +/// The time picker's two looping wheels: hour 00-23 and minute 00-59, 24 h. +library; + +import 'package:diet_guard_app/ui/theme.dart'; +import 'package:diet_guard_app/widgets/pickers/numeral_wheel.dart'; +import 'package:flutter/material.dart'; + +/// Width of one time wheel. +const double kTimeWheelWidth = 72; + +/// Whether hour [h] holds any minute of day in [min]..[max]. +bool hourAllowed(int h, int min, int max) => + h * 60 + 59 >= min && h * 60 <= max; + +/// [minute] of day pulled into [min]..[max]. +int clampMinute(int minute, int min, int max) => minute.clamp(min, max); + +/// Hour and minute wheels for a minute of day within [minMinute]..[maxMinute]. +/// +/// Hours and minutes outside the range are dimmed and inert. Changing the +/// hour pulls the minute to the nearest allowed one in that hour, so the +/// value reported is always in range. +class TimeWheels extends StatelessWidget { + /// Creates a [TimeWheels]. + const TimeWheels({ + required this.minute, + required this.minMinute, + required this.maxMinute, + required this.onChanged, + super.key, + }); + + /// The current minute of day (in range). + final int minute; + + /// Earliest allowed minute of day. + final int minMinute; + + /// Latest allowed minute of day. + final int maxMinute; + + /// Called with each new in-range minute of day. + final ValueChanged onChanged; + + @override + Widget build(BuildContext context) { + final hour = minute ~/ 60; + Widget wheel(Widget child) => SizedBox( + width: kTimeWheelWidth, + height: kWheelItemExtent * 5, + child: child, + ); + return Row( + mainAxisSize: MainAxisSize.min, + spacing: AppSpacing.xs, + children: [ + wheel( + NumeralWheel( + key: const ValueKey('hour'), + count: 24, + value: hour, + loop: true, + digits: 2, + semanticLabel: 'Hour', + autofocus: true, + enabled: (h) => hourAllowed(h, minMinute, maxMinute), + onChanged: (h) => onChanged( + clampMinute(h * 60 + minute % 60, minMinute, maxMinute), + ), + ), + ), + const Text(':', style: TextStyle(fontSize: AppTextSize.title)), + wheel( + NumeralWheel( + key: const ValueKey('minute'), + count: 60, + value: minute % 60, + loop: true, + digits: 2, + semanticLabel: 'Minute', + enabled: (m) { + final v = hour * 60 + m; + return v >= minMinute && v <= maxMinute; + }, + onChanged: (m) => onChanged(hour * 60 + m), + ), + ), + ], + ); + } +} diff --git a/app/lib/widgets/pickers/year_wheel.dart b/app/lib/widgets/pickers/year_wheel.dart new file mode 100644 index 0000000..c7a1e4b --- /dev/null +++ b/app/lib/widgets/pickers/year_wheel.dart @@ -0,0 +1,50 @@ +/// The date picker's year wheel: numerals, no loop. +library; + +import 'package:diet_guard_app/widgets/pickers/numeral_wheel.dart'; +import 'package:flutter/material.dart'; + +/// Out-of-range years listed beyond each bound, dimmed and inert, so the +/// wheel's ends read as limits rather than as a list that just stops. +const int kYearWheelPad = 2; + +/// A non-looping wheel of the years [firstYear]..[lastYear], plus +/// [kYearWheelPad] dimmed, inert years past each end (a wheel dragged onto +/// one springs back). +class YearWheel extends StatelessWidget { + /// Creates a [YearWheel]. + const YearWheel({ + required this.firstYear, + required this.lastYear, + required this.value, + required this.onChanged, + this.autofocus = false, + super.key, + }); + + /// Earliest listed year. + final int firstYear; + + /// Latest listed year. + final int lastYear; + + /// The shown year. + final int value; + + /// Called with a newly centred year. + final ValueChanged onChanged; + + /// Whether the wheel takes keyboard focus on open (the birth-date flow). + final bool autofocus; + + @override + Widget build(BuildContext context) => NumeralWheel( + count: lastYear - firstYear + 1 + 2 * kYearWheelPad, + offset: firstYear - kYearWheelPad, + enabled: (y) => y >= firstYear && y <= lastYear, + value: value, + onChanged: onChanged, + semanticLabel: 'Year', + autofocus: autofocus, + ); +} diff --git a/app/test/no_words_screens_test.dart b/app/test/no_words_screens_test.dart index 8a6bd4d..2593dc4 100644 --- a/app/test/no_words_screens_test.dart +++ b/app/test/no_words_screens_test.dart @@ -1,8 +1,8 @@ // Guard: the log-meal, history, calendar and settings screens paint no // words; only the logged food name (content), numbers and unit symbols. // -// Date/time pickers are framework chrome and are not opened here: they are a -// follow-up task (custom icon pickers), listed in the rework report. +// The date/time pickers are not opened here: pickers/no_words_pickers_test.dart +// opens each one through its call site. import 'dart:io'; diff --git a/app/test/pickers/date_dialog_test.dart b/app/test/pickers/date_dialog_test.dart new file mode 100644 index 0000000..d57815e --- /dev/null +++ b/app/test/pickers/date_dialog_test.dart @@ -0,0 +1,200 @@ +// The single-date dialog: grid state, confirm vs cancel, bounds, month and +// year navigation, keyboard and mouse, spoken labels. + +import 'package:diet_guard_app/widgets/pickers/date_dialog.dart'; +import 'package:diet_guard_app/widgets/pickers/date_selection.dart'; +import 'package:diet_guard_app/widgets/pickers/year_wheel.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/semantics.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../label_finders.dart'; +import 'picker_test_support.dart'; + +/// Tuesday 2026-03-10; March 2026 starts on a Sunday. +final _today = DateTime(2026, 3, 10); + +DateSelection _sel({DateTime? first, DateTime? last}) => DateSelection.single( + first: first ?? DateTime(2024), + last: last ?? DateTime(2027, 12, 31), + initial: _today, +); + +Future _open( + WidgetTester tester, + DateSelection sel, { + bool startOnYear = false, +}) => openDialog( + tester, + DateDialog(selection: sel, today: _today, startOnYear: startOnYear), +); + +void main() { + testWidgets('Monday first, no header: the 1st of March 2026 sits 7th', ( + tester, + ) async { + await _open(tester, _sel()); + final row = tester.getTopLeft(find.byKey(ValueKey(DateTime(2026, 3)))); + final mon = tester.getTopLeft(find.byKey(ValueKey(DateTime(2026, 3, 2)))); + expect(mon.dy, greaterThan(row.dy), reason: 'Monday 2nd starts row 2'); + expect(row.dx, greaterThan(mon.dx + 5 * 30), reason: 'Sunday is last'); + }); + + testWidgets('today is ringed, weekends dimmed with a dot', (tester) async { + await _open(tester, _sel()); + expect(cell(tester, _today).ring, isTrue); + expect(cell(tester, DateTime(2026, 3, 11)).ring, isFalse); + expect(cell(tester, DateTime(2026, 3, 14)).dot, isTrue, reason: 'Sat'); + expect(cell(tester, DateTime(2026, 3, 15)).dot, isTrue, reason: 'Sun'); + expect(cell(tester, DateTime(2026, 3, 16)).dot, isFalse); + }); + + testWidgets('a tap highlights; only the check confirms', (tester) async { + final popped = await _open(tester, _sel()); + await tester.tap(find.byKey(ValueKey(DateTime(2026, 3, 19)))); + await tester.pumpAndSettle(); + expect(popped.closed, isFalse); + expect(cell(tester, DateTime(2026, 3, 19)).selected, isTrue); + expect(cell(tester, _today).selected, isFalse); + await confirm(tester); + expect(popped.value, DateTime(2026, 3, 19)); + }); + + for (final how in ['close icon', 'outside tap', 'Esc']) { + testWidgets('$how cancels', (tester) async { + final popped = await _open(tester, _sel()); + await tester.tap(find.byKey(ValueKey(DateTime(2026, 3, 19)))); + await tester.pump(); + switch (how) { + case 'close icon': + await tester.tap(controlByLabel('Cancel')); + case 'outside tap': + await tester.tapAt(const Offset(4, 4)); + default: + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + } + await tester.pumpAndSettle(); + expect(popped.closed, isTrue); + expect(popped.value, isNull); + }); + } + + testWidgets('out-of-range days and months are dimmed and inert', ( + tester, + ) async { + final sel = _sel(first: DateTime(2026, 3, 5), last: DateTime(2026, 4, 20)); + await _open(tester, sel); + final early = DateTime(2026, 3, 4); + expect(cell(tester, early).enabled, isFalse); + await tester.tap(find.byKey(ValueKey(early))); + await tester.pump(); + expect(sel.start, _today); + expect(cell(tester, 'month-5').enabled, isFalse); + await tester.tap(find.byKey(const ValueKey('month-5'))); + await tester.pump(); + expect(sel.month, 3); + expect(cell(tester, 'month-4').enabled, isTrue); + }); + + testWidgets('a 31st moved to April lands on the 30th', (tester) async { + final sel = _sel(); + await _open(tester, sel); + await tester.tap(find.byKey(ValueKey(DateTime(2026, 3, 31)))); + await tester.pump(); + await tester.tap(find.byKey(const ValueKey('month-4'))); + await tester.pumpAndSettle(); + expect(cell(tester, DateTime(2026, 4, 30)).selected, isTrue); + await confirm(tester); + expect(sel.start, DateTime(2026, 4, 30)); + }); + + testWidgets('arrows move by a day and a week, Enter confirms', ( + tester, + ) async { + final popped = await _open(tester, _sel()); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect(cell(tester, DateTime(2026, 3, 18)).selected, isTrue); + expect(cell(tester, DateTime(2026, 3, 18)).focused, isTrue); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + expect(popped.value, DateTime(2026, 3, 10)); + }); + + testWidgets('a mouse click selects a day', (tester) async { + final sel = _sel(); + await _open(tester, sel); + await tester.tap( + find.byKey(ValueKey(DateTime(2026, 3, 3))), + kind: PointerDeviceKind.mouse, + ); + await tester.pump(); + expect(sel.start, DateTime(2026, 3, 3)); + }); + + testWidgets('the year wheel: mouse drag scrolls, a click selects, no wrap', ( + tester, + ) async { + final sel = _sel(); + await _open(tester, sel); + await tester.drag( + find.byType(YearWheel), + const Offset(0, -45), + kind: PointerDeviceKind.mouse, + ); + await tester.pumpAndSettle(); + expect(sel.year, 2027); + expect(sel.start, DateTime(2027, 3, 10)); + await tester.tap( + find.byKey(const ValueKey('wheel-2026')), + kind: PointerDeviceKind.mouse, + ); + await tester.pumpAndSettle(); + expect(sel.year, 2026); + await tester.drag(find.byType(YearWheel), const Offset(0, -400)); + await tester.pumpAndSettle(); + expect(sel.year, 2027, reason: 'the last year; the wheel does not loop'); + await tester.tap(find.byKey(const ValueKey('wheel-2028'))); + await tester.pumpAndSettle(); + expect(sel.year, 2027, reason: '2028 is past lastDate: dimmed, inert'); + await tester.drag(find.byType(YearWheel), const Offset(0, 400)); + await tester.pumpAndSettle(); + expect(sel.year, 2024, reason: 'the first year; no wrap to 2027'); + }); + + testWidgets('the birth-date flow opens on the year wheel', (tester) async { + final sel = _sel(); + await _open(tester, sel, startOnYear: true); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pumpAndSettle(); + expect(sel.year, 2025, reason: 'the arrow went to the wheel'); + expect(sel.start, DateTime(2025, 3, 10)); + }); + + testWidgets('icons and cells speak; nothing has a tooltip', (tester) async { + await _open(tester, _sel()); + expect(byIconLabel('Confirm'), findsOneWidget); + expect(byIconLabel('Cancel'), findsOneWidget); + expect(bySemLabel('Tuesday, March 10, 2026'), findsOneWidget); + expect(bySemLabel('Year'), findsOneWidget); + expect(find.byType(Tooltip), findsNothing); + }); + + testWidgets('a screen reader can tap an in-range day, not an inert one', ( + tester, + ) async { + final handle = tester.ensureSemantics(); + await _open(tester, _sel(first: DateTime(2026, 3, 5))); + SemanticsData day(int d) => tester + .getSemantics(find.byKey(ValueKey(DateTime(2026, 3, d)))) + .getSemanticsData(); + expect(day(12).hasAction(SemanticsAction.tap), isTrue); + expect(day(4).hasAction(SemanticsAction.tap), isFalse); + handle.dispose(); + }); +} diff --git a/app/test/pickers/date_range_dialog_test.dart b/app/test/pickers/date_range_dialog_test.dart new file mode 100644 index 0000000..a4b647a --- /dev/null +++ b/app/test/pickers/date_range_dialog_test.dart @@ -0,0 +1,123 @@ +// The range mode of the date dialog: two taps, shaded span, filled ends, +// the check gated on both taps, presets, restarts and navigation. + +import 'package:diet_guard_app/widgets/pickers/date_dialog.dart'; +import 'package:diet_guard_app/widgets/pickers/date_selection.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'picker_test_support.dart'; + +DateSelection _sel([DateTimeRange? initial]) => DateSelection.range( + first: DateTime(2026), + last: DateTime(2026, 12, 31), + initial: + initial ?? + DateTimeRange(start: DateTime(2026, 3, 10), end: DateTime(2026, 3, 10)), +); + +Future _open(WidgetTester tester, DateSelection sel) => + openDialog(tester, DateDialog(selection: sel, today: DateTime(2026, 3))); + +Future _tapDay(WidgetTester tester, int day) async { + await tester.tap(find.byKey(ValueKey(DateTime(2026, 3, day)))); + await tester.pump(); +} + +void main() { + testWidgets('two taps: check off after one, span shaded after two', ( + tester, + ) async { + final popped = await _open( + tester, + DateSelection.range(first: DateTime(2026), last: DateTime(2026, 12, 31)), + ); + expect(confirmButton(tester).onPressed, isNull); + await tester.tap(find.byKey(const ValueKey('month-3'))); + await tester.pump(); + await _tapDay(tester, 4); + expect(confirmButton(tester).onPressed, isNull, reason: 'one tap'); + expect(cell(tester, DateTime(2026, 3, 4)).selected, isTrue); + await _tapDay(tester, 9); + expect(confirmButton(tester).onPressed, isNotNull); + expect(cell(tester, DateTime(2026, 3, 9)).selected, isTrue, reason: 'cap'); + expect(cell(tester, DateTime(2026, 3, 6)).band, isTrue); + expect(cell(tester, DateTime(2026, 3, 6)).selected, isFalse); + expect(cell(tester, DateTime(2026, 3, 10)).band, isFalse); + await confirm(tester); + final range = popped.value! as DateTimeRange; + expect(range.start, DateTime(2026, 3, 4)); + expect(range.end, DateTime(2026, 3, 9)); + }); + + testWidgets('later day first still gives an ordered range', (tester) async { + final popped = await _open(tester, _sel()); + await _tapDay(tester, 20); + await _tapDay(tester, 12); + await confirm(tester); + final range = popped.value! as DateTimeRange; + expect((range.start.day, range.end.day), (12, 20)); + }); + + testWidgets('the same day twice is a valid one-day range', (tester) async { + final popped = await _open(tester, _sel()); + await _tapDay(tester, 5); + await _tapDay(tester, 5); + expect(cell(tester, DateTime(2026, 3, 5)).band, isFalse); + await confirm(tester); + final range = popped.value! as DateTimeRange; + expect(range.start, DateTime(2026, 3, 5)); + expect(range.end, DateTime(2026, 3, 5)); + }); + + testWidgets('a third tap restarts and turns the check off', (tester) async { + await _open(tester, _sel()); + await _tapDay(tester, 2); + await _tapDay(tester, 6); + await _tapDay(tester, 25); + expect(confirmButton(tester).onPressed, isNull); + expect(cell(tester, DateTime(2026, 3, 25)).selected, isTrue); + expect(cell(tester, DateTime(2026, 3, 4)).band, isFalse); + }); + + testWidgets('a preset range opens shaded with the check on', (tester) async { + final sel = _sel( + DateTimeRange(start: DateTime(2026, 3, 2), end: DateTime(2026, 3, 9)), + ); + await _open(tester, sel); + expect(confirmButton(tester).onPressed, isNotNull); + expect(cell(tester, DateTime(2026, 3, 5)).band, isTrue); + await tester.tap(find.byKey(const ValueKey('month-7'))); + await tester.pumpAndSettle(); + expect(sel.start, DateTime(2026, 3, 2)); + expect(sel.end, DateTime(2026, 3, 9)); + expect(confirmButton(tester).onPressed, isNotNull); + }); + + testWidgets('keyboard: arrows move the cursor, Space taps, Enter waits ' + 'for both ends', (tester) async { + final popped = await _open(tester, _sel()); + await _tapDay(tester, 10); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pump(); + expect(popped.closed, isFalse, reason: 'one end only'); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + await tester.sendKeyEvent(LogicalKeyboardKey.space); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + final range = popped.value! as DateTimeRange; + expect((range.start.day, range.end.day), (10, 12)); + }); + + testWidgets('Esc cancels a half-chosen range', (tester) async { + final popped = await _open(tester, _sel()); + await _tapDay(tester, 3); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pumpAndSettle(); + expect(popped.closed, isTrue); + expect(popped.value, isNull); + }); +} diff --git a/app/test/pickers/date_selection_test.dart b/app/test/pickers/date_selection_test.dart new file mode 100644 index 0000000..66afacd --- /dev/null +++ b/app/test/pickers/date_selection_test.dart @@ -0,0 +1,155 @@ +// The date picker's selection rules, as plain unit tests. + +import 'package:diet_guard_app/widgets/pickers/date_selection.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +final _first = DateTime(2026, 1, 15); +final _last = DateTime(2026, 6, 10); + +DateSelection _single(DateTime initial) => + DateSelection.single(first: _first, last: _last, initial: initial); + +DateSelection _range([DateTimeRange? initial]) => + DateSelection.range(first: _first, last: _last, initial: initial); + +void main() { + group('bounds', () { + test('an initial day outside the bounds is clamped in', () { + expect(_single(DateTime(2025, 12)).start, _first); + expect(_single(DateTime(2027)).start, _last); + final s = _single(DateTime(2027)); + expect((s.year, s.month), (2026, 6)); + }); + + test('a time of day is dropped from every date', () { + final s = DateSelection.single( + first: DateTime(2026, 1, 1, 13), + last: DateTime(2026, 2, 1, 23, 59), + initial: DateTime(2026, 1, 5, 18), + ); + expect(s.first, DateTime(2026)); + expect(s.last, DateTime(2026, 2)); + expect(s.start, DateTime(2026, 1, 5)); + }); + + test('out-of-range days are inert', () { + final s = _single(DateTime(2026, 3, 3))..tap(DateTime(2026, 1, 14)); + expect(s.start, DateTime(2026, 3, 3)); + }); + + test('a month is allowed when any of its days is in range', () { + final s = _single(DateTime(2026, 3, 3)); + expect(s.monthAllowed(2026, 1), isTrue); + expect(s.monthAllowed(2026, 6), isTrue); + expect(s.monthAllowed(2026, 7), isFalse); + expect(s.monthAllowed(2025, 12), isFalse); + }); + }); + + group('single', () { + test('a tap selects without confirming; the check is always on', () { + final s = _single(DateTime(2026, 3, 3))..tap(DateTime(2026, 3, 9)); + expect(s.start, DateTime(2026, 3, 9)); + expect(s.canConfirm, isTrue); + }); + + test('a 31st moved to a 30-day month lands on the 30th', () { + final s = _single(DateTime(2026, 3, 31))..showMonth(4); + expect(s.start, DateTime(2026, 4, 30)); + }); + + test('a month change clamps the day into the bounds', () { + final s = _single(DateTime(2026, 3, 20))..showMonth(6); + expect(s.start, _last); + s.showMonth(1); + expect(s.start, _first, reason: 'day 10 of January is before the 15th'); + }); + + test('a year change pulls the month into the edge year', () { + final s = DateSelection.single( + first: DateTime(2025, 9), + last: DateTime(2026, 3, 31), + initial: DateTime(2025, 11, 4), + )..showYear(2026); + expect((s.year, s.month), (2026, 3)); + expect(s.start, DateTime(2026, 3, 4)); + s.showYear(2025); + expect((s.year, s.month), (2025, 9)); + }); + + test('arrows move the selection, across months, stopping at bounds', () { + final s = _single(DateTime(2026, 1, 31))..moveCursor(1); + expect(s.start, DateTime(2026, 2)); + expect(s.month, 2); + s.moveCursor(-7); + expect(s.start, DateTime(2026, 1, 25)); + s + ..moveCursor(-7) + ..moveCursor(-7); + expect(s.start, DateTime(2026, 1, 18), reason: 'the 11th is out'); + }); + }); + + group('range', () { + test('one tap leaves the check off; two taps turn it on', () { + final s = _range()..tap(DateTime(2026, 3, 2)); + expect(s.canConfirm, isFalse); + s.tap(DateTime(2026, 3, 9)); + expect(s.canConfirm, isTrue); + expect(s.dateRange!.start, DateTime(2026, 3, 2)); + expect(s.dateRange!.end, DateTime(2026, 3, 9)); + }); + + test('a later day tapped first still gives an ordered range', () { + final s = _range() + ..tap(DateTime(2026, 3, 9)) + ..tap(DateTime(2026, 3, 2)); + expect(s.dateRange!.start, DateTime(2026, 3, 2)); + expect(s.dateRange!.end, DateTime(2026, 3, 9)); + }); + + test('the same day twice is a one-day range', () { + final s = _range() + ..tap(DateTime(2026, 3, 4)) + ..tap(DateTime(2026, 3, 4)); + expect(s.canConfirm, isTrue); + expect(s.dateRange!.duration, Duration.zero); + }); + + test('a third tap restarts from that day', () { + final s = _range() + ..tap(DateTime(2026, 3, 2)) + ..tap(DateTime(2026, 3, 9)) + ..tap(DateTime(2026, 4)); + expect(s.start, DateTime(2026, 4)); + expect(s.end, isNull); + expect(s.canConfirm, isFalse); + }); + + test('a preset range counts as both taps', () { + final s = _range( + DateTimeRange(start: DateTime(2026, 2, 2), end: DateTime(2026, 2, 8)), + ); + expect(s.canConfirm, isTrue); + expect((s.year, s.month), (2026, 2)); + }); + + test('navigating never moves the chosen ends', () { + final s = _range() + ..tap(DateTime(2026, 3, 31)) + ..tap(DateTime(2026, 4, 2)) + ..showMonth(2) + ..showYear(2026) + ..moveCursor(3); + expect(s.start, DateTime(2026, 3, 31)); + expect(s.end, DateTime(2026, 4, 2)); + }); + + test('with no preset the cursor starts on today, clamped', () { + final s = _range(); + expect(s.start, isNull); + expect(s.allows(s.cursor), isTrue); + }); + }); +} diff --git a/app/test/pickers/no_words_pickers_test.dart b/app/test/pickers/no_words_pickers_test.dart new file mode 100644 index 0000000..e159baa --- /dev/null +++ b/app/test/pickers/no_words_pickers_test.dart @@ -0,0 +1,183 @@ +// Guard: every date, date-range and time picker the app opens paints no +// words -- only numerals and punctuation. Each picker is opened through its +// real call site, so a call site that slips back to a framework picker (which +// paints "Select date", "Cancel", "OK") turns this red. + +import 'dart:io'; + +import 'package:diet_guard_app/screens/log_meal_screen.dart'; +import 'package:diet_guard_app/services/app_settings_service.dart'; +import 'package:diet_guard_app/services/budget_history_service.dart'; +import 'package:diet_guard_app/services/document_store_io.dart'; +import 'package:diet_guard_app/services/foodbank_service.dart'; +import 'package:diet_guard_app/services/log_storage_service.dart'; +import 'package:diet_guard_app/services/meal_schedule_service.dart'; +import 'package:diet_guard_app/widgets/body/dated_value_card.dart'; +import 'package:diet_guard_app/widgets/body/profile_card.dart'; +import 'package:diet_guard_app/widgets/history/history_filter.dart'; +import 'package:diet_guard_app/widgets/history/history_filter_sheet.dart'; +import 'package:diet_guard_app/widgets/meal_time_dropdown.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../label_finders.dart'; +import '../no_words_support.dart'; +import '../screens/body_screen_support.dart'; + +Future _host(WidgetTester tester, Widget child) async { + tester.view.physicalSize = const Size(800, 2400); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget(MaterialApp(home: Scaffold(body: child))); + await tester.pumpAndSettle(); +} + +/// Opens the picker behind [control] and asserts the open dialog paints at +/// least [minStrings] strings, none of them a word, and no tooltip. +Future _expectWordless( + WidgetTester tester, + Finder control, { + required int minStrings, + required String where, +}) async { + await tester.tap(control); + await tester.pumpAndSettle(); + expect(find.byType(Dialog), findsOneWidget, reason: '$where: no dialog'); + expectNoWords(tester, minStrings: minStrings, where: where); + expect( + find.descendant(of: find.byType(Dialog), matching: find.byType(Tooltip)), + findsNothing, + reason: '$where: a tooltip paints its words on long-press', + ); +} + +FilterSheet _sheet(DateTimeRange? range) => FilterSheet( + filter: HistoryFilter(dateRange: range), + sortField: HistorySortField.date, + ascending: false, + maxKcal: 1000, + maxProtein: 100, + maxCarbs: 100, + maxFat: 100, + onFilterChanged: (_) {}, + onSortChanged: ({required field, required asc}) {}, + onApply: () {}, + onClear: () {}, +); + +void main() { + testWidgets('meal-time exact picker', (tester) async { + await _host( + tester, + MealTimeDropdown( + icon: Icons.wb_sunny, + semanticLabel: 'First meal', + value: 480, + minMinute: 0, + maxMinute: 1424, + onChanged: (_) {}, + ), + ); + await _expectWordless( + tester, + byIconLabel('Type or pick an exact time'), + minStrings: 2, + where: 'time', + ); + }); + + for (final range in [ + null, + DateTimeRange(start: DateTime(2026, 3, 2), end: DateTime(2026, 3, 9)), + ]) { + testWidgets('history date-range picker (preset: ${range != null})', ( + tester, + ) async { + await _host(tester, _sheet(range)); + await _expectWordless( + tester, + find.byIcon(Icons.date_range), + minStrings: 28, + where: 'range', + ); + }); + } + + testWidgets('body dated-value day picker', (tester) async { + await _host( + tester, + DatedValueCard( + semanticLabel: 'Weight', + fieldSemanticLabel: 'Weight (kg)', + icon: Icons.monitor_weight, + unit: 'kg', + min: 20, + max: 400, + latest: null, + series: const [], + onSave: (_, _) async {}, + onDelete: (_) async {}, + onChanged: () {}, + ), + ); + await _expectWordless( + tester, + find.byIcon(Icons.event), + minStrings: 28, + where: 'dated value', + ); + }); + + testWidgets('profile birth-date picker', (tester) async { + final store = MemoryDocStore(); + await setUpBodyServices(store); + addTearDown(tearDownBodyServices); + await _host(tester, ProfileCard(onSaved: () {})); + await _expectWordless( + tester, + byIconLabel('Birth date'), + minStrings: 12, + where: 'birth', + ); + }); + + group('log meal', () { + late Directory dir; + setUp(() async { + dir = await Directory.systemTemp.createTemp('dg_pickers_'); + LogStorageService.resetForTesting(store: FileDocumentStore(dir)); + FoodBankService.resetForTesting(store: FileDocumentStore(dir)); + AppSettingsService.resetForTesting(store: FileDocumentStore(dir)); + BudgetHistoryService.resetForTesting(store: FileDocumentStore(dir)); + await MealScheduleService.initForTesting(FileDocumentStore(dir)); + }); + tearDown(() async { + LogStorageService.resetForTesting(); + FoodBankService.resetForTesting(); + AppSettingsService.resetForTesting(); + BudgetHistoryService.resetForTesting(); + MealScheduleService.resetForTesting(); + await dir.delete(recursive: true); + }); + _logLater(); + }); +} + +void _logLater() { + testWidgets('log-for-later date picker', (tester) async { + tester.view.physicalSize = const Size(800, 2400); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.runAsync(() async { + await tester.pumpWidget(const MaterialApp(home: LogMealScreen())); + await Future.delayed(const Duration(milliseconds: 200)); + await tester.pumpAndSettle(); + }); + await _expectWordless( + tester, + controlByLabel('Log for later'), + minStrings: 28, + where: 'log later', + ); + }); +} diff --git a/app/test/pickers/picker_call_sites_test.dart b/app/test/pickers/picker_call_sites_test.dart new file mode 100644 index 0000000..1aef1f8 --- /dev/null +++ b/app/test/pickers/picker_call_sites_test.dart @@ -0,0 +1,73 @@ +// The Body screen's two date controls apply what their picker confirms: +// the dated-value card's day, and the profile's birth date (whose picker +// opens with the year wheel focused). + +import 'package:diet_guard_app/models/local_time.dart'; +import 'package:diet_guard_app/widgets/body/dated_value_card.dart'; +import 'package:diet_guard_app/widgets/body/profile_card.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../label_finders.dart'; +import '../screens/body_screen_support.dart'; + +Future _host(WidgetTester tester, Widget child) async { + tester.view.physicalSize = const Size(800, 1600); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget(MaterialApp(home: Scaffold(body: child))); + await tester.pumpAndSettle(); +} + +Future _pressAndSettle( + WidgetTester tester, + LogicalKeyboardKey key, +) async { + await tester.sendKeyEvent(key); + await tester.pumpAndSettle(); +} + +void main() { + testWidgets('the dated-value card shows the confirmed day', (tester) async { + await _host( + tester, + DatedValueCard( + semanticLabel: 'Weight', + fieldSemanticLabel: 'Weight (kg)', + icon: Icons.monitor_weight, + unit: 'kg', + min: 20, + max: 400, + latest: null, + series: const [], + onSave: (_, _) async {}, + onDelete: (_) async {}, + onChanged: () {}, + ), + ); + final now = DateTime.now(); + final yesterday = localDateKey(DateTime(now.year, now.month, now.day - 1)); + await tester.tap(find.byIcon(Icons.event)); + await tester.pumpAndSettle(); + await _pressAndSettle(tester, LogicalKeyboardKey.arrowLeft); + await _pressAndSettle(tester, LogicalKeyboardKey.enter); + expect(find.byType(Dialog), findsNothing); + expect(find.text(' $yesterday'), findsOneWidget); + }); + + testWidgets('the birth date opens on the year wheel and applies', ( + tester, + ) async { + await setUpBodyServices(MemoryDocStore()); + addTearDown(tearDownBodyServices); + await _host(tester, ProfileCard(onSaved: () {})); + final year = DateTime.now().year - 31; + await tester.tap(byIconLabel('Birth date')); + await tester.pumpAndSettle(); + await _pressAndSettle(tester, LogicalKeyboardKey.arrowUp); + await _pressAndSettle(tester, LogicalKeyboardKey.enter); + expect(find.byType(Dialog), findsNothing); + expect(find.text(' $year-01-01'), findsOneWidget); + }); +} diff --git a/app/test/pickers/picker_test_support.dart b/app/test/pickers/picker_test_support.dart new file mode 100644 index 0000000..aa5f2bc --- /dev/null +++ b/app/test/pickers/picker_test_support.dart @@ -0,0 +1,84 @@ +// Shared helpers for the picker widget tests: open a dialog from a button and +// read back what it popped, and find cells by state rather than by text. + +import 'package:diet_guard_app/widgets/pickers/numeral_cell.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../label_finders.dart'; + +/// What a dialog popped: [closed] turns true once it is gone. +class Popped { + /// The popped value (null when cancelled). + Object? value; + + /// Whether the dialog has closed. + bool closed = false; +} + +/// Pumps an app whose one button opens [dialog]; taps it and settles. +Future openDialog( + WidgetTester tester, + Widget dialog, { + Size size = const Size(500, 900), +}) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final popped = Popped(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Builder( + builder: (context) => IconButton( + icon: const Icon(Icons.add, semanticLabel: 'open'), + onPressed: () async { + popped + ..value = await showDialog( + context: context, + builder: (_) => dialog, + ) + ..closed = true; + }, + ), + ), + ), + ), + ); + await tester.tap(byIconLabel('open')); + await tester.pumpAndSettle(); + return popped; +} + +/// The cell keyed [key] (a `DateTime` day, or `'month-'`). +NumeralCell cell(WidgetTester tester, Object key) => tester.widget( + find.byKey( + key is DateTime ? ValueKey(key) : ValueKey('$key'), + ), +); + +/// The check button, enabled or not. +IconButton confirmButton(WidgetTester tester) => tester.widget( + find.ancestor(of: byIconLabel('Confirm'), matching: find.byType(IconButton)), +); + +/// Scrolls the open time dialog's wheels to [hour] and [minute] (a disabled +/// value springs back) and settles. Does not confirm. +Future setWheels(WidgetTester tester, int hour, int minute) async { + for (final (key, value) in [('hour', hour), ('minute', minute)]) { + final wheel = tester.widget( + find.descendant( + of: find.byKey(ValueKey(key)), + matching: find.byType(ListWheelScrollView), + ), + ); + (wheel.controller! as FixedExtentScrollController).jumpToItem(value); + await tester.pumpAndSettle(); + } +} + +/// Taps the check and settles. +Future confirm(WidgetTester tester) async { + await tester.tap(controlByLabel('Confirm')); + await tester.pumpAndSettle(); +} diff --git a/app/test/pickers/time_dialog_test.dart b/app/test/pickers/time_dialog_test.dart new file mode 100644 index 0000000..0f2864d --- /dev/null +++ b/app/test/pickers/time_dialog_test.dart @@ -0,0 +1,156 @@ +// The time dialog: two looping 24 h wheels, bounds dimmed and inert, +// keyboard, mouse, confirm vs cancel. + +import 'package:diet_guard_app/widgets/pickers/time_dialog.dart'; +import 'package:diet_guard_app/widgets/pickers/time_wheels.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../label_finders.dart'; +import 'picker_test_support.dart'; + +Future _open( + WidgetTester tester, { + int initial = 8 * 60, + int min = 0, + int max = 1439, +}) => openDialog( + tester, + TimeDialog(initialMinute: initial, minMinute: min, maxMinute: max), +); + +Finder _wheel(String which) => find.byKey(ValueKey(which)); + +/// Moves keyboard focus to the minute wheel (the hour wheel has it first). +Future _focusMinutes(WidgetTester tester) async { + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.pump(); +} + +TimeOfDay _value(Popped p) => p.value! as TimeOfDay; + +void main() { + test('hourAllowed and clampMinute', () { + expect(hourAllowed(7, 480, 1200), isFalse); + expect(hourAllowed(8, 495, 1200), isTrue); + expect(hourAllowed(20, 480, 1200), isTrue); + expect(hourAllowed(21, 480, 1200), isFalse); + expect(clampMinute(10, 480, 1200), 480); + expect(clampMinute(1300, 480, 1200), 1200); + }); + + testWidgets('wheels show 24 h numerals and confirm the centre', ( + tester, + ) async { + final popped = await _open(tester, initial: 13 * 60 + 5); + expect(find.byKey(const ValueKey('wheel-13')), findsWidgets); + expect(find.text('13'), findsWidgets); + expect(find.text('05'), findsWidgets); + await confirm(tester); + expect(_value(popped), const TimeOfDay(hour: 13, minute: 5)); + }); + + testWidgets('arrows loop: hour 23 -> 00, minute 59 -> 00', (tester) async { + final popped = await _open(tester, initial: 23 * 60 + 59); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pumpAndSettle(); + await _focusMinutes(tester); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pumpAndSettle(); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + expect(_value(popped), const TimeOfDay(hour: 0, minute: 0)); + }); + + testWidgets('mouse drag scrolls a wheel; a click selects a number', ( + tester, + ) async { + final popped = await _open(tester, initial: 10 * 60); + await tester.drag( + _wheel('hour'), + const Offset(0, -85), + kind: PointerDeviceKind.mouse, + ); + await tester.pumpAndSettle(); + await tester.tap( + find.byKey(const ValueKey('wheel-58')), + kind: PointerDeviceKind.mouse, + ); + await tester.pumpAndSettle(); + await confirm(tester); + expect(_value(popped), const TimeOfDay(hour: 12, minute: 58)); + }); + + testWidgets('out-of-range values are inert; an hour change clamps the ' + 'minute into range', (tester) async { + final popped = await _open(tester, initial: 9 * 60 + 5, min: 8 * 60 + 15); + // 07 is dimmed: a tap does nothing. + await tester.tap(find.byKey(const ValueKey('wheel-7')).first); + await tester.pumpAndSettle(); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pumpAndSettle(); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pumpAndSettle(); + await confirm(tester); + expect( + _value(popped), + const TimeOfDay(hour: 8, minute: 15), + reason: '09:05 -> 08 pulls :05 up to :15; 07 refused', + ); + }); + + testWidgets('a wheel dragged onto a dimmed value springs back', ( + tester, + ) async { + final popped = await _open(tester, initial: 20 * 60, max: 20 * 60); + await tester.drag(_wheel('hour'), const Offset(0, -85)); + await tester.pumpAndSettle(); + await confirm(tester); + expect(_value(popped), const TimeOfDay(hour: 20, minute: 0)); + }); + + testWidgets('an initial value outside the range opens clamped', ( + tester, + ) async { + final popped = await _open(tester, initial: 6 * 60, min: 8 * 60 + 15); + await confirm(tester); + expect(_value(popped), const TimeOfDay(hour: 8, minute: 15)); + }); + + for (final how in ['close icon', 'outside tap', 'Esc']) { + testWidgets('$how cancels', (tester) async { + final popped = await _open(tester); + switch (how) { + case 'close icon': + await tester.tap(controlByLabel('Cancel')); + case 'outside tap': + await tester.tapAt(const Offset(4, 4)); + default: + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + } + await tester.pumpAndSettle(); + expect(popped.closed, isTrue); + expect(popped.value, isNull); + }); + } + + testWidgets('Enter on the focused close icon cancels', (tester) async { + final popped = await _open(tester); + await _focusMinutes(tester); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + expect(popped.closed, isTrue); + expect(popped.value, isNull); + }); + + testWidgets('wheels speak; no tooltip', (tester) async { + await _open(tester); + expect(bySemLabel('Hour'), findsOneWidget); + expect(bySemLabel('Minute'), findsOneWidget); + expect(find.byType(Tooltip), findsNothing); + }); +} diff --git a/app/test/repo_invariants_test.dart b/app/test/repo_invariants_test.dart index 37e80f0..ae8365f 100644 --- a/app/test/repo_invariants_test.dart +++ b/app/test/repo_invariants_test.dart @@ -125,6 +125,25 @@ void main() { }); }); + group('pickers paint no words', () { + // The framework pickers paint "Select date", "Cancel", "OK", weekday and + // month names and tooltips; lib/widgets/pickers/ replaces all three. + test('no showDatePicker, showDateRangePicker or showTimePicker', () { + final banned = RegExp(r'show(Date|DateRange|Time)Picker\('); + final offenders = [ + for (final file in _dartFilesIn('lib')) + if (banned.hasMatch(file.readAsStringSync())) + file.path.split('/app/lib/').last, + ]; + expect( + offenders, + isEmpty, + reason: 'A framework picker came back. Use pickDate, pickDateRange ' + 'or pickTime from widgets/pickers/pickers.dart.', + ); + }); + }); + group('singletons that silently no-op are initialised at startup', () { // Every catering entry point checks `isInitialized` first and returns // quietly when it is false, so a missing `init()` does not throw -- it diff --git a/app/test/screens/history/history_filter_source_test.dart b/app/test/screens/history/history_filter_source_test.dart index 2d0a30a..87d8b54 100644 --- a/app/test/screens/history/history_filter_source_test.dart +++ b/app/test/screens/history/history_filter_source_test.dart @@ -163,19 +163,20 @@ void main() { await tester.tap(controlByLabel('Date range')); await settle(tester); - // The picker opens on the current month (no `currentDate` override - // and a null `initialDateRange`) and its `lastDate` is capped at - // tomorrow, so days "10"+ aren't always selectable this early in a - // month. Days "1" and "2" of the displayed month are always within - // [firstDate, lastDate] regardless of which day it is when the test - // runs. + // The picker opens on the current month (a null `initialDateRange`) + // and its `lastDate` is capped at tomorrow, so days 10+ aren't always + // selectable this early in a month. Days 1 and 2 of the displayed + // month are always within [firstDate, lastDate] regardless of which + // day it is when the test runs. final now = DateTime.now(); final expectedStart = DateTime(now.year, now.month); - await tester.tap(find.text('1').last); + await tester.tap(find.byKey(ValueKey(expectedStart))); await settle(tester); - await tester.tap(find.text('2').last); + await tester.tap( + find.byKey(ValueKey(DateTime(now.year, now.month, 2))), + ); await settle(tester); - await tester.tap(find.text('Save')); + await tester.tap(controlByLabel('Confirm')); await settle(tester); // After a successful selection the filter button label shows the diff --git a/app/test/screens/log_meal_screen_future_test.dart b/app/test/screens/log_meal_screen_future_test.dart index bb1a6df..cd62f7c 100644 --- a/app/test/screens/log_meal_screen_future_test.dart +++ b/app/test/screens/log_meal_screen_future_test.dart @@ -64,7 +64,7 @@ void main() { await settle(tester); // The date picker's initialDate is already tomorrow, so confirming // immediately picks it without touching a specific calendar cell. - await tester.tap(find.text('OK')); + await tester.tap(controlByLabel('Confirm')); await settle(tester); final tomorrowKey = localDateKey(tomorrow()); @@ -106,7 +106,7 @@ void main() { await tester.tap(controlByLabel('Log for later')); await settle(tester); - await tester.tap(find.text('OK')); + await tester.tap(controlByLabel('Confirm')); await settle(tester); await tester.enterText(find.byType(TextField).at(0), 'no slot meal'); @@ -131,7 +131,7 @@ void main() { await tester.tap(controlByLabel('Log for later')); await settle(tester); - await tester.tap(find.text('OK')); + await tester.tap(controlByLabel('Confirm')); await settle(tester); expect(find.text(localDateKey(tomorrow())), findsOneWidget); diff --git a/app/test/screens/settings_screen_test.dart b/app/test/screens/settings_screen_test.dart index 7845f06..c9734a7 100644 --- a/app/test/screens/settings_screen_test.dart +++ b/app/test/screens/settings_screen_test.dart @@ -17,6 +17,7 @@ import 'package:shared_preferences/shared_preferences.dart'; import '../fake_secure_storage.dart'; import '../label_finders.dart'; +import '../pickers/picker_test_support.dart'; void main() { late Directory tempDir; @@ -88,15 +89,8 @@ void main() { await tester.tap(byIconLabel('Type or pick an exact time').first); await settle(tester); - await tester.tap(find.byIcon(Icons.keyboard_outlined)); - await settle(tester); - final fields = find.descendant( - of: find.byType(TimePickerDialog), - matching: find.byType(TextField), - ); - await tester.enterText(fields.at(0), '07'); - await tester.enterText(fields.at(1), '23'); - await tester.tap(find.text('OK')); + await setWheels(tester, 7, 23); + await tester.tap(controlByLabel('Confirm')); await settle(tester); // Through the real _applySchedule: normalised, recorded, persisted. diff --git a/app/test/widgets/meal_schedule_editor_test.dart b/app/test/widgets/meal_schedule_editor_test.dart index 0fb14c1..57de70e 100644 --- a/app/test/widgets/meal_schedule_editor_test.dart +++ b/app/test/widgets/meal_schedule_editor_test.dart @@ -1,10 +1,12 @@ import 'package:diet_guard_app/models/meal_schedule.dart'; import 'package:diet_guard_app/widgets/meal_schedule_editor.dart'; import 'package:diet_guard_app/widgets/meal_time_dropdown.dart'; +import 'package:diet_guard_app/widgets/pickers/time_dialog.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import '../label_finders.dart'; +import '../pickers/picker_test_support.dart'; /// Holds the schedule the way `_SettingsMealSchedule` does: every edit is /// normalised and fed back, so the preview reflects what would be saved. @@ -66,13 +68,13 @@ void main() { await tester.pumpAndSettle(); } - /// Taps [label]'s clock button and types [hh]:[mm] in the time picker's - /// keyboard mode. + /// Taps [label]'s clock button, scrolls the time picker's wheels to + /// [hh]:[mm] and confirms. Future pickExact( WidgetTester tester, String label, - String hh, - String mm, + int hh, + int mm, ) async { await tester.tap( find.descendant( @@ -83,17 +85,9 @@ void main() { ), ); await tester.pumpAndSettle(); - expect(find.byType(TimePickerDialog), findsOneWidget); - await tester.tap(find.byIcon(Icons.keyboard_outlined)); - await tester.pumpAndSettle(); - final fields = find.descendant( - of: find.byType(TimePickerDialog), - matching: find.byType(TextField), - ); - await tester.enterText(fields.at(0), hh); - await tester.enterText(fields.at(1), mm); - await tester.tap(find.text('OK')); - await tester.pumpAndSettle(); + expect(find.byType(TimeDialog), findsOneWidget); + await setWheels(tester, hh, mm); + await confirm(tester); } testWidgets('an off-grid value from another device renders', (tester) async { @@ -134,7 +128,7 @@ void main() { ) async { await pump(tester, _fiveMeals); - await pickExact(tester, 'First meal', '07', '23'); + await pickExact(tester, 'First meal', 7, 23); expect(edits.last.firstMinute, 443); expect(edits.last.lastMinute, 1200); @@ -159,12 +153,15 @@ void main() { expect(find.text('Custom…'), findsNothing); }); - testWidgets('an exact last meal before the first is clamped', (tester) async { + testWidgets('a last meal before the first cannot be picked', (tester) async { await pump(tester, _fiveMeals); - await pickExact(tester, 'Last meal', '06', '00'); + // The last meal's range starts 08:15, one grid step after the first. + // 06 is dimmed, so the hour wheel springs to 08, the nearest allowed + // hour, and :00 to :15: the picker never offers an illegal time, so + // nothing is clamped after the fact. + await pickExact(tester, 'Last meal', 6, 0); - // One grid step after 08:00: the shortest legal window, not a rejection. expect(edits.last.lastMinute, 495); }); diff --git a/docs/DOCS-textgate-keep.md b/docs/DOCS-textgate-keep.md index a405c95..d02a63e 100644 --- a/docs/DOCS-textgate-keep.md +++ b/docs/DOCS-textgate-keep.md @@ -49,8 +49,11 @@ Chrome window answer errors with a status code and an empty body. - Formula proper names painted outside the activity sheet: `app/lib/widgets/body/body_stats_cards.dart`, `goal_card.dart` (BMI Prime, Trefethen, ideal-weight and resting-burn formula names). The Tk gate dropped them. - Workout names (`session.label`, `session.kind`) are PC-published content. -## Framework pickers (not reworked; follow-up task filed) +## Framework pickers (replaced 2026-11-10) -`showDatePicker`, `showDateRangePicker`, `showTimePicker` paint Select date, -Cancel, OK, Save: `log_meal_future_mixin.dart`, `history_filter_sheet.dart`, -`dated_value_card.dart`, `meal_time_dropdown.dart`, `profile_card.dart`. +`showDatePicker`, `showDateRangePicker` and `showTimePicker` painted Select +date, Cancel, OK, Save. All five call sites now use the icon-only +`app/lib/widgets/pickers/` (numerals, check and close icons), guarded by +`app/test/pickers/no_words_pickers_test.dart` and a `repo_invariants_test` +ban. Lost on purpose: the weekday header (Monday-first layout plus a weekend +dot instead), month names (numerals 1-12) and both text-entry modes.