import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/show_error_dialog.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:intl/intl.dart'; import 'package:material_ui/material_ui.dart'; import 'package:table_calendar/table_calendar.dart'; class CalendarWidget extends StatefulWidget { const CalendarWidget({super.key, this.date}); final DateTime? date; @override State createState() => _CalendarWidgetState(); } class _CalendarWidgetState extends State with SingleTickerProviderStateMixin { static const _locale = 'ru_RU'; static const _kDaysOfWeekHeight = 16.0; static const _kRowHeight = 52.0; static const _dayCellMargin = 6.0; static const _dragHandlePadding = 5.0; late final _expansion = AnimationController( vsync: this, duration: const Duration(milliseconds: 180), ); DateTime _focusedDay = DateTime.now(); DateTime _selectedDay = DateTime.now(); DateTime? _dayFromState(DiaryState state) { if (state is DiaryStateLoaded) { return state.selectedDay; } if (state is DiaryStateLoadedTomorrowWithDiet) { return state.selectedDay; } return null; } @override void initState() { super.initState(); final selected = widget.date ?? _dayFromState(context.read().state); if (selected != null) { _selectedDay = selected; _focusedDay = selected; } } @override void didUpdateWidget(CalendarWidget oldWidget) { super.didUpdateWidget(oldWidget); if (widget.date != null && widget.date != oldWidget.date) { _selectedDay = widget.date!; _focusedDay = widget.date!; } } @override void dispose() { _expansion.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final rowHeight = MediaQuery.textScalerOf(context).scale(_kRowHeight); final firstOfMonth = DateTime.utc(_focusedDay.year, _focusedDay.month); final daysInMonth = DateTime.utc( _focusedDay.year, _focusedDay.month + 1, 0, ).day; final daysBeforeMonth = firstOfMonth.weekday - DateTime.monday; final weekCount = (daysBeforeMonth + daysInMonth + 6) ~/ 7; final focusedWeek = (daysBeforeMonth + _focusedDay.day - 1) ~/ 7; final extraHeight = (weekCount - 1) * rowHeight; final week = _buildDays(rowHeight, CalendarFormat.week); final month = _buildDays(rowHeight, CalendarFormat.month); return BlocListener( listener: (context, state) { final selected = _dayFromState(state); if (selected != null) { setState(() { _selectedDay = selected; _focusedDay = selected; }); } }, child: Padding( padding: const EdgeInsets.only(top: 4), child: AnimatedBuilder( animation: _expansion, child: _buildWeekdays(context), builder: (context, weekdays) { return Column( mainAxisSize: MainAxisSize.min, children: [ _buildHeader(context), weekdays!, ClipRect( child: SizedBox( height: rowHeight + extraHeight * _expansion.value, child: OverflowBox( // При раскрытии показываем строки вокруг открытой недели. alignment: Alignment( 0, 2 * focusedWeek / (weekCount - 1) - 1, ), minHeight: 0, maxHeight: double.infinity, child: _expansion.value == 0 ? week : month, ), ), ), _buildDragHandle(extraHeight), ], ); }, ), ), ); } Widget _buildHeader(BuildContext context) { final s = S.of(context); final expanded = _expansion.value >= 0.5; final label = DateFormat.yMMMM(_locale).format(_focusedDay); return Tooltip( message: expanded ? s.hide : s.expand, child: InkWell( onTap: () => _expansion.value = expanded ? 0 : 1, borderRadius: BorderRadius.circular(8), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8), child: Row( mainAxisSize: MainAxisSize.min, children: [ Text(label, style: const HeaderStyle().titleTextStyle), const SizedBox(width: 4), Icon( expanded ? Icons.keyboard_arrow_up_rounded : Icons.keyboard_arrow_down_rounded, size: 18, color: appTheme.blueA400, ), ], ), ), ), ); } Widget _buildWeekdays(BuildContext context) { const style = DaysOfWeekStyle(); final format = DateFormat.E(_locale); return ExcludeSemantics( child: SizedBox( height: _scaledDaysOfWeekHeight(context), child: Row( children: List.generate(DateTime.daysPerWeek, (index) { final day = DateTime.utc( _focusedDay.year, _focusedDay.month, _focusedDay.day - _focusedDay.weekday + DateTime.monday + index, ); return Expanded( child: Center( child: Text( format.format(day), style: day.weekday >= DateTime.saturday ? style.weekendStyle : style.weekdayStyle, ), ), ); }), ), ), ); } Widget _buildDays(double rowHeight, CalendarFormat format) { return TableCalendar( key: ValueKey(format), focusedDay: _focusedDay, firstDay: DateTime.utc(2020, 10, 16), lastDay: DateTime.utc(2030, 3, 14), locale: _locale, startingDayOfWeek: StartingDayOfWeek.monday, calendarFormat: format, availableGestures: AvailableGestures.horizontalSwipe, headerVisible: false, daysOfWeekVisible: false, rowHeight: rowHeight, onDaySelected: _selectDay, selectedDayPredicate: (day) => isSameDay(_selectedDay, day), onPageChanged: (focusedDay) => setState(() => _focusedDay = focusedDay), calendarStyle: CalendarStyle( cellMargin: const EdgeInsets.all(_dayCellMargin), weekendDecoration: const BoxDecoration( color: Colors.white, shape: BoxShape.circle, ), defaultDecoration: const BoxDecoration( color: Colors.white, shape: BoxShape.circle, ), selectedDecoration: BoxDecoration( color: appTheme.blueA400, shape: BoxShape.circle, ), todayTextStyle: const TextStyle(color: Colors.black), todayDecoration: BoxDecoration( border: Border.all(color: appTheme.blueA400, width: 2), color: Colors.white, shape: BoxShape.circle, ), ), ); } Future _selectDay(DateTime selectedDay, DateTime focusedDay) async { if (isSameDay(_selectedDay, selectedDay)) return; final previousSelectedDay = _selectedDay; final previousFocusedDay = _focusedDay; setState(() { _selectedDay = selectedDay; _focusedDay = focusedDay; }); final cubit = context.read(); final canOpenNextDay = await cubit.setSelectedDay(selectedDay); if (!mounted || cubit.state is DiaryStateError || canOpenNextDay) return; final s = S.of(context); showErrorDialog( context, title: s.want_to_see_tomorrow, description: s.can_not_see_next_day, ); setState(() { _selectedDay = previousSelectedDay; _focusedDay = previousFocusedDay; }); } double _scaledDaysOfWeekHeight(BuildContext context) { final painter = TextPainter( text: TextSpan(text: 'Щy', style: DefaultTextStyle.of(context).style), textDirection: Directionality.of(context), textScaler: MediaQuery.textScalerOf(context), maxLines: 1, )..layout(); final height = painter.height; painter.dispose(); return height.clamp(_kDaysOfWeekHeight, double.infinity); } Widget _buildDragHandle(double extraHeight) { return GestureDetector( behavior: HitTestBehavior.opaque, dragStartBehavior: DragStartBehavior.down, onVerticalDragStart: (_) => _expansion.stop(), onVerticalDragUpdate: (details) { _expansion.value = (_expansion.value + details.delta.dy / extraHeight) .clamp(0.0, 1.0); }, onVerticalDragEnd: (details) => _settleExpansion(details.velocity.pixelsPerSecond.dy), onVerticalDragCancel: _settleExpansion, child: SizedBox( width: double.infinity, child: Padding( // Отступ ячеек уже добавляет место над полоской. padding: const EdgeInsets.only( top: _dragHandlePadding, bottom: _dragHandlePadding + _dayCellMargin, ), child: Center( child: DecoratedBox( decoration: BoxDecoration( color: appTheme.blueA400, borderRadius: BorderRadius.circular(2), ), child: const SizedBox(width: 28, height: 4), ), ), ), ), ); } void _settleExpansion([double velocity = 0]) { final shouldExpand = velocity.abs() >= 400 ? velocity > 0 : _expansion.value >= 0.5; _expansion.animateTo(shouldExpand ? 1 : 0, curve: Curves.easeOutCubic); } }