Line data Source code
1 : import 'dart:async';
2 : import 'dart:math' as math;
3 :
4 : import 'package:flutter/services.dart';
5 : import 'package:flutter/widgets.dart';
6 : import 'package:fossui/src/components/button/foss_button.dart';
7 : import 'package:fossui/src/components/dialog/foss_dialog.dart';
8 : import 'package:fossui/src/foundation/foss_dialog_surface.dart'
9 : show FossDialogPresentation;
10 : import 'package:fossui/src/foundation/foss_field_box.dart';
11 : import 'package:fossui/src/foundation/foss_since.dart';
12 : import 'package:fossui/src/icons/foss_glyph.dart';
13 : import 'package:fossui/src/theme/theme.dart';
14 :
15 : part 'foss_time_picker_style.dart';
16 :
17 : const double _glyphSize = 16;
18 : const double _triggerMinHeight = 36;
19 : const double _darkFillOpacity = 0.32;
20 :
21 : /// One wheel row, matched to the trigger height so the field and the sheet
22 : /// share one rhythm.
23 : const double _itemExtent = 36;
24 : const int _visibleItemCount = 5;
25 :
26 : /// Off-centre rows that cannot be picked fade to half their resting alpha, on
27 : /// top of the wheel's own distance fade.
28 : const double _blockedOpacity = 0.5;
29 :
30 : /// How much a wheel dims its off-centre rows.
31 : const double _overAndUnderOpacity = 0.45;
32 :
33 : const double _wheelDiameterRatio = 1.6;
34 :
35 : /// Width of one wheel column as a multiple of the row height. Sets how far
36 : /// apart the values read; the cluster is centred, so the slack goes to the
37 : /// margins rather than between the columns.
38 : const double _columnWidthFactor = 1.75;
39 :
40 : const int _minutesPerHour = 60;
41 : const int _minutesPerDay = 24 * _minutesPerHour;
42 :
43 : /// A wall-clock time of day, with no date and no time zone.
44 : ///
45 : /// Stored on a 24-hour clock, so a 12-hour reading is purely a formatting
46 : /// concern. Values are ordered by [compareTo], which makes bounds checks and
47 : /// sorting one call.
48 : ///
49 : /// ```dart
50 : /// const opening = FossTimeOfDay(hour: 9, minute: 30);
51 : /// const closing = FossTimeOfDay(hour: 17, minute: 0);
52 : /// final isOpen = opening.compareTo(closing) < 0;
53 : /// ```
54 : @FossSince('0.1.2')
55 : @immutable
56 : class FossTimeOfDay implements Comparable<FossTimeOfDay> {
57 : /// Creates a time of day. [hour] is 0 to 23 and [minute] is 0 to 59.
58 3 : const FossTimeOfDay({required this.hour, required this.minute})
59 9 : : assert(hour >= 0 && hour <= 23, 'hour must be 0 to 23.'),
60 9 : assert(minute >= 0 && minute <= 59, 'minute must be 0 to 59.');
61 :
62 : /// Hour on a 24-hour clock, 0 to 23.
63 : final int hour;
64 :
65 : /// Minute past the hour, 0 to 59.
66 : final int minute;
67 :
68 : /// Minutes elapsed since midnight, 0 to 1439.
69 5 : int get _sinceMidnight => hour * _minutesPerHour + minute;
70 :
71 : /// Orders two times by their position in the day: negative when this one is
72 : /// earlier, zero when they match, positive when it is later.
73 1 : @override
74 : int compareTo(FossTimeOfDay other) =>
75 3 : _sinceMidnight.compareTo(other._sinceMidnight);
76 :
77 1 : @override
78 : bool operator ==(Object other) =>
79 : identical(this, other) ||
80 7 : other is FossTimeOfDay && other.hour == hour && other.minute == minute;
81 :
82 1 : @override
83 3 : int get hashCode => Object.hash(hour, minute);
84 :
85 1 : @override
86 3 : String toString() => 'FossTimeOfDay($hour:$minute)';
87 : }
88 :
89 : /// Builds a time from [minutes] since midnight, which must be within the day.
90 2 : FossTimeOfDay _fromMinutes(int minutes) => FossTimeOfDay(
91 1 : hour: minutes ~/ _minutesPerHour,
92 1 : minute: minutes % _minutesPerHour,
93 : );
94 :
95 : /// The built-in 24-hour label, as in `21:30`.
96 1 : String _format24(FossTimeOfDay time) =>
97 5 : '${_pad2(time.hour)}:${_pad2(time.minute)}';
98 :
99 : /// The built-in 12-hour label, as in `9:30 AM`. Midnight and noon read as 12.
100 1 : String _format12(FossTimeOfDay time) {
101 5 : final hour = time.hour % 12 == 0 ? 12 : time.hour % 12;
102 5 : return '$hour:${_pad2(time.minute)} ${time.hour < 12 ? 'AM' : 'PM'}';
103 : }
104 :
105 3 : String _pad2(int value) => value.toString().padLeft(2, '0');
106 :
107 : /// The bounds a picker applies to a candidate time: the inclusive range plus
108 : /// the caller's arbitrary predicate. Grouped so the trigger, the modal, and the
109 : /// opening-position scan all test a time the same way.
110 : @immutable
111 : class _TimeBounds {
112 1 : const _TimeBounds({this.min, this.max, this.isEnabled});
113 :
114 : final FossTimeOfDay? min;
115 : final FossTimeOfDay? max;
116 : final bool Function(FossTimeOfDay)? isEnabled;
117 :
118 : /// Whether any bound is in play. An unbounded picker loops its wheels.
119 4 : bool get isBounded => min != null || max != null || isEnabled != null;
120 :
121 1 : bool allows(FossTimeOfDay time) {
122 3 : if (min case final min? when time.compareTo(min) < 0) return false;
123 3 : if (max case final max? when time.compareTo(max) > 0) return false;
124 2 : return isEnabled?.call(time) ?? true;
125 : }
126 :
127 : /// The earliest time on the [step] grid at or after [min] that [allows]
128 : /// accepts, or the start of the scan when the whole day is blocked. Used to
129 : /// park the wheels when the picker opens with no value.
130 1 : FossTimeOfDay firstAllowed(int step) {
131 1 : final start = min ?? const FossTimeOfDay(hour: 0, minute: 0);
132 1 : final from = start._sinceMidnight;
133 : for (
134 4 : var minutes = ((from + step - 1) ~/ step) * step;
135 1 : minutes < _minutesPerDay;
136 1 : minutes += step
137 : ) {
138 1 : final candidate = _fromMinutes(minutes);
139 1 : if (allows(candidate)) return candidate;
140 : }
141 : return start;
142 : }
143 : }
144 :
145 : /// {@category Inputs}
146 : /// {@template foss.time_picker.preview}
147 : /// <img src="https://fossui.org/components/time-picker/overview/light.png"
148 : /// alt="FossTimePicker, light theme" width="480"
149 : /// style="max-width:100%;height:auto" />
150 : /// <img src="https://fossui.org/components/time-picker/overview/dark.png"
151 : /// alt="FossTimePicker, dark theme" width="480"
152 : /// style="max-width:100%;height:auto" />
153 : ///
154 : /// See the [time picker documentation ↗](https://fossui.org/docs/components/time-picker)
155 : /// or try it live in the
156 : /// [playground ↗](https://play.fossui.org/components/#/?path=components/time_picker/fosstimepicker/playground).
157 : /// {@endtemplate}
158 : ///
159 : /// A time field that opens scrolling wheels in a modal dialog and shows the
160 : /// chosen time back in its trigger.
161 : ///
162 : /// The trigger is a full-width field with a leading clock glyph and the
163 : /// formatted time, or a [placeholder] while empty. Tapping it (or pressing
164 : /// Enter, Space, or the down arrow) opens the wheels as a modal, presented as a
165 : /// bottom sheet by default or a centered card via [presentation]. Drive the
166 : /// open state yourself with [open] plus [onOpenChange], or leave it
167 : /// uncontrolled.
168 : ///
169 : /// Where a wheel stops scrolling is not the same as a choice, so the modal
170 : /// keeps a draft and commits on the footer: [confirmLabel] reports through
171 : /// [onChanged] and closes, while [cancelLabel] and the barrier discard. Bound
172 : /// the selectable range with [minTime], [maxTime], and [isTimeEnabled]. A
173 : /// blocked time stays on the wheel rather than leaving a hole in it, dimmed,
174 : /// and the confirm action is disabled while the draft sits on one.
175 : /// [minuteStep] coarsens the minute column, and [use24HourFormat] swaps the
176 : /// period column for a 24-hour reading.
177 : ///
178 : /// Colors, type, and metrics come from `context.fossTheme`; pass a
179 : /// [FossTimePickerStyle] to [style] for a one-off.
180 : ///
181 : /// {@macro foss.customize}
182 : ///
183 : /// See also [FossTimeOfDay] for the value type.
184 : ///
185 : /// ```dart
186 : /// FossTimePicker(
187 : /// value: picked,
188 : /// onChanged: (time) => setState(() => picked = time),
189 : /// );
190 : /// ```
191 : @FossSince('0.1.2')
192 : class FossTimePicker extends StatefulWidget {
193 : /// {@macro foss.time_picker.preview}
194 : ///
195 : /// Creates a time picker. [value] is the committed time (null shows the
196 : /// [placeholder]) and [onChanged] fires when the footer confirms.
197 : ///
198 : /// ```dart
199 : /// FossTimePicker(
200 : /// value: picked,
201 : /// onChanged: (time) => setState(() => picked = time),
202 : /// minuteStep: 15,
203 : /// );
204 : /// ```
205 1 : const FossTimePicker({
206 : required this.value,
207 : required this.onChanged,
208 : this.placeholder = 'Pick a time',
209 : this.format,
210 : this.use24HourFormat,
211 : this.minuteStep = 1,
212 : this.minTime,
213 : this.maxTime,
214 : this.isTimeEnabled,
215 : this.open,
216 : this.onOpenChange,
217 : this.presentation = FossDialogPresentation.bottomSheet,
218 : this.confirmLabel = 'Set',
219 : this.cancelLabel = 'Cancel',
220 : this.enabled = true,
221 : this.semanticsLabel,
222 : this.style,
223 : super.key,
224 : }) : assert(
225 5 : minuteStep >= 1 && minuteStep <= 60 && 60 % minuteStep == 0,
226 : 'minuteStep must divide 60 evenly.',
227 : );
228 :
229 : /// The committed time, or null for none.
230 : final FossTimeOfDay? value;
231 :
232 : /// Called with the draft when the footer confirms. Never fires on a scroll.
233 : final ValueChanged<FossTimeOfDay> onChanged;
234 :
235 : /// Shown in the trigger while nothing is selected, and used as the modal
236 : /// title.
237 : final String placeholder;
238 :
239 : /// Overrides the built-in trigger label, which is `9:30 AM` or `21:30`
240 : /// depending on the resolved hour format.
241 : final String Function(FossTimeOfDay)? format;
242 :
243 : /// Whether to read and pick on a 24-hour clock, which drops the period
244 : /// column. Null follows the platform setting through `MediaQuery`, falling
245 : /// back to 12-hour.
246 : final bool? use24HourFormat;
247 :
248 : /// The minute increment the wheel offers. Must divide 60 evenly; defaults to
249 : /// 1. An incoming [value] off the grid shows as-is and snaps on the first
250 : /// minute scroll.
251 : final int minuteStep;
252 :
253 : /// The earliest selectable time, inclusive.
254 : final FossTimeOfDay? minTime;
255 :
256 : /// The latest selectable time, inclusive.
257 : final FossTimeOfDay? maxTime;
258 :
259 : /// Blocks individual times on top of [minTime] and [maxTime]. Returning false
260 : /// dims the entry and disables the confirm action while the draft rests on
261 : /// it.
262 : final bool Function(FossTimeOfDay)? isTimeEnabled;
263 :
264 : /// The controlled open state. Non-null puts the dialog in controlled mode:
265 : /// pair it with [onOpenChange] and rebuild on change. Null is uncontrolled.
266 : final bool? open;
267 :
268 : /// Called with the requested open state on every open or close, including
269 : /// dismissals. Required to observe changes in controlled mode.
270 : final ValueChanged<bool>? onOpenChange;
271 :
272 : /// How the modal presents: a bottom sheet (default) or a centered card.
273 : final FossDialogPresentation presentation;
274 :
275 : /// Label of the footer action that commits the draft.
276 : final String confirmLabel;
277 :
278 : /// Label of the footer action that discards the draft.
279 : final String cancelLabel;
280 :
281 : /// Whether the trigger accepts input. When false it dims and never opens.
282 : final bool enabled;
283 :
284 : /// Accessibility name for the trigger.
285 : final String? semanticsLabel;
286 :
287 : /// Per-instance overrides layered on the theme-resolved style.
288 : final FossTimePickerStyle? style;
289 :
290 1 : @override
291 1 : State<FossTimePicker> createState() => _FossTimePickerState();
292 : }
293 :
294 : class _FossTimePickerState extends State<FossTimePicker> {
295 : final FocusNode _triggerFocus = FocusNode(
296 : debugLabel: 'FossTimePicker trigger',
297 : );
298 :
299 : bool _open = false;
300 : bool _focused = false;
301 :
302 : // Whether the modal route is currently on the navigator. Guards double push
303 : // and reconciles the open state when the route closes on its own (barrier,
304 : // system back).
305 : bool _routeShowing = false;
306 :
307 4 : bool get _isOpen => widget.open ?? _open;
308 :
309 2 : _TimeBounds get _bounds => _TimeBounds(
310 2 : min: widget.minTime,
311 2 : max: widget.maxTime,
312 2 : isEnabled: widget.isTimeEnabled,
313 : );
314 :
315 1 : @override
316 : void initState() {
317 1 : super.initState();
318 2 : if (widget.open ?? false) {
319 3 : WidgetsBinding.instance.addPostFrameCallback((_) {
320 3 : if (mounted && _isOpen) _showDialog();
321 : });
322 : }
323 : }
324 :
325 1 : @override
326 : void didUpdateWidget(FossTimePicker old) {
327 1 : super.didUpdateWidget(old);
328 : // Controlled mode: sync the route to the parent-owned open value after the
329 : // frame, since pushing a route during a build is unsafe.
330 2 : final target = widget.open;
331 2 : if (target != null && target != old.open) {
332 3 : WidgetsBinding.instance.addPostFrameCallback((_) {
333 1 : if (!mounted) return;
334 2 : if (target && !_routeShowing) _showDialog();
335 2 : if (!target && _routeShowing) _dismissDialog();
336 : });
337 : }
338 : }
339 :
340 1 : @override
341 : void dispose() {
342 2 : _triggerFocus.dispose();
343 1 : super.dispose();
344 : }
345 :
346 : /// The single intent entry point. Fires [FossTimePicker.onOpenChange]; in
347 : /// controlled mode the parent drives the route through [didUpdateWidget],
348 : /// otherwise this owns it.
349 1 : void _setOpen(bool next) {
350 2 : if (next == _isOpen) return;
351 3 : widget.onOpenChange?.call(next);
352 2 : if (widget.open != null) return;
353 3 : setState(() => _open = next);
354 2 : next ? _showDialog() : _dismissDialog();
355 : }
356 :
357 1 : void _openFromTrigger() {
358 3 : if (widget.enabled) _setOpen(true);
359 : }
360 :
361 1 : void _showDialog() {
362 1 : if (_routeShowing) return;
363 1 : _routeShowing = true;
364 2 : final use24Hour = _resolveUse24Hour(context);
365 1 : unawaited(
366 1 : showFossDialog<void>(
367 1 : context: context,
368 2 : presentation: widget.presentation,
369 2 : builder: (_) => _TimeDialog(
370 2 : initial: widget.value,
371 2 : onConfirmed: widget.onChanged,
372 2 : title: widget.placeholder,
373 2 : semanticsLabel: widget.semanticsLabel,
374 2 : presentation: widget.presentation,
375 : use24HourFormat: use24Hour,
376 2 : minuteStep: widget.minuteStep,
377 1 : bounds: _bounds,
378 2 : confirmLabel: widget.confirmLabel,
379 2 : cancelLabel: widget.cancelLabel,
380 2 : style: widget.style,
381 : ),
382 2 : ).whenComplete(() {
383 1 : if (!mounted) return;
384 1 : _routeShowing = false;
385 : // The route closed on its own (a confirm, a barrier tap, system back).
386 : // Reconcile the open state; harmless if it was already lowered.
387 2 : if (_isOpen) _setOpen(false);
388 : }),
389 : );
390 : }
391 :
392 1 : void _dismissDialog() {
393 1 : if (_routeShowing) {
394 3 : Navigator.of(context, rootNavigator: true).maybePop();
395 : }
396 : }
397 :
398 : /// The explicit flag when the caller set one, otherwise the platform setting,
399 : /// otherwise 12-hour.
400 1 : bool _resolveUse24Hour(BuildContext context) =>
401 2 : widget.use24HourFormat ??
402 1 : MediaQuery.maybeAlwaysUse24HourFormatOf(context) ??
403 : false;
404 :
405 1 : @override
406 : Widget build(BuildContext context) {
407 1 : final theme = context.fossTheme;
408 3 : final v = _resolve(theme, widget.style);
409 2 : final value = widget.value;
410 : final format =
411 3 : widget.format ?? (_resolveUse24Hour(context) ? _format24 : _format12);
412 3 : final text = value == null ? widget.placeholder : format(value);
413 2 : final textColor = value == null ? v.placeholderColor : v.foreground;
414 :
415 1 : final box = FossFieldBox(
416 2 : enabled: widget.enabled,
417 : hasError: false,
418 2 : focused: _focused || _isOpen,
419 1 : background: v.background,
420 1 : borderColor: v.borderColor,
421 1 : ringColor: v.ringColor,
422 1 : destructiveColor: v.destructiveColor,
423 1 : borderRadius: v.borderRadius,
424 : minHeight: _triggerMinHeight,
425 1 : shadow: v.shadow,
426 1 : isDark: v.isDark,
427 : // The trigger node below carries the label as its value, so the painted
428 : // glyph and text stay out of the semantics tree.
429 1 : child: ExcludeSemantics(
430 1 : child: Padding(
431 2 : padding: EdgeInsets.symmetric(horizontal: v.horizontalPadding),
432 1 : child: Row(
433 1 : children: [
434 2 : FossGlyphIcon(ClockGlyph(textColor), size: _glyphSize),
435 2 : SizedBox(width: v.gap),
436 1 : Expanded(
437 1 : child: Text(
438 : text,
439 : maxLines: 1,
440 : overflow: TextOverflow.ellipsis,
441 2 : style: v.textStyle.copyWith(color: textColor),
442 : ),
443 : ),
444 : ],
445 : ),
446 : ),
447 : ),
448 : );
449 :
450 1 : return Semantics(
451 : button: true,
452 2 : enabled: widget.enabled,
453 2 : label: widget.semanticsLabel,
454 : value: text,
455 1 : expanded: _isOpen,
456 1 : child: FocusableActionDetector(
457 1 : focusNode: _triggerFocus,
458 2 : enabled: widget.enabled,
459 2 : mouseCursor: widget.enabled
460 : ? SystemMouseCursors.click
461 : : SystemMouseCursors.basic,
462 4 : onShowFocusHighlight: (value) => setState(() => _focused = value),
463 : // Arrow Down opens the trigger, alongside the Enter and Space that
464 : // FocusableActionDetector maps to ActivateIntent by default.
465 : shortcuts: const {
466 : SingleActivator(LogicalKeyboardKey.arrowDown): ActivateIntent(),
467 : },
468 1 : actions: <Type, Action<Intent>>{
469 1 : ActivateIntent: CallbackAction<ActivateIntent>(
470 1 : onInvoke: (_) {
471 1 : _openFromTrigger();
472 : return null;
473 : },
474 : ),
475 : },
476 1 : child: GestureDetector(
477 : behavior: HitTestBehavior.opaque,
478 3 : onTap: widget.enabled ? _openFromTrigger : null,
479 : child: box,
480 : ),
481 : ),
482 : );
483 : }
484 : }
485 :
486 : /// The wheels shown inside the modal. Holds the draft so the columns update
487 : /// live while the picker's parent stays controlled; nothing reaches the
488 : /// picker's callback until the confirm action fires.
489 : class _TimeDialog extends StatefulWidget {
490 1 : const _TimeDialog({
491 : required this.initial,
492 : required this.onConfirmed,
493 : required this.title,
494 : required this.semanticsLabel,
495 : required this.presentation,
496 : required this.use24HourFormat,
497 : required this.minuteStep,
498 : required this.bounds,
499 : required this.confirmLabel,
500 : required this.cancelLabel,
501 : required this.style,
502 : });
503 :
504 : final FossTimeOfDay? initial;
505 : final ValueChanged<FossTimeOfDay> onConfirmed;
506 : final String title;
507 : final String? semanticsLabel;
508 : final FossDialogPresentation presentation;
509 : final bool use24HourFormat;
510 : final int minuteStep;
511 : final _TimeBounds bounds;
512 : final String confirmLabel;
513 : final String cancelLabel;
514 : final FossTimePickerStyle? style;
515 :
516 1 : @override
517 1 : State<_TimeDialog> createState() => _TimeDialogState();
518 : }
519 :
520 : class _TimeDialogState extends State<_TimeDialog> {
521 : late int _hourIndex;
522 : late int _minuteIndex;
523 : late bool _isPm;
524 :
525 : // The hour column's unwrapped position. A looping wheel counts past its ends,
526 : // so the number of laps it has travelled is what tells the period column to
527 : // roll over: on a 12-hour clock, stepping off 11 lands on noon, not midnight.
528 : late int _hourRaw;
529 :
530 : // An incoming value off the minute grid is reported back unchanged until the
531 : // user touches a wheel, so opening and confirming never rewrites the caller's
532 : // time behind its back. Any wheel clears it, not just the minute: the minute
533 : // column is parked on the nearest step, so holding the off-grid value past an
534 : // hour change would commit a time the wheels never showed.
535 : int? _offGridMinute;
536 :
537 4 : int get _minuteCount => _minutesPerHour ~/ widget.minuteStep;
538 :
539 3 : int get _hourCount => widget.use24HourFormat ? 24 : 12;
540 :
541 1 : @override
542 : void initState() {
543 1 : super.initState();
544 : final start =
545 7 : widget.initial ?? widget.bounds.firstAllowed(widget.minuteStep);
546 3 : _isPm = start.hour >= 12;
547 6 : _hourIndex = widget.use24HourFormat ? start.hour : start.hour % 12;
548 2 : _hourRaw = _hourIndex;
549 2 : _minuteIndex = math.min(
550 5 : (start.minute / widget.minuteStep).round(),
551 2 : _minuteCount - 1,
552 : );
553 7 : if (start.minute % widget.minuteStep != 0) _offGridMinute = start.minute;
554 : }
555 :
556 : /// The hour the [_hourIndex] row stands for, read through the period column
557 : /// in 12-hour mode where index 0 is the 12 o'clock row.
558 1 : int _hourAt(int index, {required bool pm}) =>
559 3 : widget.use24HourFormat ? index : index + (pm ? 12 : 0);
560 :
561 6 : int get _draftMinute => _offGridMinute ?? _minuteIndex * widget.minuteStep;
562 :
563 2 : FossTimeOfDay get _draft => FossTimeOfDay(
564 3 : hour: _hourAt(_hourIndex, pm: _isPm),
565 1 : minute: _draftMinute,
566 : );
567 :
568 1 : void _confirm() {
569 4 : widget.onConfirmed(_draft);
570 3 : Navigator.of(context).maybePop();
571 : }
572 :
573 : /// Takes the hour column's unwrapped position. Each lap it completes on a
574 : /// 12-hour clock crosses noon or midnight, so an odd number of laps since the
575 : /// last report flips the period.
576 1 : void _setHourRaw(int raw) {
577 2 : setState(() {
578 2 : if (!widget.use24HourFormat) {
579 : final laps =
580 8 : (raw / _hourCount).floor() - (_hourRaw / _hourCount).floor();
581 3 : if (laps.isOdd) _isPm = !_isPm;
582 : }
583 1 : _hourRaw = raw;
584 3 : _hourIndex = raw % _hourCount;
585 1 : _offGridMinute = null;
586 : });
587 : }
588 :
589 : /// The hour column: `00` to `23`, or the clock order `12, 1 ... 11`. Each row
590 : /// is tested with the draft's own minute, so the dimming answers "can I pick
591 : /// this hour" rather than "does this hour exist".
592 2 : List<_WheelCell> _hourCells() => [
593 3 : for (var i = 0; i < _hourCount; i++)
594 1 : _WheelCell(
595 5 : label: widget.use24HourFormat ? _pad2(i) : (i == 0 ? 12 : i).toString(),
596 3 : allowed: widget.bounds.allows(
597 1 : FossTimeOfDay(
598 2 : hour: _hourAt(i, pm: _isPm),
599 1 : minute: _draftMinute,
600 : ),
601 : ),
602 : ),
603 : ];
604 :
605 2 : List<_WheelCell> _minuteCells() => [
606 3 : for (var i = 0; i < _minuteCount; i++)
607 1 : _WheelCell(
608 4 : label: _pad2(i * widget.minuteStep),
609 3 : allowed: widget.bounds.allows(
610 1 : FossTimeOfDay(
611 3 : hour: _hourAt(_hourIndex, pm: _isPm),
612 3 : minute: i * widget.minuteStep,
613 : ),
614 : ),
615 : ),
616 : ];
617 :
618 2 : List<_WheelCell> _periodCells() => [
619 1 : for (final pm in const [false, true])
620 1 : _WheelCell(
621 : label: pm ? 'PM' : 'AM',
622 3 : allowed: widget.bounds.allows(
623 1 : FossTimeOfDay(
624 2 : hour: _hourAt(_hourIndex, pm: pm),
625 1 : minute: _draftMinute,
626 : ),
627 : ),
628 : ),
629 : ];
630 :
631 1 : @override
632 : Widget build(BuildContext context) {
633 1 : final theme = context.fossTheme;
634 3 : final v = _resolve(theme, widget.style);
635 3 : final extent = MediaQuery.textScalerOf(context).scale(v.itemExtent);
636 1 : final reduceMotion = MediaQuery.disableAnimationsOf(context);
637 : // A bounded picker cannot loop: an infinite column has no ends, so the
638 : // first and last allowed entries would be unreachable by scrolling. A
639 : // column too short to fill the window cannot loop either, or the same value
640 : // appears twice on screen and reads as a rendering fault: a 30-minute step
641 : // leaves two rows for five slots.
642 1 : bool loops(int count) =>
643 5 : !widget.bounds.isBounded && count > v.visibleItemCount;
644 :
645 1 : final columns = [
646 1 : _WheelColumn(
647 : label: 'Hour',
648 1 : cells: _hourCells(),
649 1 : selectedIndex: _hourIndex,
650 1 : onRawIndexChanged: _setHourRaw,
651 2 : looping: loops(_hourCount),
652 : itemExtent: extent,
653 1 : visibleItemCount: v.visibleItemCount,
654 : reduceMotion: reduceMotion,
655 : visuals: v,
656 : ),
657 1 : _WheelColumn(
658 : label: 'Minute',
659 1 : cells: _minuteCells(),
660 1 : selectedIndex: _minuteIndex,
661 3 : onRawIndexChanged: (raw) => setState(() {
662 3 : _minuteIndex = raw % _minuteCount;
663 1 : _offGridMinute = null;
664 : }),
665 2 : looping: loops(_minuteCount),
666 : itemExtent: extent,
667 1 : visibleItemCount: v.visibleItemCount,
668 : reduceMotion: reduceMotion,
669 : visuals: v,
670 : ),
671 2 : if (!widget.use24HourFormat)
672 1 : _WheelColumn(
673 : label: 'Period',
674 1 : cells: _periodCells(),
675 1 : selectedIndex: _isPm ? 1 : 0,
676 3 : onRawIndexChanged: (raw) => setState(() {
677 2 : _isPm = raw == 1;
678 1 : _offGridMinute = null;
679 : }),
680 : looping: false,
681 : itemExtent: extent,
682 1 : visibleItemCount: v.visibleItemCount,
683 : reduceMotion: reduceMotion,
684 : visuals: v,
685 : ),
686 : ];
687 :
688 2 : final height = extent * v.visibleItemCount;
689 :
690 1 : return FossDialog(
691 : showCloseButton: false,
692 2 : presentation: widget.presentation,
693 3 : title: Text(widget.title),
694 4 : semanticLabel: widget.semanticsLabel ?? widget.title,
695 1 : content: SizedBox(
696 : height: height,
697 : // The wheels read as one control, so the columns sit in a centred
698 : // cluster sized to the rows rather than splitting the sheet three ways,
699 : // which would strand each value in its own third. A narrow sheet
700 : // reclaims the margin instead of overflowing, since the cluster width
701 : // is a maximum.
702 1 : child: Center(
703 1 : child: ConstrainedBox(
704 1 : constraints: BoxConstraints(
705 : maxWidth:
706 4 : extent * _columnWidthFactor * columns.length +
707 2 : v.bandPadding * 2,
708 : ),
709 1 : child: Stack(
710 : fit: StackFit.expand,
711 1 : children: [
712 1 : Positioned(
713 : left: 0,
714 : right: 0,
715 2 : top: (height - extent) / 2,
716 : height: extent,
717 1 : child: IgnorePointer(
718 1 : child: DecoratedBox(
719 1 : decoration: ShapeDecoration(
720 1 : color: v.highlightColor,
721 1 : shape: RoundedSuperellipseBorder(
722 1 : borderRadius: BorderRadius.circular(
723 1 : v.highlightRadius,
724 : ),
725 : ),
726 : ),
727 : ),
728 : ),
729 : ),
730 : // Inset from the band so the first and last values are not
731 : // flush against its corners.
732 1 : Padding(
733 2 : padding: EdgeInsets.symmetric(horizontal: v.bandPadding),
734 1 : child: Row(
735 3 : children: [for (final c in columns) Expanded(child: c)],
736 : ),
737 : ),
738 : ],
739 : ),
740 : ),
741 : ),
742 : ),
743 1 : actions: [
744 1 : FossButton(
745 : variant: FossButtonVariant.ghost,
746 : size: FossButtonSize.sm,
747 3 : onPressed: () => Navigator.of(context).maybePop(),
748 3 : child: Text(widget.cancelLabel),
749 : ),
750 1 : FossButton(
751 : size: FossButtonSize.sm,
752 5 : onPressed: widget.bounds.allows(_draft) ? _confirm : null,
753 3 : child: Text(widget.confirmLabel),
754 : ),
755 : ],
756 : );
757 : }
758 : }
759 :
760 : /// One row of a wheel: what it reads and whether the bounds accept it.
761 : @immutable
762 : class _WheelCell {
763 1 : const _WheelCell({required this.label, required this.allowed});
764 :
765 : final String label;
766 : final bool allowed;
767 : }
768 :
769 : /// A single scrolling column.
770 : ///
771 : /// `ListWheelScrollView` exposes no semantics node and handles no key events,
772 : /// so this wraps it in an adjustable node and maps the arrow keys to a one-row
773 : /// step itself.
774 : class _WheelColumn extends StatefulWidget {
775 1 : const _WheelColumn({
776 : required this.label,
777 : required this.cells,
778 : required this.selectedIndex,
779 : required this.onRawIndexChanged,
780 : required this.looping,
781 : required this.itemExtent,
782 : required this.visibleItemCount,
783 : required this.reduceMotion,
784 : required this.visuals,
785 : });
786 :
787 : final String label;
788 : final List<_WheelCell> cells;
789 :
790 : /// The row currently in the centre band, already wrapped into [cells].
791 : final int selectedIndex;
792 :
793 : /// Reports the wheel's unwrapped position, which counts past the ends of a
794 : /// looping column so the caller can see how far it has travelled.
795 : final ValueChanged<int> onRawIndexChanged;
796 :
797 : final bool looping;
798 : final double itemExtent;
799 : final int visibleItemCount;
800 : final bool reduceMotion;
801 : final _TimePickerVisuals visuals;
802 :
803 1 : @override
804 1 : State<_WheelColumn> createState() => _WheelColumnState();
805 : }
806 :
807 : class _WheelColumnState extends State<_WheelColumn> {
808 1 : late final FixedExtentScrollController _controller =
809 3 : FixedExtentScrollController(initialItem: widget.selectedIndex);
810 :
811 : bool _focused = false;
812 :
813 1 : @override
814 : void didUpdateWidget(_WheelColumn old) {
815 1 : super.didUpdateWidget(old);
816 : // Another column moved this one: the hour wheel rolling past noon drives
817 : // the period. Catch the wheel up after the frame, since scrolling during a
818 : // build dispatches notifications the tree is not ready for.
819 4 : if (widget.selectedIndex == old.selectedIndex) return;
820 3 : WidgetsBinding.instance.addPostFrameCallback((_) {
821 1 : if (!mounted) return;
822 : // A wheel reports each row it passes, so a fling rebuilds this column
823 : // while it is still travelling. Correcting it then would fight the
824 : // gesture; only a wheel at rest is out of step with the draft.
825 2 : final position = _controller.position;
826 2 : if (position.isScrollingNotifier.value) return;
827 1 : _syncToSelected();
828 : });
829 : }
830 :
831 1 : @override
832 : void dispose() {
833 2 : _controller.dispose();
834 1 : super.dispose();
835 : }
836 :
837 : /// Moves the wheel onto [_WheelColumn.selectedIndex], leaving it alone when
838 : /// it is already there. A wheel that reported its own position is always
839 : /// already there, so in practice this only carries the period column across
840 : /// when the hour column rolls it.
841 1 : void _syncToSelected() {
842 6 : final current = _controller.selectedItem % widget.cells.length;
843 3 : if (current == widget.selectedIndex) return;
844 7 : _moveTo(_controller.selectedItem + widget.selectedIndex - current);
845 : }
846 :
847 : /// Moves the wheel [delta] rows, wrapping when the column loops and clamping
848 : /// when it does not. Jumps rather than animates under reduced motion.
849 1 : void _step(int delta) {
850 3 : final count = widget.cells.length;
851 3 : final raw = _controller.selectedItem + delta;
852 5 : _moveTo(widget.looping ? raw : raw.clamp(0, count - 1));
853 : }
854 :
855 : /// Scrolls onto the row at [target], jumping rather than animating under
856 : /// reduced motion.
857 1 : void _moveTo(int target) {
858 3 : if (target == _controller.selectedItem) return;
859 2 : if (widget.reduceMotion) {
860 2 : _controller.jumpToItem(target);
861 : } else {
862 2 : _controller.animateToItem(
863 : target,
864 3 : duration: widget.visuals.stepDuration,
865 : curve: Curves.easeOut,
866 : );
867 : }
868 : }
869 :
870 : /// The row a step of [delta] lands on, wrapping when the column loops and
871 : /// clamping when it does not. Names the announced increase and decrease.
872 1 : int _neighbour(int delta) {
873 3 : final count = widget.cells.length;
874 3 : final raw = widget.selectedIndex + delta;
875 5 : return widget.looping ? raw % count : raw.clamp(0, count - 1);
876 : }
877 :
878 1 : Color _colorFor(int index) {
879 3 : final cell = widget.cells[index];
880 2 : final colors = widget.visuals;
881 1 : if (!cell.allowed) {
882 3 : return index == widget.selectedIndex
883 1 : ? colors.mutedForeground
884 2 : : colors.mutedForeground.withValues(
885 3 : alpha: colors.mutedForeground.a * _blockedOpacity,
886 : );
887 : }
888 3 : return index == widget.selectedIndex
889 1 : ? colors.foreground
890 1 : : colors.mutedForeground;
891 : }
892 :
893 1 : @override
894 : Widget build(BuildContext context) {
895 2 : final v = widget.visuals;
896 2 : final cells = widget.cells;
897 :
898 1 : final rows = [
899 3 : for (var i = 0; i < cells.length; i++)
900 1 : Center(
901 1 : child: Text(
902 2 : cells[i].label,
903 : maxLines: 1,
904 3 : style: v.wheelTextStyle.copyWith(color: _colorFor(i)),
905 : ),
906 : ),
907 : ];
908 :
909 1 : final wheel = ListWheelScrollView.useDelegate(
910 1 : controller: _controller,
911 2 : itemExtent: widget.itemExtent,
912 : physics: const FixedExtentScrollPhysics(),
913 : diameterRatio: _wheelDiameterRatio,
914 : overAndUnderCenterOpacity: _overAndUnderOpacity,
915 : // The callback wraps its index back into the child list, which hides how
916 : // many laps a looping wheel has turned. The controller keeps the count.
917 1 : onSelectedItemChanged: (_) =>
918 5 : widget.onRawIndexChanged(_controller.selectedItem),
919 2 : childDelegate: widget.looping
920 1 : ? ListWheelChildLoopingListDelegate(children: rows)
921 1 : : ListWheelChildListDelegate(children: rows),
922 : );
923 :
924 1 : return Semantics(
925 : container: true,
926 2 : label: widget.label,
927 4 : value: cells[widget.selectedIndex].label,
928 3 : increasedValue: cells[_neighbour(1)].label,
929 4 : decreasedValue: cells[_neighbour(-1)].label,
930 2 : onIncrease: () => _step(1),
931 3 : onDecrease: () => _step(-1),
932 1 : child: FocusableActionDetector(
933 4 : onShowFocusHighlight: (value) => setState(() => _focused = value),
934 : shortcuts: const {
935 : SingleActivator(LogicalKeyboardKey.arrowUp): _StepIntent(-1),
936 : SingleActivator(LogicalKeyboardKey.arrowDown): _StepIntent(1),
937 : },
938 1 : actions: <Type, Action<Intent>>{
939 1 : _StepIntent: CallbackAction<_StepIntent>(
940 1 : onInvoke: (intent) {
941 2 : _step(intent.delta);
942 : return null;
943 : },
944 : ),
945 : },
946 1 : child: DecoratedBox(
947 : position: DecorationPosition.foreground,
948 1 : decoration: ShapeDecoration(
949 1 : shape: RoundedSuperellipseBorder(
950 1 : side: _focused
951 2 : ? BorderSide(color: v.ringColor, width: 2)
952 : : BorderSide.none,
953 2 : borderRadius: BorderRadius.circular(v.highlightRadius),
954 : ),
955 : ),
956 : // The adjustable node above speaks for the column, so the wheel's own
957 : // scrollable node stays out of the tree.
958 1 : child: ExcludeSemantics(child: wheel),
959 : ),
960 : ),
961 : );
962 : }
963 : }
964 :
965 : /// Moves a wheel column by [delta] rows.
966 : class _StepIntent extends Intent {
967 2 : const _StepIntent(this.delta);
968 :
969 : final int delta;
970 : }
971 :
972 : /// Builds the default appearance from the theme tokens, then lays the
973 : /// time-picker-specific fields of [override] over it.
974 1 : _TimePickerVisuals _resolve(
975 : FossThemeData theme,
976 : FossTimePickerStyle? override,
977 : ) {
978 1 : final c = theme.colors;
979 : // Dark lifts the resting trigger fill by the input color, matching the field
980 : // family; light is the bare surface.
981 1 : final background = c.isDark
982 1 : ? Color.alphaBlend(
983 5 : c.input.withValues(alpha: c.input.a * _darkFillOpacity),
984 1 : c.background,
985 : )
986 1 : : c.background;
987 1 : return _TimePickerVisuals(
988 : background: background,
989 1 : foreground: c.foreground,
990 1 : mutedForeground: c.mutedForeground,
991 2 : placeholderColor: override?.placeholderColor ?? c.mutedForeground,
992 1 : borderColor: c.input,
993 1 : ringColor: c.ring,
994 1 : destructiveColor: c.destructive,
995 2 : borderRadius: theme.radii.lg,
996 2 : horizontalPadding: theme.spacing(3),
997 2 : textStyle: theme.typography.sm,
998 3 : wheelTextStyle: theme.typography.base.medium,
999 2 : shadow: theme.shadows.xs,
1000 3 : gap: override?.gap ?? theme.spacing(1),
1001 1 : itemExtent: override?.itemExtent ?? _itemExtent,
1002 1 : visibleItemCount: override?.visibleItemCount ?? _visibleItemCount,
1003 2 : highlightColor: override?.highlightColor ?? c.accent,
1004 2 : highlightRadius: theme.radii.md,
1005 2 : bandPadding: theme.spacing(3),
1006 2 : stepDuration: theme.motion.overlay,
1007 1 : isDark: c.isDark,
1008 : );
1009 : }
1010 :
1011 : /// The fully resolved, non-null appearance of the trigger and the wheels.
1012 : @immutable
1013 : class _TimePickerVisuals {
1014 1 : const _TimePickerVisuals({
1015 : required this.background,
1016 : required this.foreground,
1017 : required this.mutedForeground,
1018 : required this.placeholderColor,
1019 : required this.borderColor,
1020 : required this.ringColor,
1021 : required this.destructiveColor,
1022 : required this.borderRadius,
1023 : required this.horizontalPadding,
1024 : required this.textStyle,
1025 : required this.wheelTextStyle,
1026 : required this.shadow,
1027 : required this.gap,
1028 : required this.itemExtent,
1029 : required this.visibleItemCount,
1030 : required this.highlightColor,
1031 : required this.highlightRadius,
1032 : required this.bandPadding,
1033 : required this.stepDuration,
1034 : required this.isDark,
1035 : });
1036 :
1037 : final Color background;
1038 : final Color foreground;
1039 : final Color mutedForeground;
1040 : final Color placeholderColor;
1041 : final Color borderColor;
1042 : final Color ringColor;
1043 : final Color destructiveColor;
1044 : final double borderRadius;
1045 : final double horizontalPadding;
1046 : final TextStyle textStyle;
1047 : final TextStyle wheelTextStyle;
1048 : final List<BoxShadow> shadow;
1049 : final double gap;
1050 : final double itemExtent;
1051 : final int visibleItemCount;
1052 : final Color highlightColor;
1053 : final double highlightRadius;
1054 : final double bandPadding;
1055 : final Duration stepDuration;
1056 : final bool isDark;
1057 : }
|