Line data Source code
1 : import 'package:flutter/services.dart';
2 : import 'package:flutter/widgets.dart';
3 : import 'package:fossui/src/foundation/foss_since.dart';
4 : import 'package:fossui/src/theme/theme.dart';
5 :
6 : part 'foss_calendar_painters.dart';
7 : part 'foss_calendar_style.dart';
8 :
9 : // Grid geometry, mobile base. The cell is the one fixed metric the widget
10 : // bakes; everything else resolves to a token.
11 : const double _cellSize = 40;
12 : const int _columns = 7;
13 :
14 : const double _chevronSize = 18;
15 : const double _chevronOpacity = 0.80;
16 : const double _todayDotSize = 3;
17 :
18 : const double _disabledOpacity = 0.64;
19 : const double _outsideOpacity = 0.72;
20 : const double _ringOpacity = 0.50;
21 : const double _todayDisabledOpacity = 0.30;
22 : const double _ringWidth = 3;
23 :
24 : // English labels. The package takes no localization dependency; a locale hook
25 : // is a later addition. Weekday labels are indexed by [DateTime.weekday] minus 1
26 : // (Monday first), so the header can rotate to any [firstDayOfWeek].
27 : const List<String> _weekdayAbbr = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'];
28 : const List<String> _monthNames = [
29 : 'January',
30 : 'February',
31 : 'March',
32 : 'April',
33 : 'May',
34 : 'June',
35 : 'July',
36 : 'August',
37 : 'September',
38 : 'October',
39 : 'November',
40 : 'December',
41 : ];
42 :
43 : /// An inclusive span of two calendar days, the value a [FossCalendar.range]
44 : /// selects. Both ends compare by calendar day (year, month, day), so a
45 : /// time-of-day component never splits a match.
46 : ///
47 : /// While a range is being picked, the first tap yields a one-day range
48 : /// ([start] equal to [end]); the second tap sets the far end.
49 : ///
50 : /// ```dart
51 : /// final week = FossDateRange(
52 : /// start: DateTime(2026, 3, 2),
53 : /// end: DateTime(2026, 3, 8),
54 : /// );
55 : /// ```
56 : @FossSince('0.1.1')
57 : @immutable
58 : class FossDateRange {
59 : /// Creates a range from [start] to [end], inclusive.
60 3 : const FossDateRange({required this.start, required this.end});
61 :
62 : /// The first day of the span.
63 : final DateTime start;
64 :
65 : /// The last day of the span, inclusive.
66 : final DateTime end;
67 :
68 3 : @override
69 : bool operator ==(Object other) =>
70 3 : other is FossDateRange &&
71 9 : _isSameDay(other.start, start) &&
72 9 : _isSameDay(other.end, end);
73 :
74 1 : @override
75 5 : int get hashCode => Object.hash(_dayKey(start), _dayKey(end));
76 : }
77 :
78 : enum _SelectionMode { single, multiple, range }
79 :
80 : /// {@category Inputs}
81 : /// {@template foss.calendar.preview}
82 : /// <img src="https://fossui.org/components/calendar/overview/light.png"
83 : /// alt="FossCalendar, light theme" width="480"
84 : /// style="max-width:100%;height:auto" />
85 : /// <img src="https://fossui.org/components/calendar/overview/dark.png"
86 : /// alt="FossCalendar, dark theme" width="480"
87 : /// style="max-width:100%;height:auto" />
88 : ///
89 : /// See the [calendar documentation ↗](https://fossui.org/docs/components/calendar)
90 : /// or try it live in the
91 : /// [playground ↗](https://play.fossui.org/components/#/?path=components/calendar/fosscalendar/playground).
92 : /// {@endtemplate}
93 : ///
94 : /// A month grid for viewing and picking dates: a seven-column day grid under a
95 : /// month caption with previous and next navigation.
96 : ///
97 : /// Pick one of three selection modes with the named constructors, each typing
98 : /// its value so the selection is never `dynamic`:
99 : ///
100 : /// - [FossCalendar.single] highlights one day; tapping another moves it.
101 : /// - [FossCalendar.multiple] toggles independent days in and out of a set.
102 : /// - [FossCalendar.range] sets a [FossDateRange] over two taps.
103 : ///
104 : /// Bound the grid with [minDate] and [maxDate], and disable individual days
105 : /// with [isDateEnabled]; disabled days dim and stop responding. Own the
106 : /// displayed month with [focusedMonth] and [onMonthChanged], or leave it to the
107 : /// widget by seeding [initialMonth]. Colors, type, and radius come from
108 : /// `context.fossTheme`; pass a [FossCalendarStyle] to [style] for a one-off.
109 : ///
110 : /// {@macro foss.customize}
111 : ///
112 : /// ```dart
113 : /// FossCalendar.single(
114 : /// selected: picked,
115 : /// onSelected: (day) => setState(() => picked = day),
116 : /// );
117 : /// ```
118 : @FossSince('0.1.1')
119 : class FossCalendar extends StatefulWidget {
120 2 : const FossCalendar._({
121 : required _SelectionMode mode,
122 : DateTime? singleSelected,
123 : ValueChanged<DateTime>? onSingle,
124 : Set<DateTime>? multipleSelected,
125 : ValueChanged<Set<DateTime>>? onMultiple,
126 : FossDateRange? rangeSelected,
127 : ValueChanged<FossDateRange>? onRange,
128 : this.initialMonth,
129 : this.focusedMonth,
130 : this.onMonthChanged,
131 : this.firstDayOfWeek = DateTime.monday,
132 : this.showOutsideDays = true,
133 : this.minDate,
134 : this.maxDate,
135 : this.isDateEnabled,
136 : this.semanticsLabel,
137 : this.style,
138 : super.key,
139 : }) : assert(
140 2 : focusedMonth == null || initialMonth == null,
141 : 'Pass focusedMonth (controlled) or initialMonth (uncontrolled), '
142 : 'not both.',
143 : ),
144 : assert(
145 6 : firstDayOfWeek >= DateTime.monday && firstDayOfWeek <= DateTime.sunday,
146 : 'firstDayOfWeek must be a DateTime weekday (1 to 7).',
147 : ),
148 : _mode = mode,
149 : _singleSelected = singleSelected,
150 : _onSingle = onSingle,
151 : _multipleSelected = multipleSelected,
152 : _onMultiple = onMultiple,
153 : _rangeSelected = rangeSelected,
154 : _onRange = onRange;
155 :
156 : /// {@macro foss.calendar.preview}
157 : ///
158 : /// Creates a single-day calendar. [selected] is the highlighted day (null for
159 : /// none); [onSelected] fires with the tapped day.
160 : ///
161 : /// ```dart
162 : /// FossCalendar.single(
163 : /// selected: picked,
164 : /// onSelected: (day) => setState(() => picked = day),
165 : /// );
166 : /// ```
167 2 : const FossCalendar.single({
168 : required DateTime? selected,
169 : required ValueChanged<DateTime> onSelected,
170 : DateTime? initialMonth,
171 : DateTime? focusedMonth,
172 : ValueChanged<DateTime>? onMonthChanged,
173 : int firstDayOfWeek = DateTime.monday,
174 : bool showOutsideDays = true,
175 : DateTime? minDate,
176 : DateTime? maxDate,
177 : bool Function(DateTime)? isDateEnabled,
178 : String? semanticsLabel,
179 : FossCalendarStyle? style,
180 : Key? key,
181 2 : }) : this._(
182 : mode: _SelectionMode.single,
183 : singleSelected: selected,
184 : onSingle: onSelected,
185 : initialMonth: initialMonth,
186 : focusedMonth: focusedMonth,
187 : onMonthChanged: onMonthChanged,
188 : firstDayOfWeek: firstDayOfWeek,
189 : showOutsideDays: showOutsideDays,
190 : minDate: minDate,
191 : maxDate: maxDate,
192 : isDateEnabled: isDateEnabled,
193 : semanticsLabel: semanticsLabel,
194 : style: style,
195 : key: key,
196 : );
197 :
198 : /// Creates a multi-day calendar. [selected] is the set of highlighted days;
199 : /// [onSelected] fires with the next set as each day toggles.
200 : ///
201 : /// ```dart
202 : /// FossCalendar.multiple(
203 : /// selected: picked,
204 : /// onSelected: (days) => setState(() => picked = days),
205 : /// );
206 : /// ```
207 1 : const FossCalendar.multiple({
208 : required Set<DateTime> selected,
209 : required ValueChanged<Set<DateTime>> onSelected,
210 : DateTime? initialMonth,
211 : DateTime? focusedMonth,
212 : ValueChanged<DateTime>? onMonthChanged,
213 : int firstDayOfWeek = DateTime.monday,
214 : bool showOutsideDays = true,
215 : DateTime? minDate,
216 : DateTime? maxDate,
217 : bool Function(DateTime)? isDateEnabled,
218 : String? semanticsLabel,
219 : FossCalendarStyle? style,
220 : Key? key,
221 1 : }) : this._(
222 : mode: _SelectionMode.multiple,
223 : multipleSelected: selected,
224 : onMultiple: onSelected,
225 : initialMonth: initialMonth,
226 : focusedMonth: focusedMonth,
227 : onMonthChanged: onMonthChanged,
228 : firstDayOfWeek: firstDayOfWeek,
229 : showOutsideDays: showOutsideDays,
230 : minDate: minDate,
231 : maxDate: maxDate,
232 : isDateEnabled: isDateEnabled,
233 : semanticsLabel: semanticsLabel,
234 : style: style,
235 : key: key,
236 : );
237 :
238 : /// Creates a range calendar. [selected] is the chosen span (null for none);
239 : /// [onSelected] fires as the range is set over two taps.
240 : ///
241 : /// ```dart
242 : /// FossCalendar.range(
243 : /// selected: picked,
244 : /// onSelected: (range) => setState(() => picked = range),
245 : /// );
246 : /// ```
247 2 : const FossCalendar.range({
248 : required FossDateRange? selected,
249 : required ValueChanged<FossDateRange> onSelected,
250 : DateTime? initialMonth,
251 : DateTime? focusedMonth,
252 : ValueChanged<DateTime>? onMonthChanged,
253 : int firstDayOfWeek = DateTime.monday,
254 : bool showOutsideDays = true,
255 : DateTime? minDate,
256 : DateTime? maxDate,
257 : bool Function(DateTime)? isDateEnabled,
258 : String? semanticsLabel,
259 : FossCalendarStyle? style,
260 : Key? key,
261 2 : }) : this._(
262 : mode: _SelectionMode.range,
263 : rangeSelected: selected,
264 : onRange: onSelected,
265 : initialMonth: initialMonth,
266 : focusedMonth: focusedMonth,
267 : onMonthChanged: onMonthChanged,
268 : firstDayOfWeek: firstDayOfWeek,
269 : showOutsideDays: showOutsideDays,
270 : minDate: minDate,
271 : maxDate: maxDate,
272 : isDateEnabled: isDateEnabled,
273 : semanticsLabel: semanticsLabel,
274 : style: style,
275 : key: key,
276 : );
277 :
278 : final _SelectionMode _mode;
279 : final DateTime? _singleSelected;
280 : final ValueChanged<DateTime>? _onSingle;
281 : final Set<DateTime>? _multipleSelected;
282 : final ValueChanged<Set<DateTime>>? _onMultiple;
283 : final FossDateRange? _rangeSelected;
284 : final ValueChanged<FossDateRange>? _onRange;
285 :
286 : /// The month shown first when uncontrolled ([focusedMonth] is null). Defaults
287 : /// to the month of the selection, else the current month.
288 : final DateTime? initialMonth;
289 :
290 : /// The displayed month when controlled. Pass with [onMonthChanged] to own
291 : /// navigation; leave null to let the widget hold the month.
292 : final DateTime? focusedMonth;
293 :
294 : /// Called with the first day of the next month when navigation steps.
295 : final ValueChanged<DateTime>? onMonthChanged;
296 :
297 : /// The leading weekday column, as a [DateTime] weekday (1 = Monday). Defaults
298 : /// to [DateTime.monday].
299 : final int firstDayOfWeek;
300 :
301 : /// Whether adjacent-month days fill the leading and trailing grid cells.
302 : /// Defaults to true.
303 : final bool showOutsideDays;
304 :
305 : /// The earliest selectable and navigable day, inclusive. Null for no lower
306 : /// bound.
307 : final DateTime? minDate;
308 :
309 : /// The latest selectable and navigable day, inclusive. Null for no upper
310 : /// bound.
311 : final DateTime? maxDate;
312 :
313 : /// Disables individual days on top of [minDate] and [maxDate]. Returns false
314 : /// to disable the given day.
315 : final bool Function(DateTime)? isDateEnabled;
316 :
317 : /// Accessibility label for the grid as a whole.
318 : final String? semanticsLabel;
319 :
320 : /// Per-instance overrides layered on the theme-resolved style.
321 : final FossCalendarStyle? style;
322 :
323 2 : @override
324 2 : State<FossCalendar> createState() => _FossCalendarState();
325 : }
326 :
327 : class _FossCalendarState extends State<FossCalendar> {
328 : final FocusNode _gridFocus = FocusNode(debugLabel: 'FossCalendar grid');
329 :
330 : late DateTime _internalMonth;
331 : DateTime? _focusedDay;
332 : DateTime? _hoveredDay;
333 : DateTime? _rangeAnchor;
334 : bool _showRing = false;
335 :
336 10 : DateTime get _month => _firstOfMonth(widget.focusedMonth ?? _internalMonth);
337 :
338 2 : @override
339 : void initState() {
340 2 : super.initState();
341 : final seed =
342 4 : widget.focusedMonth ??
343 4 : widget.initialMonth ??
344 2 : _selectionMonth() ??
345 2 : DateTime.now();
346 6 : _internalMonth = _clampMonth(_firstOfMonth(seed));
347 : }
348 :
349 2 : @override
350 : void dispose() {
351 4 : _gridFocus.dispose();
352 2 : super.dispose();
353 : }
354 :
355 6 : DateTime? _selectionMonth() => switch (widget._mode) {
356 6 : _SelectionMode.single => widget._singleSelected,
357 2 : _SelectionMode.multiple =>
358 3 : widget._multipleSelected?.isEmpty ?? true
359 : ? null
360 3 : : widget._multipleSelected?.first,
361 8 : _SelectionMode.range => widget._rangeSelected?.start,
362 : };
363 :
364 6 : DateTime get _today => _dayOnly(DateTime.now());
365 :
366 2 : bool _isSelectable(DateTime day) {
367 4 : final min = widget.minDate;
368 4 : final max = widget.maxDate;
369 4 : if (min != null && day.isBefore(_dayOnly(min))) return false;
370 4 : if (max != null && day.isAfter(_dayOnly(max))) return false;
371 5 : return widget.isDateEnabled?.call(day) ?? true;
372 : }
373 :
374 2 : DateTime _clampMonth(DateTime month) {
375 4 : final min = widget.minDate;
376 4 : final max = widget.maxDate;
377 4 : if (min != null && month.isBefore(_firstOfMonth(min))) {
378 1 : return _firstOfMonth(min);
379 : }
380 4 : if (max != null && month.isAfter(_firstOfMonth(max))) {
381 2 : return _firstOfMonth(max);
382 : }
383 : return month;
384 : }
385 :
386 2 : bool get _canStepBack {
387 4 : final min = widget.minDate;
388 6 : return min == null || _month.isAfter(_firstOfMonth(min));
389 : }
390 :
391 2 : bool get _canStepForward {
392 4 : final max = widget.maxDate;
393 6 : return max == null || _month.isBefore(_firstOfMonth(max));
394 : }
395 :
396 1 : void _step(int months) {
397 7 : final target = _clampMonth(DateTime(_month.year, _month.month + months));
398 2 : if (target == _month) return;
399 3 : widget.onMonthChanged?.call(target);
400 5 : if (widget.focusedMonth == null) setState(() => _internalMonth = target);
401 : }
402 :
403 : // Moves the displayed month so [day] is visible, then points the roving focus
404 : // at it. Used by the keyboard grid when an arrow crosses a month edge.
405 1 : void _focusDay(DateTime day) {
406 1 : final clamped = _clampToBounds(day);
407 1 : final targetMonth = _firstOfMonth(clamped);
408 3 : setState(() => _focusedDay = clamped);
409 2 : if (targetMonth != _month) {
410 2 : widget.onMonthChanged?.call(targetMonth);
411 3 : if (widget.focusedMonth == null) _internalMonth = targetMonth;
412 : }
413 : }
414 :
415 1 : DateTime _clampToBounds(DateTime day) {
416 2 : final min = widget.minDate;
417 2 : final max = widget.maxDate;
418 3 : if (min != null && day.isBefore(_dayOnly(min))) return _dayOnly(min);
419 3 : if (max != null && day.isAfter(_dayOnly(max))) return _dayOnly(max);
420 : return day;
421 : }
422 :
423 2 : void _handleTap(DateTime day) {
424 2 : final d = _dayOnly(day);
425 2 : if (!_isSelectable(d)) return;
426 6 : setState(() => _focusedDay = d);
427 4 : _gridFocus.requestFocus();
428 4 : switch (widget._mode) {
429 2 : case _SelectionMode.single:
430 6 : widget._onSingle?.call(d);
431 2 : case _SelectionMode.multiple:
432 : final next = {
433 3 : for (final s in widget._multipleSelected ?? const <DateTime>{})
434 1 : _dayOnly(s),
435 : };
436 2 : if (!next.add(d)) next.remove(d);
437 3 : widget._onMultiple?.call(next);
438 2 : case _SelectionMode.range:
439 2 : _handleRangeTap(d);
440 : }
441 : }
442 :
443 2 : void _handleRangeTap(DateTime day) {
444 2 : final anchor = _rangeAnchor;
445 : if (anchor == null) {
446 6 : setState(() => _rangeAnchor = day);
447 8 : widget._onRange?.call(FossDateRange(start: day, end: day));
448 : } else {
449 2 : final start = anchor.isAfter(day) ? day : anchor;
450 2 : final end = anchor.isAfter(day) ? anchor : day;
451 6 : setState(() => _rangeAnchor = null);
452 8 : widget._onRange?.call(FossDateRange(start: start, end: end));
453 : }
454 : }
455 :
456 1 : DateTime _defaultFocusDay() {
457 1 : final selection = _selectionMonth();
458 3 : if (selection != null && _firstOfMonth(selection) == _month) {
459 1 : return _dayOnly(selection);
460 : }
461 5 : if (_firstOfMonth(_today) == _month) return _today;
462 2 : return _clampToBounds(_month);
463 : }
464 :
465 1 : void _moveFocusBy(int days) {
466 1 : final from = _focusedDay ?? _defaultFocusDay();
467 6 : _focusDay(DateTime(from.year, from.month, from.day + days));
468 : }
469 :
470 1 : void _moveFocusToWeekEdge({required bool end}) {
471 1 : final from = _focusedDay ?? _defaultFocusDay();
472 3 : final offset = _leadingOffset(from, widget.firstDayOfWeek);
473 5 : final start = DateTime(from.year, from.month, from.day - offset);
474 6 : _focusDay(end ? DateTime(start.year, start.month, start.day + 6) : start);
475 : }
476 :
477 1 : void _moveFocusByMonth(int months) {
478 1 : final from = _focusedDay ?? _defaultFocusDay();
479 4 : final targetMonth = DateTime(from.year, from.month + months);
480 1 : final dim = _daysInMonth(targetMonth);
481 3 : final day = from.day < dim ? from.day : dim;
482 4 : _focusDay(DateTime(targetMonth.year, targetMonth.month, day));
483 : }
484 :
485 2 : @override
486 : Widget build(BuildContext context) {
487 2 : final theme = context.fossTheme;
488 6 : final visuals = _resolve(theme, widget.style);
489 4 : final ltr = Directionality.of(context) == TextDirection.ltr;
490 :
491 2 : return FocusableActionDetector(
492 2 : focusNode: _gridFocus,
493 1 : onShowFocusHighlight: (value) {
494 2 : setState(() {
495 1 : _showRing = value;
496 2 : if (value) _focusedDay ??= _defaultFocusDay();
497 : });
498 : },
499 2 : shortcuts: <ShortcutActivator, Intent>{
500 2 : const SingleActivator(LogicalKeyboardKey.arrowRight): _MoveDaysIntent(
501 1 : ltr ? 1 : -1,
502 : ),
503 2 : const SingleActivator(LogicalKeyboardKey.arrowLeft): _MoveDaysIntent(
504 2 : ltr ? -1 : 1,
505 : ),
506 : const SingleActivator(
507 : LogicalKeyboardKey.arrowDown,
508 : ): const _MoveDaysIntent(
509 : _columns,
510 : ),
511 : const SingleActivator(
512 : LogicalKeyboardKey.arrowUp,
513 : ): const _MoveDaysIntent(
514 : -_columns,
515 : ),
516 : const SingleActivator(LogicalKeyboardKey.home): const _WeekEdgeIntent(
517 : end: false,
518 : ),
519 : const SingleActivator(LogicalKeyboardKey.end): const _WeekEdgeIntent(
520 : end: true,
521 : ),
522 : const SingleActivator(
523 : LogicalKeyboardKey.pageUp,
524 : ): const _MoveMonthsIntent(
525 : -1,
526 : ),
527 : const SingleActivator(LogicalKeyboardKey.pageDown):
528 : const _MoveMonthsIntent(1),
529 : },
530 2 : actions: <Type, Action<Intent>>{
531 2 : _MoveDaysIntent: CallbackAction<_MoveDaysIntent>(
532 1 : onInvoke: (intent) {
533 2 : _moveFocusBy(intent.days);
534 : return null;
535 : },
536 : ),
537 2 : _WeekEdgeIntent: CallbackAction<_WeekEdgeIntent>(
538 1 : onInvoke: (intent) {
539 2 : _moveFocusToWeekEdge(end: intent.end);
540 : return null;
541 : },
542 : ),
543 2 : _MoveMonthsIntent: CallbackAction<_MoveMonthsIntent>(
544 1 : onInvoke: (intent) {
545 2 : _moveFocusByMonth(intent.months);
546 : return null;
547 : },
548 : ),
549 2 : ActivateIntent: CallbackAction<ActivateIntent>(
550 1 : onInvoke: (_) {
551 1 : final day = _focusedDay;
552 1 : if (day != null) _handleTap(day);
553 : return null;
554 : },
555 : ),
556 : },
557 2 : child: Semantics(
558 : container: true,
559 4 : label: widget.semanticsLabel,
560 : // Size to the grid width so the caption arrows align with the day
561 : // columns instead of stretching. Align passes loose constraints to the
562 : // fixed-width child, so the grid width holds even when the parent
563 : // forces a wider tight width (a full-width list, say); widthFactor
564 : // keeps the calendar shrink-wrapped when the parent leaves it loose.
565 2 : child: Align(
566 : alignment: AlignmentDirectional.centerStart,
567 : widthFactor: 1,
568 2 : child: SizedBox(
569 4 : width: _columns * visuals.cellSize,
570 2 : child: Column(
571 : mainAxisSize: MainAxisSize.min,
572 2 : children: <Widget>[
573 2 : _caption(theme, visuals, ltr),
574 2 : _weekdayHeader(visuals),
575 2 : _grid(visuals),
576 : ],
577 : ),
578 : ),
579 : ),
580 : ),
581 : );
582 : }
583 :
584 2 : Widget _caption(FossThemeData theme, _CalendarVisuals v, bool ltr) {
585 14 : final title = '${_monthNames[_month.month - 1]} ${_month.year}';
586 2 : return SizedBox(
587 2 : height: v.cellSize,
588 2 : child: Row(
589 2 : children: <Widget>[
590 2 : _NavButton(
591 : pointsLeft: ltr,
592 2 : color: v.chevronColor,
593 2 : ringColor: v.ringColor,
594 2 : size: v.cellSize,
595 2 : enabled: _canStepBack,
596 : semanticLabel: 'Previous month',
597 3 : onTap: () => _step(-1),
598 : ),
599 2 : Expanded(
600 2 : child: Center(
601 2 : child: Text(
602 : title,
603 2 : style: v.captionStyle,
604 : maxLines: 1,
605 : overflow: TextOverflow.ellipsis,
606 : ),
607 : ),
608 : ),
609 2 : _NavButton(
610 : pointsLeft: !ltr,
611 2 : color: v.chevronColor,
612 2 : ringColor: v.ringColor,
613 2 : size: v.cellSize,
614 2 : enabled: _canStepForward,
615 : semanticLabel: 'Next month',
616 2 : onTap: () => _step(1),
617 : ),
618 : ],
619 : ),
620 : );
621 : }
622 :
623 2 : Widget _weekdayHeader(_CalendarVisuals v) {
624 2 : return Row(
625 2 : children: <Widget>[
626 4 : for (var i = 0; i < _columns; i++)
627 2 : SizedBox(
628 2 : width: v.cellSize,
629 2 : child: Center(
630 2 : child: Text(
631 12 : _weekdayAbbr[(widget.firstDayOfWeek - 1 + i) % _columns],
632 2 : style: v.weekdayStyle,
633 : ),
634 : ),
635 : ),
636 : ],
637 : );
638 : }
639 :
640 2 : Widget _grid(_CalendarVisuals v) {
641 8 : final days = _gridDays(_month, widget.firstDayOfWeek);
642 2 : return Column(
643 : mainAxisSize: MainAxisSize.min,
644 2 : children: <Widget>[
645 8 : for (var row = 0; row < days.length ~/ _columns; row++)
646 2 : Row(
647 2 : children: <Widget>[
648 4 : for (var col = 0; col < _columns; col++)
649 8 : _dayCell(v, days[row * _columns + col]),
650 : ],
651 : ),
652 : ],
653 : );
654 : }
655 :
656 2 : Widget _dayCell(_CalendarVisuals v, DateTime day) {
657 16 : final outside = day.month != _month.month || day.year != _month.year;
658 4 : if (outside && !widget.showOutsideDays) {
659 2 : return SizedBox.square(dimension: v.cellSize);
660 : }
661 :
662 2 : final selectable = _isSelectable(day);
663 4 : final today = _isSameDay(day, _today);
664 2 : final fill = _fillState(day);
665 : final focused =
666 5 : _showRing && _focusedDay != null && _isSameDay(day, _focusedDay!);
667 4 : final hovered = _hoveredDay != null && _isSameDay(day, _hoveredDay!);
668 :
669 : final Color background;
670 : final Color foreground;
671 : final BorderRadiusGeometry radius;
672 : switch (fill) {
673 2 : case _DayFill.selected:
674 2 : background = v.selectedFill;
675 2 : foreground = v.selectedForeground;
676 4 : radius = BorderRadius.circular(v.dayRadius);
677 2 : case _DayFill.rangeStart:
678 2 : background = v.selectedFill;
679 2 : foreground = v.selectedForeground;
680 2 : radius = BorderRadiusDirectional.horizontal(
681 4 : start: Radius.circular(v.dayRadius),
682 : );
683 2 : case _DayFill.rangeEnd:
684 2 : background = v.selectedFill;
685 2 : foreground = v.selectedForeground;
686 2 : radius = BorderRadiusDirectional.horizontal(
687 4 : end: Radius.circular(v.dayRadius),
688 : );
689 2 : case _DayFill.rangeMiddle:
690 2 : background = v.rangeFill;
691 2 : foreground = v.foreground;
692 : radius = BorderRadius.zero;
693 2 : case _DayFill.none:
694 : background = hovered && selectable
695 1 : ? v.hoverFill
696 : : const Color(0x00000000);
697 4 : foreground = outside || !selectable ? v.mutedForeground : v.foreground;
698 4 : radius = BorderRadius.circular(v.dayRadius);
699 : }
700 :
701 : final dotColor = switch (fill) {
702 6 : _DayFill.none when !selectable => v.foreground.withValues(
703 : alpha: _todayDisabledOpacity,
704 : ),
705 2 : _DayFill.none => v.todayDotColor,
706 2 : _ => v.selectedTodayDotColor,
707 : };
708 :
709 2 : final Widget label = Text(
710 4 : '${day.day}',
711 4 : style: v.dayStyle.copyWith(
712 : color: foreground,
713 : decoration: selectable ? null : TextDecoration.lineThrough,
714 : ),
715 : );
716 :
717 2 : Widget content = DecoratedBox(
718 2 : decoration: ShapeDecoration(
719 : color: background,
720 2 : shape: RoundedSuperellipseBorder(borderRadius: radius),
721 : ),
722 2 : child: Stack(
723 : alignment: Alignment.center,
724 2 : children: <Widget>[
725 : label,
726 : if (today)
727 2 : Positioned(
728 4 : bottom: v.cellSize * 0.14,
729 2 : child: _TodayDot(color: dotColor),
730 : ),
731 : ],
732 : ),
733 : );
734 :
735 : if (focused) {
736 1 : content = CustomPaint(
737 1 : foregroundPainter: _DayRingPainter(
738 1 : color: v.ringColor,
739 3 : borderRadius: radius.resolve(Directionality.of(context)),
740 : ),
741 : child: content,
742 : );
743 : }
744 :
745 : if (!selectable) {
746 2 : content = Opacity(opacity: _disabledOpacity, child: content);
747 : }
748 :
749 2 : return MouseRegion(
750 4 : onEnter: selectable ? (_) => setState(() => _hoveredDay = day) : null,
751 : onExit: selectable
752 1 : ? (_) {
753 3 : if (_hoveredDay != null && _isSameDay(_hoveredDay!, day)) {
754 3 : setState(() => _hoveredDay = null);
755 : }
756 : }
757 : : null,
758 2 : child: Semantics(
759 : button: true,
760 2 : selected: fill != _DayFill.none,
761 : enabled: selectable,
762 2 : label: _dayLabel(day, today: today),
763 : // The gesture is excluded from semantics, so the tap action lives on
764 : // the node itself for screen-reader activation.
765 2 : onTap: selectable ? () => _handleTap(day) : null,
766 2 : child: GestureDetector(
767 : behavior: HitTestBehavior.opaque,
768 : excludeFromSemantics: true,
769 4 : onTap: selectable ? () => _handleTap(day) : null,
770 2 : child: ExcludeSemantics(
771 4 : child: SizedBox.square(dimension: v.cellSize, child: content),
772 : ),
773 : ),
774 : ),
775 : );
776 : }
777 :
778 2 : String _dayLabel(DateTime day, {required bool today}) {
779 12 : final base = '${_monthNames[day.month - 1]} ${day.day}, ${day.year}';
780 2 : return today ? '$base, today' : base;
781 : }
782 :
783 2 : _DayFill _fillState(DateTime day) {
784 4 : switch (widget._mode) {
785 2 : case _SelectionMode.single:
786 4 : final selected = widget._singleSelected;
787 2 : return selected != null && _isSameDay(day, selected)
788 : ? _DayFill.selected
789 : : _DayFill.none;
790 2 : case _SelectionMode.multiple:
791 4 : for (final s in widget._multipleSelected ?? const <DateTime>{}) {
792 1 : if (_isSameDay(day, s)) return _DayFill.selected;
793 : }
794 : return _DayFill.none;
795 2 : case _SelectionMode.range:
796 4 : final range = widget._rangeSelected;
797 : if (range == null) return _DayFill.none;
798 4 : final start = _dayOnly(range.start);
799 4 : final end = _dayOnly(range.end);
800 4 : if (_isSameDay(day, start) && _isSameDay(day, end)) {
801 : return _DayFill.selected;
802 : }
803 2 : if (_isSameDay(day, start)) return _DayFill.rangeStart;
804 2 : if (_isSameDay(day, end)) return _DayFill.rangeEnd;
805 4 : if (day.isAfter(start) && day.isBefore(end)) {
806 : return _DayFill.rangeMiddle;
807 : }
808 : return _DayFill.none;
809 : }
810 : }
811 : }
812 :
813 : /// The painted fill a day cell resolves to.
814 : enum _DayFill { none, selected, rangeStart, rangeMiddle, rangeEnd }
815 :
816 : /// Moves the roving day focus by [days], wrapping across month edges.
817 : class _MoveDaysIntent extends Intent {
818 4 : const _MoveDaysIntent(this.days);
819 :
820 : final int days;
821 : }
822 :
823 : /// Moves the roving day focus to the first or last day of its week row.
824 : class _WeekEdgeIntent extends Intent {
825 2 : const _WeekEdgeIntent({required this.end});
826 :
827 : final bool end;
828 : }
829 :
830 : /// Moves the roving day focus by [months], keeping the day of month.
831 : class _MoveMonthsIntent extends Intent {
832 2 : const _MoveMonthsIntent(this.months);
833 :
834 : final int months;
835 : }
836 :
837 : /// The bottom-center today marker: a small filled dot.
838 : class _TodayDot extends StatelessWidget {
839 2 : const _TodayDot({required this.color});
840 :
841 : final Color color;
842 :
843 2 : @override
844 2 : Widget build(BuildContext context) => Container(
845 : width: _todayDotSize,
846 : height: _todayDotSize,
847 4 : decoration: BoxDecoration(color: color, shape: BoxShape.circle),
848 : );
849 : }
850 :
851 : /// A ghost navigation button (previous / next month) with a painted chevron and
852 : /// a focus ring. Disabled at the bound.
853 : class _NavButton extends StatefulWidget {
854 2 : const _NavButton({
855 : required this.pointsLeft,
856 : required this.color,
857 : required this.ringColor,
858 : required this.size,
859 : required this.enabled,
860 : required this.semanticLabel,
861 : required this.onTap,
862 : });
863 :
864 : final bool pointsLeft;
865 : final Color color;
866 : final Color ringColor;
867 : final double size;
868 : final bool enabled;
869 : final String semanticLabel;
870 : final VoidCallback onTap;
871 :
872 2 : @override
873 2 : State<_NavButton> createState() => _NavButtonState();
874 : }
875 :
876 : class _NavButtonState extends State<_NavButton> {
877 : bool _focused = false;
878 :
879 2 : @override
880 : Widget build(BuildContext context) {
881 2 : Widget content = CustomPaint(
882 : size: const Size.square(_chevronSize),
883 2 : painter: _ChevronPainter(
884 4 : color: widget.color,
885 4 : pointsLeft: widget.pointsLeft,
886 : ),
887 : );
888 :
889 2 : if (_focused) {
890 1 : content = CustomPaint(
891 1 : foregroundPainter: _DayRingPainter(
892 2 : color: widget.ringColor,
893 2 : borderRadius: BorderRadius.circular(_chevronSize / 2),
894 : ),
895 1 : child: SizedBox.square(
896 2 : dimension: widget.size,
897 1 : child: Center(child: content),
898 : ),
899 : );
900 : } else {
901 2 : content = SizedBox.square(
902 4 : dimension: widget.size,
903 2 : child: Center(child: content),
904 : );
905 : }
906 :
907 4 : if (!widget.enabled) {
908 2 : content = Opacity(opacity: _disabledOpacity, child: content);
909 : }
910 :
911 2 : return Semantics(
912 : button: true,
913 4 : enabled: widget.enabled,
914 4 : label: widget.semanticLabel,
915 8 : onTap: widget.enabled ? widget.onTap : null,
916 2 : child: FocusableActionDetector(
917 4 : enabled: widget.enabled,
918 4 : mouseCursor: widget.enabled
919 : ? SystemMouseCursors.click
920 : : SystemMouseCursors.basic,
921 4 : onShowFocusHighlight: (value) => setState(() => _focused = value),
922 2 : actions: <Type, Action<Intent>>{
923 2 : ActivateIntent: CallbackAction<ActivateIntent>(
924 1 : onInvoke: (_) {
925 3 : widget.onTap();
926 : return null;
927 : },
928 : ),
929 : },
930 2 : child: GestureDetector(
931 : behavior: HitTestBehavior.opaque,
932 : excludeFromSemantics: true,
933 8 : onTap: widget.enabled ? widget.onTap : null,
934 : child: content,
935 : ),
936 : ),
937 : );
938 : }
939 : }
940 :
941 : /// Builds the default appearance from the theme tokens, then lays a
942 : /// per-instance [override] over it field by field.
943 2 : _CalendarVisuals _resolve(FossThemeData theme, FossCalendarStyle? override) {
944 2 : final c = theme.colors;
945 2 : final t = theme.typography;
946 4 : final muted = c.mutedForeground.withValues(alpha: _outsideOpacity);
947 2 : return _CalendarVisuals(
948 7 : dayStyle: override?.dayTextStyle ?? t.base.copyWith(color: c.foreground),
949 : weekdayStyle:
950 7 : override?.weekdayTextStyle ?? t.xs.medium.copyWith(color: muted),
951 : captionStyle:
952 1 : override?.captionTextStyle ??
953 8 : t.base.medium.copyWith(color: c.foreground),
954 3 : foreground: override?.dayForegroundColor ?? c.foreground,
955 1 : mutedForeground: override?.mutedForegroundColor ?? muted,
956 3 : selectedFill: override?.selectedColor ?? c.primary,
957 : selectedForeground:
958 3 : override?.selectedForegroundColor ?? c.primaryForeground,
959 3 : rangeFill: override?.rangeColor ?? c.accent,
960 3 : hoverFill: override?.hoverColor ?? c.accent,
961 3 : todayDotColor: override?.todayIndicatorColor ?? c.primary,
962 : selectedTodayDotColor:
963 3 : override?.selectedTodayIndicatorColor ?? c.background,
964 : ringColor:
965 5 : override?.focusRingColor ?? c.ring.withValues(alpha: _ringOpacity),
966 : chevronColor:
967 1 : override?.chevronColor ??
968 4 : c.foreground.withValues(alpha: _chevronOpacity),
969 5 : dayRadius: override?.dayRadius ?? theme.radii.lg,
970 1 : cellSize: override?.cellSize ?? _cellSize,
971 : );
972 : }
973 :
974 : /// The fully resolved, non-null appearance for the calendar. A
975 : /// [FossCalendarStyle] override is laid over it by [_resolve], so the widget
976 : /// reads only non-null fields.
977 : @immutable
978 : class _CalendarVisuals {
979 2 : const _CalendarVisuals({
980 : required this.dayStyle,
981 : required this.weekdayStyle,
982 : required this.captionStyle,
983 : required this.foreground,
984 : required this.mutedForeground,
985 : required this.selectedFill,
986 : required this.selectedForeground,
987 : required this.rangeFill,
988 : required this.hoverFill,
989 : required this.todayDotColor,
990 : required this.selectedTodayDotColor,
991 : required this.ringColor,
992 : required this.chevronColor,
993 : required this.dayRadius,
994 : required this.cellSize,
995 : });
996 :
997 : final TextStyle dayStyle;
998 : final TextStyle weekdayStyle;
999 : final TextStyle captionStyle;
1000 : final Color foreground;
1001 : final Color mutedForeground;
1002 : final Color selectedFill;
1003 : final Color selectedForeground;
1004 : final Color rangeFill;
1005 : final Color hoverFill;
1006 : final Color todayDotColor;
1007 : final Color selectedTodayDotColor;
1008 : final Color ringColor;
1009 : final Color chevronColor;
1010 : final double dayRadius;
1011 : final double cellSize;
1012 : }
1013 :
1014 : // Month math. Pure helpers over calendar days, shared by the state and tested
1015 : // through the rendered grid.
1016 :
1017 10 : DateTime _dayOnly(DateTime d) => DateTime(d.year, d.month, d.day);
1018 :
1019 8 : DateTime _firstOfMonth(DateTime d) => DateTime(d.year, d.month);
1020 :
1021 2 : int _daysInMonth(DateTime month) =>
1022 10 : DateTime(month.year, month.month + 1, 0).day;
1023 :
1024 8 : int _dayKey(DateTime d) => d.year * 10000 + d.month * 100 + d.day;
1025 :
1026 3 : bool _isSameDay(DateTime a, DateTime b) =>
1027 27 : a.year == b.year && a.month == b.month && a.day == b.day;
1028 :
1029 : // Days from [firstDayOfWeek] back to the week start containing [day].
1030 2 : int _leadingOffset(DateTime day, int firstDayOfWeek) =>
1031 8 : (day.weekday - firstDayOfWeek + _columns) % _columns;
1032 :
1033 : // The grid days for [month]: the weeks it spans (four to six rows of seven),
1034 : // padded at the ends with adjacent-month days so every row is full.
1035 2 : List<DateTime> _gridDays(DateTime month, int firstDayOfWeek) {
1036 2 : final first = _firstOfMonth(month);
1037 2 : final lead = _leadingOffset(first, firstDayOfWeek);
1038 4 : final total = lead + _daysInMonth(month);
1039 6 : final rows = (total + _columns - 1) ~/ _columns;
1040 10 : final start = DateTime(first.year, first.month, first.day - lead);
1041 2 : return <DateTime>[
1042 6 : for (var i = 0; i < rows * _columns; i++)
1043 10 : DateTime(start.year, start.month, start.day + i),
1044 : ];
1045 : }
|