Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Revamp

laurenspriem1c476eebdc43
diff --git a/mobile/apps/photos/lib/models/rituals/ritual_models.dart b/mobile/apps/photos/lib/models/rituals/ritual_models.dart
index fce9bd9ddf..359bdae222 100644
--- a/mobile/apps/photos/lib/models/rituals/ritual_models.dart
+++ b/mobile/apps/photos/lib/models/rituals/ritual_models.dart
@@ -1,38 +1,15 @@
import "package:flutter/material.dart";
import "package:photos/models/base/id.dart";
-
-class RitualDay {
- final DateTime date;
- final bool isCompleted;
-
- const RitualDay({
- required this.date,
- required this.isCompleted,
- });
-}
+import "package:photos/models/file/file.dart";
class RitualsSummary {
- final List<RitualDay> last365Days;
- final List<RitualDay> last7Days;
- final int currentStreak;
- final int longestStreak;
- final Map<int, bool> badgesUnlocked;
final Map<String, RitualProgress> ritualProgress;
final DateTime generatedAt;
- final Map<String, int> ritualLongestStreaks;
const RitualsSummary({
- required this.last365Days,
- required this.last7Days,
- required this.currentStreak,
- required this.longestStreak,
- required this.badgesUnlocked,
required this.ritualProgress,
required this.generatedAt,
- required this.ritualLongestStreaks,
});
-
- bool get hasSevenDayFire => last7Days.every((d) => d.isCompleted);
}
class Ritual {
@@ -116,21 +93,24 @@ class Ritual {
class RitualProgress {
final String ritualId;
- final Set<DateTime> completedDays;
+ final Set<int> completedDayKeys;
+ final Map<int, EnteFile> recentFilesByDay;
+ final int currentStreak;
+ final int longestStreakOverall;
+ final int longestStreakThisMonth;
const RitualProgress({
required this.ritualId,
- required this.completedDays,
+ required this.completedDayKeys,
+ this.recentFilesByDay = const {},
+ required this.currentStreak,
+ required this.longestStreakOverall,
+ required this.longestStreakThisMonth,
});
bool hasCompleted(DateTime day) {
- final dayKey = DateTime(day.year, day.month, day.day);
- return completedDays.any(
- (d) =>
- d.year == dayKey.year &&
- d.month == dayKey.month &&
- d.day == dayKey.day,
- );
+ final key = DateTime(day.year, day.month, day.day).millisecondsSinceEpoch;
+ return completedDayKeys.contains(key);
}
}
diff --git a/mobile/apps/photos/lib/services/rituals/rituals_service.dart b/mobile/apps/photos/lib/services/rituals/rituals_service.dart
index 5ea97693f9..6b44941eb5 100644
--- a/mobile/apps/photos/lib/services/rituals/rituals_service.dart
+++ b/mobile/apps/photos/lib/services/rituals/rituals_service.dart
@@ -101,7 +101,7 @@ class RitualsService {
}
final summary = await _buildSummary(rituals);
final pendingBadge =
- _resolvePendingBadge(rituals, summary.ritualLongestStreaks);
+ _resolvePendingBadge(rituals, summary.ritualProgress);
stateNotifier.value = RitualsState(
loading: false,
summary: summary,
@@ -119,46 +119,46 @@ class RitualsService {
}
}
- Future<RitualsSummary> _buildSummary(List<Ritual> rituals) async {
+ Future<RitualsSummary> _buildSummary(
+ List<Ritual> rituals,
+ ) async {
final userId = Configuration.instance.getUserID();
+ final now = DateTime.now();
+ final todayMidnight = DateTime(now.year, now.month, now.day);
+ final monthStart = DateTime(now.year, now.month, 1);
+ final lastDayOfMonth = DateTime(now.year, now.month + 1, 0);
+ final monthEndInclusive =
+ lastDayOfMonth.isAfter(todayMidnight) ? todayMidnight : lastDayOfMonth;
if (userId == null) {
return RitualsSummary(
- last365Days: _emptyDays(),
- last7Days: _emptyDays().sublist(_emptyDays().length - 7),
- currentStreak: 0,
- longestStreak: 0,
- badgesUnlocked: _badgeStates(0),
ritualProgress: {},
generatedAt: DateTime.now(),
- ritualLongestStreaks: const {},
);
}
- final today = DateTime.now();
- final todayMidnight = DateTime(today.year, today.month, today.day);
- final cutoffDate = todayMidnight.subtract(const Duration(days: 371));
- final endOfToday = todayMidnight.add(
- const Duration(
- hours: 23,
- minutes: 59,
- seconds: 59,
- milliseconds: 999,
- ),
- );
- final startMicros = cutoffDate.microsecondsSinceEpoch;
- final endMicros = endOfToday.microsecondsSinceEpoch;
- final durations = <List<int>>[
- [startMicros, endMicros + 1],
- ];
- final files = await FilesDB.instance.getFilesCreatedWithinDurations(
- durations,
- <int>{},
- order: 'ASC',
- dedupeUploadID: false,
- );
+ final ritualAlbumIds = rituals
+ .map((r) => r.albumId)
+ .whereType<int>()
+ .where((id) => id > 0)
+ .toSet();
+
+ final Map<int, Set<int>> collectionDayKeys = {};
+ final Map<int, Map<int, EnteFile>> collectionRecentFilesByDay = {};
- final Set<int> dayKeys = <int>{};
- final Map<int, Set<int>> collectionRitualDays = {};
+ if (ritualAlbumIds.isEmpty) {
+ return RitualsSummary(
+ ritualProgress: const {},
+ generatedAt: DateTime.now(),
+ );
+ }
+ final files = await FilesDB.instance.getAllFilesFromCollections(
+ ritualAlbumIds,
+ );
+ final recentStart = DateTime(
+ todayMidnight.year,
+ todayMidnight.month,
+ todayMidnight.day - 4,
+ );
for (final EnteFile file in files) {
final bool ownerMatches =
file.ownerID == null ? true : file.ownerID == userId;
@@ -168,94 +168,68 @@ class RitualsService {
continue;
}
if (file.creationTime == null) continue;
+ final int? collectionId = file.collectionID;
+ if (collectionId == null || collectionId <= 0) continue;
+ if (!ritualAlbumIds.contains(collectionId)) continue;
+
final date =
DateTime.fromMicrosecondsSinceEpoch(file.creationTime!).toLocal();
final bucket = DateTime(date.year, date.month, date.day);
+ if (bucket.isAfter(todayMidnight)) continue;
final dayKey = bucket.millisecondsSinceEpoch;
- if (bucket.isBefore(cutoffDate) || bucket.isAfter(todayMidnight)) {
+ collectionDayKeys.putIfAbsent(collectionId, () => <int>{}).add(dayKey);
+
+ if (bucket.isBefore(recentStart)) continue;
+ final byDay =
+ collectionRecentFilesByDay.putIfAbsent(collectionId, () => {});
+ final existing = byDay[dayKey];
+ if (existing == null) {
+ byDay[dayKey] = file;
continue;
}
- dayKeys.add(dayKey);
- if (file.collectionID != null && file.collectionID! > 0) {
- collectionRitualDays
- .putIfAbsent(file.collectionID!, () => <int>{})
- .add(dayKey);
- }
- }
-
- final List<RitualDay> last365Days = List.generate(372, (index) {
- final day = cutoffDate.add(Duration(days: index));
- final key = DateTime(day.year, day.month, day.day).millisecondsSinceEpoch;
- return RitualDay(date: day, isCompleted: dayKeys.contains(key));
- });
- final List<RitualDay> last7Days =
- last365Days.sublist(last365Days.length - 7);
-
- int longestStreak = 0;
- int rolling = 0;
- for (final day in last365Days) {
- if (day.isCompleted) {
- rolling += 1;
- longestStreak = max(longestStreak, rolling);
- } else {
- rolling = 0;
- }
- }
- int currentStreak = 0;
- for (int i = last365Days.length - 1; i >= 0; i--) {
- if (last365Days[i].isCompleted) {
- currentStreak += 1;
- } else {
- break;
+ if ((existing.creationTime ?? -1) < (file.creationTime ?? -1)) {
+ byDay[dayKey] = file;
}
}
final ritualProgress = <String, RitualProgress>{};
- final ritualLongestStreaks = <String, int>{};
for (final ritual in rituals) {
- if (ritual.albumId == null) continue;
- final dates = collectionRitualDays[ritual.albumId] ?? <int>{};
- final longest = _longestStreakFromDayKeys(dates, cutoffDate);
- ritualLongestStreaks[ritual.id] = longest;
+ final albumId = ritual.albumId;
+ if (albumId == null || albumId <= 0) continue;
+ final dates = collectionDayKeys[albumId] ?? <int>{};
+ final ritualLongestOverall = _longestScheduledStreakFromDayKeys(
+ dates,
+ ritual.daysOfWeek,
+ todayMidnight: todayMidnight,
+ );
+ final ritualCurrent = _currentScheduledStreakFromDayKeys(
+ dates,
+ ritual.daysOfWeek,
+ todayMidnight: todayMidnight,
+ );
+ final ritualLongestThisMonth = _longestScheduledStreakInRangeFromDayKeys(
+ dates,
+ ritual.daysOfWeek,
+ startDay: monthStart,
+ endDayInclusive: monthEndInclusive,
+ );
+
ritualProgress[ritual.id] = RitualProgress(
ritualId: ritual.id,
- completedDays: dates
- .map((millis) => DateTime.fromMillisecondsSinceEpoch(millis))
- .toSet(),
+ completedDayKeys: dates,
+ recentFilesByDay: collectionRecentFilesByDay[albumId] ?? const {},
+ currentStreak: ritualCurrent,
+ longestStreakOverall: ritualLongestOverall,
+ longestStreakThisMonth: ritualLongestThisMonth,
);
}
return RitualsSummary(
- last365Days: last365Days,
- last7Days: last7Days,
- currentStreak: currentStreak,
- longestStreak: longestStreak,
- badgesUnlocked: _badgeStates(longestStreak),
ritualProgress: ritualProgress,
generatedAt: DateTime.now(),
- ritualLongestStreaks: ritualLongestStreaks,
);
}
- List<RitualDay> _emptyDays() {
- final today = DateTime.now();
- final todayMidnight = DateTime(today.year, today.month, today.day);
- final cutoffDate = todayMidnight.subtract(const Duration(days: 371));
- return List.generate(
- 372,
- (index) => RitualDay(
- date: cutoffDate.add(Duration(days: index)),
- isCompleted: false,
- ),
- );
- }
-
- Map<int, bool> _badgeStates(int streak) {
- return {
- for (final t in _badgeThresholds) t: streak >= t,
- };
- }
-
Set<int> _normalizeBadgeSet(Set<int> seen) {
if (seen.isEmpty) return <int>{};
final valid =
@@ -449,12 +423,12 @@ class RitualsService {
RitualBadgeUnlock? _resolvePendingBadge(
List<Ritual> rituals,
- Map<String, int> ritualLongestStreaks,
+ Map<String, RitualProgress> ritualProgress,
) {
- _seedSeenBadgesForNewRituals(ritualLongestStreaks);
+ _seedSeenBadgesForNewRituals(ritualProgress);
RitualBadgeUnlock? unlock;
for (final ritual in rituals) {
- final longest = ritualLongestStreaks[ritual.id] ?? 0;
+ final longest = ritualProgress[ritual.id]?.longestStreakOverall ?? 0;
final seen = _seenRitualBadges[ritual.id] ?? <int>{};
final newlyUnlocked = _badgeThresholds
.where((t) => longest >= t && !seen.contains(t))
@@ -492,12 +466,74 @@ class RitualsService {
}
}
- int _longestStreakFromDayKeys(Set<int> dayKeys, DateTime cutoffDate) {
+ int _currentScheduledStreakFromDayKeys(
+ Set<int> dayKeys,
+ List<bool> daysOfWeek, {
+ required DateTime todayMidnight,
+ }) {
if (dayKeys.isEmpty) return 0;
+ if (!_hasAnyEnabledRitualDays(daysOfWeek)) return 0;
+
+ final start = _streakStartDateFromDayKeys(dayKeys, todayMidnight);
+ int current = 0;
+ for (var day = todayMidnight; !day.isBefore(start); day = _prevDay(day)) {
+ final dayIndex = day.weekday % 7; // Sunday -> 0
+ if (!daysOfWeek[dayIndex]) continue;
+
+ final key = DateTime(day.year, day.month, day.day).millisecondsSinceEpoch;
+ if (dayKeys.contains(key)) {
+ current += 1;
+ } else {
+ break;
+ }
+ }
+ return current;
+ }
+
+ int _longestScheduledStreakFromDayKeys(
+ Set<int> dayKeys,
+ List<bool> daysOfWeek, {
+ required DateTime todayMidnight,
+ }) {
+ if (dayKeys.isEmpty) return 0;
+ if (!_hasAnyEnabledRitualDays(daysOfWeek)) return 0;
+
+ final start = _streakStartDateFromDayKeys(dayKeys, todayMidnight);
+ int longest = 0;
+ int rolling = 0;
+ for (var day = start; !day.isAfter(todayMidnight); day = _nextDay(day)) {
+ final dayIndex = day.weekday % 7; // Sunday -> 0
+ if (!daysOfWeek[dayIndex]) continue;
+
+ final key = DateTime(day.year, day.month, day.day).millisecondsSinceEpoch;
+ if (dayKeys.contains(key)) {
+ rolling += 1;
+ longest = max(longest, rolling);
+ } else {
+ rolling = 0;
+ }
+ }
+ return longest;
+ }
+
+ int _longestScheduledStreakInRangeFromDayKeys(
+ Set<int> dayKeys,
+ List<bool> daysOfWeek, {
+ required DateTime startDay,
+ required DateTime endDayInclusive,
+ }) {
+ if (dayKeys.isEmpty) return 0;
+ if (!_hasAnyEnabledRitualDays(daysOfWeek)) return 0;
+ if (endDayInclusive.isBefore(startDay)) return 0;
+
int longest = 0;
int rolling = 0;
- for (int offset = 0; offset < 372; offset++) {
- final day = cutoffDate.add(Duration(days: offset));
+ for (var day = startDay;
+ !day.isAfter(endDayInclusive);
+ day = _nextDay(day)) {
+ final dayIndex = day.weekday % 7; // Sunday -> 0
+ if (!daysOfWeek[dayIndex]) continue;
+
final key = DateTime(day.year, day.month, day.day).millisecondsSinceEpoch;
if (dayKeys.contains(key)) {
rolling += 1;
@@ -509,13 +545,35 @@ class RitualsService {
return longest;
}
+ DateTime _streakStartDateFromDayKeys(
+ Set<int> dayKeys,
+ DateTime todayMidnight,
+ ) {
+ final minKey = dayKeys.reduce(min);
+ final minDay = DateTime.fromMillisecondsSinceEpoch(minKey);
+ final start = DateTime(minDay.year, minDay.month, minDay.day);
+ return start.isAfter(todayMidnight) ? todayMidnight : start;
+ }
+
+ bool _hasAnyEnabledRitualDays(List<bool> daysOfWeek) {
+ if (daysOfWeek.length != 7) return false;
+ for (final enabled in daysOfWeek) {
+ if (enabled) return true;
+ }
+ return false;
+ }
+
+ DateTime _nextDay(DateTime day) => DateTime(day.year, day.month, day.day + 1);
+
+ DateTime _prevDay(DateTime day) => DateTime(day.year, day.month, day.day - 1);
+
void _seedSeenBadgesForNewRituals(
- Map<String, int> ritualLongestStreaks,
+ Map<String, RitualProgress> ritualProgress,
) {
if (_recentlyAddedRitualIds.isEmpty) return;
bool changed = false;
for (final ritualId in _recentlyAddedRitualIds) {
- final longest = ritualLongestStreaks[ritualId] ?? 0;
+ final longest = ritualProgress[ritualId]?.longestStreakOverall ?? 0;
if (longest <= 0) continue;
final thresholds =
_badgeThresholds.where((threshold) => longest >= threshold);
diff --git a/mobile/apps/photos/lib/ui/rituals/achievements_row.dart b/mobile/apps/photos/lib/ui/rituals/achievements_row.dart
index 54aff4ea7c..065a5e89c8 100644
--- a/mobile/apps/photos/lib/ui/rituals/achievements_row.dart
+++ b/mobile/apps/photos/lib/ui/rituals/achievements_row.dart
@@ -4,12 +4,12 @@ import "package:photos/models/rituals/ritual_models.dart";
class AchievementsRow extends StatelessWidget {
const AchievementsRow({
- required this.summary,
+ required this.progress,
this.onBadgeTap,
super.key,
});
- final RitualsSummary? summary;
+ final RitualProgress? progress;
final void Function(int days)? onBadgeTap;
static const Map<int, String> _badgeAssets = {
@@ -20,11 +20,9 @@ class AchievementsRow extends StatelessWidget {
@override
Widget build(BuildContext context) {
- final badges = summary?.badgesUnlocked ?? const <int, bool>{};
- final unlocked = badges.entries
- .where((entry) => entry.value && _badgeAssets.containsKey(entry.key))
- .map((entry) => entry.key)
- .toList();
+ final longest = progress?.longestStreakOverall ?? 0;
+ final unlocked =
+ _badgeAssets.keys.where((days) => longest >= days).toList();
if (unlocked.isEmpty) {
return const SizedBox.shrink();
diff --git a/mobile/apps/photos/lib/ui/rituals/all_rituals_screen.dart b/mobile/apps/photos/lib/ui/rituals/all_rituals_screen.dart
index c40c71d720..63df03d990 100644
--- a/mobile/apps/photos/lib/ui/rituals/all_rituals_screen.dart
+++ b/mobile/apps/photos/lib/ui/rituals/all_rituals_screen.dart
@@ -1,13 +1,9 @@
-import "package:flutter/foundation.dart";
import "package:flutter/material.dart";
import "package:hugeicons/hugeicons.dart";
import "package:photos/l10n/l10n.dart";
import "package:photos/models/rituals/ritual_models.dart";
import "package:photos/service_locator.dart";
-import "package:photos/ui/rituals/achievements_row.dart";
-import "package:photos/ui/rituals/ritual_badge_popup.dart";
import "package:photos/ui/rituals/ritual_editor_dialog.dart";
-import "package:photos/ui/rituals/ritual_heatmap_card.dart";
import "package:photos/ui/rituals/rituals_section.dart";
class AllRitualsScreen extends StatefulWidget {
@@ -88,7 +84,6 @@ class _AllRitualsScreenState extends State<AllRitualsScreen> {
child: ValueListenableBuilder<RitualsState>(
valueListenable: ritualsService.stateNotifier,
builder: (context, state, _) {
- final summary = state.summary;
Ritual? selectedRitual = _selectedRitual;
if (selectedRitual != null) {
final match = state.rituals.where(
@@ -106,7 +101,6 @@ class _AllRitualsScreenState extends State<AllRitualsScreen> {
children: [
RitualsSection(
rituals: state.rituals,
- progress: summary?.ritualProgress ?? const {},
showHeader: false,
selectedRitualId: selectedRitual?.id,
onSelectionChanged: (ritual) {
@@ -122,29 +116,4 @@ class _AllRitualsScreenState extends State<AllRitualsScreen> {
),
);
}
-
- // TODO: lau: remove dead code?
- // ignore: unused_element
- Widget _buildAchievementsSection({
- required RitualsSummary? summary,
- required Ritual selectedRitual,
- }) {
- final displaySummary = summary != null
- ? ritualSummaryForRitual(summary, selectedRitual)
- : summary;
- return AchievementsRow(
- summary: displaySummary,
- onBadgeTap: (days) => _showDebugBadge(selectedRitual, days),
- );
- }
-
- Future<void> _showDebugBadge(Ritual ritual, int days) async {
- if (!kDebugMode) return;
- final badge = RitualBadgeUnlock(
- ritual: ritual,
- days: days,
- generatedAt: DateTime.now(),
- );
- await showRitualBadgePopup(context, badge: badge);
- }
}
diff --git a/mobile/apps/photos/lib/ui/rituals/ritual_heatmap_card.dart b/mobile/apps/photos/lib/ui/rituals/ritual_heatmap_card.dart
index 6636e453af..590080fd65 100644
--- a/mobile/apps/photos/lib/ui/rituals/ritual_heatmap_card.dart
+++ b/mobile/apps/photos/lib/ui/rituals/ritual_heatmap_card.dart
@@ -1,48 +1,63 @@
import "dart:io";
import "dart:math";
+import "dart:typed_data";
import "dart:ui" as ui;
-import "package:flutter/foundation.dart";
import "package:flutter/material.dart";
import "package:flutter/rendering.dart";
-import "package:hugeicons/hugeicons.dart";
import "package:intl/intl.dart";
import "package:logging/logging.dart";
import "package:path_provider/path_provider.dart";
-import "package:photos/l10n/l10n.dart";
import "package:photos/models/rituals/ritual_models.dart";
import "package:photos/theme/colors.dart";
import "package:photos/theme/ente_theme.dart";
-import "package:photos/utils/share_util.dart";
+import "package:photos/theme/text_style.dart";
import "package:share_plus/share_plus.dart";
-class RitualHeatmapCard extends StatelessWidget {
+class RitualHeatmapCard extends StatefulWidget {
const RitualHeatmapCard({
- required this.summary,
+ required this.ritual,
+ required this.progress,
this.compact = false,
- this.allowHorizontalScroll = false,
- this.headerTitle,
- this.headerEmoji,
+ this.allowHorizontalScroll = true,
+ this.showShareButton = false,
+ this.daysToShow = 365,
super.key,
});
- final RitualsSummary? summary;
+ final Ritual ritual;
+ final RitualProgress? progress;
final bool compact;
final bool allowHorizontalScroll;
- final String? headerTitle;
- final String? headerEmoji;
+ final bool showShareButton;
+ final int daysToShow;
+
+ @override
+ State<RitualHeatmapCard> createState() => _RitualHeatmapCardState();
+}
+
+class _RitualHeatmapCardState extends State<RitualHeatmapCard> {
+ static final Logger _logger = Logger("RitualHeatmapCard");
+ final GlobalKey _repaintKey = GlobalKey();
+ final GlobalKey _shareButtonKey = GlobalKey();
@override
Widget build(BuildContext context) {
+ final colorScheme = getEnteColorScheme(context);
final textTheme = getEnteTextTheme(context);
- final last365 = summary?.last365Days ??
- List.generate(
- 372,
- (i) => RitualDay(
- date: DateTime.now().subtract(Duration(days: 371 - i)),
- isCompleted: false,
- ),
- );
+
+ final progress = widget.progress;
+ final dayKeys = progress?.completedDayKeys ?? const <int>{};
+ final now = DateTime.now();
+ final todayMidnight = DateTime(now.year, now.month, now.day);
+ final startDay = DateTime(
+ todayMidnight.year,
+ todayMidnight.month,
+ todayMidnight.day - max(0, widget.daysToShow - 1),
+ );
+
+ final title = widget.ritual.title.isEmpty ? "Ritual" : widget.ritual.title;
+ final header = "${widget.ritual.icon} $title";
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
@@ -50,811 +65,333 @@ class RitualHeatmapCard extends StatelessWidget {
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.brightness == Brightness.dark
- ? getEnteColorScheme(context).backgroundElevated2
+ ? colorScheme.backgroundElevated2
: const Color(0xFFFAFAFA),
borderRadius: BorderRadius.circular(24),
+ border: Border.all(color: colorScheme.strokeFaint),
),
padding: const EdgeInsets.fromLTRB(12, 12, 12, 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- if ((headerTitle ?? "").isNotEmpty)
- Padding(
- padding: const EdgeInsets.fromLTRB(4, 12, 4, 12),
- child: LayoutBuilder(
- builder: (context, constraints) {
- return SizedBox(
- width: constraints.maxWidth,
- child: Row(
- mainAxisAlignment: MainAxisAlignment.center,
- mainAxisSize: MainAxisSize.max,
- children: [
- if ((headerEmoji ?? "").isNotEmpty)
- Padding(
- padding: const EdgeInsets.only(right: 10),
- child: Text(
- headerEmoji ?? "",
- style: const TextStyle(fontSize: 18),
- ),
- ),
- Flexible(
- child: Text(
- headerTitle ?? "",
- style: textTheme.bodyMuted,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- textAlign: TextAlign.center,
- ),
- ),
- ],
- ),
- );
- },
+ Row(
+ children: [
+ Expanded(
+ child: Text(
+ header,
+ style: textTheme.bodyMuted,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
),
- ),
- allowHorizontalScroll
- ? SingleChildScrollView(
- scrollDirection: Axis.horizontal,
- physics: const ClampingScrollPhysics(),
- clipBehavior: Clip.none,
- child: _Heatmap(
- days: last365,
- compact: compact,
+ if (widget.showShareButton)
+ IconButton(
+ key: _shareButtonKey,
+ onPressed: progress == null ? null : _shareHeatmap,
+ tooltip: MaterialLocalizations.of(context).shareButtonLabel,
+ icon: const Icon(Icons.share_rounded),
+ ),
+ ],
+ ),
+ const SizedBox(height: 10),
+ RepaintBoundary(
+ key: _repaintKey,
+ child: widget.allowHorizontalScroll
+ ? SingleChildScrollView(
+ scrollDirection: Axis.horizontal,
+ physics: const ClampingScrollPhysics(),
+ child: _Heatmap(
+ ritual: widget.ritual,
+ completedDayKeys: dayKeys,
+ startDay: startDay,
+ endDayInclusive: todayMidnight,
+ compact: widget.compact,
+ ),
+ )
+ : _Heatmap(
+ ritual: widget.ritual,
+ completedDayKeys: dayKeys,
+ startDay: startDay,
+ endDayInclusive: todayMidnight,
+ compact: widget.compact,
),
- )
- : _Heatmap(
- days: last365,
- compact: compact,
+ ),
+ if (progress != null) ...[
+ const SizedBox(height: 12),
+ Row(
+ children: [
+ Text(
+ "Current: ${progress.currentStreak}",
+ style: textTheme.smallMuted,
),
+ const SizedBox(width: 12),
+ Text(
+ "Month: ${progress.longestStreakThisMonth}",
+ style: textTheme.smallMuted,
+ ),
+ const SizedBox(width: 12),
+ Text(
+ "All-time: ${progress.longestStreakOverall}",
+ style: textTheme.smallMuted,
+ ),
+ ],
+ ),
+ ],
],
),
),
);
}
+
+ Future<void> _shareHeatmap() async {
+ try {
+ final RenderObject? renderObject =
+ _repaintKey.currentContext?.findRenderObject();
+ if (renderObject is! RenderRepaintBoundary) {
+ throw StateError("Heatmap boundary not found");
+ }
+ final pixelRatio =
+ (MediaQuery.devicePixelRatioOf(context) * 2).clamp(2.0, 3.5);
+ final ui.Image image = await renderObject.toImage(pixelRatio: pixelRatio);
+ final ByteData? bytes =
+ await image.toByteData(format: ui.ImageByteFormat.png);
+ final data = bytes?.buffer.asUint8List();
+ if (data == null || data.isEmpty) {
+ throw StateError("Failed to render heatmap image");
+ }
+
+ final dir = await getTemporaryDirectory();
+ final file = File(
+ "${dir.path}/ritual_heatmap_${widget.ritual.id}_${DateTime.now().millisecondsSinceEpoch}.png",
+ );
+ await file.writeAsBytes(data, flush: true);
+
+ final shareOrigin = _shareButtonRect(context, _shareButtonKey);
+ await SharePlus.instance.share(
+ ShareParams(
+ files: [XFile(file.path)],
+ sharePositionOrigin: shareOrigin,
+ ),
+ );
+ } catch (e, s) {
+ _logger.warning("Failed to share ritual heatmap", e, s);
+ if (!mounted) return;
+ ScaffoldMessenger.of(context).showSnackBar(
+ const SnackBar(content: Text("Failed to share heatmap")),
+ );
+ }
+ }
}
class _Heatmap extends StatelessWidget {
const _Heatmap({
- required this.days,
+ required this.ritual,
+ required this.completedDayKeys,
+ required this.startDay,
+ required this.endDayInclusive,
required this.compact,
});
- final List<RitualDay> days;
+ final Ritual ritual;
+ final Set<int> completedDayKeys;
+ final DateTime startDay;
+ final DateTime endDayInclusive;
final bool compact;
@override
Widget build(BuildContext context) {
- final renderDays =
- days.length > 365 ? days.sublist(days.length - 365) : days;
- final materialLocalizations = MaterialLocalizations.of(context);
- final dayHeader = [
- "",
- materialLocalizations.narrowWeekdays[1],
- "",
- materialLocalizations.narrowWeekdays[3],
- "",
- materialLocalizations.narrowWeekdays[5],
- "",
- ];
+ final colorScheme = getEnteColorScheme(context);
+ final textTheme = getEnteTextTheme(context);
final monthFormatter =
DateFormat.MMM(Localizations.localeOf(context).toString());
- final today = DateTime.now();
- final todayMidnight = DateTime(today.year, today.month, today.day);
- final DateTime firstDay = renderDays.isNotEmpty
- ? DateTime(
- renderDays.first.date.year,
- renderDays.first.date.month,
- renderDays.first.date.day,
- )
- : todayMidnight.subtract(const Duration(days: 364));
-
- final normalizedDayMap = <int, RitualDay>{
- for (final d in days)
- DateTime(d.date.year, d.date.month, d.date.day).millisecondsSinceEpoch:
- d,
- };
-
- // Always start on the Sunday before/including the first day to render
- final int startOffset = firstDay.weekday % 7;
- final DateTime gridStart =
- firstDay.subtract(Duration(days: startOffset)); // Sunday-aligned
- // End exactly on today; last row can be partial
- final DateTime gridEnd = todayMidnight;
- final int totalDays =
- gridEnd.difference(gridStart).inDays + 1; // inclusive of gridEnd
-
- final List<RitualDay?> gridDays = List.generate(totalDays, (index) {
- final date = gridStart.add(Duration(days: index));
- // Leading days before the 365-day window can still be active if present
- // in the extended map (we fetched extra days), otherwise remain empty.
- final key =
- DateTime(date.year, date.month, date.day).millisecondsSinceEpoch;
- final dayEntry = normalizedDayMap[key];
- if (date.isBefore(firstDay)) {
- return dayEntry ??
- RitualDay(
- date: date,
- isCompleted: false,
- );
- }
- return dayEntry ??
- RitualDay(
- date: date,
- isCompleted: false,
- );
- });
- final weeks = <List<RitualDay?>>[];
- for (int i = 0; i < gridDays.length; i += 7) {
- final slice = gridDays.skip(i).take(7).toList();
- while (slice.length < 7) {
- slice.add(null); // pad last row to full width
- }
- weeks.add(slice);
- }
-
- final monthLabels = <int, String>{};
- final seenMonths = <String>{};
-
- for (final day in gridDays.whereType<RitualDay>()) {
- if (day.date.day != 1) continue;
- final daysSinceStart = day.date.difference(gridStart).inDays;
- final rowIndex = daysSinceStart ~/ 7;
- final key = _monthKey(day.date);
- if (seenMonths.contains(key)) continue;
- monthLabels[rowIndex] = _monthLabel(monthFormatter, day.date.month);
- seenMonths.add(key);
- }
-
- if (monthLabels.isEmpty) {
- final rowIndex = firstDay.difference(gridStart).inDays ~/ 7;
- monthLabels[rowIndex] = _monthLabel(monthFormatter, firstDay.month);
- }
+ final cell = compact ? 10.0 : 12.0;
+ final spacing = compact ? 2.0 : 3.0;
- final String? bottomMonthLabel = monthLabels[weeks.length - 1];
- if (bottomMonthLabel != null) {
- for (final int rowIndex in [0, 1]) {
- if (rowIndex < weeks.length &&
- monthLabels[rowIndex] == bottomMonthLabel) {
- monthLabels.remove(rowIndex);
- }
- }
- }
-
- return LayoutBuilder(
- builder: (context, constraints) {
- final double baseMonthLabelWidth = compact ? 28 : 32;
- final double baseGapX = compact ? 2.5 : 4;
- final double baseGapY = compact ? 2 : 3;
- final double baseCellWidth = compact ? 30 : 38.31;
- final double baseCellHeight = compact ? 8.5 : 9.82;
- final double baseHeaderRowHeight = compact ? 13 : 16;
- final double baseHeaderToGridGap = compact ? 3 : 4;
- final double baseTotalWidth =
- (7 * baseCellWidth) + (7 * baseGapX) + baseMonthLabelWidth;
- final double availableWidth = constraints.maxWidth.isFinite
- ? constraints.maxWidth
- : baseTotalWidth;
- double scale = availableWidth / baseTotalWidth;
- scale = scale.clamp(0.7, 1.0);
- final double monthLabelWidth = baseMonthLabelWidth * scale;
- final double gapX = baseGapX * scale;
- final double gapY = baseGapY * scale;
- final double cellWidth = baseCellWidth * scale;
- final double cellHeight = baseCellHeight * scale;
- final double headerRowHeight = baseHeaderRowHeight * scale;
- final double headerToGridGap = baseHeaderToGridGap * scale;
- final double gridWidth =
- (dayHeader.length * cellWidth) + ((dayHeader.length - 1) * gapX);
- final double remainingWidth =
- max(0.0, constraints.maxWidth - gridWidth - gapX);
- // Aim for ~70% of previous right padding by biasing space to the left gutter.
- final double gutterWidth = max(monthLabelWidth, remainingWidth * 0.65);
- final EnteColorScheme colorScheme = getEnteColorScheme(context);
- final BorderRadius pillRadius = BorderRadius.circular(cellHeight);
- final TextStyle headerStyle = TextStyle(
- color: colorScheme.textMuted.withValues(alpha: 0.45),
- fontSize: (compact ? 6.2 : 6.834) * scale.clamp(0.8, 1.0),
- fontWeight: FontWeight.w600,
- height: compact ? 2.2 : 2.45,
- fontFamily: "Inter",
- decoration: TextDecoration.none,
- );
-
- final List<Widget> dayHeaderRow = [];
- for (int i = 0; i < dayHeader.length; i++) {
- dayHeaderRow.add(
- SizedBox(
- width: cellWidth,
- height: 16,
- child: Center(
- child: Text(
- dayHeader[i],
- style: headerStyle,
- textAlign: TextAlign.center,
- ),
- ),
- ),
- );
- if (i != dayHeader.length - 1) {
- dayHeaderRow.add(SizedBox(width: gapX));
- }
- }
+ final gridStart = _startOfWeekSunday(startDay);
+ final gridEnd = _endOfWeekSaturday(endDayInclusive);
+ final weeks = _weekStarts(gridStart, gridEnd);
+ final monthLabels = _monthLabelsForWeeks(monthFormatter, weeks);
- return SizedBox(
- width: constraints.maxWidth,
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ SizedBox(
+ height: 18,
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- SizedBox(
- width: gutterWidth,
- child: Padding(
- padding: EdgeInsets.only(
- top: headerRowHeight + headerToGridGap + (8 * scale),
- ),
- child: Column(
- children: weeks.asMap().entries.map((entry) {
- final isLast = entry.key == weeks.length - 1;
- return SizedBox(
- height: cellHeight + (isLast ? 0 : gapY),
- width: gutterWidth,
- child: Center(
- child: Transform.translate(
- offset: const Offset(0, -1),
- child: Text(
- monthLabels[entry.key] ?? "",
- style: headerStyle.copyWith(
- fontSize: 8.542 * scale.clamp(0.8, 1.0),
- height: 1.4,
- ),
- textAlign: TextAlign.center,
- ),
- ),
+ children: List.generate(
+ weeks.length,
+ (index) {
+ final label = monthLabels[index];
+ return SizedBox(
+ width: cell + spacing,
+ child: label == null
+ ? const SizedBox.shrink()
+ : Text(
+ label,
+ style: textTheme.miniMuted,
+ maxLines: 1,
+ overflow: TextOverflow.clip,
),
- );
- }).toList(),
- ),
- ),
- ),
- SizedBox(width: gapX),
+ );
+ },
+ growable: false,
+ ),
+ ),
+ ),
+ Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ if (!compact)
SizedBox(
- width: gridWidth,
+ width: 18,
child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
children: [
- SizedBox(height: 8 * scale),
- Row(children: dayHeaderRow),
- SizedBox(height: headerToGridGap),
- ...weeks.asMap().entries.map(
- (entry) {
- final isLast = entry.key == weeks.length - 1;
- final week = entry.value;
- return Padding(
- padding: EdgeInsets.only(bottom: isLast ? 0 : gapY),
- child: Row(
- children: week.asMap().entries.map((cell) {
- final isLastCell =
- cell.key == dayHeader.length - 1;
- final Color activeColor = colorScheme.primary500;
- final Color inactiveColor = colorScheme.primary500
- .withValues(alpha: 0.28);
- final color = cell.value == null
- ? Colors.transparent
- : cell.value!.isCompleted
- ? activeColor
- : inactiveColor;
- return Row(
- children: [
- Container(
- width: cellWidth,
- height: cellHeight,
- decoration: BoxDecoration(
- color: color,
- borderRadius: pillRadius,
- ),
- ),
- if (!isLastCell) SizedBox(width: gapX),
- ],
- );
- }).toList(),
- ),
- );
- },
- ),
+ _weekdayLabel(textTheme, "M", cell),
+ SizedBox(height: cell + spacing),
+ _weekdayLabel(textTheme, "W", cell),
+ SizedBox(height: cell + spacing),
+ _weekdayLabel(textTheme, "F", cell),
],
),
),
- const SizedBox.shrink(),
- ],
- ),
- );
- },
+ Row(
+ children: weeks
+ .map(
+ (weekStart) => Padding(
+ padding: EdgeInsets.only(right: spacing),
+ child: Column(
+ children: List.generate(7, (dayOffset) {
+ final day = DateTime(
+ weekStart.year,
+ weekStart.month,
+ weekStart.day + dayOffset,
+ );
+ final bool inRange = !day.isBefore(startDay) &&
+ !day.isAfter(endDayInclusive);
+ final bool scheduled = _isScheduledDay(
+ ritual.daysOfWeek,
+ day,
+ );
+ final bool completed = completedDayKeys.contains(
+ DateTime(day.year, day.month, day.day)
+ .millisecondsSinceEpoch,
+ );
+
+ final Color fill = _cellColor(
+ colorScheme: colorScheme,
+ inRange: inRange,
+ scheduled: scheduled,
+ completed: completed,
+ );
+
+ return Padding(
+ padding: EdgeInsets.only(bottom: spacing),
+ child: Container(
+ width: cell,
+ height: cell,
+ decoration: BoxDecoration(
+ color: fill,
+ borderRadius: BorderRadius.circular(3),
+ ),
+ ),
+ );
+ }),
+ ),
+ ),
+ )
+ .toList(growable: false),
+ ),
+ ],
+ ),
+ ],
);
}
- String _monthLabel(DateFormat formatter, int month) {
- return formatter.format(DateTime(2024, month));
- }
-
- String _monthKey(DateTime date) => "${date.year}-${date.month}";
-}
-
-RitualsSummary ritualSummaryForRitual(
- RitualsSummary summary,
- Ritual ritual,
-) {
- final ritualProgress = summary.ritualProgress[ritual.id];
- final Set<int> dayKeys = ritualProgress == null
- ? <int>{}
- : ritualProgress.completedDays
- .map(
- (d) => DateTime(d.year, d.month, d.day).millisecondsSinceEpoch,
- )
- .toSet();
-
- final last365Days = summary.last365Days
- .map(
- (day) => RitualDay(
- date: day.date,
- isCompleted: _isRitualDayEnabled(ritual.daysOfWeek, day.date) &&
- dayKeys.contains(
- DateTime(
- day.date.year,
- day.date.month,
- day.date.day,
- ).millisecondsSinceEpoch,
- ),
+ Widget _weekdayLabel(EnteTextTheme textTheme, String label, double cell) {
+ return SizedBox(
+ width: 18,
+ height: cell,
+ child: Center(
+ child: Text(
+ label,
+ style: textTheme.miniMuted,
),
- )
- .toList();
- final last7Days = last365Days.length >= 7
- ? last365Days.sublist(last365Days.length - 7)
- : List<RitualDay>.from(last365Days);
-
- final now = DateTime.now();
- final todayMidnight = DateTime(now.year, now.month, now.day);
- final (currentStreak, longestStreak) =
- _scheduledStreaks(dayKeys, ritual.daysOfWeek, todayMidnight);
-
- final unlockedBadges = <int, bool>{
- for (final entry in summary.badgesUnlocked.keys)
- entry: longestStreak >= entry,
- };
-
- return RitualsSummary(
- last365Days: last365Days,
- last7Days: last7Days,
- currentStreak: currentStreak,
- longestStreak: longestStreak,
- badgesUnlocked: unlockedBadges,
- ritualProgress: {
- ritual.id: RitualProgress(
- ritualId: ritual.id,
- completedDays: ritualProgress?.completedDays ?? <DateTime>{},
),
- },
- generatedAt: summary.generatedAt,
- ritualLongestStreaks: {ritual.id: longestStreak},
- );
-}
-
-bool _isRitualDayEnabled(List<bool> daysOfWeek, DateTime day) {
- if (daysOfWeek.length != 7) return false;
- final dayIndex = day.weekday % 7; // Sunday -> 0
- return daysOfWeek[dayIndex];
-}
-
-// Streaks are computed only on days enabled by the ritual (Sunday-first).
-// A streak increments by 1 per enabled day that has at least one photo, and
-// breaks on the first enabled day that has no photo.
-(int current, int longest) _scheduledStreaks(
- Set<int> completedDayKeys,
- List<bool> daysOfWeek,
- DateTime todayMidnight,
-) {
- if (completedDayKeys.isEmpty) return (0, 0);
- if (!_hasAnyEnabledRitualDays(daysOfWeek)) return (0, 0);
-
- final start = _streakStartDateFromDayKeys(completedDayKeys, todayMidnight);
-
- int longest = 0;
- int rolling = 0;
- for (var day = start; !day.isAfter(todayMidnight); day = _nextDay(day)) {
- final dayIndex = day.weekday % 7; // Sunday -> 0
- if (!daysOfWeek[dayIndex]) continue;
+ );
+ }
- final key = DateTime(day.year, day.month, day.day).millisecondsSinceEpoch;
- if (completedDayKeys.contains(key)) {
- rolling += 1;
- if (rolling > longest) longest = rolling;
- } else {
- rolling = 0;
+ Color _cellColor({
+ required EnteColorScheme colorScheme,
+ required bool inRange,
+ required bool scheduled,
+ required bool completed,
+ }) {
+ if (!inRange) {
+ return Colors.transparent;
+ }
+ if (!scheduled) {
+ return colorScheme.fillFaint.withValues(alpha: 0.35);
}
+ if (completed) {
+ return const Color(0xFF1DB954);
+ }
+ return colorScheme.fillFaintPressed;
}
+}
- int current = 0;
- for (var day = todayMidnight; !day.isBefore(start); day = _prevDay(day)) {
- final dayIndex = day.weekday % 7; // Sunday -> 0
- if (!daysOfWeek[dayIndex]) continue;
-
- final key = DateTime(day.year, day.month, day.day).millisecondsSinceEpoch;
- if (completedDayKeys.contains(key)) {
- current += 1;
+List<String?> _monthLabelsForWeeks(DateFormat formatter, List<DateTime> weeks) {
+ final labels = <String?>[];
+ int? lastLabeledMonth;
+ for (final weekStart in weeks) {
+ if (weekStart.day <= 7 && weekStart.month != lastLabeledMonth) {
+ labels.add(formatter.format(weekStart));
+ lastLabeledMonth = weekStart.month;
} else {
- break;
+ labels.add(null);
}
}
-
- return (current, longest);
-}
-
-DateTime _streakStartDateFromDayKeys(Set<int> dayKeys, DateTime todayMidnight) {
- final minKey = dayKeys.reduce(min);
- final minDay = DateTime.fromMillisecondsSinceEpoch(minKey);
- final start = DateTime(minDay.year, minDay.month, minDay.day);
- return start.isAfter(todayMidnight) ? todayMidnight : start;
+ return labels;
}
-bool _hasAnyEnabledRitualDays(List<bool> daysOfWeek) {
+bool _isScheduledDay(List<bool> daysOfWeek, DateTime day) {
if (daysOfWeek.length != 7) return false;
- for (final enabled in daysOfWeek) {
- if (enabled) return true;
- }
- return false;
+ final dayIndex = day.weekday % 7; // Sunday -> 0
+ return daysOfWeek[dayIndex];
}
-DateTime _nextDay(DateTime day) => DateTime(day.year, day.month, day.day + 1);
-
-DateTime _prevDay(DateTime day) => DateTime(day.year, day.month, day.day - 1);
-
-class RitualHeatmapLegacy {
- RitualHeatmapLegacy._();
-
- static final Logger _logger = Logger("RitualHeatmapLegacy");
- static final GlobalKey _shareButtonKey = GlobalKey();
-
- // TODO: lau: remove dead code?
- // ignore: unused_element
- static List<Widget> buildHeatmapSection({
- required BuildContext context,
- required RitualsSummary? summary,
- required Ritual? selectedRitual,
- }) {
- final displaySummary = summary != null && selectedRitual != null
- ? ritualSummaryForRitual(summary, selectedRitual)
- : summary;
- final summaryToShare = displaySummary;
- final iconColor = Theme.of(context).iconTheme.color;
- final colorScheme = getEnteColorScheme(context);
- final l10n = context.l10n;
- final String heatmapTitle = selectedRitual == null
- ? l10n.ritualDefaultHeatmapTitle
- : (selectedRitual.title.isEmpty
- ? l10n.ritualUntitled
- : selectedRitual.title);
- final String heatmapEmoji =
- selectedRitual?.icon ?? (selectedRitual == null ? "πŸ“Έ" : "");
- final bool shareEnabled = summaryToShare != null;
- return [
- Padding(
- padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
- child: SizedBox(
- width: double.infinity,
- child: Row(
- children: [
- Text(
- l10n.ritualActivityHeading,
- style: Theme.of(context).textTheme.titleMedium,
- ),
- const Spacer(),
- SizedBox(
- width: 48,
- height: 48,
- child: Material(
- key: _shareButtonKey,
- color: colorScheme.fillFaint,
- borderRadius: BorderRadius.circular(10),
- clipBehavior: Clip.antiAlias,
- child: InkWell(
- borderRadius: BorderRadius.circular(10),
- onTap: summaryToShare != null
- ? () => _shareRitualSummary(
- context: context,
- summary: summaryToShare,
- title: heatmapTitle,
- emoji: heatmapEmoji,
- )
- : null,
- child: Padding(
- padding: const EdgeInsets.all(8),
- child: Center(
- child: HugeIcon(
- icon: HugeIcons.strokeRoundedShare08,
- size: 24,
- color: shareEnabled
- ? iconColor
- : Theme.of(context)
- .disabledColor
- .withValues(alpha: 0.7),
- ),
- ),
- ),
- ),
- ),
- ),
- ],
- ),
- ),
- ),
- RitualHeatmapCard(
- summary: displaySummary,
- headerTitle: heatmapTitle,
- headerEmoji: heatmapEmoji,
- ),
- ];
- }
-
- static Future<void> _shareRitualSummary({
- required BuildContext context,
- required RitualsSummary summary,
- required String title,
- String? emoji,
- }) async {
- _logger.info("Ritual share: start");
- _logger.fine("Ritual share: precache assets begin");
- await _precacheRitualShareAssets(context);
- _logger.fine("Ritual share: precache assets done");
- OverlayEntry? entry;
- final prevPaintSize = debugPaintSizeEnabled;
- final prevPaintBaselines = debugPaintBaselinesEnabled;
- final prevPaintPointers = debugPaintPointersEnabled;
- final prevRepaintRainbow = debugRepaintRainbowEnabled;
- try {
- debugPaintSizeEnabled = false;
- debugPaintBaselinesEnabled = false;
- debugPaintPointersEnabled = false;
- debugRepaintRainbowEnabled = false;
-
- final overlay = Overlay.maybeOf(context, rootOverlay: true);
- if (overlay == null) {
- throw StateError("Overlay not available for sharing");
- }
- final key = GlobalKey();
- entry = OverlayEntry(
- builder: (context) {
- return Center(
- child: Material(
- type: MaterialType.transparency,
- child: IgnorePointer(
- child: Opacity(
- opacity: 0.01,
- child: RepaintBoundary(
- key: key,
- child: _RitualShareCard(
- summary: summary,
- title: title,
- emoji: emoji,
- ),
- ),
- ),
- ),
- ),
- );
- },
- );
- overlay.insert(entry);
- _logger.fine("Ritual share: overlay inserted, waiting for boundary");
- final boundary = await _waitForBoundaryReady(repaintKey: key);
- bool needsPaint = false;
- assert(() {
- needsPaint = boundary.debugNeedsPaint;
- return true;
- }());
- _logger.fine(
- "Ritual share: boundary ready, size=${boundary.size}, needsPaint=$needsPaint",
- );
- final double pixelRatio =
- (MediaQuery.of(context).devicePixelRatio * 1.6).clamp(2.0, 3.5);
- late final ui.Image image;
- try {
- image = await boundary.toImage(pixelRatio: pixelRatio.toDouble());
- } catch (e, s) {
- _logger.warning("Ritual share: toImage failed", e, s);
- rethrow;
- }
- final ByteData? byteData;
- try {
- byteData = await image.toByteData(format: ui.ImageByteFormat.png);
- } catch (e, s) {
- _logger.warning("Ritual share: toByteData failed", e, s);
- rethrow;
- }
- final data = byteData?.buffer.asUint8List();
- if (data == null || data.isEmpty) {
- throw StateError("Ritual share image encoding produced no data");
- }
- final dir = await getTemporaryDirectory();
- final file = File(
- "${dir.path}/ritual_share_${DateTime.now().millisecondsSinceEpoch}.png",
- );
- await file.writeAsBytes(data, flush: true);
- _logger.info(
- "Ritual share: file written (${data.length} bytes) -> ${file.path}",
- );
- await SharePlus.instance.share(
- ShareParams(
- files: [XFile(file.path)],
- sharePositionOrigin: shareButtonRect(context, _shareButtonKey),
- ),
- );
- _logger.info("Ritual share: SharePlus invoked");
- } catch (e, s) {
- _logger.warning("Failed to share ritual summary", e, s);
- if (!context.mounted) return;
- ScaffoldMessenger.of(context).showSnackBar(
- SnackBar(content: Text(context.l10n.ritualShareUnavailable)),
- );
- } finally {
- debugPaintSizeEnabled = prevPaintSize;
- debugPaintBaselinesEnabled = prevPaintBaselines;
- debugPaintPointersEnabled = prevPaintPointers;
- debugRepaintRainbowEnabled = prevRepaintRainbow;
- entry?.remove();
- }
- }
-
- static Future<void> _precacheRitualShareAssets(BuildContext context) async {
- const assets = [
- "assets/rituals/ente_io_black_white.png",
- "assets/splash-screen-icon.png",
- ];
- for (final asset in assets) {
- try {
- await precacheImage(AssetImage(asset), context);
- } catch (e, s) {
- _logger.warning(
- "Ritual share: failed to precache asset $asset",
- e,
- s,
- );
- }
- }
- }
-
- static Future<RenderRepaintBoundary> _waitForBoundaryReady({
- required GlobalKey repaintKey,
- }) async {
- const int maxAttempts = 8;
- const Duration attemptDelay = Duration(milliseconds: 40);
+DateTime _startOfWeekSunday(DateTime day) {
+ final idx = day.weekday % 7; // Sunday -> 0
+ return DateTime(day.year, day.month, day.day - idx);
+}
- for (int attempt = 0; attempt < maxAttempts; attempt++) {
- final boundary = repaintKey.currentContext?.findRenderObject()
- as RenderRepaintBoundary?;
- bool needsPaint = false;
- assert(() {
- needsPaint = boundary?.debugNeedsPaint ?? false;
- return true;
- }());
- if (boundary == null) {
- _logger.fine(
- "Ritual share boundary missing (attempt ${attempt + 1})",
- );
- } else if (boundary.size.isEmpty) {
- _logger.fine(
- "Ritual share boundary has zero size (attempt ${attempt + 1})",
- );
- } else if (needsPaint) {
- _logger.fine(
- "Ritual share boundary needs paint (attempt ${attempt + 1}), waiting",
- );
- } else {
- return boundary;
- }
- await WidgetsBinding.instance.endOfFrame;
- await Future.delayed(attemptDelay);
- }
+DateTime _endOfWeekSaturday(DateTime day) {
+ final idx = day.weekday % 7; // Sunday -> 0
+ return DateTime(day.year, day.month, day.day + (6 - idx));
+}
- final boundary =
- repaintKey.currentContext?.findRenderObject() as RenderRepaintBoundary?;
- if (boundary == null) {
- throw StateError("Render boundary unavailable");
- }
- if (boundary.size.isEmpty) {
- throw StateError("Render boundary has zero size");
- }
- bool needsPaint = false;
- assert(() {
- needsPaint = boundary.debugNeedsPaint;
- return true;
- }());
- if (needsPaint) {
- throw StateError("Render boundary not ready to paint");
- }
- return boundary;
+List<DateTime> _weekStarts(DateTime start, DateTime endInclusive) {
+ final weeks = <DateTime>[];
+ for (var day = start;
+ !day.isAfter(endInclusive);
+ day = day.add(const Duration(days: 7))) {
+ weeks.add(day);
}
+ return weeks;
}
-class _RitualShareCard extends StatelessWidget {
- const _RitualShareCard({
- required this.summary,
- required this.title,
- this.emoji,
- });
-
- final RitualsSummary summary;
- final String title;
- final String? emoji;
-
- @override
- Widget build(BuildContext context) {
- const Color shareBackgroundColor = Color(0xFF08C225);
- final String shareHeaderTitle =
- (emoji ?? "").isNotEmpty ? "${emoji!} $title" : title;
- final double maxWidth =
- min(max(MediaQuery.of(context).size.width - 32, 360), 440).toDouble();
- return Align(
- alignment: Alignment.topCenter,
- widthFactor: 1,
- heightFactor: 1,
- child: ClipRRect(
- borderRadius: BorderRadius.circular(24),
- child: Container(
- color: shareBackgroundColor,
- child: Stack(
- children: [
- Padding(
- padding: const EdgeInsets.symmetric(horizontal: 12),
- child: ConstrainedBox(
- constraints: BoxConstraints(maxWidth: maxWidth),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.center,
- children: [
- const SizedBox(height: 48),
- Padding(
- padding: const EdgeInsets.symmetric(horizontal: 6),
- child: Theme(
- data: Theme.of(context).copyWith(
- brightness: Brightness.light,
- colorScheme: Theme.of(context).colorScheme.copyWith(
- brightness: Brightness.light,
- ),
- ),
- child: RitualHeatmapCard(
- summary: summary,
- compact: true,
- allowHorizontalScroll: false,
- headerTitle: shareHeaderTitle,
- headerEmoji: null,
- ),
- ),
- ),
- const SizedBox(height: 24),
- Image.asset(
- "assets/rituals/ente_io_black_white.png",
- width: 62,
- height: 16,
- fit: BoxFit.contain,
- ),
- const SizedBox(height: 12),
- ],
- ),
- ),
- ),
- Positioned(
- top: 0,
- right: 0,
- child: Image.asset(
- "assets/splash-screen-icon.png",
- width: 48,
- height: 48,
- fit: BoxFit.contain,
- ),
- ),
- ],
- ),
- ),
- ),
- );
+Rect _shareButtonRect(BuildContext context, GlobalKey key) {
+ final size = MediaQuery.sizeOf(context);
+ final RenderObject? renderObject = key.currentContext?.findRenderObject();
+ if (renderObject is! RenderBox) {
+ return Rect.fromLTWH(0, 0, size.width, size.height / 2);
}
+ final buttonSize = renderObject.size;
+ final position = renderObject.localToGlobal(Offset.zero);
+ return Rect.fromCenter(
+ center: position + Offset(buttonSize.width / 2, buttonSize.height / 2),
+ width: buttonSize.width,
+ height: buttonSize.height,
+ );
}
diff --git a/mobile/apps/photos/lib/ui/rituals/rituals_banner.dart b/mobile/apps/photos/lib/ui/rituals/rituals_banner.dart
index 6811f968dc..cc7fbecd82 100644
--- a/mobile/apps/photos/lib/ui/rituals/rituals_banner.dart
+++ b/mobile/apps/photos/lib/ui/rituals/rituals_banner.dart
@@ -1,8 +1,7 @@
import "package:flutter/material.dart";
+import "package:photos/models/rituals/ritual_models.dart";
import "package:photos/service_locator.dart";
-import "package:photos/theme/colors.dart";
import "package:photos/theme/ente_theme.dart";
-import "package:photos/theme/text_style.dart";
import "package:photos/ui/rituals/all_rituals_screen.dart";
import "package:photos/utils/navigation_util.dart";
@@ -14,172 +13,78 @@ class RitualsBanner extends StatelessWidget {
if (!flagService.ritualsFlag) {
return const SizedBox.shrink();
}
- final List<DateTime> last7Days = List.generate(
- 7,
- (index) => DateTime.now().subtract(Duration(days: 6 - index)),
- );
-
- final colorScheme = getEnteColorScheme(context);
- final textTheme = getEnteTextTheme(context);
- final narrowWeekdays = MaterialLocalizations.of(context).narrowWeekdays;
- final today = DateTime.now();
- return Padding(
- padding: const EdgeInsets.symmetric(horizontal: 12),
- child: Material(
- color: Colors.transparent,
- borderRadius: BorderRadius.circular(20),
- child: InkWell(
- borderRadius: BorderRadius.circular(20),
- onTap: () {
- routeToPage(context, const AllRitualsScreen());
- },
- child: Container(
- decoration: BoxDecoration(
- color: Theme.of(context).brightness == Brightness.dark
- ? colorScheme.backgroundElevated2
- : const Color(0xFFFAFAFA),
+ return ValueListenableBuilder<RitualsState>(
+ valueListenable: ritualsService.stateNotifier,
+ builder: (context, state, _) {
+ final ritualsCount = state.rituals.length;
+ final colorScheme = getEnteColorScheme(context);
+ final textTheme = getEnteTextTheme(context);
+ return Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 12),
+ child: Material(
+ color: Colors.transparent,
+ borderRadius: BorderRadius.circular(20),
+ child: InkWell(
borderRadius: BorderRadius.circular(20),
- border: Border.all(
- color: colorScheme.strokeFaint,
- width: 1,
- ),
- ),
- padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.center,
- children: [
- SizedBox(
- width: 55,
- height: 55,
- child: Image.asset(
- "assets/rituals/take_a_photo.png",
- fit: BoxFit.contain,
+ onTap: () {
+ routeToPage(context, const AllRitualsScreen());
+ },
+ child: Container(
+ decoration: BoxDecoration(
+ color: Theme.of(context).brightness == Brightness.dark
+ ? colorScheme.backgroundElevated2
+ : const Color(0xFFFAFAFA),
+ borderRadius: BorderRadius.circular(20),
+ border: Border.all(
+ color: colorScheme.strokeFaint,
+ width: 1,
),
),
- const SizedBox(width: 12),
- Expanded(
- child: LayoutBuilder(
- builder: (context, constraints) {
- const double baseCell = 30;
- const double minCell = baseCell * 0.8; // 24
- const double maxCell = baseCell * 1.3; // 39
- const double spacing = 4;
- double cellWidth =
- (constraints.maxWidth - (6 * spacing)) / 7;
- cellWidth = cellWidth.clamp(minCell, maxCell);
-
- return Row(
- mainAxisSize: MainAxisSize.max,
- children: last7Days.asMap().entries.map((entry) {
- final bool isLast = entry.key == last7Days.length - 1;
- final bool isToday = _isSameDay(entry.value, today);
- final String label =
- _dayLabel(narrowWeekdays, entry.value);
- final Widget pill = _DayPill(
- label: label,
- active: true,
- width: cellWidth,
- textTheme: textTheme,
- colorScheme: colorScheme,
- );
- return Padding(
- padding: EdgeInsets.only(
- right: isLast ? 0 : spacing,
- ),
- child: SizedBox(
- width: cellWidth,
- height: cellWidth,
- child: Stack(
- clipBehavior: Clip.none,
- children: [
- Positioned.fill(child: pill),
- if (isToday)
- Positioned(
- bottom: -(cellWidth * 0.4),
- left: (cellWidth - 6) / 2,
- child: Container(
- width: 6,
- height: 6,
- decoration: BoxDecoration(
- color: colorScheme.primary500,
- shape: BoxShape.circle,
- ),
- ),
- ),
- ],
- ),
- ),
- );
- }).toList(),
- );
- },
- ),
+ padding:
+ const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.center,
+ children: [
+ SizedBox(
+ width: 55,
+ height: 55,
+ child: Image.asset(
+ "assets/rituals/take_a_photo.png",
+ fit: BoxFit.contain,
+ ),
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ Text(
+ "Rituals",
+ style: textTheme.bodyBold,
+ ),
+ const SizedBox(height: 2),
+ Text(
+ ritualsCount == 0
+ ? "Create reminders to take photos"
+ : "$ritualsCount ritual${ritualsCount == 1 ? "" : "s"}",
+ style: textTheme.smallMuted,
+ ),
+ ],
+ ),
+ ),
+ const SizedBox(width: 12),
+ Icon(
+ Icons.chevron_right_rounded,
+ color: colorScheme.blurStrokePressed,
+ ),
+ ],
),
- const SizedBox(width: 12),
- Icon(
- Icons.chevron_right_rounded,
- color: colorScheme.blurStrokePressed,
- ),
- ],
+ ),
),
),
- ),
- ),
- );
- }
-
- String _dayLabel(List<String> narrowWeekdays, DateTime date) {
- return narrowWeekdays[date.weekday % narrowWeekdays.length];
- }
-
- bool _isSameDay(DateTime a, DateTime b) {
- return a.year == b.year && a.month == b.month && a.day == b.day;
- }
-}
-
-class _DayPill extends StatelessWidget {
- const _DayPill({
- required this.label,
- required this.active,
- required this.width,
- required this.textTheme,
- required this.colorScheme,
- });
-
- final String label;
- final bool active;
- final double width;
- final EnteTextTheme textTheme;
- final EnteColorScheme colorScheme;
-
- @override
- Widget build(BuildContext context) {
- final bool isDark = Theme.of(context).brightness == Brightness.dark;
- final Color inactiveBackground =
- isDark ? colorScheme.fillFaintPressed : colorScheme.fillFaint;
- final Color backgroundColor =
- active ? const Color(0xFF1DB954) : inactiveBackground;
- final Color textColor = active ? Colors.white : colorScheme.textBase;
-
- return Container(
- width: width,
- height: 32,
- decoration: BoxDecoration(
- color: backgroundColor,
- borderRadius: BorderRadius.circular(8),
- border: Border.all(
- color: active ? Colors.transparent : colorScheme.strokeFaint,
- ),
- ),
- alignment: Alignment.center,
- child: Text(
- label,
- style: textTheme.miniBold.copyWith(
- color: textColor,
- fontWeight: FontWeight.w900,
- letterSpacing: -0.05,
- ),
- ),
+ );
+ },
);
}
}
diff --git a/mobile/apps/photos/lib/ui/rituals/rituals_section.dart b/mobile/apps/photos/lib/ui/rituals/rituals_section.dart
index 9ab4568d34..c134bd1e07 100644
--- a/mobile/apps/photos/lib/ui/rituals/rituals_section.dart
+++ b/mobile/apps/photos/lib/ui/rituals/rituals_section.dart
@@ -12,7 +12,6 @@ import "package:photos/utils/navigation_util.dart";
class RitualsSection extends StatelessWidget {
const RitualsSection({
required this.rituals,
- required this.progress,
this.selectedRitualId,
this.onSelectionChanged,
this.showHeader = true,
@@ -20,7 +19,6 @@ class RitualsSection extends StatelessWidget {
});
final List<Ritual> rituals;
- final Map<String, RitualProgress> progress;
final String? selectedRitualId;
final ValueChanged<Ritual?>? onSelectionChanged;
final bool showHeader;