From 56b1a74d888d8bfef1f30b71084de571422bbf01 Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 25 Nov 2026 01:08:40 +0530 Subject: [PATCH 1/2] feat(calendar): one row per show per day Episodes of one series airing on the same day on the same instance share a row in the calendar list, the grid's day list and the dashboard's Upcoming releases, with the first episode and +N more. In the calendar the chip opens the other episodes under the card, each with its status; the rest of the card still opens the series. A group reads Missing if any aired episode has no file, Upcoming if any is still to air, and Downloaded only when all have files. The dashboard counts rows, and an episode that two months' calendars both return counts once. --- .../dashboard/widgets/upcoming_widget.dart | 62 +++-- app/lib/src/screens/calendar_groups.dart | 90 +++++++ app/lib/src/screens/calendar_screen.dart | 228 ++++++++++++++--- app/test/calendar_group_rows_test.dart | 168 +++++++++++++ app/test/calendar_groups_test.dart | 235 ++++++++++++++++++ app/test/dashboard_widgets_test.dart | 40 +++ 6 files changed, 766 insertions(+), 57 deletions(-) create mode 100644 app/lib/src/screens/calendar_groups.dart create mode 100644 app/test/calendar_group_rows_test.dart create mode 100644 app/test/calendar_groups_test.dart diff --git a/app/lib/src/dashboard/widgets/upcoming_widget.dart b/app/lib/src/dashboard/widgets/upcoming_widget.dart index fcc068d0..b594999d 100644 --- a/app/lib/src/dashboard/widgets/upcoming_widget.dart +++ b/app/lib/src/dashboard/widgets/upcoming_widget.dart @@ -5,6 +5,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; import 'package:intl/intl.dart'; +import '../../screens/calendar_groups.dart'; import '../../screens/calendar_screen.dart'; import '../dashboard_widget_card.dart'; import '../dashboard_widget_kind.dart'; @@ -54,7 +55,10 @@ class DashboardUpcomingWidget extends ConsumerWidget { return !d.isBefore(windowStart) && d.isBefore(windowEnd); }).toList() ..sort((CalendarEvent a, CalendarEvent b) => a.date.compareTo(b.date)); - final List top = upcoming.take(5).toList(); + // A series' episodes on one day are one row, so a season dropped at once + // does not fill the widget; every count below is in rows. + final List groups = groupCalendarEvents(upcoming); + final List top = groups.take(5).toList(); Widget body; if (upcoming.isEmpty && anyLoading) { @@ -81,8 +85,8 @@ class DashboardUpcomingWidget extends ConsumerWidget { } else { final List rows = []; DateTime? lastDay; - for (final CalendarEvent e in top) { - final DateTime d = e.date.toLocal(); + for (final CalendarGroup g in top) { + final DateTime d = g.date.toLocal(); final DateTime day = DateTime(d.year, d.month, d.day); if (lastDay == null || day != lastDay) { lastDay = day; @@ -118,13 +122,12 @@ class DashboardUpcomingWidget extends ConsumerWidget { } else { rows.add(const SizedBox(height: Insets.sm)); } - rows.add(_ReleaseBanner(event: e)); + rows.add(_ReleaseBanner(group: g)); } - if (upcoming.length > top.length) { + if (groups.length > top.length) { rows.add(Padding( padding: const EdgeInsets.only(top: Insets.sm), - child: - DashboardIdleRow(text: '+${upcoming.length - top.length} more'), + child: DashboardIdleRow(text: '+${groups.length - top.length} more'), )); } body = Column( @@ -137,11 +140,10 @@ class DashboardUpcomingWidget extends ConsumerWidget { kind: DashboardWidgetKind.upcoming, accent: cs.secondary, onTap: () => context.goNamed(AtriumRoutes.calendarName), - trailing: upcoming.isNotEmpty + trailing: groups.isNotEmpty ? DashboardPill( icon: Icons.calendar_today_outlined, - label: - '${upcoming.length} release${upcoming.length == 1 ? '' : 's'}', + label: '${groups.length} release${groups.length == 1 ? '' : 's'}', color: cs.primary, ) : null, @@ -164,12 +166,13 @@ class DashboardUpcomingWidget extends ConsumerWidget { /// poster thumb, title + meta line, and a trailing badge - a check for a /// grabbed release, an airtime chip for an episode still to air. class _ReleaseBanner extends StatelessWidget { - const _ReleaseBanner({required this.event}); + const _ReleaseBanner({required this.group}); - final CalendarEvent event; + final CalendarGroup group; @override Widget build(BuildContext context) { + final CalendarEvent event = group.first; final ThemeData theme = Theme.of(context); final ColorScheme cs = theme.colorScheme; final String? backdrop = event.backdropUrl; @@ -186,9 +189,10 @@ class _ReleaseBanner extends StatelessWidget { hasArt ? onArt.withValues(alpha: 0.78) : cs.onSurfaceVariant; // Episodes carry a real airtime; movie release dates do not. final String? airTime = event is SonarrCalendarEvent - ? DateFormat.jm().format(event.date.toLocal()) + ? DateFormat.jm().format(group.date.toLocal()) : null; + return ClipRRect( borderRadius: BorderRadius.circular(16), child: SizedBox( @@ -254,12 +258,30 @@ class _ReleaseBanner extends StatelessWidget { ), ), const SizedBox(height: 3), - Text( - event.subtitle, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: theme.textTheme.bodySmall - ?.copyWith(color: subColor), + Row( + children: [ + Flexible( + child: Text( + event.subtitle, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.bodySmall + ?.copyWith(color: subColor), + ), + ), + // Its own text, so a long episode title is cut + // before the count is. + if (group.more > 0) ...[ + const SizedBox(width: Insets.xs), + Text( + '+${group.more} more', + style: theme.textTheme.bodySmall?.copyWith( + color: subColor, + fontWeight: FontWeight.w700, + ), + ), + ], + ], ), ], ), @@ -267,7 +289,7 @@ class _ReleaseBanner extends StatelessWidget { const SizedBox(width: Insets.sm), _StatusBadge( hasArt: hasArt, - hasFile: event.hasFile, + hasFile: group.allHaveFiles, airTime: airTime, onArt: onArt, scrim: scrim, diff --git a/app/lib/src/screens/calendar_groups.dart b/app/lib/src/screens/calendar_groups.dart new file mode 100644 index 00000000..5984680f --- /dev/null +++ b/app/lib/src/screens/calendar_groups.dart @@ -0,0 +1,90 @@ +import 'calendar_screen.dart'; + +/// Where a release stands, as the calendar's badge and accent show it. +enum CalendarStatus { downloaded, upcoming, missing } + +/// [event]'s own status at [now]: downloaded with a file, upcoming until it +/// airs, missing once it has aired without one. +CalendarStatus calendarStatusOf(CalendarEvent event, DateTime now) { + if (event.hasFile) return CalendarStatus.downloaded; + return event.date.isAfter(now) + ? CalendarStatus.upcoming + : CalendarStatus.missing; +} + +/// One calendar row: a release, or every episode of one series that airs on +/// the same day on the same instance (a season dropped at once). +class CalendarGroup { + CalendarGroup._(this.events); + + /// Oldest episode first; a single release is a group of one. + final List events; + + /// The event the row is drawn from. + CalendarEvent get first => events.first; + + /// How many more the row stands for, shown as "+N more". + int get more => events.length - 1; + + /// The earliest air time in the group. + DateTime get date => events + .map((CalendarEvent e) => e.date) + .reduce((DateTime a, DateTime b) => b.isBefore(a) ? b : a); + + /// Monitored when any of them is, since Sonarr will grab that one. + bool get monitored => events.any((CalendarEvent e) => e.monitored); + + bool get allHaveFiles => events.every((CalendarEvent e) => e.hasFile); + + /// Missing if any has aired without a file, so a gap is never hidden + /// behind a happier badge; then upcoming if any is still to air; + /// downloaded only when every one has its file. + CalendarStatus status(DateTime now) { + final Iterable all = + events.map((CalendarEvent e) => calendarStatusOf(e, now)); + if (all.contains(CalendarStatus.missing)) return CalendarStatus.missing; + if (all.contains(CalendarStatus.upcoming)) return CalendarStatus.upcoming; + return CalendarStatus.downloaded; + } +} + +/// Folds [events] into calendar rows, in time order. +/// +/// Episodes of the same series on the same instance and the same local day +/// share a row. Movies and albums keep one row each. An episode that arrives +/// twice, as it can from two months' calendars meeting at a boundary, counts +/// once. +List groupCalendarEvents(Iterable events) { + final Map> byKey = >{}; + final Set<(String, int)> seenEpisodes = <(String, int)>{}; + for (final CalendarEvent e in events) { + final Object key; + if (e is SonarrCalendarEvent) { + if (!seenEpisodes.add((e.instance.id, e.episode.id))) continue; + final DateTime local = e.date.toLocal(); + key = ( + e.instance.id, + e.episode.seriesId, + DateTime(local.year, local.month, local.day), + ); + } else { + key = e; + } + byKey.putIfAbsent(key, () => []).add(e); + } + final List groups = [ + for (final List list in byKey.values) + CalendarGroup._(list..sort(_episodeOrder)), + ]..sort((CalendarGroup a, CalendarGroup b) => a.date.compareTo(b.date)); + return groups; +} + +int _episodeOrder(CalendarEvent a, CalendarEvent b) { + if (a is SonarrCalendarEvent && b is SonarrCalendarEvent) { + final int bySeason = + a.episode.seasonNumber.compareTo(b.episode.seasonNumber); + if (bySeason != 0) return bySeason; + return a.episode.episodeNumber.compareTo(b.episode.episodeNumber); + } + return a.date.compareTo(b.date); +} diff --git a/app/lib/src/screens/calendar_screen.dart b/app/lib/src/screens/calendar_screen.dart index 983ab382..a4a076fc 100644 --- a/app/lib/src/screens/calendar_screen.dart +++ b/app/lib/src/screens/calendar_screen.dart @@ -14,6 +14,7 @@ import 'package:service_radarr/service_radarr.dart'; import 'package:service_sonarr/service_sonarr.dart'; import '../arr_artwork.dart'; +import 'calendar_groups.dart'; /// Aggregated calendar event representation. sealed class CalendarEvent { @@ -664,9 +665,9 @@ class _CalendarScreenState extends ConsumerState { child: _DateHeader(date: date), ), ); - for (final CalendarEvent event in entriesMap[date]! - ..sort((a, b) => a.date.compareTo(b.date))) { - rows.add(_EventTile(event: event)); + for (final CalendarGroup group + in groupCalendarEvents(entriesMap[date]!)) { + rows.add(_EventTile(group: group)); } } @@ -1088,8 +1089,9 @@ class _CalendarScreenState extends ConsumerState { ), ) else - for (final CalendarEvent event in selectedDayEntries) - _EventTile(event: event), + for (final CalendarGroup group + in groupCalendarEvents(selectedDayEntries)) + _EventTile(group: group), ], ); } @@ -1178,13 +1180,25 @@ class _DateHeader extends StatelessWidget { } } -class _EventTile extends ConsumerWidget { - const _EventTile({required this.event}); - final CalendarEvent event; +/// One calendar row: a release, or a series' episodes on one day. For a +/// group, "+N more" opens the other episodes under the card; the rest of the +/// card opens the series as before. +class _EventTile extends ConsumerStatefulWidget { + const _EventTile({required this.group}); + final CalendarGroup group; + + @override + ConsumerState<_EventTile> createState() => _EventTileState(); +} + +class _EventTileState extends ConsumerState<_EventTile> { + bool _open = false; @override - Widget build(BuildContext context, WidgetRef ref) { + Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); + final CalendarGroup group = widget.group; + final CalendarEvent event = group.first; final Instance instance = event.instance; Widget? posterWidget; @@ -1192,7 +1206,7 @@ class _EventTile extends ConsumerWidget { VoidCallback? onTap; if (event is RadarrCalendarEvent) { - final RadarrMovie movie = (event as RadarrCalendarEvent).movie; + final RadarrMovie movie = event.movie; final RadarrApi? api = ref.watch(radarrApiProvider(instance)).value; final RadarrImage? poster = movie.images .firstWhereOrNull((RadarrImage i) => i.coverType == 'poster'); @@ -1223,7 +1237,7 @@ class _EventTile extends ConsumerWidget { posterWidget = _Poster(imageUrl: imageUrl, icon: Icons.movie_outlined); } else if (event is SonarrCalendarEvent) { - final SonarrEpisode episode = (event as SonarrCalendarEvent).episode; + final SonarrEpisode episode = event.episode; final SonarrApi? api = ref.watch(sonarrApiProvider(instance)).value; final SonarrImage? poster = episode.series?.images .firstWhereOrNull((SonarrImage i) => i.coverType == 'poster'); @@ -1244,7 +1258,7 @@ class _EventTile extends ConsumerWidget { posterWidget = _Poster(imageUrl: imageUrl, icon: Icons.tv_outlined); } else if (event is LidarrCalendarEvent) { - final AlbumResource album = (event as LidarrCalendarEvent).album; + final AlbumResource album = event.album; final String? imageUrl = LidarrArtwork.albumCoverUrl(instance, album.images) ?? LidarrArtwork.artistPosterUrl(instance, album.artist?.images); @@ -1268,27 +1282,28 @@ class _EventTile extends ConsumerWidget { posterWidget = _Poster(imageUrl: imageUrl, icon: Icons.album_outlined); } - final bool isFuture = event.date.isAfter(clock.now()); - final (String label, Color bg, Color fg, Color accentColor) = event.hasFile - ? ( - 'Downloaded', - theme.colorScheme.primaryContainer, - theme.colorScheme.onPrimaryContainer, - theme.colorScheme.tertiary, - ) - : isFuture - ? ( - 'Upcoming', - theme.colorScheme.secondaryContainer, - theme.colorScheme.onSecondaryContainer, - theme.colorScheme.primary, - ) - : ( - 'Missing', - theme.colorScheme.errorContainer, - theme.colorScheme.onErrorContainer, - theme.colorScheme.error, - ); + final DateTime now = clock.now(); + final (String label, Color bg, Color fg, Color accentColor) = + switch (group.status(now)) { + CalendarStatus.downloaded => ( + 'Downloaded', + theme.colorScheme.primaryContainer, + theme.colorScheme.onPrimaryContainer, + theme.colorScheme.tertiary, + ), + CalendarStatus.upcoming => ( + 'Upcoming', + theme.colorScheme.secondaryContainer, + theme.colorScheme.onSecondaryContainer, + theme.colorScheme.primary, + ), + CalendarStatus.missing => ( + 'Missing', + theme.colorScheme.errorContainer, + theme.colorScheme.onErrorContainer, + theme.colorScheme.error, + ), + }; return Card( margin: const EdgeInsets.only(bottom: Insets.sm), @@ -1312,7 +1327,10 @@ class _EventTile extends ConsumerWidget { ), ), padding: const EdgeInsets.all(Insets.md), - child: Row( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ ClipRRect( @@ -1370,6 +1388,12 @@ class _EventTile extends ConsumerWidget { color: theme.colorScheme.outline, ), ), + if (group.more > 0) + _MoreChip( + count: group.more, + open: _open, + onTap: () => setState(() => _open = !_open), + ), ], ), const SizedBox(height: 8), @@ -1382,14 +1406,14 @@ class _EventTile extends ConsumerWidget { ), const SizedBox(width: 4), Text( - DateFormat.jm().format(event.date.toLocal()), + DateFormat.jm().format(group.date.toLocal()), style: theme.textTheme.labelMedium?.copyWith( color: theme.colorScheme.outline, ), ), const SizedBox(width: Insets.md), Icon( - event.monitored + group.monitored ? Icons.bookmark : Icons.bookmark_border, size: 14, @@ -1397,7 +1421,7 @@ class _EventTile extends ConsumerWidget { ), const SizedBox(width: 4), Text( - event.monitored ? 'Monitored' : 'Unmonitored', + group.monitored ? 'Monitored' : 'Unmonitored', style: theme.textTheme.labelMedium?.copyWith( color: theme.colorScheme.outline, ), @@ -1427,6 +1451,15 @@ class _EventTile extends ConsumerWidget { ), ), ], + ), + if (_open) + for (final CalendarEvent other in group.events.skip(1)) + _GroupedEpisode( + event: other, + shownTime: group.date, + now: now, + ), + ], ), ), ), @@ -1434,6 +1467,127 @@ class _EventTile extends ConsumerWidget { } } +/// "+N more" on a grouped card, with a chevron saying it opens in place. +class _MoreChip extends StatelessWidget { + const _MoreChip({ + required this.count, + required this.open, + required this.onTap, + }); + + final int count; + final bool open; + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + final ThemeData theme = Theme.of(context); + return Semantics( + button: true, + expanded: open, + child: InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(6), + child: Container( + padding: const EdgeInsets.fromLTRB(8, 2, 4, 2), + decoration: BoxDecoration( + color: theme.colorScheme.secondaryContainer, + borderRadius: BorderRadius.circular(6), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + '+$count more', + style: theme.textTheme.labelSmall?.copyWith( + color: theme.colorScheme.onSecondaryContainer, + fontWeight: FontWeight.bold, + ), + ), + Icon( + open ? Icons.expand_less : Icons.expand_more, + size: 16, + color: theme.colorScheme.onSecondaryContainer, + ), + ], + ), + ), + ), + ); + } +} + +/// One of a group's other episodes, under its opened card: a status dot, the +/// episode code and title, and the time when it differs from the card's. +class _GroupedEpisode extends StatelessWidget { + const _GroupedEpisode({ + required this.event, + required this.shownTime, + required this.now, + }); + + final CalendarEvent event; + final DateTime shownTime; + final DateTime now; + + @override + Widget build(BuildContext context) { + final ThemeData theme = Theme.of(context); + final ColorScheme cs = theme.colorScheme; + final SonarrEpisode? episode = + event is SonarrCalendarEvent ? (event as SonarrCalendarEvent).episode : null; + final String code = episode == null + ? '' + : 'S${episode.seasonNumber.toString().padLeft(2, '0')}' + 'E${episode.episodeNumber.toString().padLeft(2, '0')}'; + final String title = episode?.title ?? event.title; + final Color dot = switch (calendarStatusOf(event, now)) { + CalendarStatus.downloaded => cs.tertiary, + CalendarStatus.upcoming => cs.primary, + CalendarStatus.missing => cs.error, + }; + final bool sameTime = event.date.toLocal().hour == shownTime.toLocal().hour && + event.date.toLocal().minute == shownTime.toLocal().minute; + return Padding( + padding: const EdgeInsets.only(top: Insets.sm), + child: Row( + children: [ + const SizedBox(width: 52 + Insets.md - 14), + Container( + width: 8, + height: 8, + decoration: BoxDecoration(color: dot, shape: BoxShape.circle), + ), + const SizedBox(width: 6), + Text( + code, + style: theme.textTheme.labelMedium?.copyWith( + fontWeight: FontWeight.bold, + color: cs.onSurfaceVariant, + ), + ), + const SizedBox(width: Insets.sm), + Expanded( + child: Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.bodySmall, + ), + ), + if (!sameTime) ...[ + const SizedBox(width: Insets.sm), + Text( + DateFormat.jm().format(event.date.toLocal()), + style: theme.textTheme.labelSmall?.copyWith(color: cs.outline), + ), + ], + ], + ), + ); + } +} + class _Poster extends StatelessWidget { const _Poster({required this.imageUrl, required this.icon}); final String? imageUrl; diff --git a/app/test/calendar_group_rows_test.dart b/app/test/calendar_group_rows_test.dart new file mode 100644 index 00000000..f61e78fa --- /dev/null +++ b/app/test/calendar_group_rows_test.dart @@ -0,0 +1,168 @@ +import 'package:atrium/src/preferences.dart'; +import 'package:atrium/src/screens/calendar_screen.dart'; +import 'package:clock/clock.dart'; +import 'package:core_models/core_models.dart'; +import 'package:core_profile/core_profile.dart'; +import 'package:core_ui/core_ui.dart'; +import 'package:dio/dio.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/misc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:service_sonarr/service_sonarr.dart'; + +class _Prefs extends PreferencesController { + _Prefs(this._initial); + final Preferences _initial; + + @override + Preferences build() => _initial; +} + +const Instance _sonarr = Instance( + id: 'test-sonarr', + name: 'Test Sonarr', + kind: ServiceKind.sonarr, + localUrl: 'http://localhost:8989', + externalUrl: '', + urlMode: UrlMode.auto, + auth: InstanceAuth.apiKey(apiKey: 'k'), +); + +const SonarrSeries _drop = + SonarrSeries(id: 7, title: 'Blade Runner 2099', monitored: true); +const SonarrSeries _weekly = SonarrSeries(id: 8, title: 'Stick', monitored: true); + +/// Ten episodes of one series at 07:30 on the 25th, and one of another at +/// 09:00 the next day. With [fifthAiredWithoutFile], episode 5 aired at 06:00 +/// and has no file, so it is missing while the rest are still to air. +List _episodes({bool fifthAiredWithoutFile = false}) => + [ + for (int n = 1; n <= 10; n++) + SonarrEpisode( + id: n, + seriesId: _drop.id, + seasonNumber: 1, + episodeNumber: n, + title: 'Chapter $n', + monitored: true, + airDateUtc: (n == 5 && fifthAiredWithoutFile + ? DateTime(2026, 11, 25, 6) + : DateTime(2026, 11, 25, 7, 30)) + .toUtc() + .toIso8601String(), + series: _drop, + ), + SonarrEpisode( + id: 99, + seriesId: _weekly.id, + seasonNumber: 2, + episodeNumber: 5, + title: 'Go Time!', + monitored: true, + airDateUtc: DateTime(2026, 11, 26, 9).toUtc().toIso8601String(), + series: _weekly, + ), + ]; + +Future _pump( + WidgetTester tester, { + bool listView = true, + bool fifthAiredWithoutFile = false, +}) async { + tester.view.physicalSize = const Size(800, 1600); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + await tester.pumpWidget( + ProviderScope( + overrides: [ + preferencesProvider.overrideWith( + () => _Prefs(Preferences(calendarListView: listView)), + ), + activeInstancesProvider.overrideWith((Ref ref) => [_sonarr]), + sonarrApiProvider(_sonarr).overrideWith( + (Ref ref) async => SonarrApi(Dio(), apiKey: 'k'), + ), + sonarrCalendarProvider.overrideWith( + (Ref ref, (Instance, DateTime, bool) key) async => + key.$2.month == 11 + ? _episodes(fifthAiredWithoutFile: fifthAiredWithoutFile) + : [], + ), + ], + child: MaterialApp( + theme: AtriumTheme.light(null), + home: const CalendarScreen(), + ), + ), + ); + for (int i = 0; i < 6; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } +} + +/// The morning of the 25th, before the drop airs. +final Clock _morning = Clock.fixed(DateTime(2026, 11, 25, 7)); + +void main() { + testWidgets('a season drop is one card with +9 more', + (WidgetTester tester) async { + await withClock(_morning, () async { + await _pump(tester); + expect(find.text('Blade Runner 2099 - S01E01'), findsOneWidget); + expect(find.text('Blade Runner 2099 - S01E02'), findsNothing); + expect(find.text('+9 more'), findsOneWidget); + }); + }); + + testWidgets('a single episode gets no chip', (WidgetTester tester) async { + await withClock(_morning, () async { + await _pump(tester); + expect(find.text('Stick - S02E05'), findsOneWidget); + expect(find.textContaining('more'), findsOneWidget); + }); + }); + + testWidgets('the chip opens and closes the other episodes', + (WidgetTester tester) async { + await withClock(_morning, () async { + await _pump(tester); + expect(find.text('Chapter 2'), findsNothing); + await tester.tap(find.text('+9 more')); + await tester.pump(); + expect(find.text('S01E02'), findsOneWidget); + expect(find.text('Chapter 2'), findsOneWidget); + expect(find.text('Chapter 10'), findsOneWidget); + // The first episode is the card itself, not listed again. + expect(find.text('Chapter 1'), findsNothing); + await tester.tap(find.text('+9 more')); + await tester.pump(); + expect(find.text('Chapter 2'), findsNothing); + }); + }); + + testWidgets('a later episode aired without a file makes the card Missing', + (WidgetTester tester) async { + await withClock(_morning, () async { + await _pump(tester, fifthAiredWithoutFile: true); + final Finder card = find.ancestor( + of: find.text('Blade Runner 2099 - S01E01'), + matching: find.byType(Card), + ); + expect( + find.descendant(of: card, matching: find.text('Missing')), + findsOneWidget, + ); + }); + }); + + testWidgets("the grid's day list is grouped too", + (WidgetTester tester) async { + await withClock(_morning, () async { + await _pump(tester, listView: false); + expect(find.text('Blade Runner 2099 - S01E01'), findsOneWidget); + expect(find.text('Blade Runner 2099 - S01E02'), findsNothing); + expect(find.text('+9 more'), findsOneWidget); + }); + }); +} diff --git a/app/test/calendar_groups_test.dart b/app/test/calendar_groups_test.dart new file mode 100644 index 00000000..31c2026e --- /dev/null +++ b/app/test/calendar_groups_test.dart @@ -0,0 +1,235 @@ +import 'package:atrium/src/screens/calendar_groups.dart'; +import 'package:atrium/src/screens/calendar_screen.dart'; +import 'package:core_models/core_models.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:service_radarr/service_radarr.dart'; +import 'package:service_sonarr/service_sonarr.dart'; + +Instance _sonarr(String id) => Instance( + id: id, + name: id, + kind: ServiceKind.sonarr, + localUrl: 'http://$id.test', + externalUrl: '', + urlMode: UrlMode.auto, + auth: const InstanceAuth.apiKey(apiKey: 'k'), + ); + +final Instance _a = _sonarr('sonarr-a'); +final Instance _b = _sonarr('sonarr-b'); + +const SonarrSeries _bladeRunner = + SonarrSeries(id: 7, title: 'Blade Runner 2099', monitored: true); +const SonarrSeries _stick = SonarrSeries(id: 8, title: 'Stick', monitored: true); + +int _ids = 0; + +SonarrCalendarEvent _ep( + SonarrSeries series, + int episode, + DateTime airs, { + Instance? instance, + int season = 1, + bool hasFile = false, + bool monitored = true, +}) => + SonarrCalendarEvent( + SonarrEpisode( + id: ++_ids, + seriesId: series.id, + seasonNumber: season, + episodeNumber: episode, + title: 'Episode $episode', + hasFile: hasFile, + monitored: monitored, + airDateUtc: airs.toUtc().toIso8601String(), + series: series, + ), + instance ?? _a, + ); + +String _code(CalendarEvent e) { + final SonarrEpisode ep = (e as SonarrCalendarEvent).episode; + return 'S${ep.seasonNumber}E${ep.episodeNumber}'; +} + +void main() { + final DateTime day = DateTime(2026, 11, 25, 7, 30); + + group('grouping', () { + test('one series on one day is one row, first episode first', () { + final List groups = groupCalendarEvents([ + _ep(_bladeRunner, 3, day), + _ep(_bladeRunner, 1, day.add(const Duration(minutes: 30))), + _ep(_bladeRunner, 2, day), + ]); + expect(groups, hasLength(1)); + final CalendarGroup g = groups.single; + expect(_code(g.first), 'S1E1'); + expect(g.more, 2); + expect(g.events.map(_code), ['S1E1', 'S1E2', 'S1E3']); + // The earliest air time, not the first episode's. + expect(g.date, day); + }); + + test('a later season sorts after an earlier one', () { + final CalendarGroup g = groupCalendarEvents([ + _ep(_bladeRunner, 1, day, season: 2), + _ep(_bladeRunner, 10, day, season: 1), + ]).single; + expect(_code(g.first), 'S1E10'); + }); + + test('other days, other series and other instances stay apart', () { + final List groups = groupCalendarEvents([ + _ep(_bladeRunner, 1, day), + _ep(_bladeRunner, 2, day.add(const Duration(days: 1))), + _ep(_stick, 5, day), + _ep(_bladeRunner, 1, day, instance: _b), + ]); + expect(groups, hasLength(4)); + expect(groups.every((CalendarGroup g) => g.more == 0), isTrue); + }); + + test('the same episode fetched twice counts once', () { + // Two months' calendars can both carry an episode near the boundary, + // as separate objects. + SonarrCalendarEvent copy(int id, int n) => SonarrCalendarEvent( + SonarrEpisode( + id: id, + seriesId: _bladeRunner.id, + seasonNumber: 1, + episodeNumber: n, + title: 'Episode $n', + airDateUtc: day.toUtc().toIso8601String(), + series: _bladeRunner, + ), + _a, + ); + final List groups = groupCalendarEvents([ + copy(501, 1), + copy(502, 2), + copy(501, 1), + copy(502, 2), + ]); + expect(groups.single.more, 1); + }); + + test('a single episode is a group of one', () { + final CalendarGroup g = + groupCalendarEvents([_ep(_stick, 5, day)]).single; + expect(g.more, 0); + expect(g.events, hasLength(1)); + }); + + test('movies never group, even on one day', () { + final Instance radarr = Instance( + id: 'radarr', + name: 'radarr', + kind: ServiceKind.radarr, + localUrl: 'http://radarr.test', + externalUrl: '', + urlMode: UrlMode.auto, + auth: const InstanceAuth.apiKey(apiKey: 'k'), + ); + RadarrCalendarEvent movie(int id) => RadarrCalendarEvent( + RadarrMovie( + id: id, + title: 'Movie $id', + inCinemas: day.toIso8601String(), + monitored: true, + hasFile: false, + ), + radarr, + DateTime(day.year, day.month), + ); + expect( + groupCalendarEvents([movie(1), movie(2)]), + hasLength(2), + ); + }); + + test('groups come out in time order', () { + final List groups = groupCalendarEvents([ + _ep(_stick, 5, day.add(const Duration(hours: 3))), + _ep(_bladeRunner, 1, day), + _ep(_bladeRunner, 2, day), + ]); + expect(groups.map((CalendarGroup g) => g.first.primaryTitle), [ + 'Blade Runner 2099', + 'Stick', + ]); + }); + }); + + group('status', () { + final DateTime now = day; + final DateTime before = day.subtract(const Duration(hours: 1)); + final DateTime after = day.add(const Duration(hours: 1)); + + CalendarStatus of(List events) => + groupCalendarEvents(events).single.status(now); + + test('all downloaded reads Downloaded', () { + expect( + of([ + _ep(_bladeRunner, 1, before, hasFile: true), + _ep(_bladeRunner, 2, before, hasFile: true), + ]), + CalendarStatus.downloaded, + ); + }); + + test('one aired without a file among upcoming ones reads Missing', () { + expect( + of([ + _ep(_bladeRunner, 1, before), + _ep(_bladeRunner, 2, after), + _ep(_bladeRunner, 3, after), + ]), + CalendarStatus.missing, + ); + }); + + test('downloaded and still to air reads Upcoming', () { + expect( + of([ + _ep(_bladeRunner, 1, before, hasFile: true), + _ep(_bladeRunner, 2, after), + ]), + CalendarStatus.upcoming, + ); + }); + + test('a single episode keeps its own status', () { + expect(of([_ep(_stick, 5, after)]), + CalendarStatus.upcoming); + expect(of([_ep(_stick, 5, before)]), + CalendarStatus.missing); + }); + + test('monitored when any episode is', () { + final CalendarGroup g = groupCalendarEvents([ + _ep(_bladeRunner, 1, day, monitored: false), + _ep(_bladeRunner, 2, day), + ]).single; + expect(g.monitored, isTrue); + expect( + groupCalendarEvents([ + _ep(_bladeRunner, 1, day, monitored: false), + ]).single.monitored, + isFalse, + ); + }); + + test('all have files only when every episode has one', () { + expect( + groupCalendarEvents([ + _ep(_bladeRunner, 1, before, hasFile: true), + _ep(_bladeRunner, 2, before), + ]).single.allHaveFiles, + isFalse, + ); + }); + }); +} diff --git a/app/test/dashboard_widgets_test.dart b/app/test/dashboard_widgets_test.dart index 7a852683..9bf9ccd3 100644 --- a/app/test/dashboard_widgets_test.dart +++ b/app/test/dashboard_widgets_test.dart @@ -251,6 +251,46 @@ void main() { expect(find.textContaining('Test Show'), findsOneWidget); }); + testWidgets('DashboardUpcomingWidget gives a season drop one banner', + (WidgetTester tester) async { + final Instance sonarr = makeInstance(ServiceKind.sonarr); + final DateTime tomorrow = DateTime.now().add(const Duration(days: 1)); + const SonarrSeries drop = SonarrSeries(id: 7, title: 'Blade Runner 2099'); + SonarrCalendarEvent episode(SonarrSeries series, int n) => + SonarrCalendarEvent( + SonarrEpisode( + id: series.id * 100 + n, + seriesId: series.id, + title: 'Chapter $n', + seasonNumber: 1, + episodeNumber: n, + airDateUtc: tomorrow.toUtc().toIso8601String(), + monitored: true, + series: series, + ), + sonarr, + ); + final List events = [ + for (int n = 1; n <= 10; n++) episode(drop, n), + episode(const SonarrSeries(id: 8, title: 'Stick'), 5), + ]; + await pumpBody( + tester, + [ + for (final DateTime m in upcomingWindowMonths(DateTime.now())) + globalCalendarProvider((m, false)) + .overrideWith((Ref ref) async => events), + ], + const DashboardUpcomingWidget(), + ); + expect(find.text('Blade Runner 2099'), findsOneWidget); + expect(find.text('Stick'), findsOneWidget); + expect(find.textContaining('+9 more'), findsOneWidget); + expect(find.textContaining('Chapter 2'), findsNothing); + // Rows, not episodes: the pill agrees with what is listed. + expect(find.text('2 releases'), findsOneWidget); + }); + testWidgets('DashboardRecentlyAddedWidget shows newest series and movies', (WidgetTester tester) async { final Instance sonarr = makeInstance(ServiceKind.sonarr); From 0e705b48fb4abd11c8fdfb3075a67754e61263dc Mon Sep 17 00:00:00 2001 From: retransmit Date: Wed, 25 Nov 2026 01:19:24 +0530 Subject: [PATCH 2/2] fix(calendar): keep an opened row with its own group Rows had no key, so selecting another day in the grid reused an opened row's state and the new day's group showed its episodes untapped. Each group now carries a stable id (instance, series and day for episodes; the item otherwise) and its row is keyed by it. --- app/lib/src/screens/calendar_groups.dart | 32 ++++++++++++---------- app/lib/src/screens/calendar_screen.dart | 6 ++-- app/test/calendar_group_rows_test.dart | 35 +++++++++++++++++++++++- 3 files changed, 55 insertions(+), 18 deletions(-) diff --git a/app/lib/src/screens/calendar_groups.dart b/app/lib/src/screens/calendar_groups.dart index 5984680f..442f589d 100644 --- a/app/lib/src/screens/calendar_groups.dart +++ b/app/lib/src/screens/calendar_groups.dart @@ -15,7 +15,12 @@ CalendarStatus calendarStatusOf(CalendarEvent event, DateTime now) { /// One calendar row: a release, or every episode of one series that airs on /// the same day on the same instance (a season dropped at once). class CalendarGroup { - CalendarGroup._(this.events); + CalendarGroup._(this.id, this.events); + + /// Stable across rebuilds and refreshes: the instance, the series and the + /// day for a group of episodes, the item itself otherwise. Rows are keyed + /// by it so an opened row stays with its own group. + final Object id; /// Oldest episode first; a single release is a group of one. final List events; @@ -58,23 +63,22 @@ List groupCalendarEvents(Iterable events) { final Map> byKey = >{}; final Set<(String, int)> seenEpisodes = <(String, int)>{}; for (final CalendarEvent e in events) { - final Object key; - if (e is SonarrCalendarEvent) { - if (!seenEpisodes.add((e.instance.id, e.episode.id))) continue; - final DateTime local = e.date.toLocal(); - key = ( - e.instance.id, - e.episode.seriesId, - DateTime(local.year, local.month, local.day), - ); - } else { - key = e; + final DateTime local = e.date.toLocal(); + final DateTime day = DateTime(local.year, local.month, local.day); + final Object key = switch (e) { + SonarrCalendarEvent() => ('episodes', e.instance.id, e.episode.seriesId, day), + RadarrCalendarEvent() => ('movie', e.instance.id, e.movie.id, day), + LidarrCalendarEvent() => ('album', e.instance.id, e.album.id, day), + }; + if (e is SonarrCalendarEvent && + !seenEpisodes.add((e.instance.id, e.episode.id))) { + continue; } byKey.putIfAbsent(key, () => []).add(e); } final List groups = [ - for (final List list in byKey.values) - CalendarGroup._(list..sort(_episodeOrder)), + for (final MapEntry> entry in byKey.entries) + CalendarGroup._(entry.key, entry.value..sort(_episodeOrder)), ]..sort((CalendarGroup a, CalendarGroup b) => a.date.compareTo(b.date)); return groups; } diff --git a/app/lib/src/screens/calendar_screen.dart b/app/lib/src/screens/calendar_screen.dart index a4a076fc..77ccb0e5 100644 --- a/app/lib/src/screens/calendar_screen.dart +++ b/app/lib/src/screens/calendar_screen.dart @@ -667,7 +667,7 @@ class _CalendarScreenState extends ConsumerState { ); for (final CalendarGroup group in groupCalendarEvents(entriesMap[date]!)) { - rows.add(_EventTile(group: group)); + rows.add(_EventTile(key: ValueKey(group.id), group: group)); } } @@ -1091,7 +1091,7 @@ class _CalendarScreenState extends ConsumerState { else for (final CalendarGroup group in groupCalendarEvents(selectedDayEntries)) - _EventTile(group: group), + _EventTile(key: ValueKey(group.id), group: group), ], ); } @@ -1184,7 +1184,7 @@ class _DateHeader extends StatelessWidget { /// group, "+N more" opens the other episodes under the card; the rest of the /// card opens the series as before. class _EventTile extends ConsumerStatefulWidget { - const _EventTile({required this.group}); + const _EventTile({required this.group, super.key}); final CalendarGroup group; @override diff --git a/app/test/calendar_group_rows_test.dart b/app/test/calendar_group_rows_test.dart index f61e78fa..40c4ae90 100644 --- a/app/test/calendar_group_rows_test.dart +++ b/app/test/calendar_group_rows_test.dart @@ -69,6 +69,7 @@ Future _pump( WidgetTester tester, { bool listView = true, bool fifthAiredWithoutFile = false, + List? episodes, }) async { tester.view.physicalSize = const Size(800, 1600); tester.view.devicePixelRatio = 1.0; @@ -86,7 +87,8 @@ Future _pump( sonarrCalendarProvider.overrideWith( (Ref ref, (Instance, DateTime, bool) key) async => key.$2.month == 11 - ? _episodes(fifthAiredWithoutFile: fifthAiredWithoutFile) + ? episodes ?? + _episodes(fifthAiredWithoutFile: fifthAiredWithoutFile) : [], ), ], @@ -165,4 +167,35 @@ void main() { expect(find.text('+9 more'), findsOneWidget); }); }); + + testWidgets("another day's group opens closed", (WidgetTester tester) async { + // A three-part show the next day, so both days have a group in the same + // place in the grid's day list. + const SonarrSeries miniseries = + SonarrSeries(id: 9, title: 'The Night Shift', monitored: true); + final List episodes = [ + ..._episodes().where((SonarrEpisode e) => e.seriesId == _drop.id), + for (int n = 1; n <= 3; n++) + SonarrEpisode( + id: 900 + n, + seriesId: miniseries.id, + seasonNumber: 1, + episodeNumber: n, + title: 'Part $n', + monitored: true, + airDateUtc: DateTime(2026, 11, 26, 21).toUtc().toIso8601String(), + series: miniseries, + ), + ]; + await withClock(_morning, () async { + await _pump(tester, listView: false, episodes: episodes); + await tester.tap(find.text('+9 more')); + await tester.pump(); + expect(find.text('Chapter 2'), findsOneWidget); + await tester.tap(find.text('26')); + await tester.pump(); + expect(find.text('The Night Shift - S01E01'), findsOneWidget); + expect(find.text('Part 2'), findsNothing); + }); + }); }