diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a521953..bafe22b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,8 @@ # [Unreleased - 11 May 2026] +- [BREAKING] Added `BuildContextExtension` to public API for theme access. +- Added `ScheduleView`, a scrollable, agenda-style calendar that groups events by day and month. [#101](https://github.com/SimformSolutionsPvtLtd/flutter_calendar_view/issues/101) +- Added localized `months` and `monthsAbbr` fields to `CalendarLocalizations`, with the `DateTime.getMonthName({abbreviated})` and `DateTime.getMonthYear({abbreviatedMonth})` extensions. - [BREAKING] Changed `RecurrenceSettings.weekdays` type from `List` to `List`. [#509](https://github.com/SimformSolutionsPvtLtd/flutter_calendar_view/issues/509) - [BREAKING] `WeekDayBuilder`'s parameter changed from `int day` to `WeekDays weekDay`. - [BREAKING] Removed `startTime` and `endTime` from `CalendarEventData` constructor and `copyWith` parameters. Time is now embedded in the `date` and `endDate` `DateTime` parameters. [#231](https://github.com/SimformSolutionsPvtLtd/flutter_calendar_view/issues/231) diff --git a/doc/documentation.md b/doc/documentation.md index d3ca168b..966859a2 100644 --- a/doc/documentation.md +++ b/doc/documentation.md @@ -14,6 +14,7 @@ This package is a comprehensive Flutter solution that enables you to easily impl - Day View - Week View - MultiDay View + - Schedule View - Highly customisable UI components - Manage events (add, remove, update) - Manage reminders (add, remove, update) @@ -109,6 +110,14 @@ Scaffold( ); ``` +### Schedule View + +```dart +Scaffold( + body: ScheduleView(), +); +``` + ## Managing Events ### Adding an event @@ -553,6 +562,84 @@ MultiDayView( ); ``` +## Schedule View Customization + +`ScheduleView` is a scrollable, agenda-style calendar that groups events by day and month. Months are built lazily as they scroll into view, and the list is anchored at `initialDay`. + +```dart +ScheduleView( + controller: EventController(), + // Anchor and date boundaries + initialDay: DateTime.now(), // Date pinned to the top of the viewport + minDay: DateTime(2000), // Earliest date the view will display + maxDay: DateTime(2050), // Latest date the view will display + // Which days/months are rendered + showEmptyMonths: true, // Render months that contain no events (default true) + showDaysWithoutEvents: false, // Render a row for every day, even empty ones (default false) + // Date placement + dateLayout: ScheduleDateLayout.left, // .left (date column) or .top (full-width date header) + // Custom builders + monthHeaderBuilder: (date) => Text(date.getMonthYear()), + dateHeaderBuilder: (date, events, layout) => Text('${date.day}'), + // dayDetectorBuilder takes full control of the date column, including gestures. + // When set, onDateTap / onDateLongPress are ignored. + dayDetectorBuilder: (date, events, layout) => Container(), + eventTileBuilder: (event, date) => ListTile( + leading: CircleAvatar(backgroundColor: event.color), + title: Text(event.title), + ), + emptyMonthBuilder: (date) => Text('No events this month'), // Replaces empty months (showEmptyMonths must be true) + emptyTextWidget: Text('No events'), // Empty-day placeholder (needs showDaysWithoutEvents: true) + todayEmptyWidget: Text('Nothing planned today'), // Takes precedence over emptyTextWidget for today + // Floating month header pinned above the scroll view + floatingMonthHeaderBuilder: (context, visibleMonth) => Padding( + padding: const EdgeInsets.all(12), + child: Text(visibleMonth.getMonthYear()), + ), + onVisibleMonthChanged: (month) => print('Visible month: $month'), + // Sentinels shown once the scroll limits are reached + pastSentinelBuilder: (context) => const Center(child: Text('Start of calendar')), + futureSentinelBuilder: (context) => const Center(child: Text('End of calendar')), + // I18n / formatting for the default renderers + dateStringBuilder: (date, {secondaryDate}) => date.getMonthYear(), + weekDayStringBuilder: (weekday) => ['M', 'T', 'W', 'T', 'F', 'S', 'S'][weekday - 1], + // Sort events within a single day (defaults to ascending start time) + eventSorter: (a, b) => a.title.compareTo(b.title), + // Divider beneath the default date header in ScheduleDateLayout.top + defaultDateHeaderDividerSettings: DividerSettings(thickness: 1, color: Colors.grey), + // Event callbacks (each receives a single-element list + the date) + onEventTap: (events, date) => print(events), + onEventDoubleTap: (events, date) => print(events), + onEventLongTap: (events, date) => print(events), + onDateTap: (date) => print('Tapped: $date'), + onDateLongPress: (date) => print('Long pressed: $date'), + // Boundary callbacks (fire once when each end of the range is reached) + onHasReachedStart: () => print('Reached earliest available month'), + onHasReachedEnd: () => print('Reached latest available month'), + // Appearance + backgroundColor: Colors.white, + width: 400, // Explicit width; null fills available space + scrollPhysics: const BouncingScrollPhysics(), +); +``` + +### Navigating programmatically + +Use a `GlobalKey` to jump to a specific date. The target date is pinned to the top of the viewport, with earlier days reachable by scrolling up. + +```dart +final key = GlobalKey(); + +ScheduleView(key: key); + +key.currentState?.jumpToDate(DateTime(2026, 1, 1)); +``` + +### Sparse vs. dense rendering + +- **Dense (default)** — `showEmptyMonths: true` always renders every month in range, and/or `showDaysWithoutEvents: true` renders a row for every day. +- **Sparse** — set `showEmptyMonths: false` (with `showDaysWithoutEvents: false`) so only days with events (plus today) render, and the scrollable range is clamped to the actual extent of the controller's events. This keeps the view responsive even when `minDay`/`maxDay` span decades. + ## Show Only Working Days in `WeekView` You can control visible weekdays using the `weekDays` parameter: @@ -857,6 +944,7 @@ The package supports dark mode out of the box. Each calendar view has a dedicate | `DayViewThemeData` | `DayView` | | `WeekViewThemeData` | `WeekView` | | `MultiDayViewThemeData` | `MultiDayView` | +| `ScheduleViewThemeData` | `ScheduleView` | ## Default colours @@ -926,6 +1014,25 @@ The package supports dark mode out of the box. Each calendar view has a dedicate | `headerTextColor` | `onPrimary` | | `headerBackgroundColor` | `primary` | +### ScheduleViewThemeData + +| Property | Default (light) | +|----------|----------------| +| `todayHighlightColor` | `primary` | +| `todayTextColor` | `onPrimary` | +| `dateTextColor` | `onSurface` | +| `weekdayTextColor` | `outlineVariant` | +| `dateDividerColor` | `outlineVariant` | +| `emptyContentColor` | `emptyContent` | +| `eventTitleColor` | `onSurface` | +| `eventSecondaryTextColor` | `outline` | +| `eventTileAlpha` | `28` (light) / `45` (dark) | +| `eventTimeColorLightnessAdjust` | `-0.1` (light) / `0.0` (dark) | +| `monthHeaderTextColor` | `monthHeaderText` | +| `monthHeaderGradientStartColor` | `transparent` | +| `monthHeaderGradientEndColor` | `monthHeaderGradientEnd` | +| `monthHeaderTextShadowColor` | `monthHeaderTextShadow` | + To customise `MonthView`, `DayView`, `WeekView` & `MultiDayView` page header use `HeaderStyle`. ```dart @@ -953,6 +1060,7 @@ There are two main ways to customize the theme for calendar views: dayViewTheme: DayViewThemeData.light(), weekViewTheme: WeekViewThemeData.light(), multiDayViewTheme: MultiDayViewThemeData.light(), + scheduleViewTheme: ScheduleViewThemeData.light(), ), child: YourApp(), ) @@ -973,6 +1081,7 @@ There are two main ways to customize the theme for calendar views: DayViewThemeData.light(), WeekViewThemeData.light(), MultiDayViewThemeData.light(), + ScheduleViewThemeData.light(), ], ); ``` @@ -1112,6 +1221,30 @@ Hide divider in multiday view. dividerSettings: DividerSettings.none(), ``` +### Schedule View +* All schedule colours resolve from `ScheduleViewThemeData` (`context.scheduleViewColors`), falling back to `.light()` / `.dark()` based on `Theme.of(context).brightness`. +* Today's date badge uses `todayHighlightColor` (background) and `todayTextColor` (number). Other dates use `dateTextColor`, and weekday abbreviations use `weekdayTextColor`. +* Event tiles tint the event's own colour by `eventTileAlpha`; the time label is adjusted by `eventTimeColorLightnessAdjust`. Title and secondary text use `eventTitleColor` and `eventSecondaryTextColor`. +* Empty-state labels (per-day placeholder and the past/future sentinels) use `emptyContentColor`. +* The month-header image overlay uses `monthHeaderGradientStartColor` → `monthHeaderGradientEndColor`, with `monthHeaderTextColor` and `monthHeaderTextShadowColor` for the title. +* In `ScheduleDateLayout.top`, the divider beneath the default date header uses `dateDividerColor`; override it per-widget with `defaultDateHeaderDividerSettings` (use `DividerSettings.none()` to hide it). + +```dart +CalendarThemeProvider( + calendarTheme: CalendarThemeData( + monthViewTheme: MonthViewThemeData.light(), + dayViewTheme: DayViewThemeData.light(), + weekViewTheme: WeekViewThemeData.light(), + multiDayViewTheme: MultiDayViewThemeData.light(), + scheduleViewTheme: ScheduleViewThemeData.light().copyWith( + todayHighlightColor: Colors.blue, + eventTileAlpha: 40, + ), + ), + child: YourApp(), +) +``` + # Migration Guides ## Migrating from 2.x.x to latest diff --git a/example/assets/images/april_header.jpg b/example/assets/images/april_header.jpg new file mode 100644 index 00000000..b93d5f03 Binary files /dev/null and b/example/assets/images/april_header.jpg differ diff --git a/example/assets/images/august_header.jpg b/example/assets/images/august_header.jpg new file mode 100644 index 00000000..bbdefdb1 Binary files /dev/null and b/example/assets/images/august_header.jpg differ diff --git a/example/assets/images/december_header.jpg b/example/assets/images/december_header.jpg new file mode 100644 index 00000000..4b0d61bb Binary files /dev/null and b/example/assets/images/december_header.jpg differ diff --git a/example/assets/images/february_header.jpg b/example/assets/images/february_header.jpg new file mode 100644 index 00000000..96df4c6e Binary files /dev/null and b/example/assets/images/february_header.jpg differ diff --git a/example/assets/images/january_header.jpg b/example/assets/images/january_header.jpg new file mode 100644 index 00000000..f819bd48 Binary files /dev/null and b/example/assets/images/january_header.jpg differ diff --git a/example/assets/images/july_header.jpg b/example/assets/images/july_header.jpg new file mode 100644 index 00000000..2408a170 Binary files /dev/null and b/example/assets/images/july_header.jpg differ diff --git a/example/assets/images/june_header.jpg b/example/assets/images/june_header.jpg new file mode 100644 index 00000000..8be4f292 Binary files /dev/null and b/example/assets/images/june_header.jpg differ diff --git a/example/assets/images/march_header.jpg b/example/assets/images/march_header.jpg new file mode 100644 index 00000000..40287e90 Binary files /dev/null and b/example/assets/images/march_header.jpg differ diff --git a/example/assets/images/may_header.jpg b/example/assets/images/may_header.jpg new file mode 100644 index 00000000..5b1c8b8e Binary files /dev/null and b/example/assets/images/may_header.jpg differ diff --git a/example/assets/images/november_header.jpg b/example/assets/images/november_header.jpg new file mode 100644 index 00000000..56afe5a7 Binary files /dev/null and b/example/assets/images/november_header.jpg differ diff --git a/example/assets/images/october_header.jpg b/example/assets/images/october_header.jpg new file mode 100644 index 00000000..bd1dd97d Binary files /dev/null and b/example/assets/images/october_header.jpg differ diff --git a/example/assets/images/september_header.jpg b/example/assets/images/september_header.jpg new file mode 100644 index 00000000..e196287b Binary files /dev/null and b/example/assets/images/september_header.jpg differ diff --git a/example/lib/enumerations.dart b/example/lib/enumerations.dart index c14950ee..1bc16c86 100644 --- a/example/lib/enumerations.dart +++ b/example/lib/enumerations.dart @@ -1 +1,18 @@ -enum CalendarView { month, day, week, multiday } +/// Defines the type of calendar view. +enum CalendarView { month, day, week, multiday, schedule } + +/// Defines the months of the year. +enum Months { + january, + february, + march, + april, + may, + june, + july, + august, + september, + october, + november, + december, +} diff --git a/example/lib/extension.dart b/example/lib/extension.dart index cae830f1..2b01bb57 100644 --- a/example/lib/extension.dart +++ b/example/lib/extension.dart @@ -1,7 +1,10 @@ +import 'package:calendar_view/calendar_view.dart'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; +import 'enumerations.dart'; import 'l10n/app_localizations.dart'; +import 'localization/locale_controller.dart'; import 'theme/app_colors.dart'; import 'theme/app_theme_extension.dart'; @@ -13,9 +16,33 @@ extension NavigatorExtention on BuildContext { void pop([dynamic value]) => Navigator.of(this).pop(value); - void showSnackBarWithText(String text) => ScaffoldMessenger.of(this) + void showSnackBarWithText( + String text, { + Duration duration = const Duration(seconds: 3), + }) => ScaffoldMessenger.of(this) ..hideCurrentSnackBar() - ..showSnackBar(SnackBar(content: Text(text))); + ..showSnackBar(SnackBar(content: Text(text), duration: duration)); +} + +extension MonthHeaderImageExtension on Months { + /// Returns the asset path for this month's header image. + String get imagePath { + const paths = [ + 'assets/images/january_header.jpg', + 'assets/images/february_header.jpg', + 'assets/images/march_header.jpg', + 'assets/images/april_header.jpg', + 'assets/images/may_header.jpg', + 'assets/images/june_header.jpg', + 'assets/images/july_header.jpg', + 'assets/images/august_header.jpg', + 'assets/images/september_header.jpg', + 'assets/images/october_header.jpg', + 'assets/images/november_header.jpg', + 'assets/images/december_header.jpg', + ]; + return paths[index]; + } } extension DateUtils on DateTime { @@ -40,12 +67,15 @@ extension DateUtils on DateTime { ); String dateToStringWithFormat({String format = 'y-M-d'}) { - return DateFormat(format).format(this); + // Localize the digits of the formatted date so non-Latin locales + // (Arabic, Hindi, …) render their own numerals instead of `0-9`. + return PackageStrings.localizeNumberString(DateFormat(format).format(this)); } - String getTimeInFormat(TimeStampFormat format) => DateFormat( - 'h:mm${format == TimeStampFormat.parse_12 ? " a" : ""}', - ).format(this).toUpperCase(); + /// Formats the time component, delegating to [TimeOfDayExtension] so both + /// the digits and the AM/PM marker follow the current package locale. + String getTimeInFormat(TimeStampFormat format) => + TimeOfDay.fromDateTime(this).getTimeInFormat(format); } extension ColorExtension on Color { @@ -58,17 +88,26 @@ extension ColorExtension on Color { } extension TimeOfDayExtension on TimeOfDay { - /// Formats the time as a string (e.g., "2:30 PM" or "14:30") + /// Formats the time as a localized string (e.g., "2:30 p. m." or "14:30"). + /// + /// Digits are localized via [PackageStrings.localizeNumberString] and the + /// AM/PM marker via the current locale's [CalendarLocalizations], so both + /// follow the locale set through [PackageStrings.setLocale]. String getTimeInFormat(TimeStampFormat format) { + final locale = PackageStrings.currentLocale; if (format == TimeStampFormat.parse_12) { - final period = hour >= 12 ? 'PM' : 'AM'; + final period = hour >= 12 ? locale.pm : locale.am; final displayHour = hour == 0 ? 12 : (hour > 12 ? hour - 12 : hour); final minuteStr = minute.toString().padLeft(2, '0'); - return '$displayHour:$minuteStr $period'; + // Localize the whole "h:mm" chunk at once to keep the leading zero. + final time = PackageStrings.localizeNumberString( + '$displayHour:$minuteStr', + ); + return '$time $period'; } else { final hourStr = hour.toString().padLeft(2, '0'); final minuteStr = minute.toString().padLeft(2, '0'); - return '$hourStr:$minuteStr'; + return PackageStrings.localizeNumberString('$hourStr:$minuteStr'); } } } @@ -79,6 +118,30 @@ extension BuildContextExtension on BuildContext { AppThemeExtension.light(); } +extension LocalizedDateExtension on DateTime { + /// Returns the day-of-month as a localized string, rebuilding the widget + /// whenever the locale changes via [LocaleController]. + String localizedDay(BuildContext context) { + LocaleController.of(context); + return PackageStrings.localizeNumber(day); + } + + /// Returns the date formatted as a localized short date (e.g. "6/4/2026") + /// using the current Flutter locale from [context]. + /// + /// `intl` provides the locale-aware field order and separators (e.g. the + /// RTL layout for Arabic), but its generic `ar` data carries no native + /// digits, so the digits are localized afterwards through + /// [PackageStrings.localizeNumberString] to stay consistent with + /// [localizedDay]. + String localizedShortDate(BuildContext context) { + final locale = Localizations.localeOf(context).toString(); + return PackageStrings.localizeNumberString( + DateFormat.yMd(locale).format(this), + ); + } +} + extension Translate on BuildContext { AppLocalizations get translate => AppLocalizations.of(this)!; } diff --git a/example/lib/l10n/app_ar.arb b/example/lib/l10n/app_ar.arb index 69f2f750..b9e30153 100644 --- a/example/lib/l10n/app_ar.arb +++ b/example/lib/l10n/app_ar.arb @@ -6,6 +6,7 @@ "dayView": "عرض يومي", "weekView": "عرض أسبوعي", "multidayView": "عرض متعدد الأيام", + "scheduleView": "عرض الجدول الزمني", "appTitle": "مثال صفحة تقويم فلاتر", "projectMeetingTitle": "اجتماع المشروع", "projectMeetingDesc": "اليوم هو اجتماع المشروع.", @@ -17,7 +18,7 @@ "weddingAnniversaryDesc": "حضور ذكرى زواج العم.", "footballTournamentTitle": "بطولة كرة القدم", "footballTournamentDesc": "الذهاب إلى بطولة كرة القدم.", - "sprintMeetingTitle": "اجتماع Sprint", + "sprintMeetingTitle": "اجتماع السبرينت", "sprintMeetingDesc": "آخر يوم لتسليم المشروع للسنة الماضية.", "teamMeetingTitle": "اجتماع الفريق", "teamMeetingDesc": "اجتماع الفريق", @@ -119,5 +120,19 @@ "lateNightWorkTitle": "عمل متأخر في الليل", "lateNightWorkDesc": "اختبار حدود نهاية اليوم", "companyRetreatTitle": "رحلة شركة", - "companyRetreatDesc": "اختبار حدث متعدد الأيام طوال اليوم" + "companyRetreatDesc": "اختبار حدث متعدد الأيام طوال اليوم", + "doctorsAppointmentTitle": "موعد مع الطبيب", + "doctorsAppointmentDesc": "فحص شهري دوري", + "today": "اليوم", + "scheduleAllDay": "طوال اليوم", + "scheduleNoEvents": "لا توجد خطط. اضغط للإنشاء!", + "scheduleNoEventsThisMonth": "لا أحداث هذا الشهر", + "scheduleTodayNoEvents": "لا توجد أحداث اليوم. استمتع بيومك!", + "scheduleLongPressed": "ضغط مطوّل", + "scheduleSettings": "إعدادات الجدول", + "scheduleShowDaysWithoutEvents": "إظهار الأيام بدون أحداث", + "scheduleShowEmptyMonths": "إظهار الأشهر الفارغة", + "scheduleDateLayout": "تخطيط التاريخ", + "scheduleDateLayoutLeft": "عمود", + "scheduleDateLayoutTop": "صف" } diff --git a/example/lib/l10n/app_en.arb b/example/lib/l10n/app_en.arb index 6bb4f611..9807e101 100644 --- a/example/lib/l10n/app_en.arb +++ b/example/lib/l10n/app_en.arb @@ -6,6 +6,7 @@ "dayView": "Day View", "weekView": "Week View", "multidayView": "Multi-Day View", + "scheduleView": "Schedule View", "appTitle": "Flutter Calendar Page Demo", "projectMeetingTitle": "Project meeting", "projectMeetingDesc": "Today is project meeting.", @@ -119,5 +120,19 @@ "lateNightWorkTitle": "Late Night Work", "lateNightWorkDesc": "Tests end of day boundary", "companyRetreatTitle": "Company Retreat", - "companyRetreatDesc": "Tests multi-day all-day event" + "companyRetreatDesc": "Tests multi-day all-day event", + "doctorsAppointmentTitle": "Doctor's appointment", + "doctorsAppointmentDesc": "Regular monthly checkup", + "today": "Today", + "scheduleAllDay": "All day", + "scheduleNoEvents": "Nothing planned. Tap to create!", + "scheduleNoEventsThisMonth": "No events this month", + "scheduleTodayNoEvents": "No events planned today.\nEnjoy your day!", + "scheduleLongPressed": "Long pressed", + "scheduleSettings": "Schedule settings", + "scheduleShowDaysWithoutEvents": "Show days without events", + "scheduleShowEmptyMonths": "Show empty months", + "scheduleDateLayout": "Date layout", + "scheduleDateLayoutLeft": "Column", + "scheduleDateLayoutTop": "Row" } diff --git a/example/lib/l10n/app_es.arb b/example/lib/l10n/app_es.arb index 0cd1b82c..1e378953 100644 --- a/example/lib/l10n/app_es.arb +++ b/example/lib/l10n/app_es.arb @@ -6,6 +6,7 @@ "dayView": "Vista Diaria", "weekView": "Vista Semanal", "multidayView": "Vista de Varios Días", + "scheduleView":"Vista de programación", "appTitle": "Demo de Página de Calendario Flutter", "projectMeetingTitle": "Reunión del proyecto", "projectMeetingDesc": "Hoy hay reunión del proyecto.", @@ -119,5 +120,19 @@ "lateNightWorkTitle": "Trabajo Tarde en la Noche", "lateNightWorkDesc": "Prueba límite de fin de día", "companyRetreatTitle": "Retiro de Empresa", - "companyRetreatDesc": "Prueba evento de varios días de todo el día" + "companyRetreatDesc": "Prueba evento de varios días de todo el día", + "doctorsAppointmentTitle": "Cita con el médico", + "doctorsAppointmentDesc": "Revisión mensual regular", + "today":"Hoy", + "scheduleAllDay": "Todo el día", + "scheduleNoEvents": "Sin planes. ¡Toca para crear!", + "scheduleNoEventsThisMonth": "Sin eventos este mes", + "scheduleTodayNoEvents": "No hay eventos hoy.\n¡Disfruta tu día!", + "scheduleLongPressed": "Pulsado prolongadamente", + "scheduleSettings": "Configuración de agenda", + "scheduleShowDaysWithoutEvents": "Mostrar días sin eventos", + "scheduleShowEmptyMonths": "Mostrar meses vacíos", + "scheduleDateLayout": "Diseño de fecha", + "scheduleDateLayoutLeft": "Columna", + "scheduleDateLayoutTop": "Fila" } diff --git a/example/lib/localization/calendar_locales.dart b/example/lib/localization/calendar_locales.dart index 3e406202..8801919a 100644 --- a/example/lib/localization/calendar_locales.dart +++ b/example/lib/localization/calendar_locales.dart @@ -12,6 +12,8 @@ class CalendarLocales { pm: PackageStrings.spanish.pm, more: 'Ver más', weekdays: ['Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb', 'Dom'], + months: PackageStrings.spanish.months, + monthsAbbr: PackageStrings.spanish.monthsAbbr, ); /// Initialize and register calendar localizations diff --git a/example/lib/main.dart b/example/lib/main.dart index febc0474..b171da49 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -55,6 +55,9 @@ class _MyAppState extends State { multiDayViewTheme: isDarkMode ? MultiDayViewThemeData.dark() : MultiDayViewThemeData.light(), + scheduleViewTheme: isDarkMode + ? ScheduleViewThemeData.dark() + : ScheduleViewThemeData.light(), ), child: CalendarControllerProvider( controller: EventController(), diff --git a/example/lib/pages/home_page.dart b/example/lib/pages/home_page.dart index ad036477..66b40ef1 100644 --- a/example/lib/pages/home_page.dart +++ b/example/lib/pages/home_page.dart @@ -37,6 +37,7 @@ class _HomePageState extends State { DateTime(base.year, base.month, base.day, hour, minute); final translate = context.translate; + //#region Calendar Events final events = [ // ========== EDGE CASE 1: Midnight boundary events ========== // Event that spans across midnight (23:00 to 01:00 next day) @@ -194,7 +195,7 @@ class _HomePageState extends State { color: Colors.deepPurple, ), - // ========== EDGE CASE 11: Monthly recurring event ========== + // ========== EDGE CASE 11: Monthly recurring events ========== CalendarEventData.timeRanged( title: translate.monthlyReviewTitle, description: translate.monthlyReviewDesc, @@ -209,6 +210,19 @@ class _HomePageState extends State { color: Colors.pink, ), + CalendarEventData.timeRanged( + title: translate.doctorsAppointmentTitle, + description: translate.doctorsAppointmentDesc, + date: shortDate(_now, 12, 0), + endDate: shortDate(_now, 13, 0), + recurrenceSettings: RecurrenceSettings.withCalculatedEndDate( + startDate: _now, + frequency: RepeatFrequency.monthly, + recurrenceEndOn: RecurrenceEnd.never, + ), + color: Colors.lightGreen, + ), + // ========== EDGE CASE 12: Event with custom styles ========== CalendarEventData.timeRanged( title: translate.vipClientMeetingTitle, @@ -330,6 +344,7 @@ class _HomePageState extends State { endDate: shortDate(_now.subtract(Duration(days: 2)), 16, 0), ), ]; + //#endregion _controller!.addAll(events); } } diff --git a/example/lib/pages/mobile/mobile_home_page.dart b/example/lib/pages/mobile/mobile_home_page.dart index 3f8e55fb..34f02253 100644 --- a/example/lib/pages/mobile/mobile_home_page.dart +++ b/example/lib/pages/mobile/mobile_home_page.dart @@ -5,6 +5,7 @@ import '../../localization/locale_controller.dart'; import '../day_view_page.dart'; import '../month_view_page.dart'; import '../multi_day_view_page.dart'; +import '../schedule_view_page.dart'; import '../week_view_page.dart'; class MobileHomePage extends StatefulWidget { @@ -121,6 +122,11 @@ class _MobileHomePageState extends State { onPressed: () => context.pushRoute(MultiDayViewDemo()), child: Text(translate.multidayView), ), + SizedBox(height: 20), + ElevatedButton( + onPressed: () => context.pushRoute(ScheduleViewPageDemo()), + child: Text(translate.scheduleView), + ), ], ), ), diff --git a/example/lib/pages/schedule_view_page.dart b/example/lib/pages/schedule_view_page.dart new file mode 100644 index 00000000..d6ba09b9 --- /dev/null +++ b/example/lib/pages/schedule_view_page.dart @@ -0,0 +1,82 @@ +import 'package:flutter/material.dart'; + +import '../enumerations.dart'; +import '../extension.dart'; +import '../widgets/responsive_widget.dart'; +import '../widgets/schedule_view/schedule_view_settings.dart'; +import '../widgets/schedule_view/schedule_view_widget.dart'; +import 'create_event_page.dart'; +import 'web/web_home_page.dart'; + +class ScheduleViewPageDemo extends StatefulWidget { + @override + _ScheduleViewPageDemoState createState() => _ScheduleViewPageDemoState(); +} + +class _ScheduleViewPageDemoState extends State { + DateTime _focusDate = DateTime.now(); + int _jumpKey = 0; + + final ValueNotifier _config = ValueNotifier( + const ScheduleViewConfig(), + ); + + @override + void dispose() { + _config.dispose(); + super.dispose(); + } + + void _jumpToToday() { + setState(() { + _focusDate = DateTime.now(); + _jumpKey++; + }); + } + + @override + Widget build(BuildContext context) { + final appColors = context.appColors; + final translate = context.translate; + + return ResponsiveWidget( + webWidget: WebHomePage(selectedView: CalendarView.schedule), + mobileWidget: Scaffold( + appBar: AppBar( + title: Text(translate.scheduleView), + centerTitle: true, + actions: [ScheduleSettingsButton(config: _config)], + ), + floatingActionButton: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + FloatingActionButton.small( + heroTag: 'jump_to_today_schedule_view', + backgroundColor: appColors.primary, + onPressed: _jumpToToday, + tooltip: translate.today, + child: Icon(Icons.today, color: appColors.onPrimary), + ), + const SizedBox(height: 8), + FloatingActionButton( + heroTag: 'add_event_schedule_view', + backgroundColor: appColors.primary, + child: Icon(Icons.add, color: appColors.onPrimary), + elevation: 8, + onPressed: () => context.pushRoute(CreateEventPage()), + ), + ], + ), + body: ValueListenableBuilder( + valueListenable: _config, + builder: (context, config, _) => ScheduleViewWidget( + initialDay: _focusDate, + jumpKey: _jumpKey, + scheduleViewConfig: config, + ), + ), + ), + ); + } +} diff --git a/example/lib/theme/app_colors.dart b/example/lib/theme/app_colors.dart index b667b109..5423a536 100644 --- a/example/lib/theme/app_colors.dart +++ b/example/lib/theme/app_colors.dart @@ -1,6 +1,5 @@ import 'dart:ui'; -// TODO(Shubham): Remove if not required class AppColors { AppColors._(); @@ -16,4 +15,9 @@ class AppColors { static const Color lightNavyBlue = Color(0xffb3b9ed); static const Color red = Color(0xfff96c6c); static const Color grey = Color(0xffe0e0e0); + static const Color transparent = Color(0x00000000); + static const Color background = Color(0xffffffff); + static const Color surface = Color(0xffffffff); + static const Color onSurface = Color(0xff22191a); + static const Color onSurfaceVariant = Color(0xff857373); } diff --git a/example/lib/theme/app_theme.dart b/example/lib/theme/app_theme.dart index 001adc25..eea77b62 100644 --- a/example/lib/theme/app_theme.dart +++ b/example/lib/theme/app_theme.dart @@ -27,9 +27,12 @@ class AppTheme { ); // Light colors + static final _appLightTheme = AppThemeExtension.light(); + static final _monthViewTheme = MonthViewThemeData.light(); static final _dayViewTheme = DayViewThemeData.light(); static final _weekViewTheme = WeekViewThemeData.light(); static final _multiDayViewTheme = MultiDayViewThemeData.light(); + static final _scheduleViewTheme = ScheduleViewThemeData.light(); // Dark colors static final _appDarkTheme = AppThemeExtension.dark(); @@ -37,6 +40,7 @@ class AppTheme { static final _dayViewDarkTheme = DayViewThemeData.dark(); static final _weekViewDarkTheme = WeekViewThemeData.dark(); static final _multiDayViewDarkTheme = MultiDayViewThemeData.dark(); + static final _scheduleViewDarkTheme = ScheduleViewThemeData.dark(); // Light theme static final light = ThemeData.light().copyWith( @@ -57,7 +61,14 @@ class AppTheme { radioTheme: RadioThemeData( fillColor: WidgetStateColor.resolveWith((_) => AppColors.primary), ), - extensions: [_dayViewTheme, _weekViewTheme, _multiDayViewTheme], + extensions: [ + _appLightTheme, + _scheduleViewTheme, + _monthViewTheme, + _dayViewTheme, + _weekViewTheme, + _multiDayViewTheme, + ], ); // Dark theme @@ -95,13 +106,14 @@ class AppTheme { radioTheme: RadioThemeData( fillColor: WidgetStateColor.resolveWith((_) => DarkAppColors.primary), ), - // TODO(Shubham): Test dark theme update + extensions: [ _appDarkTheme, _monthViewDarkTheme, _dayViewDarkTheme, _weekViewDarkTheme, _multiDayViewDarkTheme, + _scheduleViewDarkTheme, ], ); } diff --git a/example/lib/theme/app_theme_extension.dart b/example/lib/theme/app_theme_extension.dart index 68c056bb..518eb5e8 100644 --- a/example/lib/theme/app_theme_extension.dart +++ b/example/lib/theme/app_theme_extension.dart @@ -8,34 +8,64 @@ class AppThemeExtension extends ThemeExtension { this.primary = AppColors.primary, this.onPrimary = AppColors.onPrimary, this.outlineVariant = AppColors.outlineVariant, + this.transparent = AppColors.transparent, + this.backgroundColor = AppColors.background, + this.surface = AppColors.surface, + this.onSurface = AppColors.onSurface, + this.onSurfaceVariant = AppColors.onSurfaceVariant, }); // Light theme constructor AppThemeExtension.light() : primary = AppColors.primary, onPrimary = AppColors.onPrimary, - outlineVariant = AppColors.outlineVariant; + outlineVariant = AppColors.outlineVariant, + transparent = AppColors.transparent, + backgroundColor = AppColors.background, + surface = AppColors.surface, + onSurface = AppColors.onSurface, + onSurfaceVariant = AppColors.onSurfaceVariant; // Dark theme constructor AppThemeExtension.dark() : primary = DarkAppColors.primary, onPrimary = DarkAppColors.onPrimary, - outlineVariant = DarkAppColors.outlineVariant; + outlineVariant = DarkAppColors.outlineVariant, + transparent = DarkAppColors.transparent, + backgroundColor = DarkAppColors.background, + surface = DarkAppColors.surface, + onSurface = DarkAppColors.onSurface, + onSurfaceVariant = DarkAppColors.onSurfaceVariant; final Color primary; final Color onPrimary; final Color outlineVariant; + final Color transparent; + final Color backgroundColor; + final Color surface; + final Color onSurface; + final Color onSurfaceVariant; @override ThemeExtension copyWith({ Color? primary, Color? onPrimary, Color? outlineVariant, + Color? transparent, + Color? backgroundColor, + Color? surface, + Color? onSurface, + Color? onSurfaceVariant, }) { return AppThemeExtension( primary: primary ?? this.primary, onPrimary: onPrimary ?? this.onPrimary, outlineVariant: outlineVariant ?? this.outlineVariant, + transparent: transparent ?? this.transparent, + backgroundColor: backgroundColor ?? this.backgroundColor, + surface: surface ?? this.surface, + onSurface: onSurface ?? this.onSurface, + onSurfaceVariant: onSurfaceVariant ?? this.onSurfaceVariant, ); } @@ -52,6 +82,15 @@ class AppThemeExtension extends ThemeExtension { onPrimary: Color.lerp(onPrimary, other.onPrimary, t) ?? onPrimary, outlineVariant: Color.lerp(outlineVariant, other.outlineVariant, t) ?? outlineVariant, + transparent: Color.lerp(transparent, other.transparent, t) ?? transparent, + backgroundColor: + Color.lerp(backgroundColor, other.backgroundColor, t) ?? + backgroundColor, + surface: Color.lerp(surface, other.surface, t) ?? surface, + onSurface: Color.lerp(onSurface, other.onSurface, t) ?? onSurface, + onSurfaceVariant: + Color.lerp(onSurfaceVariant, other.onSurfaceVariant, t) ?? + onSurfaceVariant, ); } } diff --git a/example/lib/theme/dark_app_colors.dart b/example/lib/theme/dark_app_colors.dart index a5ec0a7d..c0eb08a6 100644 --- a/example/lib/theme/dark_app_colors.dart +++ b/example/lib/theme/dark_app_colors.dart @@ -7,4 +7,9 @@ class DarkAppColors { static const Color onPrimary = Color(0xff561d23); static const Color outline = Color(0xff9f8c8c); static const Color outlineVariant = Color(0xff524343); + static const Color transparent = Color(0x00000000); + static const Color background = Color(0xff140c0c); + static const Color surface = Color(0xff140c0c); + static const Color onSurface = Color(0xfff0dede); + static const Color onSurfaceVariant = Color(0xff9f8c8c); } diff --git a/example/lib/widgets/calendar_configs.dart b/example/lib/widgets/calendar_configs.dart index c4101a6e..27c135f3 100644 --- a/example/lib/widgets/calendar_configs.dart +++ b/example/lib/widgets/calendar_configs.dart @@ -125,6 +125,8 @@ class _CalendarConfigState extends State { viewName = translate.weekView; case CalendarView.multiday: viewName = translate.multidayView; + case CalendarView.schedule: + viewName = translate.scheduleView; } return GestureDetector( onTap: () => widget.onViewChange(view), diff --git a/example/lib/widgets/calendar_views.dart b/example/lib/widgets/calendar_views.dart index fea4dcc9..03172f0d 100644 --- a/example/lib/widgets/calendar_views.dart +++ b/example/lib/widgets/calendar_views.dart @@ -7,6 +7,7 @@ import '../theme/app_colors.dart'; import 'day_view_widget.dart'; import 'month_view_widget.dart'; import 'multi_day_view_widget.dart'; +import 'schedule_view/schedule_view_widget.dart'; import 'week_view_widget.dart'; class CalendarViews extends StatelessWidget { @@ -32,7 +33,9 @@ class CalendarViews extends StatelessWidget { ? DayViewWidget(width: width) : view == CalendarView.week ? WeekViewWidget(width: width) - : MultiDayViewWidget(width: width), + : view == CalendarView.multiday + ? MultiDayViewWidget(width: width) + : ScheduleViewWidget(width: width), ), ); } diff --git a/example/lib/widgets/schedule_view/empty_text_widget.dart b/example/lib/widgets/schedule_view/empty_text_widget.dart new file mode 100644 index 00000000..e542d8d0 --- /dev/null +++ b/example/lib/widgets/schedule_view/empty_text_widget.dart @@ -0,0 +1,39 @@ +import 'package:calendar_view/calendar_view.dart'; +import 'package:example/extension.dart'; +import 'package:flutter/material.dart'; + +class EmptyTextWidget extends StatelessWidget { + const EmptyTextWidget({super.key}); + + @override + Widget build(BuildContext context) { + final scheduleColors = context.scheduleViewColors; + final translate = context.translate; + return Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(8), + border: Border.all(color: scheduleColors.emptyContentColor), + ), + padding: const EdgeInsets.all(8), + child: Row( + mainAxisSize: MainAxisSize.min, + spacing: 6, + children: [ + Icon( + Icons.add_circle_outline, + size: 14, + color: scheduleColors.emptyContentColor, + ), + Text( + translate.scheduleNoEvents, + style: TextStyle( + fontSize: 14, + color: scheduleColors.emptyContentColor, + fontStyle: FontStyle.italic, + ), + ), + ], + ), + ); + } +} diff --git a/example/lib/widgets/schedule_view/schedule_view_day_detector.dart b/example/lib/widgets/schedule_view/schedule_view_day_detector.dart new file mode 100644 index 00000000..bec6dd73 --- /dev/null +++ b/example/lib/widgets/schedule_view/schedule_view_day_detector.dart @@ -0,0 +1,172 @@ +import 'package:calendar_view/calendar_view.dart'; +import 'package:example/extension.dart'; +import 'package:flutter/material.dart'; + +class ScheduleViewDayDetector extends StatelessWidget { + final DateTime date; + final List events; + + /// Where the date sits relative to the events. Drives whether the date is + /// rendered as a narrow vertical badge (left) or a full-width inline header + /// (top), so the same detector adapts to either [ScheduleView.dateLayout]. + final ScheduleDateLayout layout; + + const ScheduleViewDayDetector({ + super.key, + required this.date, + required this.events, + this.layout = ScheduleDateLayout.left, + }); + + @override + Widget build(BuildContext context) { + final scheduleColors = context.scheduleViewColors; + final now = DateTime.now(); + final isToday = + date.year == now.year && date.month == now.month && date.day == now.day; + + return GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () => + context.showSnackBarWithText(date.localizedShortDate(context)), + onLongPress: () => context.showSnackBarWithText( + '${context.translate.scheduleLongPressed} ${date.localizedShortDate(context)}', + ), + child: layout == ScheduleDateLayout.top + ? _buildTopHeader(context, scheduleColors, isToday) + : _buildLeftBadge(context, scheduleColors, isToday), + ); + } + + /// Vertical badge for the left layout: weekday over a circular day number + /// with event dots beneath, sized to fit the fixed-width date column. + Widget _buildLeftBadge( + BuildContext context, + ScheduleViewThemeData colors, + bool isToday, + ) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + date.weekDayEnum.abbreviation, + style: TextStyle( + fontSize: 11, + color: isToday + ? colors.todayHighlightColor + : colors.weekdayTextColor, + fontWeight: FontWeight.w600, + letterSpacing: 0.5, + ), + ), + const SizedBox(height: 4), + Container( + width: 34, + height: 34, + decoration: BoxDecoration( + color: isToday ? colors.todayHighlightColor : colors.transparent, + shape: BoxShape.circle, + ), + alignment: Alignment.center, + child: Text( + date.localizedDay(context), + style: TextStyle( + fontSize: 15, + fontWeight: isToday ? FontWeight.bold : FontWeight.w500, + color: isToday ? colors.todayTextColor : colors.dateTextColor, + ), + ), + ), + if (events.isNotEmpty) ...[ + const SizedBox(height: 4), + _EventDots(events: events), + ], + ], + ), + ); + } + + /// Inline, full-width header for the top layout: the weekday in a circle — + /// highlighted on today — beside the "day month" label, with event dots + /// trailing and a divider separating it from the events. + Widget _buildTopHeader( + BuildContext context, + ScheduleViewThemeData colors, + bool isToday, + ) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + width: 32, + height: 32, + decoration: BoxDecoration( + color: isToday + ? colors.todayHighlightColor + : colors.transparent, + shape: BoxShape.circle, + ), + alignment: Alignment.center, + child: Text( + date.weekDayEnum.abbreviation, + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.bold, + color: isToday + ? colors.todayTextColor + : colors.weekdayTextColor, + ), + ), + ), + const SizedBox(width: 12), + Text( + '${date.localizedDay(context)} ' + '${date.getMonthName(abbreviated: true)}', + style: TextStyle( + fontSize: 14, + fontWeight: isToday ? FontWeight.bold : FontWeight.w600, + color: colors.dateTextColor, + ), + ), + if (events.isNotEmpty) ...[ + const Spacer(), + _EventDots(events: events), + ], + ], + ), + const SizedBox(height: 8), + Divider(height: 1, thickness: 1, color: colors.dateDividerColor), + ], + ); + } +} + +/// Up to three small colored dots, one per event, used as an at-a-glance +/// density indicator in both date layouts. +class _EventDots extends StatelessWidget { + const _EventDots({required this.events}); + + final List events; + + @override + Widget build(BuildContext context) { + return Row( + mainAxisSize: MainAxisSize.min, + children: events + .take(3) + .map( + (e) => Container( + margin: const EdgeInsets.symmetric(horizontal: 1), + width: 5, + height: 5, + decoration: BoxDecoration(color: e.color, shape: BoxShape.circle), + ), + ) + .toList(), + ); + } +} diff --git a/example/lib/widgets/schedule_view/schedule_view_event_tile.dart b/example/lib/widgets/schedule_view/schedule_view_event_tile.dart new file mode 100644 index 00000000..7f087c89 --- /dev/null +++ b/example/lib/widgets/schedule_view/schedule_view_event_tile.dart @@ -0,0 +1,124 @@ +import 'package:calendar_view/calendar_view.dart'; +import 'package:example/extension.dart'; +import 'package:flutter/material.dart'; + +class ScheduleViewEventTile extends StatelessWidget { + const ScheduleViewEventTile({ + super.key, + required this.event, + required this.date, + }); + + final CalendarEventData event; + final DateTime date; + + @override + Widget build(BuildContext context) { + final scheduleColors = context.scheduleViewColors; + final tileColor = event.color.withAlpha(scheduleColors.eventTileAlpha); + final hsl = HSLColor.fromColor(event.color); + final timeColor = hsl + .withLightness( + (hsl.lightness + scheduleColors.eventTimeColorLightnessAdjust).clamp( + 0.0, + 1.0, + ), + ) + .toColor() + .withAlpha(200); + final timeLabel = _buildTimeLabel(context, event); + + return Container( + margin: const EdgeInsets.symmetric(vertical: 2, horizontal: 2), + decoration: BoxDecoration( + color: tileColor, + borderRadius: BorderRadius.circular(8), + border: Border(left: BorderSide(color: event.color, width: 4)), + ), + child: Padding( + padding: const EdgeInsets.fromLTRB(10, 8, 12, 8), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + // Time + badges row + Row( + children: [ + Text( + timeLabel, + style: TextStyle( + fontSize: 12, + color: timeColor, + fontWeight: FontWeight.w600, + ), + ), + if (event.isRecurringEvent) ...[ + const SizedBox(width: 6), + Icon(Icons.repeat, size: 12, color: timeColor), + ], + if (event.isRangingEvent) ...[ + const SizedBox(width: 6), + Icon(Icons.date_range, size: 12, color: timeColor), + ], + ], + ), + const SizedBox(height: 4), + // Title + Text( + event.title, + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + color: scheduleColors.eventTitleColor, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + // Description preview + if (event.description?.isNotEmpty ?? false) ...[ + const SizedBox(height: 2), + Text( + event.description!, + style: TextStyle( + fontSize: 12, + color: scheduleColors.eventSecondaryTextColor, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ], + ], + ), + ), + Icon( + Icons.chevron_right, + size: 16, + color: scheduleColors.eventSecondaryTextColor.withAlpha(120), + ), + ], + ), + ), + ); + } + + // Demo-only: always renders 12-hour times (digits/AM-PM are still localized + // via PackageStrings inside getTimeInFormat). A real app would pick the + // format from the locale / MediaQuery.alwaysUse24HourFormat. + String _formatTime(TimeOfDay time) => + time.getTimeInFormat(TimeStampFormat.parse_12); + + String _buildTimeLabel(BuildContext context, CalendarEventData event) { + final translate = context.translate; + if (event.isFullDayEvent) return translate.scheduleAllDay; + final start = event.startTime; + final end = event.endTime; + if (start != null && end != null) { + return '${_formatTime(start)} – ${_formatTime(end)}'; + } + if (start != null) return _formatTime(start); + return translate.scheduleAllDay; + } +} diff --git a/example/lib/widgets/schedule_view/schedule_view_month_header.dart b/example/lib/widgets/schedule_view/schedule_view_month_header.dart new file mode 100644 index 00000000..8da0d3cf --- /dev/null +++ b/example/lib/widgets/schedule_view/schedule_view_month_header.dart @@ -0,0 +1,114 @@ +import 'package:calendar_view/calendar_view.dart'; +import 'package:example/enumerations.dart'; +import 'package:example/extension.dart'; +import 'package:flutter/material.dart'; + +class ScheduleViewMonthHeader extends StatelessWidget { + const ScheduleViewMonthHeader({ + super.key, + required this.date, + this.showNoEventsTile = false, + }); + + final DateTime date; + final bool showNoEventsTile; + + @override + Widget build(BuildContext context) { + const headerHeight = 160.0; + final colors = context.scheduleViewColors; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Stack( + alignment: Alignment.bottomLeft, + children: [ + SizedBox( + height: headerHeight, + width: double.infinity, + child: Image.asset( + Months.values[date.month - 1].imagePath, + fit: BoxFit.cover, + ), + ), + Container( + decoration: BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [ + colors.monthHeaderGradientStartColor, + colors.monthHeaderGradientEndColor, + ], + ), + ), + height: headerHeight, + width: double.infinity, + ), + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + date.getMonthYear(), + style: TextStyle( + fontSize: 22, + fontWeight: FontWeight.w700, + color: colors.monthHeaderTextColor, + letterSpacing: 0.3, + shadows: [ + Shadow( + blurRadius: 4, + color: colors.monthHeaderTextShadowColor, + ), + ], + ), + ), + ], + ), + ), + ], + ), + if (showNoEventsTile) ...[ + _NoEventsInMonthTile(), + Divider(height: 1, thickness: 1, color: colors.dateDividerColor), + ], + ], + ); + } +} + +class _NoEventsInMonthTile extends StatelessWidget { + const _NoEventsInMonthTile(); + + @override + Widget build(BuildContext context) { + final colors = context.scheduleViewColors; + return Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 16), + child: Row( + mainAxisSize: MainAxisSize.min, + spacing: 10, + children: [ + Icon( + Icons.calendar_today_outlined, + size: 16, + color: colors.emptyContentColor, + ), + Text( + context.translate.scheduleNoEventsThisMonth, + style: TextStyle( + fontSize: 14, + color: colors.emptyContentColor, + fontStyle: FontStyle.italic, + ), + ), + ], + ), + ); + } +} diff --git a/example/lib/widgets/schedule_view/schedule_view_settings.dart b/example/lib/widgets/schedule_view/schedule_view_settings.dart new file mode 100644 index 00000000..f05a6946 --- /dev/null +++ b/example/lib/widgets/schedule_view/schedule_view_settings.dart @@ -0,0 +1,183 @@ +import 'package:calendar_view/calendar_view.dart'; +import 'package:example/extension.dart'; +import 'package:flutter/material.dart'; + +/// Immutable bag of the [ScheduleView] knobs the demo lets the user flip at +/// runtime. Held in a [ValueNotifier] so a change rebuilds only the schedule — +/// the AppBar and FABs around it stay put. +/// +/// Defaults mirror the values [ScheduleViewWidget] previously hard-coded, so +/// the first frame looks identical to before the settings menu existed. +@immutable +class ScheduleViewConfig { + final bool showDaysWithoutEvents; + final bool showEmptyMonths; + final ScheduleDateLayout dateLayout; + + const ScheduleViewConfig({ + this.showDaysWithoutEvents = false, + this.showEmptyMonths = true, + this.dateLayout = ScheduleDateLayout.left, + }); + + ScheduleViewConfig copyWith({ + bool? showDaysWithoutEvents, + bool? showEmptyMonths, + ScheduleDateLayout? dateLayout, + }) { + return ScheduleViewConfig( + showDaysWithoutEvents: + showDaysWithoutEvents ?? this.showDaysWithoutEvents, + showEmptyMonths: showEmptyMonths ?? this.showEmptyMonths, + dateLayout: dateLayout ?? this.dateLayout, + ); + } + + @override + bool operator ==(Object other) => + other is ScheduleViewConfig && + other.showDaysWithoutEvents == showDaysWithoutEvents && + other.showEmptyMonths == showEmptyMonths && + other.dateLayout == dateLayout; + + @override + int get hashCode => + Object.hash(showDaysWithoutEvents, showEmptyMonths, dateLayout); +} + +/// AppBar action that opens a stay-open popup panel for editing [config]. +/// +/// Edits are staged in a local draft while the menu is open; the shared +/// [config] notifier — and therefore the schedule — is updated only once, when +/// the menu closes. Both close paths (the Done button and a tap outside) pop +/// the menu with a `null` result, which routes through +/// [PopupMenuButton.onCanceled], the single commit point. +class ScheduleSettingsButton extends StatefulWidget { + final ValueNotifier config; + + const ScheduleSettingsButton({super.key, required this.config}); + + @override + State createState() => _ScheduleSettingsButtonState(); +} + +class _ScheduleSettingsButtonState extends State { + // Pending edits, kept out of the shared notifier so toggling a switch does + // not rebuild the schedule. Re-synced from the committed config on each open. + late ScheduleViewConfig _draft = widget.config.value; + + @override + Widget build(BuildContext context) { + return PopupMenuButton( + tooltip: context.translate.scheduleSettings, + icon: const Icon(Icons.tune), + // Start each session from the currently committed config. Runs after + // itemBuilder but before the menu route builds, so the panel reads it. + onOpened: () => _draft = widget.config.value, + // Fires on every dismissal — Done button or tap outside — and is the only + // place the staged draft is published, so the schedule rebuilds once. + onCanceled: () => widget.config.value = _draft, + // A single `enabled: false` item gives its InkWell a null onTap, so it + // never joins the gesture arena — a stray row tap can't dismiss the menu + // — while the controls inside still win their own taps and work normally. + itemBuilder: (context) => [ + PopupMenuItem( + enabled: false, + padding: EdgeInsets.zero, + // The open menu lives in its own route and won't rebuild when this + // button does, so a StatefulBuilder gives the panel a local setState + // to reflect draft edits while staying open. + child: StatefulBuilder( + builder: (context, setMenuState) => _SettingsPanel( + value: _draft, + onChanged: (next) => setMenuState(() => _draft = next), + onDone: () => Navigator.pop(context), + ), + ), + ), + ], + ); + } +} + +class _SettingsPanel extends StatelessWidget { + final ScheduleViewConfig value; + final ValueChanged onChanged; + final VoidCallback onDone; + + const _SettingsPanel({ + required this.value, + required this.onChanged, + required this.onDone, + }); + + @override + Widget build(BuildContext context) { + final appColors = context.appColors; + final translate = context.translate; + + return ConstrainedBox( + constraints: const BoxConstraints(minWidth: 280), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SwitchListTile( + contentPadding: const EdgeInsets.symmetric(horizontal: 16), + title: Text( + translate.scheduleShowDaysWithoutEvents, + style: TextStyle(color: appColors.onSurfaceVariant), + ), + value: value.showDaysWithoutEvents, + onChanged: (v) => + onChanged(value.copyWith(showDaysWithoutEvents: v)), + ), + SwitchListTile( + contentPadding: const EdgeInsets.symmetric(horizontal: 16), + title: Text( + translate.scheduleShowEmptyMonths, + style: TextStyle(color: appColors.onSurfaceVariant), + ), + value: value.showEmptyMonths, + onChanged: (v) => onChanged(value.copyWith(showEmptyMonths: v)), + ), + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 6), + child: Text( + translate.scheduleDateLayout, + style: TextStyle(color: appColors.onSurfaceVariant), + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), + child: SegmentedButton( + showSelectedIcon: false, + segments: [ + ButtonSegment( + value: ScheduleDateLayout.left, + icon: const Icon(Icons.view_sidebar_outlined), + label: Text(translate.scheduleDateLayoutLeft), + ), + ButtonSegment( + value: ScheduleDateLayout.top, + icon: const Icon(Icons.view_agenda_outlined), + label: Text(translate.scheduleDateLayoutTop), + ), + ], + selected: {value.dateLayout}, + onSelectionChanged: (s) => + onChanged(value.copyWith(dateLayout: s.first)), + ), + ), + Align( + alignment: AlignmentDirectional.centerEnd, + child: Padding( + padding: const EdgeInsets.fromLTRB(8, 0, 8, 8), + child: TextButton(onPressed: onDone, child: Text(translate.done)), + ), + ), + ], + ), + ); + } +} diff --git a/example/lib/widgets/schedule_view/schedule_view_widget.dart b/example/lib/widgets/schedule_view/schedule_view_widget.dart new file mode 100644 index 00000000..647ab4fe --- /dev/null +++ b/example/lib/widgets/schedule_view/schedule_view_widget.dart @@ -0,0 +1,180 @@ +import 'package:calendar_view/calendar_view.dart'; +import 'package:example/extension.dart'; +import 'package:example/pages/create_event_page.dart'; +import 'package:example/pages/event_details_page.dart'; +import 'package:example/widgets/schedule_view/empty_text_widget.dart'; +import 'package:example/widgets/schedule_view/schedule_view_day_detector.dart'; +import 'package:example/widgets/schedule_view/schedule_view_event_tile.dart'; +import 'package:example/widgets/schedule_view/schedule_view_month_header.dart'; +import 'package:example/widgets/schedule_view/schedule_view_settings.dart'; +import 'package:flutter/material.dart'; + +/// Displays a [ScheduleView] calendar with events. +class ScheduleViewWidget extends StatefulWidget { + const ScheduleViewWidget({ + this.scheduleViewConfig = const ScheduleViewConfig(), + this.width, + this.initialDay, + this.jumpKey = 0, + super.key, + }); + + final ScheduleViewConfig scheduleViewConfig; + final double? width; + final DateTime? initialDay; + final int jumpKey; + + @override + State createState() => _ScheduleViewWidgetState(); +} + +class _ScheduleViewWidgetState extends State { + // Drives the view via [ScheduleViewState.jumpToDate] instead of recreating it + // with a ValueKey, so scroll state survives unrelated rebuilds. + final GlobalKey _scheduleKey = + GlobalKey(); + + // Boundary snack bars should only appear once the user has actually dragged + // to an edge — not on the first build, when short content already fills the + // viewport and the boundary callbacks fire immediately. + bool _userHasScrolled = false; + + @override + void didUpdateWidget(ScheduleViewWidget oldWidget) { + super.didUpdateWidget(oldWidget); + // The parent bumps [jumpKey] every time it wants to re-anchor (e.g. the + // "jump to today" button), even when [initialDay] is unchanged. + if (widget.jumpKey != oldWidget.jumpKey) { + _scheduleKey.currentState?.jumpToDate( + widget.initialDay ?? DateTime.now(), + ); + } + } + + @override + Widget build(BuildContext context) { + final scheduleColors = context.scheduleViewColors; + final backgroundColor = context.appColors.backgroundColor; + final translate = context.translate; + + return NotificationListener( + // Only count user-initiated drags, not programmatic jumpTo() scrolls. + onNotification: (notification) { + if (notification.dragDetails != null) _userHasScrolled = true; + return false; + }, + child: ScheduleView( + key: _scheduleKey, + width: widget.width, + initialDay: widget.initialDay ?? DateTime.now(), + backgroundColor: backgroundColor, + + // ── Custom event sort: by start time, then alphabetically by title ─ + eventSorter: (a, b) { + final ta = a.startTime; + final tb = b.startTime; + if (ta != null && tb != null) { + final diff = + (ta.hour * 60 + ta.minute) - (tb.hour * 60 + tb.minute); + if (diff != 0) return diff; + } else if (ta != null) { + return -1; + } else if (tb != null) { + return 1; + } + return a.title.compareTo(b.title); + }, + + // ------------ Empty month with header + "no events" row ------------ + showEmptyMonths: widget.scheduleViewConfig.showEmptyMonths, + emptyMonthBuilder: (date) => + ScheduleViewMonthHeader(date: date, showNoEventsTile: true), + + // ----------- Month and year with background image ------------ + monthHeaderBuilder: (date) => ScheduleViewMonthHeader(date: date), + + // ---------- Date indicator with today's date highlighted ---------- + dayDetectorBuilder: (date, events, layout) => + ScheduleViewDayDetector(date: date, events: events, layout: layout), + + // ----------------- Event Tile ------------------- + dateLayout: widget.scheduleViewConfig.dateLayout, + eventTileBuilder: (event, date) => + ScheduleViewEventTile(event: event, date: date), + + // ---------- Empty Text PlaceHolder ---------- + showDaysWithoutEvents: widget.scheduleViewConfig.showDaysWithoutEvents, + emptyTextWidget: widget.scheduleViewConfig.showDaysWithoutEvents + ? InkWell( + onTap: () => context.pushRoute(CreateEventPage()), + borderRadius: BorderRadius.circular(8), + child: EmptyTextWidget(), + ) + : null, + + // ---------- Today — No Events PlaceHolder ---------- + todayEmptyWidget: Padding( + padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 10), + child: Text( + translate.scheduleTodayNoEvents, + style: TextStyle( + fontSize: 14, + color: scheduleColors.emptyContentColor, + fontStyle: FontStyle.italic, + fontWeight: FontWeight.w500, + ), + ), + ), + + // ------------- Floating Month Header -------------- + floatingMonthHeaderBuilder: (context, month) { + final headerColors = context.appColors; + return Material( + elevation: 2, + color: headerColors.surface, + child: Container( + decoration: BoxDecoration( + border: Border( + bottom: BorderSide(color: scheduleColors.dateDividerColor), + ), + ), + padding: const EdgeInsets.symmetric( + horizontal: 16.0, + vertical: 10.0, + ), + child: Text( + month.getMonthYear(), + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + color: headerColors.onSurface, + ), + ), + ), + ); + }, + + // ------------- Boundary Callbacks -------------- + // Suppressed until the user has scrolled, so the snack bars don't pop + // on open when short content already reaches a boundary on first build. + onHasReachedStart: () { + if (!_userHasScrolled) return; + context.showSnackBarWithText(translate.reachedTheStartPage); + }, + onHasReachedEnd: () { + if (!_userHasScrolled) return; + context.showSnackBarWithText(translate.reachedTheEndPage); + }, + + // ---------------Event Callbacks-------------- + onEventTap: (events, date) => + context.pushRoute(DetailsPage(event: events.first, date: date)), + onEventDoubleTap: (events, date) => + context.pushRoute(CreateEventPage(event: events.first)), + onEventLongTap: (events, date) => context.showSnackBarWithText( + '${translate.scheduleLongPressed} ${events.first.title}', + ), + ), + ); + } +} diff --git a/example/pubspec.yaml b/example/pubspec.yaml index 80008b57..518ca1b0 100644 --- a/example/pubspec.yaml +++ b/example/pubspec.yaml @@ -5,16 +5,6 @@ description: A new Flutter project. # pub.dev using `pub publish`. This is preferred for private packages. publish_to: 'none' # Remove this line if you wish to publish to pub.dev -# The following defines the version and build number for your application. -# A version number is three numbers separated by dots, like 1.2.43 -# followed by an optional build number separated by a +. -# Both the version and the builder number may be overridden in flutter -# build by specifying --build-name and --build-number, respectively. -# In Android, build-name is used as versionName while build-number used as versionCode. -# Read more about Android versioning at https://developer.android.com/studio/publish/versioning -# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion. -# Read more about iOS versioning at -# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html version: 1.0.0+1 environment: @@ -43,45 +33,10 @@ dev_dependencies: build_runner: ^2.0.6 build_web_compilers: ^3.0.0 -# For information on the generic Dart part of this file, see the -# following page: https://dart.dev/tools/pub/pubspec - # The following section is specific to Flutter. flutter: - - # The following line ensures that the Material Icons font is - # included with your application, so that you can use the icons in - # the material Icons class. uses-material-design: true generate: true - # To add assets to your application, add an assets section, like this: - # assets: - # - images/a_dot_burr.jpeg - # - images/a_dot_ham.jpeg - - # An image asset can refer to one or more resolution-specific "variants", see - # https://flutter.dev/assets-and-images/#resolution-aware. - - # For details regarding adding assets from package dependencies, see - # https://flutter.dev/assets-and-images/#from-packages - - # To add custom fonts to your application, add a fonts section here, - # in this "flutter" section. Each entry in this list should have a - # "family" key with the font family name, and a "fonts" key with a - # list giving the asset and other descriptors for the font. For - # example: - # fonts: - # - family: Schyler - # fonts: - # - asset: fonts/Schyler-Regular.ttf - # - asset: fonts/Schyler-Italic.ttf - # style: italic - # - family: Trajan Pro - # fonts: - # - asset: fonts/TrajanPro.ttf - # - asset: fonts/TrajanPro_Bold.ttf - # weight: 700 - # - # For details regarding fonts from package dependencies, - # see https://flutter.dev/custom-fonts/#from-packages + assets: + - assets/images/ \ No newline at end of file diff --git a/lib/calendar_view.dart b/lib/calendar_view.dart index d6179243..8660ef57 100644 --- a/lib/calendar_view.dart +++ b/lib/calendar_view.dart @@ -17,20 +17,22 @@ export './src/day_view/day_view.dart'; export './src/enumerations.dart'; export './src/event_arrangers/event_arrangers.dart'; export './src/event_controller.dart'; -export './src/extensions.dart' hide BuildContextExtension; +export './src/extensions.dart'; export './src/localization/calendar_localizations.dart'; export './src/localization/package_locals.dart'; -export './src/modals.dart'; +export './src/models.dart'; export './src/month_view/month_view.dart'; +export './src/month_view/month_view_builders.dart'; +export './src/month_view/month_view_style.dart'; +export './src/month_view/month_view_theme_settings.dart'; +export './src/multi_day_view/multi_day_view.dart'; +export './src/schedule_view/schedule_view.dart'; export './src/style/header_style.dart'; export './src/theme/calendar_theme_data.dart'; export './src/theme/day_view_theme_data.dart'; export './src/theme/month_view_theme_data.dart'; export './src/theme/multi_day_view_theme_data.dart'; +export './src/theme/schedule_view_theme_data.dart'; export './src/theme/week_view_theme_data.dart'; export './src/typedefs.dart'; export './src/week_view/week_view.dart'; -export './src/month_view/month_view_style.dart'; -export './src/month_view/month_view_theme_settings.dart'; -export './src/month_view/month_view_builders.dart'; -export './src/multi_day_view/multi_day_view.dart'; diff --git a/lib/src/components/month_view_components.dart b/lib/src/components/month_view_components.dart index 91a37ec7..b0b378a2 100644 --- a/lib/src/components/month_view_components.dart +++ b/lib/src/components/month_view_components.dart @@ -6,7 +6,6 @@ import 'package:flutter/material.dart'; import '../../calendar_view.dart'; import '../constants.dart'; -import '../extensions.dart'; class CircularCell extends StatelessWidget { /// Defines how a cell will be displayed. diff --git a/lib/src/day_view/_internal_day_view_page.dart b/lib/src/day_view/_internal_day_view_page.dart index 94d02735..1b7c5544 100644 --- a/lib/src/day_view/_internal_day_view_page.dart +++ b/lib/src/day_view/_internal_day_view_page.dart @@ -10,7 +10,7 @@ import '../enumerations.dart'; import '../event_arrangers/event_arrangers.dart'; import '../event_controller.dart'; import '../extensions.dart'; -import '../modals.dart'; +import '../models.dart'; import '../painters.dart'; import '../typedefs.dart'; import '../zoom_scroll_controller.dart'; diff --git a/lib/src/day_view/day_view.dart b/lib/src/day_view/day_view.dart index a9a8ee6c..c6e627f1 100644 --- a/lib/src/day_view/day_view.dart +++ b/lib/src/day_view/day_view.dart @@ -8,7 +8,6 @@ import 'package:flutter/material.dart'; import '../../calendar_view.dart'; import '../constants.dart'; -import '../extensions.dart'; import '../painters.dart'; import '../current_time_scroller.dart'; import '../zoom_scroll_controller.dart'; diff --git a/lib/src/enumerations.dart b/lib/src/enumerations.dart index b33c8d34..82da7823 100644 --- a/lib/src/enumerations.dart +++ b/lib/src/enumerations.dart @@ -83,3 +83,15 @@ enum DeleteEvent { current, following, } + +/// Controls where the date information is placed relative to the event list +/// in each [ScheduleView] day row. +enum ScheduleDateLayout { + /// Date column is fixed on the left; events are listed to its right. + /// + /// This is the default layout. + left, + + /// Date header spans the full row width above the event list. + top, +} diff --git a/lib/src/extensions.dart b/lib/src/extensions.dart index 3f4911c7..c7f32321 100644 --- a/lib/src/extensions.dart +++ b/lib/src/extensions.dart @@ -192,6 +192,50 @@ extension DateTimeExtensions on DateTime { /// print(date.weekDayEnum); // WeekDays.monday /// ``` WeekDays get weekDayEnum => WeekDays.values[weekday - 1]; + + /// Returns the localized month name for this DateTime. + /// + /// Uses the current locale set in [PackageStrings] to retrieve the month name. + /// If abbreviated is true, returns the abbreviated month name if available. + /// + /// Example: + /// ```dart + /// final date = DateTime(2024, 6, 15); + /// print(date.getMonthName()); // "June" + /// print(date.getMonthName(abbreviated: true)); // "Jun" + /// + /// PackageStrings.setLocale('es'); + /// print(date.getMonthName()); // "Junio" + /// ``` + String getMonthName({bool abbreviated = false}) { + final monthsList = abbreviated + ? (PackageStrings.currentLocale.monthsAbbr ?? + PackageStrings.currentLocale.months) + : PackageStrings.currentLocale.months; + return monthsList[month - 1]; + } + + /// Returns a localized string representation of the month and year. + /// + /// Combines the localized month name with the localized year number. + /// Respects the current locale set in [PackageStrings]. + /// + /// Example: + /// ```dart + /// final date = DateTime(2024, 6, 15); + /// print(date.getMonthYear()); // "June 2024" + /// + /// PackageStrings.setLocale('es'); + /// print(date.getMonthYear()); // "Junio 2024" + /// + /// PackageStrings.setLocale('ar'); + /// print(date.getMonthYear()); // "يونيو ٢٠٢٤" + /// ``` + String getMonthYear({bool abbreviatedMonth = false}) { + final monthName = getMonthName(abbreviated: abbreviatedMonth); + final yearStr = PackageStrings.localizeNumber(year); + return '$monthName $yearStr'; + } } extension TimeOfDayExtension on TimeOfDay { @@ -228,6 +272,11 @@ extension ColorExtension on Color { } } +extension WeekDaysExtension on WeekDays { + /// Returns the localized abbreviation for this weekday using the current locale. + String get abbreviation => PackageStrings.currentLocale.weekdays[index]; +} + extension MinutesExtension on MinuteSlotSize { /// Returns minutes for respective [MinuteSlotSize] int get minutes { @@ -335,12 +384,29 @@ extension BuildContextExtension on BuildContext { Theme.of(this).extension() ?? WeekViewThemeData.light(); - /// Get [MultiDayViewThemeData] from theme, if null returns light theme. + /// Get [MultiDayViewThemeData] from theme, if null returns light or dark theme + /// based on the ambient [Theme]'s brightness. /// [MultiDayViewThemeData] needs to be added in [MaterialApp] theme extensions /// to get theme data with this type. - MultiDayViewThemeData get multiDayViewColors => - Theme.of(this).extension() ?? - MultiDayViewThemeData.light(); + MultiDayViewThemeData get multiDayViewColors { + final theme = Theme.of(this); + return theme.extension() ?? + (theme.brightness == Brightness.dark + ? MultiDayViewThemeData.dark() + : MultiDayViewThemeData.light()); + } + + /// Get [ScheduleViewThemeData] from theme, if null returns light or dark theme + /// based on the ambient [Theme]'s brightness. + /// [ScheduleViewThemeData] needs to be added in [MaterialApp] theme extensions + /// to get theme data with this type. + ScheduleViewThemeData get scheduleViewColors { + final theme = Theme.of(this); + return theme.extension() ?? + (theme.brightness == Brightness.dark + ? ScheduleViewThemeData.dark() + : ScheduleViewThemeData.light()); + } } extension BuildContextMultiDayViewThemeExtension on BuildContext { diff --git a/lib/src/localization/calendar_localizations.dart b/lib/src/localization/calendar_localizations.dart index 0a46056d..8db6490a 100644 --- a/lib/src/localization/calendar_localizations.dart +++ b/lib/src/localization/calendar_localizations.dart @@ -5,14 +5,18 @@ class CalendarLocalizations { final List weekdays; final List? numbers; final bool isRTL; + final List months; + final List? monthsAbbr; const CalendarLocalizations({ required this.am, required this.pm, required this.more, required this.weekdays, - this.numbers = const ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], + this.numbers = _numbers, this.isRTL = false, + this.months = _months, + this.monthsAbbr, }); /// Create CalendarLocalizations from a Map (e.g., parsed ARB/JSON) @@ -21,19 +25,70 @@ class CalendarLocalizations { am: map['am'] ?? 'am', pm: map['pm'] ?? 'pm', more: map['more'] ?? '', - weekdays: List.from(map['weekdays'] ?? []), - numbers: List.from(map['numbers'] ?? []), + weekdays: List.from(map['weekdays'] ?? _weekdays), + numbers: List.from(map['numbers'] ?? _numbers), isRTL: map['isRTL'] ?? false, + months: List.from(map['months'] ?? _months), + monthsAbbr: map['monthsAbbr'] != null + ? List.from(map['monthsAbbr']) + : null, ); } + static const List _months = [ + 'January', + 'February', + 'March', + 'April', + 'May', + 'June', + 'July', + 'August', + 'September', + 'October', + 'November', + 'December', + ]; + + static const List _numbers = [ + '0', + '1', + '2', + '3', + '4', + '5', + '6', + '7', + '8', + '9' + ]; + + static const List _monthsAbbr = [ + 'Jan', + 'Feb', + 'Mar', + 'Apr', + 'May', + 'Jun', + 'Jul', + 'Aug', + 'Sep', + 'Oct', + 'Nov', + 'Dec', + ]; + + static const List _weekdays = ['M', 'T', 'W', 'T', 'F', 'S', 'S']; + /// Built-in English localization static const CalendarLocalizations en = CalendarLocalizations( am: 'am', pm: 'pm', more: 'more', - weekdays: ['M', 'T', 'W', 'T', 'F', 'S', 'S'], - numbers: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], + weekdays: _weekdays, + numbers: _numbers, isRTL: false, + months: _months, + monthsAbbr: _monthsAbbr, ); } diff --git a/lib/src/localization/package_locals.dart b/lib/src/localization/package_locals.dart index fa84e005..1a86ab41 100644 --- a/lib/src/localization/package_locals.dart +++ b/lib/src/localization/package_locals.dart @@ -22,6 +22,34 @@ class PackageStrings { pm: 'p. m.', more: 'Más', weekdays: ['L', 'M', 'X', 'J', 'V', 'S', 'D'], + months: [ + 'Enero', + 'Febrero', + 'Marzo', + 'Abril', + 'Mayo', + 'Junio', + 'Julio', + 'Agosto', + 'Septiembre', + 'Octubre', + 'Noviembre', + 'Diciembre', + ], + monthsAbbr: [ + 'Ene', + 'Feb', + 'Mar', + 'Abr', + 'May', + 'Jun', + 'Jul', + 'Ago', + 'Sep', + 'Oct', + 'Nov', + 'Dic', + ], ); /// Arabic (العربية) localizations with RTL support @@ -30,6 +58,34 @@ class PackageStrings { pm: 'م', more: 'المزيد', weekdays: ['ن', 'ث', 'ر', 'خ', 'ج', 'س', 'ح'], + months: [ + 'يناير', + 'فبراير', + 'مارس', + 'أبريل', + 'مايو', + 'يونيو', + 'يوليو', + 'أغسطس', + 'سبتمبر', + 'أكتوبر', + 'نوفمبر', + 'ديسمبر', + ], + monthsAbbr: [ + 'يناير', + 'فبراير', + 'مارس', + 'أبريل', + 'مايو', + 'يونيو', + 'يوليو', + 'أغسطس', + 'سبتمبر', + 'أكتوبر', + 'نوفمبر', + 'ديسمبر', + ], numbers: [ '٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩', // 0-9 '١٠', '١١', '١٢', '١٣', '١٤', '١٥', '١٦', '١٧', '١٨', '١٩', // 10-19 @@ -48,6 +104,34 @@ class PackageStrings { pm: 'PM', more: 'Plus', weekdays: ['L', 'M', 'M', 'J', 'V', 'S', 'D'], + months: [ + 'Janvier', + 'Février', + 'Mars', + 'Avril', + 'Mai', + 'Juin', + 'Juillet', + 'Août', + 'Septembre', + 'Octobre', + 'Novembre', + 'Décembre', + ], + monthsAbbr: [ + 'Jan', + 'Fév', + 'Mar', + 'Avr', + 'Mai', + 'Jun', + 'Jul', + 'Aoû', + 'Sep', + 'Oct', + 'Nov', + 'Déc', + ], ); /// German (Deutsch) localizations @@ -56,6 +140,34 @@ class PackageStrings { pm: 'PM', more: 'Mehr', weekdays: ['M', 'D', 'M', 'D', 'F', 'S', 'S'], + months: [ + 'Januar', + 'Februar', + 'März', + 'April', + 'Mai', + 'Juni', + 'Juli', + 'August', + 'September', + 'Oktober', + 'November', + 'Dezember', + ], + monthsAbbr: [ + 'Jan', + 'Feb', + 'Mär', + 'Apr', + 'Mai', + 'Jun', + 'Jul', + 'Aug', + 'Sep', + 'Okt', + 'Nov', + 'Dez', + ], ); /// Hindi (हिन्दी) localizations with Devanagari numbers @@ -64,6 +176,34 @@ class PackageStrings { pm: 'अपराह्न', more: 'अधिक', weekdays: ['सो', 'मं', 'बु', 'गु', 'शु', 'श', 'र'], + months: [ + 'जनवरी', + 'फरवरी', + 'मार्च', + 'अप्रैल', + 'मई', + 'जून', + 'जुलाई', + 'अगस्त', + 'सितंबर', + 'अक्टूबर', + 'नवंबर', + 'दिसंबर', + ], + monthsAbbr: [ + 'जन', + 'फर', + 'मार्च', + 'अप्रै', + 'मई', + 'जून', + 'जुला', + 'अग', + 'सित', + 'अक्टू', + 'नव', + 'दिस', + ], numbers: [ '०', '१', '२', '३', '४', '५', '६', '७', '८', '९', // 0-9 '१०', '११', '१२', '१३', '१४', '१५', '१६', '१७', '१८', '१९', // 10-19 @@ -81,6 +221,34 @@ class PackageStrings { pm: '下午', more: '更多', weekdays: ['一', '二', '三', '四', '五', '六', '日'], + months: [ + '一月', + '二月', + '三月', + '四月', + '五月', + '六月', + '七月', + '八月', + '九月', + '十月', + '十一月', + '十二月', + ], + monthsAbbr: [ + '1月', + '2月', + '3月', + '4月', + '5月', + '6月', + '7月', + '8月', + '9月', + '10月', + '11月', + '12月', + ], ); /// Japanese (日本語) localizations @@ -89,6 +257,34 @@ class PackageStrings { pm: '午後', more: 'もっと', weekdays: ['月', '火', '水', '木', '金', '土', '日'], + months: [ + '1月', + '2月', + '3月', + '4月', + '5月', + '6月', + '7月', + '8月', + '9月', + '10月', + '11月', + '12月', + ], + monthsAbbr: [ + '1月', + '2月', + '3月', + '4月', + '5月', + '6月', + '7月', + '8月', + '9月', + '10月', + '11月', + '12月', + ], ); /// Set the current locale for the package strings (e.g., 'en', 'es'). @@ -110,25 +306,38 @@ class PackageStrings { static String get selectedLocale => _currentLocale; - /// Converts any integer (0-60) to a localized string using current locale's numbers. + /// Converts [number] to a string using the current locale's localized + /// digits. /// - /// If the locale has a numbers array with at least 61 elements (0-60), - /// it will return the localized representation directly from the array. - /// Otherwise, it returns the number as a string. - static String localizeNumber(int number) { - final numbers = currentLocale.numbers; + /// Works for integers of any magnitude — days, months, hours and large + /// values such as years are all localized (e.g. `2026` -> `"٢٠٢٦"` for the + /// Arabic locale). Delegates to [localizeNumberString]. + static String localizeNumber(int number) => + localizeNumberString(number.toString()); - // Check if numbers array is available and has enough elements - if (numbers == null || numbers.length < 61) { - return number.toString(); - } + /// Replaces every Western digit (`0`-`9`) in [input] with the current + /// locale's localized digit, taken from [CalendarLocalizations.numbers]. + /// + /// All other characters — separators (`/`, `:`, `-`), directionality marks, + /// AM/PM markers and letters — are preserved untouched, so already-formatted + /// strings (e.g. the output of `intl`'s `DateFormat`) can be localized in + /// place. When the current locale does not define a digit set (i.e. it uses + /// Western digits, like English), [input] is returned unchanged. + /// + /// This is the single source of truth for digit localization across the + /// package and is unaffected by the magnitude of the number, unlike a fixed + /// lookup table. + static String localizeNumberString(String input) { + final numbers = currentLocale.numbers; - // Validate range (0-60 for calendar usage) - if (number < 0 || number > 60) { - return number.toString(); + // Locale uses Western digits (or defines no digit set) — nothing to map. + if (numbers == null || numbers.length < 10) { + return input; } - // Return the localized number directly from the array - return numbers[number]; + return input.replaceAllMapped( + RegExp(r'[0-9]'), + (match) => numbers[int.parse(match[0]!)], + ); } } diff --git a/lib/src/modals.dart b/lib/src/models.dart similarity index 93% rename from lib/src/modals.dart rename to lib/src/models.dart index c2373796..91694f96 100644 --- a/lib/src/modals.dart +++ b/lib/src/models.dart @@ -6,6 +6,31 @@ import 'package:flutter/material.dart'; import '../calendar_view.dart'; +/// A single month section rendered by the ScheduleView, pairing a month's +/// first day with the day to start rendering from. +/// +/// [startDay] is the day-of-month to start iterating from (1 for most months). +/// Each entry always renders through the end of its month; the only bounded +/// range — the leading piece of a split anchor month — is built directly, +/// not via a [ScheduleMonthSection]. +/// +/// [showHeader] controls whether the month header is rendered for this entry. +/// The anchor month is split into two sections — a header-bearing piece for the +/// days before the anchor date and a header-less piece starting at the anchor +/// date — so this is set to `false` on the second piece to avoid a duplicate +/// header. +class ScheduleMonthSection { + final DateTime date; + final int startDay; + final bool showHeader; + + const ScheduleMonthSection( + this.date, + this.startDay, { + this.showHeader = true, + }); +} + /// Settings for hour lines class HourIndicatorSettings { final double height; diff --git a/lib/src/month_view/month_view.dart b/lib/src/month_view/month_view.dart index 7ca298c0..34302a14 100644 --- a/lib/src/month_view/month_view.dart +++ b/lib/src/month_view/month_view.dart @@ -5,7 +5,6 @@ import 'package:flutter/material.dart'; import '../../calendar_view.dart'; -import '../extensions.dart'; class MonthView extends StatefulWidget { /// Main [Widget] to display month view. diff --git a/lib/src/multi_day_view/_internal_multi_day_view_page.dart b/lib/src/multi_day_view/_internal_multi_day_view_page.dart index 92353333..6fc75193 100644 --- a/lib/src/multi_day_view/_internal_multi_day_view_page.dart +++ b/lib/src/multi_day_view/_internal_multi_day_view_page.dart @@ -11,7 +11,7 @@ import '../enumerations.dart'; import '../event_arrangers/event_arrangers.dart'; import '../event_controller.dart'; import '../extensions.dart'; -import '../modals.dart'; +import '../models.dart'; import '../painters.dart'; import '../typedefs.dart'; import '../zoom_scroll_controller.dart'; @@ -313,7 +313,7 @@ class _InternalMultiDayViewPageState @override Widget build(BuildContext context) { final filteredDates = _filteredDate(); - final themeColor = context.multiDayViewTheme; + final themeColor = context.multiDayViewColors; final direction = Directionality.of(context); return Container( diff --git a/lib/src/multi_day_view/multi_day_view.dart b/lib/src/multi_day_view/multi_day_view.dart index 7c2dca93..1ad76a41 100644 --- a/lib/src/multi_day_view/multi_day_view.dart +++ b/lib/src/multi_day_view/multi_day_view.dart @@ -6,7 +6,6 @@ import 'package:flutter/material.dart'; import '../../calendar_view.dart'; import '../constants.dart'; -import '../extensions.dart'; import '../painters.dart'; import '../current_time_scroller.dart'; import '../zoom_scroll_controller.dart'; diff --git a/lib/src/schedule_view/_internal_schedule_view_page.dart b/lib/src/schedule_view/_internal_schedule_view_page.dart new file mode 100644 index 00000000..c86928ec --- /dev/null +++ b/lib/src/schedule_view/_internal_schedule_view_page.dart @@ -0,0 +1,387 @@ +// Copyright (c) 2021 Simform Solutions. All rights reserved. +// Use of this source code is governed by a MIT-style license +// that can be found in the LICENSE file. + +import 'package:flutter/material.dart'; + +import '../../calendar_view.dart'; + +/// Renders a single month block in the schedule view. +/// +/// Displays the month header followed by a row for each day that has events, +/// is today, or should be shown due to [showDaysWithoutEvents]. +class InternalScheduleViewPage extends StatelessWidget { + final DateTime monthDate; + final int startDay; + final int? endDay; + final bool showHeader; + final DateTime minDay; + final DateTime maxDay; + final bool showDaysWithoutEvents; + final List> Function(DateTime date) eventsForDay; + final ScheduleMonthHeaderBuilder? monthHeaderBuilder; + final ScheduleDateWidgetBuilder? dateHeaderBuilder; + final ScheduleDateWidgetBuilder? dayDetectorBuilder; + final ScheduleEventTileBuilder? eventTileBuilder; + final Widget? emptyTextWidget; + final DateTapCallback? onDateTap; + final DatePressCallback? onDateLongPress; + final CellTapCallback? onEventTap; + final CellTapCallback? onEventLongTap; + final CellTapCallback? onEventDoubleTap; + final StringProvider? dateStringBuilder; + final String Function(int weekday)? weekDayStringBuilder; + final ScheduleMonthHeaderBuilder? emptyMonthBuilder; + final EventSorter? eventSorter; + final ScheduleDateLayout dateLayout; + final DividerSettings? dividerSettings; + final Widget? todayEmptyWidget; + + const InternalScheduleViewPage({ + Key? key, + required this.monthDate, + required this.startDay, + this.endDay, + this.showHeader = true, + required this.minDay, + required this.maxDay, + required this.showDaysWithoutEvents, + required this.eventsForDay, + this.monthHeaderBuilder, + this.dateHeaderBuilder, + this.dayDetectorBuilder, + this.eventTileBuilder, + this.emptyTextWidget, + this.onDateTap, + this.onDateLongPress, + this.onEventTap, + this.onEventLongTap, + this.onEventDoubleTap, + this.dateStringBuilder, + this.weekDayStringBuilder, + this.emptyMonthBuilder, + this.eventSorter, + this.dateLayout = ScheduleDateLayout.left, + this.dividerSettings, + this.todayEmptyWidget, + }) : super(key: key); + + @override + Widget build(BuildContext context) { + final theme = context.scheduleViewColors; + final daysInMonth = DateTime(monthDate.year, monthDate.month + 1, 0).day; + final lastDay = (endDay ?? daysInMonth).clamp(1, daysInMonth); + final List dayWidgets = []; + final now = DateTime.now(); + + for (int day = startDay; day <= lastDay; day++) { + final date = DateTime(monthDate.year, monthDate.month, day); + + if (date.isBefore(DateTime(minDay.year, minDay.month, minDay.day)) || + date.isAfter(DateTime(maxDay.year, maxDay.month, maxDay.day))) { + continue; + } + + final events = eventsForDay(date); + final isToday = date == DateTime(now.year, now.month, now.day); + + if (events.isNotEmpty || isToday || showDaysWithoutEvents) { + dayWidgets.add(_buildDayRow(theme, date, events, isToday)); + } + } + + // Empty month: pre-filtering guarantees this only occurs when + // showEmptyMonths: true (false case is filtered before reaching here). + // Restricted to the header-bearing piece (showHeader): the split anchor + // month's head piece (endDay != null) renders just its header, and its + // tail piece (showHeader == false) must not render a second standalone + // empty-month block below that header for the same month. + if (dayWidgets.isEmpty && + endDay == null && + showHeader && + emptyMonthBuilder != null) { + return emptyMonthBuilder!(monthDate); + } + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (!showHeader) + const SizedBox.shrink() + else if (monthHeaderBuilder != null) + monthHeaderBuilder!(monthDate) + else + Container( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16), + child: Text( + dateStringBuilder != null + ? dateStringBuilder!(monthDate) + : monthDate.getMonthYear(), + style: TextStyle( + fontSize: 22, + fontWeight: FontWeight.w600, + color: theme.dateTextColor, + ), + ), + ), + ...dayWidgets, + ], + ); + } + + /// Builds the row for a single [date]: a date cell paired with that day's + /// events. + /// + /// When [eventSorter] is supplied the [events] are re-sorted with it; + /// otherwise the controller-provided order is kept. An empty day falls back + /// to [todayEmptyWidget] (when [isToday]), then [emptyTextWidget], then a + /// plain divider. The cell and events are laid out vertically for + /// [ScheduleDateLayout.top] and side by side otherwise. + Widget _buildDayRow( + ScheduleViewThemeData theme, + DateTime date, + List> events, + bool isToday, + ) { + // [eventsForDay] returns a controller-sorted list; only re-sort when + // this view supplies an eventSorter to override the controller's order. + final sortedEvents = + eventSorter == null ? events : (List.of(events)..sort(eventSorter!)); + + final dateCell = _buildDateCell(theme, date, sortedEvents, isToday); + + Widget eventsArea; + if (sortedEvents.isEmpty) { + // [emptyTextWidget] only applies when empty days are rendered as a + // first-class row (showDaysWithoutEvents). Today is always rendered even + // in sparse mode, but there only [todayEmptyWidget] (then the divider) + // applies — keeping release behaviour in step with the debug assert and + // docs. + eventsArea = (isToday ? todayEmptyWidget : null) ?? + (showDaysWithoutEvents ? emptyTextWidget : null) ?? + SizedBox( + height: 60, + child: Divider(color: theme.dateDividerColor), + ); + } else { + eventsArea = Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: sortedEvents.map((event) { + final tile = eventTileBuilder != null + ? eventTileBuilder!(event, date) + : _defaultEventTile(theme, event); + + return GestureDetector( + onTap: onEventTap != null ? () => onEventTap!([event], date) : null, + onLongPress: onEventLongTap != null + ? () => onEventLongTap!([event], date) + : null, + onDoubleTap: onEventDoubleTap != null + ? () => onEventDoubleTap!([event], date) + : null, + child: tile, + ); + }).toList(), + ); + } + + if (dateLayout == ScheduleDateLayout.top) { + // The date header spans the full row width above the events. `stretch` + // lets the header (and its divider) fill the row, matching how the left + // layout's [Expanded] events column already fills its side. + return Padding( + padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + dateCell, + const SizedBox(height: 8), + eventsArea, + ], + ), + ); + } + + return Padding( + padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0), + child: Row( + crossAxisAlignment: sortedEvents.isEmpty + ? CrossAxisAlignment.center + : CrossAxisAlignment.start, + children: [ + SizedBox(width: 50, child: dateCell), + const SizedBox(width: 16), + Expanded(child: eventsArea), + ], + ), + ); + } + + /// Builds the date cell shown alongside a day's events. + /// + /// Prefers [dayDetectorBuilder] when provided (it owns its own gestures). + /// Otherwise renders [dateHeaderBuilder] or the default header wrapped in a + /// [GestureDetector] that forwards taps to [onDateTap] / [onDateLongPress]. + Widget _buildDateCell( + ScheduleViewThemeData theme, + DateTime date, + List> events, + bool isToday, + ) { + if (dayDetectorBuilder != null) { + return dayDetectorBuilder!(date, events, dateLayout); + } + + final content = dateHeaderBuilder != null + ? dateHeaderBuilder!(date, events, dateLayout) + : _defaultDateHeader(theme, date, isToday); + + return GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: onDateTap != null ? () => onDateTap!(date) : null, + onLongPress: + onDateLongPress != null ? () => onDateLongPress!(date) : null, + child: content, + ); + } + + /// Builds the default date header for a day. + /// + /// Shows the localized weekday abbreviation above the day number, with the + /// number circled and recoloured when [isToday]. Delegates to + /// [_defaultTopDateHeader] for the [ScheduleDateLayout.top] layout. + Widget _defaultDateHeader( + ScheduleViewThemeData theme, + DateTime date, + bool isToday, + ) { + final weekday = weekDayStringBuilder != null + ? weekDayStringBuilder!(date.weekday) + : date.weekDayEnum.abbreviation; + + if (dateLayout == ScheduleDateLayout.top) { + return _defaultTopDateHeader(theme, date, isToday, weekday); + } + + return Column( + children: [ + Text( + weekday, + style: TextStyle( + fontSize: 12, + color: isToday ? theme.todayHighlightColor : theme.weekdayTextColor, + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 4), + Container( + width: 32, + height: 32, + decoration: BoxDecoration( + color: isToday ? theme.todayHighlightColor : theme.transparent, + shape: BoxShape.circle, + ), + alignment: Alignment.center, + child: Text( + PackageStrings.localizeNumber(date.day), + style: TextStyle( + fontSize: 16, + fontWeight: isToday ? FontWeight.bold : FontWeight.w500, + color: isToday ? theme.todayTextColor : theme.dateTextColor, + ), + ), + ), + ], + ); + } + + /// Builds the default date header for the [ScheduleDateLayout.top] layout. + /// + /// Lays out a circled [weekday] badge next to a localized "day month" label + /// (e.g. "5 Jun"), followed by a full-width divider from [dividerSettings]. + Widget _defaultTopDateHeader( + ScheduleViewThemeData theme, + DateTime date, + bool isToday, + String weekday, + ) { + // e.g. "5 Jun" — day-of-month and abbreviated month, both localized. + final dayMonth = '${PackageStrings.localizeNumber(date.day)} ' + '${date.getMonthName(abbreviated: true)}'; + + final divider = + dividerSettings ?? DividerSettings(color: theme.dateDividerColor); + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + width: 32, + height: 32, + decoration: BoxDecoration( + color: isToday ? theme.todayHighlightColor : theme.transparent, + shape: BoxShape.circle, + ), + alignment: Alignment.center, + child: Text( + weekday, + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.bold, + color: + isToday ? theme.todayTextColor : theme.weekdayTextColor, + ), + ), + ), + const SizedBox(width: 12), + Text( + dayMonth, + style: TextStyle( + fontSize: 14, + fontWeight: isToday ? FontWeight.bold : FontWeight.w600, + color: theme.dateTextColor, + ), + ), + ], + ), + const SizedBox(height: 8), + Divider( + height: divider.height, + thickness: divider.thickness, + color: divider.color, + indent: divider.indent, + endIndent: divider.endIndent, + ), + ], + ); + } + + /// Builds the default tile for a single [event]. + /// + /// Renders the event title on a tinted background (the event colour at + /// [ScheduleViewThemeData.eventTileAlpha]) with a coloured left border. + Widget _defaultEventTile( + ScheduleViewThemeData theme, + CalendarEventData event, + ) { + return Container( + margin: const EdgeInsets.only(bottom: 8.0), + padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0), + decoration: BoxDecoration( + color: event.color.withAlpha(theme.eventTileAlpha), + borderRadius: BorderRadius.circular(10.0), + border: Border(left: BorderSide(color: event.color, width: 4)), + ), + child: Text( + event.title, + style: TextStyle( + color: theme.eventTitleColor, + fontSize: 14, + fontWeight: FontWeight.w500, + ), + ), + ); + } +} diff --git a/lib/src/schedule_view/schedule_view.dart b/lib/src/schedule_view/schedule_view.dart new file mode 100644 index 00000000..02165236 --- /dev/null +++ b/lib/src/schedule_view/schedule_view.dart @@ -0,0 +1,1139 @@ +// Copyright (c) 2021 Simform Solutions. All rights reserved. +// Use of this source code is governed by a MIT-style license +// that can be found in the LICENSE file. + +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; + +import '../../calendar_view.dart'; +import '_internal_schedule_view_page.dart'; + +/// A scrollable agenda-style calendar that displays events grouped by day and month. +/// +/// Events are provided by an [EventController], either through [controller] +/// or the nearest [CalendarControllerProvider]. Each day with events (or every +/// day when [showDaysWithoutEvents] is `true`) is shown as a row, with the date +/// displayed beside or above the events depending on [dateLayout]. +/// +/// Use a [GlobalKey] and [ScheduleViewState.jumpToDate] to programmatically +/// navigate to a specific date. +/// +/// Visual styling is resolved from the nearest [ScheduleViewThemeData] +/// extension on [ThemeData], typically provided by +/// [CalendarThemeProvider]. +/// +/// ## Scrolling model +/// +/// Months are built lazily, one section at a time, as they scroll into view — +/// only the sections needed to fill the viewport are ever constructed. The +/// view is anchored at [initialDay] (pinned to the top of the viewport); +/// earlier days scroll up and later days scroll down, both within the limits +/// defined by [minDay] and [maxDay]. +/// +/// When [showEmptyMonths] is `false` (sparse mode), the scrollable range is +/// additionally bounded by the actual events held by the [controller], so that +/// long stretches of empty months are never traversed. This keeps the view +/// responsive even when [minDay]/[maxDay] span decades but events are sparse. +/// +/// See also: +/// - [ScheduleViewState] for navigation APIs. +/// - [CalendarControllerProvider] for sharing an [EventController]. +/// - [CalendarThemeProvider] for providing [ScheduleViewThemeData]. +class ScheduleView extends StatefulWidget { + /// The event controller that provides events to this view. + /// + /// When `null`, the view looks up the nearest [CalendarControllerProvider] + /// ancestor. Provide this explicitly when you need multiple independent + /// schedule views with different data sources. + final EventController? controller; + + /// The date the view is initially anchored to. + /// + /// The scroll position starts at this exact date, pinned to the top of the + /// viewport. Earlier days of the same month (and the month header) are + /// rendered above and become visible by scrolling up; later days and future + /// months are below. Defaults to [DateTime.now] when `null`. + final DateTime? initialDay; + + /// The earliest date the view will ever display. + /// + /// Months before this date are never loaded, and scrolling stops at the + /// month containing this date. Defaults to [CalendarConstants.epochDate] + /// when `null`. + final DateTime? minDay; + + /// The latest date the view will ever display. + /// + /// Months after this date are never loaded, and scrolling stops at the + /// month containing this date. Defaults to [CalendarConstants.maxDate] + /// when `null`. + final DateTime? maxDay; + + /// Builds a custom header widget for each month section. + /// + /// Receives the first day of the month. When `null`, a default text header + /// is rendered using [ScheduleViewThemeData] styles. + /// + /// Example — bold month name with a divider below: + /// ```dart + /// monthHeaderBuilder: (date) => Column( + /// children: [ + /// Text(DateFormat.yMMMM().format(date), + /// style: const TextStyle(fontWeight: FontWeight.bold)), + /// const Divider(), + /// ], + /// ), + /// ``` + final ScheduleMonthHeaderBuilder? monthHeaderBuilder; + + /// Builds a custom widget for the date indicator of each day row. + /// + /// If you supply this builder alongside [onDateTap] or + /// [onDateLongPress], those callbacks are still wrapped around the returned + /// widget automatically. + /// + /// To take full control of gesture handling too, use [dayDetectorBuilder] + /// instead. + final ScheduleDateWidgetBuilder? dateHeaderBuilder; + + /// Replaces the entire date indicator widget — including its gesture + /// detection. + /// + /// When set, [onDateTap] and [onDateLongPress] are **not** applied + /// automatically; the builder is fully responsible for all interactions. + /// Use this when you need non-standard hit-testing or custom gesture + /// recognisers on the date area. + /// + /// Prefer [dateHeaderBuilder] when you only want to change the visual + /// appearance and are happy to keep the default tap/long-press behaviour. + final ScheduleDateWidgetBuilder? dayDetectorBuilder; + + /// Builds a custom event tile for a single event on a given date. + /// + /// When `null`, the default tile shows the event color and title. + /// + /// Example: + /// ```dart + /// eventTileBuilder: (event, date) => ListTile( + /// leading: CircleAvatar(backgroundColor: event.color), + /// title: Text(event.title), + /// ), + /// ``` + final ScheduleEventTileBuilder? eventTileBuilder; + + /// Widget displayed in the events area when a day has no events. + /// + /// Only relevant when [showDaysWithoutEvents] is `true` (otherwise empty + /// days are not rendered at all). For today specifically, + /// [todayEmptyWidget] takes precedence when provided. + /// + /// Defaults to a full length [Divider] when `null`. + final Widget? emptyTextWidget; + + /// Called when the user taps the date circle / left column of a day row. + /// + /// Receives the tapped [DateTime] (time component zeroed). Not called when + /// [dayDetectorBuilder] is provided, since that builder owns all gesture + /// handling. + final DateTapCallback? onDateTap; + + /// Called when the user long-presses the date circle / left column of a + /// day row. + /// + /// Receives the pressed [DateTime] (time component zeroed). Not called when + /// [dayDetectorBuilder] is provided. + final DatePressCallback? onDateLongPress; + + /// Called when the user taps an event tile. + /// + /// Receives a single-element list containing the tapped event, plus the + /// date the tile was rendered for. The list wrapper matches the signature + /// used by other calendar view callbacks. + final CellTapCallback? onEventTap; + + /// Called when the user long-presses an event tile. + /// + /// Same signature as [onEventTap]. + final CellTapCallback? onEventLongTap; + + /// Called when the user double-taps an event tile. + /// + /// Same signature as [onEventTap]. + final CellTapCallback? onEventDoubleTap; + + /// Returns a custom formatted string for the month header label. + /// + /// Use this for i18n or custom date formatting without replacing + /// the entire header widget. + /// + /// Only used by the default header renderer; has no effect when + /// [monthHeaderBuilder] is provided. + final StringProvider? dateStringBuilder; + + /// Returns a custom weekday abbreviation for a given weekday number. + /// + /// The integer follows Dart's [DateTime.weekday] convention: + /// 1 = Monday … 7 = Sunday. + /// + /// Example — single-letter abbreviations: + /// ```dart + /// weekDayStringBuilder: (wd) => + /// ['M','T','W','T','F','S','S'][wd - 1], + /// ``` + /// + /// Only used by the default date badge renderer; has no effect when + /// [dateHeaderBuilder] or [dayDetectorBuilder] is provided. + final String Function(int weekday)? weekDayStringBuilder; + + /// Whether to render months that contain no visible day rows. + /// + /// When `false`, any month that would produce zero day rows is completely + /// omitted from the scroll list, and the scrollable range is bounded by the + /// actual events in the [controller] (plus today). This keeps long, sparse + /// date ranges responsive. + /// + /// When `true` (the default), every month in the [minDay]–[maxDay] range is + /// always shown; the optional [emptyMonthBuilder] can customise the + /// appearance of empty months. + final bool showEmptyMonths; + + /// Builds a replacement widget for months that have no events. + /// + /// When provided and a month has no visible day rows, this builder replaces + /// the entire month block (header + day rows). Only relevant when + /// [showEmptyMonths] is `true`. + /// + /// When `null` and the month is empty, only the month header is rendered + /// with no day rows beneath it. + /// + /// The returned widget **must have a non-zero height**. A zero-height widget + /// can never fill the viewport, which forces the lazy list to keep building + /// further months and degrades performance. + final ScheduleMonthHeaderBuilder? emptyMonthBuilder; + + /// Whether to show day rows for days that have no events. + /// + /// When `false` (the default), only days with at least one event, and + /// today, produce a visible row. When `true`, every day in the loaded date + /// range is rendered and [emptyTextWidget] (or [todayEmptyWidget] for today) + /// fills the events area on empty days. + /// + /// Enabling this implies every month has content, so it behaves like + /// [showEmptyMonths] for the purpose of which months are rendered. + final bool showDaysWithoutEvents; + + /// Background color of the schedule scroll view. + /// + /// When `null`, the view is transparent and inherits the background from + /// its parent widget. + final Color? backgroundColor; + + /// Explicit width for the schedule view. + /// + /// When `null` (the default), the view expands to fill all available + /// horizontal space. + final double? width; + + /// Scroll physics to apply to the agenda list. + /// + /// Defaults to the platform default when `null` (bouncing on iOS, + /// clamping on Android). + final ScrollPhysics? scrollPhysics; + + /// Called once when the earliest available month has been reached. + /// + /// Fires when the view has built up to the earliest month that can contain + /// content — either [minDay] or, in sparse mode, the month of the earliest + /// event. Use this to show a UI cue or trigger a data fetch. + final VoidCallback? onHasReachedStart; + + /// Called once when the latest available month has been reached. + /// + /// Fires when the view has built up to the latest month that can contain + /// content — either [maxDay] or, in sparse mode, the month of the latest + /// event. When an event recurs without an end date the future extent is + /// clamped to [maxDay], so this fires only once the user reaches [maxDay] + /// (effectively never in practice for an end-less recurrence). Use this to + /// show a UI cue or trigger a data fetch. + final VoidCallback? onHasReachedEnd; + + /// Custom comparator used to sort events within a single day. + /// + /// When `null`, events are sorted by start time only (ascending), using + /// [defaultEventSorter]; events that share a start time keep their existing + /// relative order. + /// + /// Example — sort by title alphabetically: + /// ```dart + /// eventSorter: (a, b) => a.title.compareTo(b.title), + /// ``` + final EventSorter? eventSorter; + + /// Builds the widget shown above all past content once the earliest + /// available month has been reached. + /// + /// Rendered only when the past scroll limit has been reached. When `null`, + /// no sentinel is shown. + final WidgetBuilder? pastSentinelBuilder; + + /// Builds the widget shown below all future content once the latest + /// available month has been reached. + /// + /// Rendered only when the future scroll limit has been reached. When `null`, + /// no sentinel is shown. + final WidgetBuilder? futureSentinelBuilder; + + /// Controls the position of the date indicator relative to the event list. + /// + /// - [ScheduleDateLayout.left] (default) — classic two-column layout with + /// the date badge on the left and events stacked on the right. + /// - [ScheduleDateLayout.top] — renders the date as a full-width header + /// above the event list for each day. Useful on narrow screens or when + /// more horizontal space is needed for event content. + final ScheduleDateLayout dateLayout; + + /// Styling for the divider drawn beneath the **default** date header in + /// [ScheduleDateLayout.top]. + /// + /// When `null`, a divider is drawn using [ScheduleViewThemeData.dateDividerColor]. + /// Pass [DividerSettings.none] to remove it, or your own [DividerSettings] + /// to customise thickness, height, color, and indents. + /// + /// Has no effect in [ScheduleDateLayout.left], nor when a custom + /// [dateHeaderBuilder] or [dayDetectorBuilder] is supplied — those builders + /// own the entire date indicator, divider included. + final DividerSettings? defaultDateHeaderDividerSettings; + + /// Widget shown in the events area specifically when **today** has no + /// events. + /// + /// Takes precedence over [emptyTextWidget] for today's row only. When + /// `null`, [emptyTextWidget] (or the built-in fallback) is used for all + /// empty days including today. + final Widget? todayEmptyWidget; + + /// Builds a pinned header showing the month currently at the top of the + /// viewport. + /// + /// Rendered **above** the scroll view (not overlaid), so content is never + /// hidden. Receives the first day of the visible month; rebuilds only when + /// the month changes. When `null`, no header is shown. + /// + /// Use [onVisibleMonthChanged] to drive an external title bar instead. + /// + /// ```dart + /// floatingMonthHeaderBuilder: (context, month) => Material( + /// elevation: 2, + /// child: Padding( + /// padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10), + /// child: Text(month.getMonthYear(), + /// style: const TextStyle(fontWeight: FontWeight.bold)), + /// ), + /// ), + /// ``` + final ScheduleFloatingHeaderBuilder? floatingMonthHeaderBuilder; + + /// Called whenever the month visible at the top of the viewport changes. + /// + /// Receives the first day of the newly-visible month. Useful for updating + /// external UI (e.g. a title bar outside the widget tree) without needing + /// to supply [floatingMonthHeaderBuilder]. + final void Function(DateTime month)? onVisibleMonthChanged; + + /// Creates a new [ScheduleView]. + const ScheduleView({ + Key? key, + this.controller, + this.initialDay, + this.minDay, + this.maxDay, + this.monthHeaderBuilder, + this.dateHeaderBuilder, + this.dayDetectorBuilder, + this.eventTileBuilder, + this.emptyTextWidget, + this.onDateTap, + this.onDateLongPress, + this.onEventTap, + this.onEventLongTap, + this.onEventDoubleTap, + this.dateStringBuilder, + this.weekDayStringBuilder, + this.showEmptyMonths = true, + this.emptyMonthBuilder, + this.showDaysWithoutEvents = false, + this.backgroundColor, + this.width, + this.scrollPhysics, + this.onHasReachedStart, + this.onHasReachedEnd, + this.eventSorter, + this.pastSentinelBuilder, + this.futureSentinelBuilder, + this.dateLayout = ScheduleDateLayout.left, + this.defaultDateHeaderDividerSettings, + this.todayEmptyWidget, + this.floatingMonthHeaderBuilder, + this.onVisibleMonthChanged, + }) : assert( + dayDetectorBuilder == null || dateHeaderBuilder == null, + 'dayDetectorBuilder takes full control of the date column — ' + 'dateHeaderBuilder will be ignored.', + ), + assert( + dayDetectorBuilder == null || + (onDateTap == null && onDateLongPress == null), + 'dayDetectorBuilder owns gesture handling — ' + 'onDateTap and onDateLongPress will be ignored.', + ), + assert( + monthHeaderBuilder == null || dateStringBuilder == null, + 'dateStringBuilder has no effect when monthHeaderBuilder is provided.', + ), + assert( + emptyTextWidget == null || showDaysWithoutEvents, + 'emptyTextWidget has no visible effect when showDaysWithoutEvents is ' + 'false — empty non-today days are never rendered in that mode. ' + 'Set showDaysWithoutEvents: true, or use todayEmptyWidget to ' + 'customise the empty state for today specifically.', + ), + super(key: key); + + @override + ScheduleViewState createState() => ScheduleViewState(); +} + +/// State class for [ScheduleView]. +/// +/// Obtain a reference via a [GlobalKey] to call [jumpToDate] from outside +/// the widget tree: +/// +/// ```dart +/// final key = GlobalKey(); +/// ScheduleView(key: key, ...); +/// key.currentState?.jumpToDate(DateTime(2025, 12, 1)); +/// ``` +/// +/// ## Implementation +/// +/// The view is a center-anchored [CustomScrollView] with two [SliverList]s: +/// the future list (the center sliver) grows downward from [_anchorMonth], +/// and the past list grows upward. Each list builds its month sections +/// **lazily by index** — [SliverList] only asks for the sections needed to +/// fill the viewport, so no manual prefetching or pagination is required. +/// +/// Month sections are produced on demand by [_growFuture] / [_growPast], which +/// step month-by-month from the anchor and (in sparse mode) skip months with +/// no visible content. The stepping is bounded by [_pastBoundMonth] and +/// [_futureBoundMonth]: in dense mode these are the [minDay]/[maxDay] months, +/// and in sparse mode they are clamped to the actual event extent so empty +/// spans are never walked. +class ScheduleViewState extends State> { + late EventController _controller; + + // The controller currently being listened to, used to detect controller + // swaps without re-subscribing on every dependency change. + EventController? _activeController; + + late DateTime _initialDay; + late DateTime _minDay; + late DateTime _maxDay; + + final ScrollController _scrollController = ScrollController(); + + // The center key identifies the sliver that anchors the scroll at the top + // of the viewport. Slivers before it (past months) grow upward; slivers + // after it (future months) grow downward. + final GlobalKey _centerKey = GlobalKey(); + + // Identifies the scroll view's render object so the visible-month detection + // can measure the viewport's top edge directly. With a floating month header + // the scroll view is laid out below the header, so the State's own render box + // no longer starts at the viewport top. + final GlobalKey _viewportKey = GlobalKey(); + + // Memoised event lookups: cleared on every reset so stale results are never + // served after an event is added/removed. + final Map>> _eventCache = {}; + + // `dense` is true when every month in range is rendered (showEmptyMonths or + // showDaysWithoutEvents). In that case bounds span the whole [minDay, maxDay] + // range. Otherwise (sparse) the bounds are clamped to the months that can + // actually contain content, derived from the controller's events. + late bool _dense; + late DateTime _anchorMonth; + late DateTime _pastBoundMonth; + late DateTime _futureBoundMonth; + + // True when the anchor month is split into a header-bearing head piece + // (days before the anchor, rendered in the past list) and the anchor piece + // (anchor day onward, in the future list). Only set when the anchor date is + // past the 1st AND that head range actually has content — otherwise an empty + // head would render a lone month header with no rows in sparse mode. + late bool _hasAnchorHead; + + // Month sections built so far, in display order. Future entries start at the + // anchor month and go forward; past entries start one month before the + // anchor and go backward (index 0 = nearest to the anchor). + final List _futureEntries = []; + final List _pastEntries = []; + + // Next month offset (relative to the anchor month) each direction will + // examine when grown. Future starts at the anchor (0); past starts one month + // back (1), since the anchor month itself belongs to the future list. + int _futureCursor = 0; + int _pastCursor = 1; + + // True once a direction has been walked to its bound and no further sections + // can be produced. + bool _futureFinished = false; + bool _pastFinished = false; + + // One-shot guards so the boundary callbacks fire at most once per reset. + bool _reachedStartFired = false; + bool _reachedEndFired = false; + + // True while a deferred reload is already pending, so a burst of controller + // notifications during a single frame schedules only one rebuild. + bool _reloadScheduled = false; + + // True while a visible-month check is already pending for this frame, so a + // burst of scroll notifications schedules only one _checkVisibleMonth call. + bool _visibleCheckScheduled = false; + + // Tracks the month currently visible at the top of the viewport, used to + // drive the optional floating header overlay and onVisibleMonthChanged. + late ValueNotifier _visibleMonthNotifier; + + // GlobalKey per built month page, used by _checkVisibleMonth to locate each + // section's RenderBox. The split anchor month's head piece uses _anchorHeadKey + // instead — reusing the month key for both pieces would mount the same + // GlobalKey twice and corrupt the tree. + final Map _monthPageKeys = {}; + final GlobalKey _anchorHeadKey = GlobalKey(); + + @override + void initState() { + super.initState(); + // Bounds first: _clampToDayBounds reads _minDay/_maxDay. + _minDay = widget.minDay ?? CalendarConstants.epochDate; + _maxDay = widget.maxDay ?? CalendarConstants.maxDate; + _initialDay = + _clampToDayBounds((widget.initialDay ?? DateTime.now()).withoutTime); + _visibleMonthNotifier = + ValueNotifier(DateTime(_initialDay.year, _initialDay.month, 1)); + _scrollController.addListener(_scheduleVisibleMonthCheck); + } + + /// Clamps [day] into `[minDay, maxDay]` at day granularity. + /// + /// Asserts (debug only) when [day] falls outside the range so callers learn + /// they passed an out-of-range [initialDay] / [jumpToDate] target; release + /// builds clamp silently so the view always has a renderable anchor. + DateTime _clampToDayBounds(DateTime day) { + final minDay = _minDay.withoutTime; + final maxDay = _maxDay.withoutTime; + assert( + !day.isBefore(minDay) && !day.isAfter(maxDay), + 'ScheduleView: $day is outside [minDay, maxDay] = [$minDay, $maxDay]; ' + 'it will be clamped into range.', + ); + if (day.isBefore(minDay)) return minDay; + if (day.isAfter(maxDay)) return maxDay; + return day; + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + if (_resolveController()) _rebuildSections(); + } + + /// Resolves the active controller from [ScheduleView.controller] or the + /// nearest [CalendarControllerProvider], swapping the listener subscription + /// when it changed. Returns `true` when the controller was swapped. + bool _resolveController() { + final resolved = widget.controller ?? + CalendarControllerProvider.of(context).controller; + if (identical(resolved, _activeController)) return false; + _activeController?.removeListener(_reload); + _controller = resolved; + _activeController = resolved; + _controller.addListener(_reload); + return true; + } + + @override + void didUpdateWidget(ScheduleView oldWidget) { + super.didUpdateWidget(oldWidget); + + var resetScroll = false; + var needsRebuild = false; + + // Re-resolve whenever the explicit `controller` parameter changes — + // including the non-null -> null transition, where the view must fall back + // to the nearest CalendarControllerProvider instead of staying subscribed + // to the stale explicit controller. + if (widget.controller != oldWidget.controller) { + if (_resolveController()) needsRebuild = true; + } + + if (widget.minDay != oldWidget.minDay) { + _minDay = widget.minDay ?? CalendarConstants.epochDate; + needsRebuild = true; + } + if (widget.maxDay != oldWidget.maxDay) { + _maxDay = widget.maxDay ?? CalendarConstants.maxDate; + needsRebuild = true; + } + + // Compare at day granularity against the stored (normalized) anchor: a + // caller passing `initialDay: DateTime.now()` inline yields a new + // now()-with-time on every parent rebuild, which would otherwise always + // be `!=` and reset the scroll position on each rebuild. + final newInitial = + _clampToDayBounds((widget.initialDay ?? DateTime.now()).withoutTime); + if (newInitial != _initialDay) { + _initialDay = newInitial; + needsRebuild = true; + resetScroll = true; + } + + if (widget.showEmptyMonths != oldWidget.showEmptyMonths || + widget.showDaysWithoutEvents != oldWidget.showDaysWithoutEvents) { + needsRebuild = true; + } + + if (needsRebuild) { + _rebuildSections(); + if (resetScroll) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted && _scrollController.hasClients) { + _scrollController.jumpTo(0); + } + }); + } + } + } + + @override + void dispose() { + _activeController?.removeListener(_reload); + _scrollController.removeListener(_scheduleVisibleMonthCheck); + _scrollController.dispose(); + _visibleMonthNotifier.dispose(); + super.dispose(); + } + + /// Resets all section state and triggers a rebuild in response to a + /// controller mutation (event added, removed, or updated). + /// + /// When the controller notifies its listeners while the framework is already + /// building — e.g. another widget mutates the controller from its own + /// `didChangeDependencies`/`build` — calling [setState] synchronously would + /// throw "setState() called during build". In that case the rebuild is + /// deferred to the end of the current frame. + void _reload() { + if (!mounted) return; + if (SchedulerBinding.instance.schedulerPhase == + SchedulerPhase.persistentCallbacks) { + if (_reloadScheduled) return; + _reloadScheduled = true; + WidgetsBinding.instance.addPostFrameCallback((_) { + _reloadScheduled = false; + if (mounted) setState(_rebuildSections); + }); + } else { + setState(_rebuildSections); + } + } + + /// Resets the view so that [date] becomes the new anchor and scrolls so that + /// [date] sits at the top of the viewport (earlier days of its month remain + /// reachable by scrolling up). + /// + /// All built sections, caches, and cursors are reset; the bounds are + /// recomputed for the new anchor. + /// + /// Example: + /// ```dart + /// final key = GlobalKey(); + /// // … + /// key.currentState?.jumpToDate(DateTime(2026, 1, 1)); + /// ``` + void jumpToDate(DateTime date) { + if (!mounted) return; + setState(() { + _initialDay = _clampToDayBounds(date.withoutTime); + _rebuildSections(); + }); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted && _scrollController.hasClients) _scrollController.jumpTo(0); + }); + } + + /// Recomputes the anchor and scroll bounds, then discards every built + /// section so the lazy lists rebuild from scratch. + /// + /// In sparse mode ([showEmptyMonths] == false and [showDaysWithoutEvents] == + /// false) the bounds are clamped to the months that can actually contain + /// content, derived from the controller's events plus today. This is what + /// prevents the view from walking the entire [minDay]–[maxDay] span — which + /// can be thousands of empty months — when events are sparse. + void _rebuildSections() { + _dense = widget.showEmptyMonths || widget.showDaysWithoutEvents; + _anchorMonth = DateTime(_initialDay.year, _initialDay.month, 1); + + final minMonth = DateTime(_minDay.year, _minDay.month, 1); + final maxMonth = DateTime(_maxDay.year, _maxDay.month, 1); + + if (_dense) { + _pastBoundMonth = minMonth; + _futureBoundMonth = maxMonth; + } else { + final today = DateTime.now().withoutTime; + var earliest = today; + var latest = today; + var unbounded = false; + + // The anchor (initialDay / jumpToDate target) must always fall within the + // scroll bounds, even when it lands outside the event range and after + // today — otherwise the anchor month is clamped away, onHasReachedEnd + // fires prematurely, and the navigated-to date renders blank. + if (_initialDay.isBefore(earliest)) earliest = _initialDay; + if (_initialDay.isAfter(latest)) latest = _initialDay; + + for (final event in _controller.allEvents) { + final start = event.date.withoutTime; + if (start.isBefore(earliest)) earliest = start; + + if (event.isRecurringEvent) { + // A recurrence with no end date repeats forever, so content can + // extend all the way to [maxDay]. + final end = event.recurrenceSettings?.endDate?.withoutTime; + if (end == null) { + unbounded = true; + } else if (end.isAfter(latest)) { + latest = end; + } + } else { + final end = event.endDate.withoutTime; + if (end.isAfter(latest)) latest = end; + } + } + + final earliestMonth = DateTime(earliest.year, earliest.month, 1); + final latestMonth = + unbounded ? maxMonth : DateTime(latest.year, latest.month, 1); + + _pastBoundMonth = + earliestMonth.isAfter(minMonth) ? earliestMonth : minMonth; + _futureBoundMonth = + latestMonth.isBefore(maxMonth) ? latestMonth : maxMonth; + } + + _eventCache.clear(); + _futureEntries.clear(); + _pastEntries.clear(); + _monthPageKeys.clear(); + _futureCursor = 0; + _pastCursor = 1; + _futureFinished = false; + _pastFinished = false; + _reachedStartFired = false; + _reachedEndFired = false; + // Drives both the floating header (via the notifier) and an external title + // bar (via onVisibleMonthChanged), so a programmatic jump/rebuild keeps the + // latter in sync — _checkVisibleMonth otherwise only fires it on scroll. + _updateVisibleMonth(_anchorMonth); + + // Split the anchor month only when the anchor date is past the 1st and the + // preceding day range (1 … _initialDay.day - 1) has content. In sparse mode + // an empty head range is suppressed so it can't render a lone month header + // with no rows; the anchor piece in the future list then carries the + // header instead (see _growFuture). + _hasAnchorHead = _initialDay.day > 1 && + (_dense || + _monthHasContent(_anchorMonth, + startDay: 1, endDay: _initialDay.day - 1)); + } + + /// Returns the future section at [index], growing the list as needed. + /// + /// Returns `null` when [index] lies past the last future section (the future + /// direction has been walked to its bound). + ScheduleMonthSection? _futureEntryAt(int index) { + while (_futureEntries.length <= index && !_futureFinished) { + _growFuture(); + } + return index < _futureEntries.length ? _futureEntries[index] : null; + } + + /// Appends the next future section, stepping past empty months in sparse + /// mode, or marks the future direction finished once [_futureBoundMonth] is + /// passed. + void _growFuture() { + while (true) { + final monthDate = + DateTime(_anchorMonth.year, _anchorMonth.month + _futureCursor, 1); + + if (monthDate.isAfter(_futureBoundMonth)) { + _futureFinished = true; + _fireReachedEnd(); + return; + } + + // The anchor month's center piece starts at _initialDay.day so the + // anchor date sits at the top of the viewport. When the anchor has a head + // piece (see _hasAnchorHead), the days before it and the header are + // rendered above in the past list, so the header is suppressed here. + // Otherwise — anchor on the 1st, or an empty head range in sparse mode — + // this anchor piece carries the header itself. + final isAnchor = _futureCursor == 0; + final startDay = isAnchor ? _initialDay.day : 1; + final showHeader = isAnchor ? !_hasAnchorHead : true; + _futureCursor++; + + if (_dense || _monthHasContent(monthDate, startDay: startDay)) { + _futureEntries.add( + ScheduleMonthSection(monthDate, startDay, showHeader: showHeader)); + return; + } + } + } + + /// Returns the past section at [index] (0 = nearest to the anchor), growing + /// the list as needed. + /// + /// Returns `null` when [index] lies past the oldest section (the past + /// direction has been walked to its bound). + ScheduleMonthSection? _pastEntryAt(int index) { + while (_pastEntries.length <= index && !_pastFinished) { + _growPast(); + } + return index < _pastEntries.length ? _pastEntries[index] : null; + } + + /// Appends the next past section, stepping past empty months in sparse mode, + /// or marks the past direction finished once [_pastBoundMonth] is passed. + void _growPast() { + while (true) { + final monthDate = + DateTime(_anchorMonth.year, _anchorMonth.month - _pastCursor, 1); + + if (monthDate.isBefore(_pastBoundMonth)) { + _pastFinished = true; + _fireReachedStart(); + return; + } + _pastCursor++; + + if (_dense || _monthHasContent(monthDate, startDay: 1)) { + _pastEntries.add(ScheduleMonthSection(monthDate, 1, showHeader: true)); + return; + } + } + } + + /// Returns `true` when the day range [startDay] … [endDay] (inclusive) of + /// [monthDate] contains at least one day row that would be rendered: a day + /// with events, or today. When [endDay] is `null`, the range extends to the + /// end of the month. + /// + /// Only consulted in sparse mode (dense mode renders every month + /// unconditionally). Uses [_eventCache] so each date is queried from the + /// controller at most once between resets. + bool _monthHasContent(DateTime monthDate, + {required int startDay, int? endDay}) { + final today = DateTime.now().withoutTime; + final minDay = _minDay.withoutTime; + final maxDay = _maxDay.withoutTime; + final daysInMonth = DateTime(monthDate.year, monthDate.month + 1, 0).day; + final lastDay = endDay ?? daysInMonth; + + for (int day = startDay; day <= lastDay; day++) { + final date = DateTime(monthDate.year, monthDate.month, day); + if (date.isBefore(minDay) || date.isAfter(maxDay)) continue; + if (date == today) return true; + + final events = _eventCache.putIfAbsent( + date, + () => _controller.getEventsOnDay(date), + ); + if (events.isNotEmpty) return true; + } + return false; + } + + /// Schedules a single [_checkVisibleMonth] call for the end of the current + /// frame. Batches rapid scroll ticks so at most one check runs per frame. + void _scheduleVisibleMonthCheck() { + if (widget.floatingMonthHeaderBuilder == null && + widget.onVisibleMonthChanged == null) { + return; + } + // Dedupe within a frame: many scroll notifications can fire before the + // post-frame callback runs, so without this guard each would register its + // own callback and run _checkVisibleMonth N times for the same frame. + if (_visibleCheckScheduled) return; + _visibleCheckScheduled = true; + WidgetsBinding.instance.addPostFrameCallback((_) { + _visibleCheckScheduled = false; + _checkVisibleMonth(); + }); + } + + /// Sets the visible-month notifier (driving the floating header) and notifies + /// [ScheduleView.onVisibleMonthChanged] for the same month. + /// + /// The callback is invoked after the current frame so listeners may safely + /// call `setState`. Used by the rebuild/jump path; [_checkVisibleMonth] + /// fires the callback directly on scroll, where it already runs post-frame. + void _updateVisibleMonth(DateTime month) { + _visibleMonthNotifier.value = month; + final callback = widget.onVisibleMonthChanged; + if (callback == null) return; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) callback(month); + }); + } + + /// The stable [GlobalKey] for the month page rendering [month], created on + /// first use. The split anchor month's head piece uses [_anchorHeadKey] + /// instead (see [_monthPageKeys]). + GlobalKey _keyForMonth(DateTime month) => + _monthPageKeys.putIfAbsent(month, GlobalKey.new); + + /// Walks all built month sections and finds the one whose [RenderBox] + /// straddles the viewport's top edge. Updates [_visibleMonthNotifier] and + /// fires [ScheduleView.onVisibleMonthChanged] when the month changes. + void _checkVisibleMonth() { + if (!mounted) return; + // Measure the scroll view itself rather than the State's render object: + // with a floating month header the scroll view is laid out below the + // header, so the State's box top no longer coincides with the viewport top. + final scrollBox = + _viewportKey.currentContext?.findRenderObject() as RenderBox?; + if (scrollBox == null || !scrollBox.attached) return; + + final viewportTop = scrollBox.localToGlobal(Offset.zero).dy; + + // (key, month) for every built section. Sections are stacked vertically + // and never overlap, so at most one straddles the top edge — order is + // irrelevant. The split anchor head is tracked under its own key so its + // month still resolves while it sits at the top. + final sections = >[ + if (_hasAnchorHead) MapEntry(_anchorHeadKey, _anchorMonth), + for (final e in _futureEntries) MapEntry(_keyForMonth(e.date), e.date), + for (final e in _pastEntries) MapEntry(_keyForMonth(e.date), e.date), + ]; + + for (final section in sections) { + final rb = section.key.currentContext?.findRenderObject() as RenderBox?; + if (rb == null || !rb.attached) continue; + + final sectionTop = rb.localToGlobal(Offset.zero).dy; + final sectionBottom = sectionTop + rb.size.height; + + if (sectionTop <= viewportTop && sectionBottom > viewportTop) { + if (section.value != _visibleMonthNotifier.value) { + _visibleMonthNotifier.value = section.value; + widget.onVisibleMonthChanged?.call(section.value); + } + return; + } + } + } + + /// Fires [ScheduleView.onHasReachedStart] once, after the current frame so + /// callbacks may safely call `setState`. + void _fireReachedStart() { + if (_reachedStartFired) return; + _reachedStartFired = true; + final callback = widget.onHasReachedStart; + if (callback == null) return; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) callback(); + }); + } + + /// Fires [ScheduleView.onHasReachedEnd] once, after the current frame so + /// callbacks may safely call `setState`. + void _fireReachedEnd() { + if (_reachedEndFired) return; + _reachedEndFired = true; + final callback = widget.onHasReachedEnd; + if (callback == null) return; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) callback(); + }); + } + + @override + Widget build(BuildContext context) { + // The anchor month is split when it has a head piece (see _hasAnchorHead): + // its leading days and the header render in the past list so the anchor + // date stays pinned to the top of the viewport. + final hasAnchorHead = _hasAnchorHead; + + Widget child = CustomScrollView( + key: _viewportKey, + controller: _scrollController, + physics: widget.scrollPhysics, + // The center sliver anchors at the top of the viewport. Slivers listed + // before it render above (past) and grow upward as the user scrolls up; + // slivers listed after it grow downward (future). + center: _centerKey, + slivers: [ + // ------------- Past months (grow upward) -------------- + // Index 0 is rendered ADJACENT to the center and higher indices go + // further back in time. Sections are built lazily on demand; a `null` + // return signals the start of available content. + SliverList( + delegate: SliverChildBuilderDelegate( + (context, index) => + _buildPastSliverChild(context, index, hasAnchorHead), + ), + ), + + // ── Anchor month + future months (center anchor, grow downward) ──── + SliverList( + key: _centerKey, + delegate: SliverChildBuilderDelegate( + (context, index) => _buildFutureSliverChild(context, index), + ), + ), + ], + ); + + if (widget.backgroundColor != null) { + child = ColoredBox(color: widget.backgroundColor!, child: child); + } + + if (widget.floatingMonthHeaderBuilder != null) { + // The header reserves its own height above the scroll view instead of + // overlaying it, so the anchor row (on first build) and the topmost row + // (at the past boundary) are never hidden behind it. Only the header + // rebuilds when the visible month changes; the scroll content is left + // untouched. + child = Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + ValueListenableBuilder( + valueListenable: _visibleMonthNotifier, + builder: (ctx, month, _) => + widget.floatingMonthHeaderBuilder!(ctx, month), + ), + Expanded(child: child), + ], + ); + } + + if (widget.width != null) { + child = SizedBox(width: widget.width, child: child); + } + + return child; + } + + /// Builds a child of the future (center) sliver: the lazily-grown future + /// month at [index], or the future sentinel once the end is reached. + Widget? _buildFutureSliverChild(BuildContext context, int index) { + final entry = _futureEntryAt(index); + if (entry != null) { + return _buildMonthPage( + entry.date, + key: _keyForMonth(entry.date), + startDay: entry.startDay, + showHeader: entry.showHeader, + ); + } + // First slot past the last future month: optionally show the sentinel. + if (_futureFinished && + index == _futureEntries.length && + widget.futureSentinelBuilder != null) { + return widget.futureSentinelBuilder!(context); + } + return null; + } + + /// Builds a child of the past sliver: the anchor head piece at index 0 (when + /// the anchor date is past the 1st), then lazily-grown earlier months, then + /// the past sentinel once the start is reached. + Widget? _buildPastSliverChild( + BuildContext context, int index, bool hasAnchorHead) { + if (hasAnchorHead && index == 0) { + // The header-bearing leading piece of the anchor month, covering the + // days that precede the anchor date (1 … _initialDay.day - 1). It uses a + // dedicated key so it never collides with the anchor piece's month key. + return _buildMonthPage( + _anchorMonth, + key: _anchorHeadKey, + startDay: 1, + endDay: _initialDay.day - 1, + showHeader: true, + ); + } + + final pastIndex = hasAnchorHead ? index - 1 : index; + final entry = _pastEntryAt(pastIndex); + if (entry != null) { + return _buildMonthPage(entry.date, + key: _keyForMonth(entry.date), + startDay: entry.startDay, + showHeader: entry.showHeader); + } + // First slot past the oldest month: optionally show the sentinel. + if (_pastFinished && + pastIndex == _pastEntries.length && + widget.pastSentinelBuilder != null) { + return widget.pastSentinelBuilder!(context); + } + return null; + } + + /// Builds the [InternalScheduleViewPage] for a single month, forwarding all + /// widget-level configuration properties. + /// + /// [key] is supplied by the caller so the split anchor month's two pieces + /// never share a [GlobalKey]; see [_monthPageKeys]. + Widget _buildMonthPage( + DateTime monthDate, { + required Key key, + int startDay = 1, + int? endDay, + bool showHeader = true, + }) { + return InternalScheduleViewPage( + key: key, + monthDate: monthDate, + startDay: startDay, + endDay: endDay, + showHeader: showHeader, + minDay: _minDay, + maxDay: _maxDay, + showDaysWithoutEvents: widget.showDaysWithoutEvents, + eventsForDay: (date) => _eventCache.putIfAbsent( + date, + () => _controller.getEventsOnDay(date), + ), + monthHeaderBuilder: widget.monthHeaderBuilder, + dateHeaderBuilder: widget.dateHeaderBuilder, + dayDetectorBuilder: widget.dayDetectorBuilder, + eventTileBuilder: widget.eventTileBuilder, + emptyTextWidget: widget.emptyTextWidget, + onDateTap: widget.onDateTap, + onDateLongPress: widget.onDateLongPress, + onEventTap: widget.onEventTap, + onEventLongTap: widget.onEventLongTap, + onEventDoubleTap: widget.onEventDoubleTap, + dateStringBuilder: widget.dateStringBuilder, + weekDayStringBuilder: widget.weekDayStringBuilder, + emptyMonthBuilder: widget.emptyMonthBuilder, + eventSorter: widget.eventSorter, + dateLayout: widget.dateLayout, + dividerSettings: widget.defaultDateHeaderDividerSettings, + todayEmptyWidget: widget.todayEmptyWidget, + ); + } +} diff --git a/lib/src/theme/calendar_theme_data.dart b/lib/src/theme/calendar_theme_data.dart index 943d8c33..90f49385 100644 --- a/lib/src/theme/calendar_theme_data.dart +++ b/lib/src/theme/calendar_theme_data.dart @@ -6,12 +6,14 @@ class CalendarThemeData { required this.dayViewTheme, required this.weekViewTheme, required this.multiDayViewTheme, + required this.scheduleViewTheme, }); final MonthViewThemeData monthViewTheme; final DayViewThemeData dayViewTheme; final WeekViewThemeData weekViewTheme; final MultiDayViewThemeData multiDayViewTheme; + final ScheduleViewThemeData scheduleViewTheme; /// Creates a copy of this `CalendarThemeData` with optional overrides. CalendarThemeData copyWith({ @@ -19,12 +21,14 @@ class CalendarThemeData { DayViewThemeData? dayViewTheme, WeekViewThemeData? weekViewTheme, MultiDayViewThemeData? multiDayViewTheme, + ScheduleViewThemeData? scheduleViewTheme, }) { return CalendarThemeData( monthViewTheme: monthViewTheme ?? this.monthViewTheme, dayViewTheme: dayViewTheme ?? this.dayViewTheme, weekViewTheme: weekViewTheme ?? this.weekViewTheme, multiDayViewTheme: multiDayViewTheme ?? this.multiDayViewTheme, + scheduleViewTheme: scheduleViewTheme ?? this.scheduleViewTheme, ); } @@ -37,6 +41,7 @@ class CalendarThemeData { dayViewTheme: other.dayViewTheme, weekViewTheme: other.weekViewTheme, multiDayViewTheme: other.multiDayViewTheme, + scheduleViewTheme: other.scheduleViewTheme, ); } } diff --git a/lib/src/theme/dark_app_colors.dart b/lib/src/theme/dark_app_colors.dart index 2538021e..aabe43ce 100644 --- a/lib/src/theme/dark_app_colors.dart +++ b/lib/src/theme/dark_app_colors.dart @@ -5,10 +5,15 @@ class DarkAppColors { static const Color primary = Color(0xffffb3b6); static const Color onPrimary = Color(0xff561d23); + static const Color outline = Color(0xff9f8c8c); static const Color surfaceContainerHigh = Color(0xff322828); static const Color outlineVariant = Color(0xff524343); static const Color onSurface = Color(0xfff0dede); static const Color surfaceContainerLowest = Color(0xff140c0c); static const Color surfaceContainerLow = Color(0xff22191a); static const Color surfaceContainerHighest = Color(0xff3d3232); + static const Color emptyContent = Color(0xFF8C8C8C); + static const Color monthHeaderText = Color(0xFFFFFFFF); + static const Color monthHeaderGradientEnd = Color(0x8A000000); + static const Color monthHeaderTextShadow = Color(0x73000000); } diff --git a/lib/src/theme/light_app_colors.dart b/lib/src/theme/light_app_colors.dart index 50c31788..6938d74e 100644 --- a/lib/src/theme/light_app_colors.dart +++ b/lib/src/theme/light_app_colors.dart @@ -6,9 +6,15 @@ class LightAppColors { static const Color primary = Color(0xffEF5366); static const Color onPrimary = Color(0xffffffff); static const Color surfaceContainerHigh = Color(0xfff6e4e4); + static const Color outline = Color(0xff857373); static const Color outlineVariant = Color(0xffd7c1c2); static const Color onSurface = Color(0xff22191a); static const Color surfaceContainerLowest = Color(0xffffffff); static const Color surfaceContainerLow = Color(0xfffff0f0); static const Color surfaceContainerHighest = Color(0xfff0dede); + static const Color transparent = Color(0x00000000); + static const Color emptyContent = Color(0xFFAFAFAF); + static const Color monthHeaderText = Color(0xFFFFFFFF); + static const Color monthHeaderGradientEnd = Color(0x8A000000); + static const Color monthHeaderTextShadow = Color(0x73000000); } diff --git a/lib/src/theme/schedule_view_theme_data.dart b/lib/src/theme/schedule_view_theme_data.dart new file mode 100644 index 00000000..601cdcce --- /dev/null +++ b/lib/src/theme/schedule_view_theme_data.dart @@ -0,0 +1,268 @@ +import 'dart:ui' show lerpDouble; + +import 'package:flutter/material.dart'; + +import 'dark_app_colors.dart'; +import 'light_app_colors.dart'; + +/// Theme data for the default built-in widget builders of [ScheduleView]. +/// +/// Colors are applied only when the package-provided fallback widgets render +/// (e.g. the default date cell, event tile, or empty-state labels). Fully +/// custom builders supplied via [ScheduleView.dayDetectorBuilder], +/// [ScheduleView.eventTileBuilder], etc. are unaffected. +/// +/// Register as a [ThemeExtension] on [MaterialApp.theme] / [MaterialApp.darkTheme] +/// to override the defaults: +/// +/// ```dart +/// MaterialApp( +/// theme: ThemeData( +/// extensions: [ScheduleViewThemeData.light().copyWith(todayHighlightColor: Colors.teal)], +/// ), +/// ) +/// ``` +class ScheduleViewThemeData extends ThemeExtension { + const ScheduleViewThemeData({ + required this.todayHighlightColor, + required this.todayTextColor, + required this.dateTextColor, + required this.weekdayTextColor, + required this.dateDividerColor, + required this.emptyContentColor, + required this.eventTitleColor, + required this.eventSecondaryTextColor, + required this.eventTileAlpha, + required this.eventTimeColorLightnessAdjust, + required this.monthHeaderTextColor, + required this.transparent, + required this.monthHeaderGradientStartColor, + required this.monthHeaderGradientEndColor, + required this.monthHeaderTextShadowColor, + }); + + /// Background fill of the circular highlight drawn on today's date cell. + final Color todayHighlightColor; + + /// Color of the date number rendered inside the today highlight circle. + final Color todayTextColor; + + /// Default color of date numbers on non-today days. + final Color dateTextColor; + + /// Color of weekday abbreviations (Mon, Tue, …) on non-today days. + /// Also used for today's weekday abbreviation alongside [todayHighlightColor]. + final Color weekdayTextColor; + + /// Color of the divider drawn beneath the date header when + /// [ScheduleView.dateLayout] is [ScheduleDateLayout.top], separating each + /// day's header from its events (and from the previous day). + final Color dateDividerColor; + + /// Color for empty-state labels: the day-level "no events" placeholder, + /// the past sentinel, and the future sentinel. + final Color emptyContentColor; + + /// Color for event tile title text. + final Color eventTitleColor; + + /// Color for event tile description text and secondary UI (chevron, badges). + final Color eventSecondaryTextColor; + + /// Alpha value applied to the event's own color for the tile background: + /// `event.color.withAlpha(eventTileAlpha)`. + /// Lower in light mode (~28) to avoid overpowering the background; + /// higher in dark mode (~45) to keep the tint visible. + final int eventTileAlpha; + + /// HSL lightness adjustment applied to the event color for the time label. + /// Negative values darken the color (use in light mode for contrast); + /// 0.0 means no adjustment (use in dark mode to preserve the event color). + final double eventTimeColorLightnessAdjust; + + /// Text and icon color for the month-header image overlay. + /// Typically white in both light and dark mode because the header always + /// has a dark gradient over the photograph. + final Color monthHeaderTextColor; + + /// Fully transparent color; used as the date-cell background for non-today + /// days and as the start of the month-header gradient overlay. + final Color transparent; + + /// Start color of the gradient overlay drawn on top of the month-header + /// image (transparent end, so the image shows through at the top). + final Color monthHeaderGradientStartColor; + + /// End color of the gradient overlay drawn on top of the month-header + /// image; a semi-opaque dark color so white text remains readable. + final Color monthHeaderGradientEndColor; + + /// Color used for text shadow on the month-header title, providing contrast + /// against the background image. + final Color monthHeaderTextShadowColor; + + /// Pre-defined colors for a light theme. + const ScheduleViewThemeData.light() + : todayHighlightColor = LightAppColors.primary, + todayTextColor = LightAppColors.onPrimary, + dateTextColor = LightAppColors.onSurface, + weekdayTextColor = LightAppColors.outlineVariant, + dateDividerColor = LightAppColors.outlineVariant, + emptyContentColor = LightAppColors.emptyContent, + eventTitleColor = LightAppColors.onSurface, + eventSecondaryTextColor = LightAppColors.outline, + eventTileAlpha = 28, + eventTimeColorLightnessAdjust = -0.1, + monthHeaderTextColor = LightAppColors.monthHeaderText, + transparent = LightAppColors.transparent, + monthHeaderGradientStartColor = LightAppColors.transparent, + monthHeaderGradientEndColor = LightAppColors.monthHeaderGradientEnd, + monthHeaderTextShadowColor = LightAppColors.monthHeaderTextShadow; + + /// Pre-defined colors for a dark theme. + const ScheduleViewThemeData.dark() + : todayHighlightColor = DarkAppColors.primary, + todayTextColor = DarkAppColors.onPrimary, + dateTextColor = DarkAppColors.onSurface, + weekdayTextColor = DarkAppColors.outlineVariant, + dateDividerColor = DarkAppColors.outlineVariant, + emptyContentColor = DarkAppColors.emptyContent, + eventTitleColor = DarkAppColors.onSurface, + eventSecondaryTextColor = DarkAppColors.outline, + eventTileAlpha = 45, + eventTimeColorLightnessAdjust = 0.0, + monthHeaderTextColor = DarkAppColors.monthHeaderText, + transparent = LightAppColors.transparent, + monthHeaderGradientStartColor = LightAppColors.transparent, + monthHeaderGradientEndColor = DarkAppColors.monthHeaderGradientEnd, + monthHeaderTextShadowColor = DarkAppColors.monthHeaderTextShadow; + + @override + ThemeExtension copyWith({ + Color? todayHighlightColor, + Color? todayTextColor, + Color? dateTextColor, + Color? weekdayTextColor, + Color? dateDividerColor, + Color? emptyContentColor, + Color? eventTitleColor, + Color? eventSecondaryTextColor, + int? eventTileAlpha, + double? eventTimeColorLightnessAdjust, + Color? monthHeaderTextColor, + Color? transparent, + Color? monthHeaderGradientStartColor, + Color? monthHeaderGradientEndColor, + Color? monthHeaderTextShadowColor, + }) { + return ScheduleViewThemeData( + todayHighlightColor: todayHighlightColor ?? this.todayHighlightColor, + todayTextColor: todayTextColor ?? this.todayTextColor, + dateTextColor: dateTextColor ?? this.dateTextColor, + weekdayTextColor: weekdayTextColor ?? this.weekdayTextColor, + dateDividerColor: dateDividerColor ?? this.dateDividerColor, + emptyContentColor: emptyContentColor ?? this.emptyContentColor, + eventTitleColor: eventTitleColor ?? this.eventTitleColor, + eventSecondaryTextColor: + eventSecondaryTextColor ?? this.eventSecondaryTextColor, + eventTileAlpha: eventTileAlpha ?? this.eventTileAlpha, + eventTimeColorLightnessAdjust: + eventTimeColorLightnessAdjust ?? this.eventTimeColorLightnessAdjust, + monthHeaderTextColor: monthHeaderTextColor ?? this.monthHeaderTextColor, + transparent: transparent ?? this.transparent, + monthHeaderGradientStartColor: + monthHeaderGradientStartColor ?? this.monthHeaderGradientStartColor, + monthHeaderGradientEndColor: + monthHeaderGradientEndColor ?? this.monthHeaderGradientEndColor, + monthHeaderTextShadowColor: + monthHeaderTextShadowColor ?? this.monthHeaderTextShadowColor, + ); + } + + @override + ThemeExtension lerp( + covariant ThemeExtension? other, + double t, + ) { + if (other is! ScheduleViewThemeData) return this; + return ScheduleViewThemeData( + todayHighlightColor: + Color.lerp(todayHighlightColor, other.todayHighlightColor, t) ?? + todayHighlightColor, + todayTextColor: + Color.lerp(todayTextColor, other.todayTextColor, t) ?? todayTextColor, + dateTextColor: + Color.lerp(dateTextColor, other.dateTextColor, t) ?? dateTextColor, + weekdayTextColor: + Color.lerp(weekdayTextColor, other.weekdayTextColor, t) ?? + weekdayTextColor, + dateDividerColor: + Color.lerp(dateDividerColor, other.dateDividerColor, t) ?? + dateDividerColor, + emptyContentColor: + Color.lerp(emptyContentColor, other.emptyContentColor, t) ?? + emptyContentColor, + eventTitleColor: Color.lerp(eventTitleColor, other.eventTitleColor, t) ?? + eventTitleColor, + eventSecondaryTextColor: Color.lerp( + eventSecondaryTextColor, + other.eventSecondaryTextColor, + t, + ) ?? + eventSecondaryTextColor, + eventTileAlpha: + lerpDouble(eventTileAlpha, other.eventTileAlpha, t)?.round() ?? + eventTileAlpha, + eventTimeColorLightnessAdjust: lerpDouble( + eventTimeColorLightnessAdjust, + other.eventTimeColorLightnessAdjust, + t, + ) ?? + eventTimeColorLightnessAdjust, + monthHeaderTextColor: + Color.lerp(monthHeaderTextColor, other.monthHeaderTextColor, t) ?? + monthHeaderTextColor, + transparent: Color.lerp(transparent, other.transparent, t) ?? transparent, + monthHeaderGradientStartColor: Color.lerp( + monthHeaderGradientStartColor, + other.monthHeaderGradientStartColor, + t, + ) ?? + monthHeaderGradientStartColor, + monthHeaderGradientEndColor: Color.lerp( + monthHeaderGradientEndColor, + other.monthHeaderGradientEndColor, + t, + ) ?? + monthHeaderGradientEndColor, + monthHeaderTextShadowColor: Color.lerp( + monthHeaderTextShadowColor, + other.monthHeaderTextShadowColor, + t, + ) ?? + monthHeaderTextShadowColor, + ); + } + + /// Merges another [ScheduleViewThemeData] into this one. + ThemeExtension merge(ScheduleViewThemeData? other) { + if (other == null) return this; + return copyWith( + todayHighlightColor: other.todayHighlightColor, + todayTextColor: other.todayTextColor, + dateTextColor: other.dateTextColor, + weekdayTextColor: other.weekdayTextColor, + dateDividerColor: other.dateDividerColor, + emptyContentColor: other.emptyContentColor, + eventTitleColor: other.eventTitleColor, + eventSecondaryTextColor: other.eventSecondaryTextColor, + eventTileAlpha: other.eventTileAlpha, + eventTimeColorLightnessAdjust: other.eventTimeColorLightnessAdjust, + monthHeaderTextColor: other.monthHeaderTextColor, + transparent: other.transparent, + monthHeaderGradientStartColor: other.monthHeaderGradientStartColor, + monthHeaderGradientEndColor: other.monthHeaderGradientEndColor, + monthHeaderTextShadowColor: other.monthHeaderTextShadowColor, + ); + } +} diff --git a/lib/src/typedefs.dart b/lib/src/typedefs.dart index 32819101..a8644b0c 100644 --- a/lib/src/typedefs.dart +++ b/lib/src/typedefs.dart @@ -93,6 +93,22 @@ typedef TileDoubleTapDetailsCallback = void Function( TapDownDetails? doubleTapDetails, ); +typedef ScheduleDateWidgetBuilder = Widget Function( + DateTime date, + List events, + ScheduleDateLayout layout, +); + +typedef ScheduleMonthHeaderBuilder = Widget Function(DateTime date); + +typedef ScheduleFloatingHeaderBuilder = Widget Function( + BuildContext context, + DateTime visibleMonth, +); + +typedef ScheduleEventTileBuilder = Widget Function( + CalendarEventData event, DateTime date); + typedef CellTapCallback = void Function( List> events, DateTime date); diff --git a/lib/src/week_view/_internal_week_view_page.dart b/lib/src/week_view/_internal_week_view_page.dart index adfaabe6..661aa8ad 100644 --- a/lib/src/week_view/_internal_week_view_page.dart +++ b/lib/src/week_view/_internal_week_view_page.dart @@ -6,7 +6,6 @@ import 'package:flutter/material.dart'; import '../../calendar_view.dart'; import '../components/_internal_components.dart'; -import '../extensions.dart'; import '../painters.dart'; import '../zoom_scroll_controller.dart'; diff --git a/lib/src/week_view/week_view.dart b/lib/src/week_view/week_view.dart index 831e1894..3f61228a 100644 --- a/lib/src/week_view/week_view.dart +++ b/lib/src/week_view/week_view.dart @@ -6,7 +6,6 @@ import 'package:flutter/material.dart'; import '../../calendar_view.dart'; import '../constants.dart'; -import '../extensions.dart'; import '../painters.dart'; import '../current_time_scroller.dart'; import '../zoom_scroll_controller.dart'; diff --git a/test/extensions_test.dart b/test/extensions_test.dart index b0b79c6a..d22b488e 100644 --- a/test/extensions_test.dart +++ b/test/extensions_test.dart @@ -49,6 +49,47 @@ void main() { testAllLastDayOfTheWeek(DateTime(2023, 10, 30)); }); }); + + group('Number & date localization', () { + // PackageStrings holds global state, restore the default after each test. + tearDown(() => PackageStrings.setLocale('en')); + + test('localizeNumber localizes numbers larger than 60 (e.g. a year)', () { + PackageStrings.setLocale('ar'); + // The bug: years (> 60) fell back to Western digits. They must now be + // localized digit-by-digit. + expect(PackageStrings.localizeNumber(2026), '٢٠٢٦'); + }); + + test('localizeNumber stays consistent with the old 0-60 lookup', () { + PackageStrings.setLocale('ar'); + expect(PackageStrings.localizeNumber(0), '٠'); + expect(PackageStrings.localizeNumber(9), '٩'); + expect(PackageStrings.localizeNumber(15), '١٥'); + expect(PackageStrings.localizeNumber(60), '٦٠'); + }); + + test('localizeNumberString preserves non-digit characters', () { + PackageStrings.setLocale('ar'); + // Separators, slashes and spaces must survive untouched. + expect(PackageStrings.localizeNumberString('6/4/2026'), '٦/٤/٢٠٢٦'); + expect(PackageStrings.localizeNumberString('12:05'), '١٢:٠٥'); + }); + + test('getMonthYear localizes both the month name and the year', () { + PackageStrings.setLocale('ar'); + expect(DateTime(2026, 6, 15).getMonthYear(), 'يونيو ٢٠٢٦'); + }); + + test('Western-digit locales are returned unchanged', () { + PackageStrings.setLocale('en'); + expect(PackageStrings.localizeNumber(2026), '2026'); + expect(PackageStrings.localizeNumberString('6/4/2026'), '6/4/2026'); + // Locales without a `numbers` set (e.g. German) keep Western digits. + PackageStrings.setLocale('de'); + expect(PackageStrings.localizeNumber(2026), '2026'); + }); + }); } /// Does datesOfWeek tests for this date with all 7 [WeekDays] as starts. diff --git a/test/schedule_view_test.dart b/test/schedule_view_test.dart new file mode 100644 index 00000000..99cbf4d9 --- /dev/null +++ b/test/schedule_view_test.dart @@ -0,0 +1,247 @@ +import 'package:calendar_view/calendar_view.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +// Fixed "today" keeps these widget tests deterministic — DateTime.now() can +// flake around midnight or under odd test-host clocks/timezones. +final today = DateTime(2024, 6, 15); + +void main() { + group('ScheduleView sparse mode (showEmptyMonths: false)', () { + // Builds a ScheduleView whose date range spans 20 years but whose only + // event is a single day near "now". This is the configuration that used to + // freeze the UI: the prefetch loop walked every empty month back to + // [minDay] trying (and failing) to fill the viewport. + Future pumpSparseSchedule( + WidgetTester tester, { + required EventController controller, + required DateTime initialDay, + }) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SizedBox( + height: 600, + width: 400, + child: ScheduleView( + controller: controller, + initialDay: initialDay, + minDay: DateTime(initialDay.year - 10), + maxDay: DateTime(initialDay.year + 10), + showEmptyMonths: false, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + } + + testWidgets('does not scan the whole min/max range when events are sparse', + (tester) async { + // Count how many distinct days are queried from the controller. With the + // bug this ran into the tens of thousands (≈ 240 months × 30 days); + // with the fix only the months around the single event are inspected. + var queriedDays = 0; + final controller = EventController( + eventFilter: (date, events) { + queriedDays++; + return events + .where((e) => e.date.withoutTime == date.withoutTime) + .toList(); + }, + ); + controller.add( + CalendarEventData( + title: 'Lonely event', + date: DateTime(today.year, today.month, today.day), + ), + ); + + await pumpSparseSchedule(tester, + controller: controller, initialDay: today); + + expect(find.text('Lonely event'), findsOneWidget); + // A couple of months' worth of day lookups is plenty of headroom; the + // broken implementation blew far past this. + expect(queriedDays, lessThan(500), + reason: 'sparse mode should not walk the entire date range'); + }); + + testWidgets('reports the start once it reaches the earliest event month', + (tester) async { + var reachedStart = false; + final controller = EventController() + ..add( + CalendarEventData( + title: 'Lonely event', + date: DateTime(today.year, today.month, today.day), + ), + ); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SizedBox( + height: 600, + width: 400, + child: ScheduleView( + controller: controller, + initialDay: today, + minDay: DateTime(today.year - 10), + maxDay: DateTime(today.year + 10), + showEmptyMonths: false, + onHasReachedStart: () => reachedStart = true, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + // The past direction is bounded to the earliest event's month, so the + // start is reached without scrolling through a decade of empty months. + expect(reachedStart, isTrue); + }); + }); + + group('ScheduleView dateLayout: top', () { + testWidgets('renders the inline date header without overflow', ( + tester, + ) async { + final controller = EventController() + ..add( + CalendarEventData( + title: 'Today event', + date: DateTime(today.year, today.month, today.day), + ), + ); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SizedBox( + height: 600, + width: 400, + child: ScheduleView( + controller: controller, + initialDay: today, + dateLayout: ScheduleDateLayout.top, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + // pumpAndSettle would surface any RenderFlex overflow as a test failure. + expect(tester.takeException(), isNull); + expect(find.text('Today event'), findsOneWidget); + // The top layout's default header draws a divider beneath each date. + expect(find.byType(Divider), findsWidgets); + }); + + testWidgets('applies dividerSettings to the default header divider', ( + tester, + ) async { + final controller = EventController() + ..add( + CalendarEventData( + title: 'Today event', + date: DateTime(today.year, today.month, today.day), + ), + ); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SizedBox( + height: 600, + width: 400, + child: ScheduleView( + controller: controller, + initialDay: today, + dateLayout: ScheduleDateLayout.top, + defaultDateHeaderDividerSettings: + const DividerSettings(thickness: 3, color: Colors.purple), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + final divider = tester.widget(find.byType(Divider).first); + expect(divider.thickness, 3); + expect(divider.color, Colors.purple); + }); + + testWidgets('passes the active layout to dayDetectorBuilder', ( + tester, + ) async { + final controller = EventController() + ..add( + CalendarEventData( + title: 'Today event', + date: DateTime(today.year, today.month, today.day), + ), + ); + + final seenLayouts = {}; + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SizedBox( + height: 600, + width: 400, + child: ScheduleView( + controller: controller, + initialDay: today, + dateLayout: ScheduleDateLayout.top, + dayDetectorBuilder: (date, events, layout) { + seenLayouts.add(layout); + return const SizedBox(height: 24); + }, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(seenLayouts, contains(ScheduleDateLayout.top)); + expect(seenLayouts, isNot(contains(ScheduleDateLayout.left))); + }); + }); + + group('ScheduleView dense mode (showEmptyMonths: true)', () { + testWidgets('renders the current month and settles', (tester) async { + final controller = EventController() + ..add( + CalendarEventData( + title: 'Today event', + date: DateTime(today.year, today.month, today.day), + ), + ); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SizedBox( + height: 600, + width: 400, + child: ScheduleView( + controller: controller, + initialDay: today, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('Today event'), findsOneWidget); + }); + }); +}