Skip to content

armgit / ente

Public Imported from GitHub
0

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

Reuse social overlay in gallery viewer

ashilkn36e2481e8893
diff --git a/mobile/apps/photos/changes/reuse-social-overlay-in-gallery.md b/mobile/apps/photos/changes/reuse-social-overlay-in-gallery.md
new file mode 100644
index 0000000000..43cc7cf632
--- /dev/null
+++ b/mobile/apps/photos/changes/reuse-social-overlay-in-gallery.md
@@ -0,0 +1 @@
+- Added consistent likes and comments controls to the gallery photo viewer.
diff --git a/mobile/apps/photos/lib/db/social_db.dart b/mobile/apps/photos/lib/db/social_db.dart
index 4ef36cf6b0..bb6a019fc2 100644
--- a/mobile/apps/photos/lib/db/social_db.dart
+++ b/mobile/apps/photos/lib/db/social_db.dart
@@ -296,6 +296,20 @@ class SocialDB {
return rows.map(_rowToReaction).toList();
}
+ Future<bool> hasUserReactedToFile(int fileID, int userID) async {
+ final db = await database;
+ final rows = await db.rawQuery(
+ '''
+ SELECT 1 FROM $_reactionsTable
+ WHERE file_id = ? AND user_id = ?
+ AND comment_id IS NULL AND is_deleted = 0
+ LIMIT 1
+ ''',
+ [fileID, userID],
+ );
+ return rows.isNotEmpty;
+ }
+
Future<List<Reaction>> getReactionsForFileInCollection(
int fileID,
int collectionID,
diff --git a/mobile/apps/photos/lib/models/social/social_data_provider.dart b/mobile/apps/photos/lib/models/social/social_data_provider.dart
index b551dc04f0..2b297f6f4f 100644
--- a/mobile/apps/photos/lib/models/social/social_data_provider.dart
+++ b/mobile/apps/photos/lib/models/social/social_data_provider.dart
@@ -48,6 +48,10 @@ class SocialDataProvider {
return _db.getReactionsForFile(fileID);
}
+ Future<bool> hasUserReactedToFile(int fileID, int userID) {
+ return _db.hasUserReactedToFile(fileID, userID);
+ }
+
Future<List<Reaction>> getReactionsForFileInCollection(
int fileID,
int collectionID,
diff --git a/mobile/apps/photos/lib/services/collections_service.dart b/mobile/apps/photos/lib/services/collections_service.dart
index 924afca103..4ad53d6be7 100644
--- a/mobile/apps/photos/lib/services/collections_service.dart
+++ b/mobile/apps/photos/lib/services/collections_service.dart
@@ -325,13 +325,14 @@ class CollectionsService {
return sharedCollections;
}
- /// Returns IDs of non-hidden shared collections containing [uploadedFileID].
+ /// Returns IDs of shared collections containing [uploadedFileID].
///
- /// Use this to scope social content that may be rendered in the UI without
- /// constructing a list of collection objects on the view path.
- Future<List<int>> getNonHiddenSharedCollectionIDsForFile(
- int uploadedFileID,
- ) async {
+ /// Use this to scope social content on the view path without constructing a
+ /// list of collection objects.
+ Future<List<int>> getSharedCollectionIDsForFile(
+ int uploadedFileID, {
+ bool includeHidden = false,
+ }) async {
final collectionIDs = await _filesDB.getAllCollectionIDsOfFile(
uploadedFileID,
);
@@ -345,7 +346,7 @@ class CollectionsService {
if (_isEligibleSharedCollection(
_collectionIDToCollections[collectionID],
currentUserID,
- includeHidden: false,
+ includeHidden: includeHidden,
)) {
sharedCollectionIDs.add(collectionID);
}
diff --git a/mobile/apps/photos/lib/ui/home/memories/full_screen_memory.dart b/mobile/apps/photos/lib/ui/home/memories/full_screen_memory.dart
index 221f2a24c5..60ae24690a 100644
--- a/mobile/apps/photos/lib/ui/home/memories/full_screen_memory.dart
+++ b/mobile/apps/photos/lib/ui/home/memories/full_screen_memory.dart
@@ -44,6 +44,9 @@ import "package:photos/ui/viewer/gallery/jump_to_date_gallery.dart";
import "package:photos/utils/dialog_util.dart";
import "package:photos/utils/share_util.dart";
+const _socialRightInset = 24.0;
+const _socialToActionBarGap = 14.0;
+
//There are two states of variables that FullScreenMemory depends on:
//1. The list of memories
//2. The current index of the page view
@@ -761,12 +764,21 @@ class _FullScreenMemoryState extends State<FullScreenMemory> {
inheritedData.memories.length,
);
if (safeIndex == null) return const SizedBox.shrink();
- return FileSocialOverlay(
- file: inheritedData.memories[safeIndex].file,
- currentUserID: Configuration.instance.getUserID(),
- onInteractionStart: _pauseViewer,
- onInteractionEnd: _resumeViewer,
- onVisibilityChanged: _setSocialControlsVisible,
+ final padding = MediaQuery.paddingOf(context);
+ return Positioned(
+ right: padding.right + _socialRightInset,
+ bottom:
+ padding.bottom +
+ kMemoryBottomActionBarHeight +
+ _socialToActionBarGap,
+ child: FileSocialOverlay(
+ file: inheritedData.memories[safeIndex].file,
+ currentUserID: Configuration.instance.getUserID(),
+ openingCollectionID: null,
+ onInteractionStart: _pauseViewer,
+ onInteractionEnd: _resumeViewer,
+ onVisibilityChanged: _setSocialControlsVisible,
+ ),
);
},
),
diff --git a/mobile/apps/photos/lib/ui/social/comments_screen.dart b/mobile/apps/photos/lib/ui/social/comments_screen.dart
index 8390c472a4..884476e156 100644
--- a/mobile/apps/photos/lib/ui/social/comments_screen.dart
+++ b/mobile/apps/photos/lib/ui/social/comments_screen.dart
@@ -4,7 +4,6 @@ import "package:flutter/material.dart";
import "package:logging/logging.dart";
import "package:photos/core/configuration.dart";
import "package:photos/core/event_bus.dart";
-import "package:photos/db/files_db.dart";
import "package:photos/events/comment_deleted_event.dart";
import "package:photos/generated/l10n.dart";
import "package:photos/models/api/collection/user.dart";
@@ -42,6 +41,7 @@ Future<void> showFileCommentsBottomSheet(
required int collectionID,
required int fileID,
String? highlightCommentID,
+ List<Collection>? sharedCollections,
}) {
return showModalBottomSheet(
context: context,
@@ -52,6 +52,7 @@ Future<void> showFileCommentsBottomSheet(
collectionID: collectionID,
fileID: fileID,
highlightCommentID: highlightCommentID,
+ sharedCollections: sharedCollections,
),
);
}
@@ -61,12 +62,14 @@ class _DraggableCommentsSheet extends StatefulWidget {
final int collectionID;
final int fileID;
final String? highlightCommentID;
+ final List<Collection>? sharedCollections;
const _DraggableCommentsSheet({
required this.launchContext,
required this.collectionID,
required this.fileID,
this.highlightCommentID,
+ this.sharedCollections,
});
@override
@@ -99,6 +102,7 @@ class _DraggableCommentsSheetState extends State<_DraggableCommentsSheet> {
collectionID: widget.collectionID,
fileID: widget.fileID,
highlightCommentID: widget.highlightCommentID,
+ sharedCollections: widget.sharedCollections,
dragController: scrollController,
sheetController: sheetController,
),
@@ -110,6 +114,7 @@ class FileCommentsBottomSheet extends StatefulWidget {
final BuildContext launchContext;
final int collectionID;
final int fileID;
+ final List<Collection>? sharedCollections;
/// Optional comment ID to scroll to and highlight.
final String? highlightCommentID;
@@ -124,6 +129,7 @@ class FileCommentsBottomSheet extends StatefulWidget {
required this.launchContext,
required this.collectionID,
required this.fileID,
+ this.sharedCollections,
required this.dragController,
required this.sheetController,
this.highlightCommentID,
@@ -206,28 +212,14 @@ class _FileCommentsBottomSheetState extends State<FileCommentsBottomSheet> {
}
Future<void> _loadSharedCollections() async {
- final collectionIDs = await FilesDB.instance.getAllCollectionIDsOfFile(
- widget.fileID,
- );
-
- // Filter to shared collections first (sync operation)
- var sharedCollectionsList = collectionIDs
- .map((id) => CollectionsService.instance.getCollectionByID(id))
- .whereType<Collection>()
- .where((c) => c.hasSharees || c.hasLink || !c.isOwner(_currentUserID))
- .toList();
-
- // Filter out hidden collections unless viewing from a hidden collection
- final hiddenCollectionIds = CollectionsService.instance
- .getHiddenCollectionIds();
- final isInitialCollectionHidden = hiddenCollectionIds.contains(
- widget.collectionID,
- );
- if (!isInitialCollectionHidden) {
- sharedCollectionsList = sharedCollectionsList
- .where((c) => !hiddenCollectionIds.contains(c.id))
- .toList();
- }
+ final sharedCollectionsList =
+ widget.sharedCollections ??
+ await CollectionsService.instance.getSharedCollectionsForFile(
+ widget.fileID,
+ includeHidden: CollectionsService.instance
+ .getHiddenCollectionIds()
+ .contains(widget.collectionID),
+ );
// Fetch data in parallel
final sharedCollections = await Future.wait(
diff --git a/mobile/apps/photos/lib/ui/social/likes_bottom_sheet.dart b/mobile/apps/photos/lib/ui/social/likes_bottom_sheet.dart
index 325347eb95..5ec894df4e 100644
--- a/mobile/apps/photos/lib/ui/social/likes_bottom_sheet.dart
+++ b/mobile/apps/photos/lib/ui/social/likes_bottom_sheet.dart
@@ -3,7 +3,6 @@ import "dart:async";
import "package:ente_icons/ente_icons.dart";
import "package:flutter/material.dart";
import "package:photos/core/configuration.dart";
-import "package:photos/db/files_db.dart";
import "package:photos/generated/l10n.dart";
import "package:photos/models/api/collection/user.dart";
import "package:photos/models/collection/collection.dart";
@@ -26,6 +25,7 @@ Future<void> showLikesBottomSheet(
BuildContext context, {
required int fileID,
required int initialCollectionID,
+ List<Collection>? sharedCollections,
}) {
return showModalBottomSheet(
context: context,
@@ -35,6 +35,7 @@ Future<void> showLikesBottomSheet(
launchContext: context,
fileID: fileID,
initialCollectionID: initialCollectionID,
+ sharedCollections: sharedCollections,
),
);
}
@@ -43,11 +44,13 @@ class LikesBottomSheet extends StatefulWidget {
final BuildContext launchContext;
final int fileID;
final int initialCollectionID;
+ final List<Collection>? sharedCollections;
const LikesBottomSheet({
required this.launchContext,
required this.fileID,
required this.initialCollectionID,
+ this.sharedCollections,
super.key,
});
@@ -78,29 +81,14 @@ class _LikesBottomSheetState extends State<LikesBottomSheet> {
Future<void> _loadSharedCollections() async {
try {
- // Get all collections containing this file
- final collectionIDs = await FilesDB.instance.getAllCollectionIDsOfFile(
- widget.fileID,
- );
-
- // Filter to shared collections only
- var sharedCollectionsList = collectionIDs
- .map((id) => CollectionsService.instance.getCollectionByID(id))
- .whereType<Collection>()
- .where((c) => c.hasSharees || c.hasLink || !c.isOwner(_currentUserID))
- .toList();
-
- // Filter out hidden collections unless viewing from a hidden collection
- final hiddenCollectionIds = CollectionsService.instance
- .getHiddenCollectionIds();
- final isInitialCollectionHidden = hiddenCollectionIds.contains(
- widget.initialCollectionID,
- );
- if (!isInitialCollectionHidden) {
- sharedCollectionsList = sharedCollectionsList
- .where((c) => !hiddenCollectionIds.contains(c.id))
- .toList();
- }
+ final sharedCollectionsList =
+ widget.sharedCollections ??
+ await CollectionsService.instance.getSharedCollectionsForFile(
+ widget.fileID,
+ includeHidden: CollectionsService.instance
+ .getHiddenCollectionIds()
+ .contains(widget.initialCollectionID),
+ );
// Fetch like counts and thumbnails in parallel
final sharedCollections = await Future.wait(
diff --git a/mobile/apps/photos/lib/ui/social/widgets/file_social_overlay.dart b/mobile/apps/photos/lib/ui/social/widgets/file_social_overlay.dart
index b27eb88b92..e751ccfd6e 100644
--- a/mobile/apps/photos/lib/ui/social/widgets/file_social_overlay.dart
+++ b/mobile/apps/photos/lib/ui/social/widgets/file_social_overlay.dart
@@ -10,13 +10,12 @@ import "package:photos/core/event_bus.dart";
import "package:photos/events/social_data_updated_event.dart";
import "package:photos/generated/l10n.dart";
import "package:photos/models/api/collection/user.dart";
+import "package:photos/models/collection/collection.dart";
import "package:photos/models/file/file.dart";
import "package:photos/models/social/comment.dart";
import "package:photos/models/social/comment_author_utils.dart";
-import "package:photos/models/social/reaction.dart";
import "package:photos/models/social/social_data_provider.dart";
import "package:photos/services/collections_service.dart";
-import "package:photos/ui/home/memories/memory_viewer_constants.dart";
import "package:photos/ui/notification/toast.dart";
import "package:photos/ui/sharing/user_avator_widget.dart";
import "package:photos/ui/social/comments_screen.dart";
@@ -28,24 +27,50 @@ final _logger = Logger("FileSocialOverlay");
const _likedColor = Color(0xFF08C225);
const _socialControlsSize = 40.0;
const _socialIconSize = 32.0;
-const _socialToActionBarGap = 14.0;
+typedef FileSocialContextIdentity = ({
+ int? uploadedFileID,
+ int? openingCollectionID,
+ int? currentUserID,
+});
+
+bool fileSocialContextIncludesHiddenCollections(
+ int? openingCollectionID,
+ Set<int> hiddenCollectionIDs,
+) {
+ return openingCollectionID != null &&
+ hiddenCollectionIDs.contains(openingCollectionID);
+}
+
+/// Social content for a file. The host owns placement and visibility effects.
class FileSocialOverlay extends StatefulWidget {
final EnteFile file;
final int? currentUserID;
- final VoidCallback onInteractionStart;
- final VoidCallback onInteractionEnd;
- final ValueChanged<bool> onVisibilityChanged;
+
+ /// The collection the viewer was opened from, or null when there is no
+ /// opening collection context. Memories must not pass a deduped file row's
+ /// collection ID here.
+ final int? openingCollectionID;
+ final VoidCallback? onInteractionStart;
+ final VoidCallback? onInteractionEnd;
+ final ValueChanged<bool>? onVisibilityChanged;
const FileSocialOverlay({
required this.file,
required this.currentUserID,
- required this.onInteractionStart,
- required this.onInteractionEnd,
- required this.onVisibilityChanged,
+ required this.openingCollectionID,
+ this.onInteractionStart,
+ this.onInteractionEnd,
+ this.onVisibilityChanged,
super.key,
});
+ FileSocialContextIdentity get contextIdentity => (
+ uploadedFileID: file.uploadedFileID,
+ openingCollectionID: openingCollectionID,
+ currentUserID: currentUserID,
+ );
+
@override
State<FileSocialOverlay> createState() => _FileSocialOverlayState();
}
@@ -54,7 +79,7 @@ class _FileSocialOverlayState extends State<FileSocialOverlay> {
late final StreamSubscription<SocialDataUpdatedEvent>
_socialDataUpdatedSubscription;
- List<int> _visibleSharedCollectionIDs = const [];
+ List<int> _eligibleSharedCollectionIDs = const [];
bool _hasLiked = false;
int _commentCount = 0;
Comment? _latestComment;
@@ -74,8 +99,7 @@ class _FileSocialOverlayState extends State<FileSocialOverlay> {
@override
void didUpdateWidget(covariant FileSocialOverlay oldWidget) {
super.didUpdateWidget(oldWidget);
- if (oldWidget.file.uploadedFileID != widget.file.uploadedFileID ||
- oldWidget.currentUserID != widget.currentUserID) {
+ if (oldWidget.contextIdentity != widget.contextIdentity) {
_clearSocialState();
unawaited(_refreshSocialState());
}
@@ -88,7 +112,7 @@ class _FileSocialOverlayState extends State<FileSocialOverlay> {
}
void _clearSocialState() {
- _visibleSharedCollectionIDs = const [];
+ _eligibleSharedCollectionIDs = const [];
_hasLiked = false;
_commentCount = 0;
_latestComment = null;
@@ -96,17 +120,26 @@ class _FileSocialOverlayState extends State<FileSocialOverlay> {
}
bool _canApplySocialRefresh({
- required int requestedFileID,
+ required FileSocialContextIdentity requestedContext,
required int refreshID,
}) {
return mounted &&
refreshID == _latestRefreshID &&
- widget.file.uploadedFileID == requestedFileID;
+ widget.contextIdentity == requestedContext;
+ }
+
+ bool get _includeHiddenCollections {
+ return fileSocialContextIncludesHiddenCollections(
+ widget.openingCollectionID,
+ CollectionsService.instance.getHiddenCollectionIds(),
+ );
}
Future<void> _refreshSocialState() async {
+ // Recheck the captured context after every await before touching state.
final fileID = widget.file.uploadedFileID;
final currentUserID = widget.currentUserID;
+ final requestedContext = widget.contextIdentity;
final refreshID = ++_latestRefreshID;
if (fileID == null || currentUserID == null) {
@@ -115,20 +148,22 @@ class _FileSocialOverlayState extends State<FileSocialOverlay> {
scheduleMicrotask(() {
if (!mounted ||
refreshID != _latestRefreshID ||
- widget.file.uploadedFileID != fileID ||
- widget.currentUserID != currentUserID) {
+ widget.contextIdentity != requestedContext) {
return;
}
- widget.onVisibilityChanged(false);
+ widget.onVisibilityChanged?.call(false);
});
return;
}
try {
final collectionIDs = await CollectionsService.instance
- .getNonHiddenSharedCollectionIDsForFile(fileID);
+ .getSharedCollectionIDsForFile(
+ fileID,
+ includeHidden: _includeHiddenCollections,
+ );
if (!_canApplySocialRefresh(
- requestedFileID: fileID,
+ requestedContext: requestedContext,
refreshID: refreshID,
)) {
return;
@@ -136,13 +171,13 @@ class _FileSocialOverlayState extends State<FileSocialOverlay> {
if (collectionIDs.isEmpty) {
setState(_clearSocialState);
- widget.onVisibilityChanged(false);
+ widget.onVisibilityChanged?.call(false);
return;
}
final provider = SocialDataProvider.instance;
final results = await Future.wait<Object?>([
- provider.getReactionsForFile(fileID),
+ provider.hasUserReactedToFile(fileID, currentUserID),
provider.getCommentCountForFile(fileID),
provider.getLatestCommentForFile(
fileID,
@@ -150,13 +185,13 @@ class _FileSocialOverlayState extends State<FileSocialOverlay> {
),
]);
if (!_canApplySocialRefresh(
- requestedFileID: fileID,
+ requestedContext: requestedContext,
refreshID: refreshID,
)) {
return;
}
- final reactions = results[0] as List<Reaction>;
+ final hasLiked = results[0] as bool;
final commentCount = results[1] as int;
final latestComment = results[2] as Comment?;
User? latestCommentAuthor;
@@ -167,7 +202,7 @@ class _FileSocialOverlayState extends State<FileSocialOverlay> {
)
: const <String, String>{};
if (!_canApplySocialRefresh(
- requestedFileID: fileID,
+ requestedContext: requestedContext,
refreshID: refreshID,
)) {
return;
@@ -182,21 +217,19 @@ class _FileSocialOverlayState extends State<FileSocialOverlay> {
}
if (!_canApplySocialRefresh(
- requestedFileID: fileID,
+ requestedContext: requestedContext,
refreshID: refreshID,
)) {
return;
}
setState(() {
- _visibleSharedCollectionIDs = collectionIDs;
- _hasLiked = reactions.any(
- (reaction) => reaction.userID == currentUserID,
- );
+ _eligibleSharedCollectionIDs = collectionIDs;
+ _hasLiked = hasLiked;
_commentCount = commentCount;
_latestComment = latestComment;
_latestCommentAuthor = latestCommentAuthor;
});
- widget.onVisibilityChanged(true);
+ widget.onVisibilityChanged?.call(true);
} catch (error, stackTrace) {
// Preserve last-good state; page changes clear state and visibility.
_logger.warning(
@@ -211,9 +244,10 @@ class _FileSocialOverlayState extends State<FileSocialOverlay> {
final file = widget.file;
final fileID = file.uploadedFileID;
final currentUserID = widget.currentUserID;
+ final actionContext = widget.contextIdentity;
if (fileID == null ||
currentUserID == null ||
- _visibleSharedCollectionIDs.isEmpty ||
+ _eligibleSharedCollectionIDs.isEmpty ||
_reactionUpdateFileIDs.contains(fileID)) {
return;
}
@@ -221,15 +255,17 @@ class _FileSocialOverlayState extends State<FileSocialOverlay> {
_reactionUpdateFileIDs.add(fileID);
try {
if (_hasLiked) {
- await _unlikeFromAllCollections(fileID, currentUserID);
+ await _unlikeFromAllCollections(fileID, currentUserID, actionContext);
return;
}
final sharedCollections = await CollectionsService.instance
- .getSharedCollectionsForFile(fileID);
+ .getSharedCollectionsForFile(
+ fileID,
+ includeHidden: _includeHiddenCollections,
+ );
if (!mounted ||
- widget.file.uploadedFileID != fileID ||
- widget.currentUserID != currentUserID ||
+ widget.contextIdentity != actionContext ||
sharedCollections.isEmpty) {
return;
}
@@ -245,7 +281,7 @@ class _FileSocialOverlayState extends State<FileSocialOverlay> {
);
} catch (error, stackTrace) {
_logger.severe("Failed to like photo", error, stackTrace);
- if (mounted && widget.file.uploadedFileID == fileID) {
+ if (mounted && widget.contextIdentity == actionContext) {
setState(() => _hasLiked = previousState);
showShortToast(
context,
@@ -270,7 +306,11 @@ class _FileSocialOverlayState extends State<FileSocialOverlay> {
}
}
- Future<void> _unlikeFromAllCollections(int fileID, int currentUserID) async {
+ Future<void> _unlikeFromAllCollections(
+ int fileID,
+ int currentUserID,
+ FileSocialContextIdentity actionContext,
+ ) async {
final previousState = _hasLiked;
setState(() => _hasLiked = false);
@@ -302,7 +342,9 @@ class _FileSocialOverlayState extends State<FileSocialOverlay> {
}
}
- if (failedCount > 0 && mounted && widget.file.uploadedFileID == fileID) {
+ if (failedCount > 0 &&
+ mounted &&
+ widget.contextIdentity == actionContext) {
setState(() => _hasLiked = previousState);
showShortToast(
context,
@@ -315,7 +357,7 @@ class _FileSocialOverlayState extends State<FileSocialOverlay> {
error,
stackTrace,
);
- if (mounted && widget.file.uploadedFileID == fileID) {
+ if (mounted && widget.contextIdentity == actionContext) {
setState(() => _hasLiked = previousState);
showShortToast(
context,
@@ -327,74 +369,96 @@ class _FileSocialOverlayState extends State<FileSocialOverlay> {
Future<void> _showLikes() async {
final fileID = widget.file.uploadedFileID;
- if (fileID == null || _visibleSharedCollectionIDs.isEmpty) return;
+ final actionContext = widget.contextIdentity;
+ if (fileID == null || _eligibleSharedCollectionIDs.isEmpty) return;
await _runSheetAndRefresh(() async {
final sharedCollections = await CollectionsService.instance
- .getSharedCollectionsForFile(fileID);
+ .getSharedCollectionsForFile(
+ fileID,
+ includeHidden: _includeHiddenCollections,
+ );
if (!mounted ||
- widget.file.uploadedFileID != fileID ||
+ widget.contextIdentity != actionContext ||
sharedCollections.isEmpty) {
return;
}
+ final initialCollection = sharedCollections.firstWhereOrNull(
+ (collection) => collection.id == actionContext.openingCollectionID,
+ );
await showLikesBottomSheet(
context,
fileID: fileID,
- initialCollectionID: sharedCollections.first.id,
+ initialCollectionID:
+ initialCollection?.id ?? sharedCollections.first.id,
+ sharedCollections: sharedCollections,
);
});
}
Future<void> _openComments({Comment? comment}) async {
final fileID = widget.file.uploadedFileID;
- if (fileID == null || _visibleSharedCollectionIDs.isEmpty) return;
+ final actionContext = widget.contextIdentity;
+ if (fileID == null || _eligibleSharedCollectionIDs.isEmpty) return;
await _runSheetAndRefresh(() async {
final sharedCollections = await CollectionsService.instance
- .getSharedCollectionsForFile(fileID);
+ .getSharedCollectionsForFile(
+ fileID,
+ includeHidden: _includeHiddenCollections,
+ );
if (!mounted ||
- widget.file.uploadedFileID != fileID ||
+ widget.contextIdentity != actionContext ||
sharedCollections.isEmpty) {
return;
}
- final preferredCollectionID =
- comment?.collectionID ?? _latestComment?.collectionID;
- final preferredCollection = sharedCollections.firstWhereOrNull(
- (collection) => collection.id == preferredCollectionID,
- );
+ Collection? commentCollection;
+ Collection? openingCollection;
+ Collection? latestCommentCollection;
+ for (final collection in sharedCollections) {
+ if (collection.id == comment?.collectionID) {
+ commentCollection = collection;
+ }
+ if (collection.id == actionContext.openingCollectionID) {
+ openingCollection = collection;
+ }
+ if (collection.id == _latestComment?.collectionID) {
+ latestCommentCollection = collection;
+ }
+ }
+ final initialCollection =
+ commentCollection ??
+ openingCollection ??
+ latestCommentCollection ??
+ sharedCollections.first;
await showFileCommentsBottomSheet(
context,
- collectionID: preferredCollection?.id ?? sharedCollections.first.id,
+ collectionID: initialCollection.id,
fileID: fileID,
- highlightCommentID: preferredCollection == null ? null : comment?.id,
+ highlightCommentID: commentCollection == null ? null : comment?.id,
+ sharedCollections: sharedCollections,
);
});
}
Future<void> _runSheetAndRefresh(Future<void> Function() showSheet) async {
- widget.onInteractionStart();
+ widget.onInteractionStart?.call();
try {
await showSheet();
await _refreshSocialState();
} finally {
- widget.onInteractionEnd();
+ widget.onInteractionEnd?.call();
}
}
@override
Widget build(BuildContext context) {
- if (_visibleSharedCollectionIDs.isEmpty) {
+ if (_eligibleSharedCollectionIDs.isEmpty) {
return const SizedBox.shrink();
}
- final safePadding = MediaQuery.paddingOf(context);
- return Positioned(
- right: safePadding.right + 24,
- bottom:
- safePadding.bottom +
- kMemoryBottomActionBarHeight +
- _socialToActionBarGap,
- child: Row(
+ return LayoutBuilder(
+ builder: (context, constraints) => Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
if (_latestComment != null && _latestCommentAuthor != null)
@@ -403,6 +467,7 @@ class _FileSocialOverlayState extends State<FileSocialOverlay> {
child: _buildLatestCommentPill(
_latestComment!,
_latestCommentAuthor!,
+ math.min(constraints.maxWidth * 0.5, 200),
),
),
Column(
@@ -456,14 +521,16 @@ class _FileSocialOverlayState extends State<FileSocialOverlay> {
);
}
- Widget _buildLatestCommentPill(Comment comment, User author) {
+ Widget _buildLatestCommentPill(
+ Comment comment,
+ User author,
+ double maxWidth,
+ ) {
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => unawaited(_openComments(comment: comment)),
child: ConstrainedBox(
- constraints: BoxConstraints(
- maxWidth: math.min(MediaQuery.sizeOf(context).width * 0.5, 200),
- ),
+ constraints: BoxConstraints(maxWidth: maxWidth),
child: Stack(
clipBehavior: Clip.none,
children: [
diff --git a/mobile/apps/photos/lib/ui/viewer/file/detail_page.dart b/mobile/apps/photos/lib/ui/viewer/file/detail_page.dart
index 0f77e15997..995789b57c 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/detail_page.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/detail_page.dart
@@ -25,6 +25,7 @@ import "package:photos/services/collections_service.dart";
import "package:photos/states/detail_page_state.dart";
import "package:photos/ui/common/fast_scroll_physics.dart";
import 'package:photos/ui/notification/toast.dart';
+import "package:photos/ui/social/widgets/file_social_overlay.dart";
import "package:photos/ui/tools/editor/image_editor/image_editor_page.dart";
import "package:photos/ui/tools/editor/video_editor_page.dart";
import "package:photos/ui/viewer/file/file_app_bar.dart";
@@ -37,6 +38,9 @@ import "package:photos/ui/viewer/file/qr_code_highlight_overlay.dart";
import 'package:photos/ui/viewer/gallery/gallery.dart';
import 'package:photos/utils/dialog_util.dart';
+const _socialRightInset = 24.0;
+const _socialBottomBarClearance = 74.0;
+
enum DetailPageMode { minimalistic, full }
class DetailPageConfiguration {
@@ -283,6 +287,12 @@ class _BodyState extends State<_Body> {
},
valueListenable: _selectedIndexNotifier,
),
+ ValueListenableBuilder(
+ valueListenable: _selectedIndexNotifier,
+ builder: (BuildContext context, int selectedIndex, _) {
+ return _buildSocialOverlay(_files![selectedIndex]);
+ },
+ ),
ValueListenableBuilder(
valueListenable: _selectedIndexNotifier,
builder: (BuildContext context, int selectedIndex, _) {
@@ -393,6 +403,40 @@ class _BodyState extends State<_Body> {
.ignore();
}
+ Widget _buildSocialOverlay(EnteFile file) {
+ if (widget.config.mode == DetailPageMode.minimalistic ||
+ isGuestView ||
+ file is TrashFile) {
+ return const SizedBox.shrink();
+ }
+
+ final padding = MediaQuery.paddingOf(context);
+ final fullScreenNotifier = InheritedDetailPageState.of(
+ context,
+ ).enableFullScreenNotifier;
+ return Positioned(
+ right: padding.right + _socialRightInset,
+ bottom: padding.bottom + _socialBottomBarClearance,
+ child: ValueListenableBuilder<bool>(
+ valueListenable: fullScreenNotifier,
+ builder: (context, isFullScreen, child) => IgnorePointer(
+ ignoring: isFullScreen,
+ child: AnimatedOpacity(
+ opacity: isFullScreen ? 0 : 1,
+ duration: const Duration(milliseconds: 250),
+ curve: Curves.easeInOut,
+ child: child,
+ ),
+ ),
+ child: FileSocialOverlay(
+ file: file,
+ currentUserID: Configuration.instance.getUserID(),
+ openingCollectionID: file.collectionID,
+ ),
+ ),
+ );
+ }
+
Widget _buildPageView() {
return PageView.builder(
clipBehavior: Clip.none,
diff --git a/mobile/apps/photos/lib/ui/viewer/file/file_bottom_bar.dart b/mobile/apps/photos/lib/ui/viewer/file/file_bottom_bar.dart
index 728284292d..e179696946 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/file_bottom_bar.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/file_bottom_bar.dart
@@ -1,13 +1,10 @@
import "dart:async";
import "dart:io";
-import "package:collection/collection.dart";
import "package:ente_icons/ente_icons.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
-import "package:logging/logging.dart";
import "package:photos/core/event_bus.dart";
-import "package:photos/db/files_db.dart";
import "package:photos/events/guest_view_event.dart";
import "package:photos/generated/l10n.dart";
import "package:photos/models/collection/collection.dart";
@@ -15,23 +12,16 @@ import "package:photos/models/file/extensions/file_props.dart";
import "package:photos/models/file/file.dart";
import "package:photos/models/file/trash_file.dart";
import "package:photos/models/selected_files.dart";
-import "package:photos/models/social/social_data_provider.dart";
import 'package:photos/module/metadata/panorama.dart';
import "package:photos/service_locator.dart";
import "package:photos/services/collections_service.dart";
import "package:photos/states/detail_page_state.dart";
import "package:photos/ui/actions/file/file_actions.dart";
import "package:photos/ui/collections/collection_action_sheet.dart";
-import "package:photos/ui/notification/toast.dart";
-import "package:photos/ui/social/comments_screen.dart";
-import "package:photos/ui/social/like_collection_selector_sheet.dart";
-import "package:photos/ui/social/likes_bottom_sheet.dart";
import "package:photos/ui/viewer/actions/suggest_delete_sheet.dart";
import "package:photos/utils/delete_file_util.dart";
import "package:photos/utils/share_util.dart";
-final _logger = Logger("FileBottomBar");
-
class FileBottomBar extends StatefulWidget {
final EnteFile file;
final Function(EnteFile) onFileRemoved;
@@ -57,13 +47,10 @@ class FileBottomBarState extends State<FileBottomBar> {
bool isGuestView = false;
late final StreamSubscription<GuestViewEvent> _guestViewEventSubscription;
int? lastFileGenID;
- bool _hasLiked = false;
- int _commentCount = 0;
@override
void initState() {
super.initState();
- _updateSocialState();
_guestViewEventSubscription = Bus.instance.on<GuestViewEvent>().listen((
event,
) {
@@ -73,44 +60,6 @@ class FileBottomBarState extends State<FileBottomBar> {
});
}
- @override
- void didUpdateWidget(FileBottomBar oldWidget) {
- super.didUpdateWidget(oldWidget);
- if (oldWidget.file.uploadedFileID != widget.file.uploadedFileID) {
- _updateSocialState();
- }
- }
-
- Future<void> _updateSocialState({bool sync = false}) async {
- if (widget.file.uploadedFileID == null) {
- _hasLiked = false;
- _commentCount = 0;
- return;
- }
-
- final fileID = widget.file.uploadedFileID!;
- final collectionID = widget.file.collectionID;
- final provider = SocialDataProvider.instance;
-
- // Sync from server if requested and we have a collection ID
- if (sync && collectionID != null) {
- try {
- await provider.syncFileReactions(collectionID, fileID);
- } catch (_) {
- // Ignore sync errors, continue with local data
- }
- }
-
- // Check if user has liked
- final reactions = await provider.getReactionsForFile(fileID);
- _hasLiked = reactions.any((r) => r.userID == widget.userID && !r.isDeleted);
-
- // Get comment count
- _commentCount = await provider.getCommentCountForFile(fileID);
-
- safeRefresh();
- }
-
@override
void dispose() {
_guestViewEventSubscription.cancel();
@@ -142,17 +91,7 @@ class FileBottomBarState extends State<FileBottomBar> {
);
}
- void safeRefresh() {
- if (mounted) {
- setState(() {});
- }
- }
-
Widget _getBottomBar() {
- Logger(
- "FileBottomBar",
- ).fine("building bottom bar ${widget.file.generatedID}");
-
final isInSharedCollection =
InheritedDetailPageState.maybeOf(
context,
@@ -257,12 +196,6 @@ class FileBottomBarState extends State<FileBottomBar> {
),
);
}
-
- // Add social icons (heart, comment) for files in shared collections.
- if (isInSharedCollection) {
- children.add(_buildHeartIcon());
- children.add(_buildCommentIcon());
- }
}
return ValueListenableBuilder(
valueListenable: widget.enableFullScreenNotifier,
@@ -373,151 +306,6 @@ class FileBottomBarState extends State<FileBottomBar> {
);
}
- Widget _buildHeartIcon() {
- return Tooltip(
- message: AppLocalizations.of(context).like,
- child: Padding(
- padding: const EdgeInsets.only(top: 12),
- child: GestureDetector(
- onLongPress: _showLikesBottomSheet,
- child: IconButton(
- style: IconButton.styleFrom(
- overlayColor: WidgetStateColor.transparent,
- ),
- onPressed: _toggleReaction,
- icon: Icon(
- _hasLiked ? EnteIcons.likeFilled : EnteIcons.likeStroke,
- color: _hasLiked ? const Color(0xFF08C225) : Colors.white,
- ),
- ),
- ),
- ),
- );
- }
-
- Future<void> _toggleReaction() async {
- final file = widget.file;
- if (file.uploadedFileID == null || widget.userID == null) {
- return;
- }
-
- // If already liked, unlike from ALL shared collections
- if (_hasLiked) {
- await _unlikeFromAllCollections();
- return;
- }
-
- final sharedCollections = await CollectionsService.instance
- .getSharedCollectionsForFile(file.uploadedFileID!, includeHidden: true);
-
- if (sharedCollections.isEmpty) {
- return;
- }
-
- if (sharedCollections.length == 1) {
- // Single shared collection: like directly
- final previousState = _hasLiked;
- _hasLiked = true;
- safeRefresh();
-
- try {
- await SocialDataProvider.instance.toggleReaction(
- userID: widget.userID!,
- collectionID: sharedCollections.single.id,
- fileID: file.uploadedFileID,
- );
- } catch (e) {
- _logger.severe("Failed to like photo", e);
- if (mounted) {
- _hasLiked = previousState;
- safeRefresh();
- showShortToast(context, "Failed to like photo");
- }
- }
- } else {
- // Multiple shared collections: show selector bottom sheet
- if (!mounted) return;
- await showLikeCollectionSelectorSheet(
- context,
- fileID: file.uploadedFileID!,
- currentUserID: widget.userID!,
- collections: sharedCollections,
- file: file,
- );
- // Refresh state after sheet closes to sync heart icon
- await _updateSocialState();
- }
- }
-
- /// Removes the user's like from all shared collections containing this file
- Future<void> _unlikeFromAllCollections() async {
- final file = widget.file;
- if (file.uploadedFileID == null || widget.userID == null) return;
-
- final currentUserID = widget.userID!;
- final fileID = file.uploadedFileID!;
-
- // Optimistic UI update
- final previousState = _hasLiked;
- _hasLiked = false;
- safeRefresh();
-
- try {
- // Get all collections containing this file
- final collectionIDs = await FilesDB.instance.getAllCollectionIDsOfFile(
- fileID,
- );
-
- // Filter to shared collections
- final sharedCollections = collectionIDs
- .map((id) => CollectionsService.instance.getCollectionByID(id))
- .whereType<Collection>()
- .where((c) => c.hasSharees || c.hasLink || !c.isOwner(currentUserID))
- .toList();
-
- // Track failures
- int failedCount = 0;
-
- // Unlike from each collection where user has an active like
- for (final collection in sharedCollections) {
- try {
- final reactions = await SocialDataProvider.instance
- .getReactionsForFileInCollection(fileID, collection.id);
-
- final userReaction = reactions.firstWhereOrNull(
- (r) => r.userID == currentUserID && !r.isDeleted,
- );
-
- if (userReaction != null) {
- await SocialDataProvider.instance.toggleReaction(
- userID: currentUserID,
- collectionID: collection.id,
- fileID: fileID,
- );
- }
- } catch (e) {
- failedCount++;
- debugPrint("Failed to unlike from ${collection.displayName}: $e");
- }
- }
-
- // Show toast and rollback if any failed
- if (failedCount > 0 && mounted) {
- _hasLiked = previousState;
- safeRefresh();
- showShortToast(context, "Failed to unlike photo");
- }
- } catch (e) {
- // Rollback on error (e.g., fetching collections failed)
- debugPrint("Failed to unlike from all collections: $e");
- if (mounted) {
- _hasLiked = previousState;
- safeRefresh();
- showShortToast(context, "Failed to remove like");
- }
- }
- }
-
Future<void> _onSuggestDelete(Collection collection) async {
if (widget.file.uploadedFileID == null) {
return;
@@ -533,76 +321,4 @@ class FileBottomBarState extends State<FileBottomBar> {
},
);
}
-
- void _showLikesBottomSheet() {
- final file = widget.file;
- if (file.uploadedFileID == null || file.collectionID == null) return;
-
- showLikesBottomSheet(
- context,
- fileID: file.uploadedFileID!,
- initialCollectionID: file.collectionID!,
- );
- }
-
- Widget _buildCommentIcon() {
- return Tooltip(
- message: AppLocalizations.of(context).comments,
- child: Padding(
- padding: const EdgeInsets.only(top: 12),
- child: IconButton(
- onPressed: _openCommentsScreen,
- icon: Stack(
- clipBehavior: Clip.none,
- children: [
- const Icon(EnteIcons.commentBubbleStroke, color: Colors.white),
- if (_commentCount > 0)
- Positioned(
- right: -4,
- top: -4,
- child: Container(
- padding: const EdgeInsets.symmetric(
- horizontal: 4,
- vertical: 1,
- ),
- decoration: BoxDecoration(
- color: Colors.white,
- borderRadius: const BorderRadius.all(Radius.circular(16)),
- border: Border.all(
- color: Colors.black,
- width: 2,
- strokeAlign: BorderSide.strokeAlignOutside,
- ),
- ),
- child: Text(
- _commentCount > 99 ? '99+' : _commentCount.toString(),
- style: const TextStyle(
- color: Colors.black,
- fontSize: 8,
- fontWeight: FontWeight.w500,
- ),
- textAlign: TextAlign.center,
- ),
- ),
- ),
- ],
- ),
- ),
- ),
- );
- }
-
- void _openCommentsScreen() {
- final file = widget.file;
- if (file.collectionID == null) return;
-
- showFileCommentsBottomSheet(
- context,
- collectionID: file.collectionID!,
- fileID: file.uploadedFileID!,
- ).then((_) {
- // Refresh comment count when returning from comments bottom sheet
- _updateSocialState();
- });
- }
}
diff --git a/mobile/apps/photos/pubspec.yaml b/mobile/apps/photos/pubspec.yaml
index 35cdb37959..153c14740f 100644
--- a/mobile/apps/photos/pubspec.yaml
+++ b/mobile/apps/photos/pubspec.yaml
@@ -260,6 +260,8 @@ dev_dependencies:
json_annotation: 4.9.0
json_serializable: 6.11.2
mockito: 5.5.1
+ path_provider_platform_interface: 2.1.3
+ sqflite_common_ffi: 2.3.7+1
test: 1.26.3
# ------------------------------
diff --git a/mobile/apps/photos/test/db/social_db_test.dart b/mobile/apps/photos/test/db/social_db_test.dart
new file mode 100644
index 0000000000..097c37a781
--- /dev/null
+++ b/mobile/apps/photos/test/db/social_db_test.dart
@@ -0,0 +1,133 @@
+import "dart:io";
+
+import "package:flutter_test/flutter_test.dart";
+import "package:path_provider_platform_interface/path_provider_platform_interface.dart";
+import "package:photos/db/social_db.dart";
+import "package:photos/models/social/comment.dart";
+import "package:photos/models/social/reaction.dart";
+import "package:sqflite_common_ffi/sqflite_ffi.dart";
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ late Directory tempDir;
+ late PathProviderPlatform previousPathProvider;
+
+ setUpAll(() async {
+ sqfliteFfiInit();
+ databaseFactory = databaseFactoryFfi;
+ previousPathProvider = PathProviderPlatform.instance;
+ tempDir = await Directory.systemTemp.createTemp("social_db_test_");
+ PathProviderPlatform.instance = _FakePathProvider(tempDir.path);
+ });
+
+ setUp(() => SocialDB.instance.clearAllData());
+
+ tearDownAll(() async {
+ await (await SocialDB.instance.database).close();
+ PathProviderPlatform.instance = previousPathProvider;
+ await tempDir.delete(recursive: true);
+ });
+
+ test("heart state is file-wide across collections", () async {
+ await SocialDB.instance.upsertReactions([
+ _reaction(id: "visible", collectionID: 10, userID: 1),
+ _reaction(id: "hidden", collectionID: 20, userID: 2),
+ _reaction(id: "deleted", collectionID: 20, userID: 3, isDeleted: true),
+ _reaction(
+ id: "comment-reaction",
+ collectionID: 10,
+ userID: 4,
+ commentID: "comment",
+ ),
+ ]);
+
+ expect(await SocialDB.instance.hasUserReactedToFile(100, 1), isTrue);
+ expect(await SocialDB.instance.hasUserReactedToFile(100, 2), isTrue);
+ expect(await SocialDB.instance.hasUserReactedToFile(100, 3), isFalse);
+ expect(await SocialDB.instance.hasUserReactedToFile(100, 4), isFalse);
+ });
+
+ test("latest comment stays inside the eligible collection scope", () async {
+ await SocialDB.instance.upsertComments([
+ _comment(id: "visible", collectionID: 10, createdAt: 10),
+ _comment(id: "hidden", collectionID: 20, createdAt: 20),
+ ]);
+
+ final visibleLatest = await SocialDB.instance.getLatestCommentForFile(
+ 100,
+ candidateCollectionIDs: [10],
+ );
+ final hiddenLatest = await SocialDB.instance.getLatestCommentForFile(
+ 100,
+ candidateCollectionIDs: [20],
+ );
+
+ expect(visibleLatest?.id, "visible");
+ expect(hiddenLatest?.id, "hidden");
+ expect(
+ await SocialDB.instance.getLatestCommentForFile(
+ 100,
+ candidateCollectionIDs: const [],
+ ),
+ isNull,
+ );
+ });
+
+ test("comment count is aggregated across collections", () async {
+ await SocialDB.instance.upsertComments([
+ _comment(id: "visible", collectionID: 10, createdAt: 10),
+ _comment(id: "hidden", collectionID: 20, createdAt: 20),
+ _comment(id: "deleted", collectionID: 20, createdAt: 30, isDeleted: true),
+ ]);
+
+ expect(await SocialDB.instance.getCommentCountForFile(100), 2);
+ });
+}
+
+Reaction _reaction({
+ required String id,
+ required int collectionID,
+ required int userID,
+ bool isDeleted = false,
+ String? commentID,
+}) {
+ return Reaction(
+ id: id,
+ collectionID: collectionID,
+ fileID: 100,
+ commentID: commentID,
+ data: "❀",
+ isDeleted: isDeleted,
+ userID: userID,
+ createdAt: 1,
+ updatedAt: 1,
+ );
+}
+
+Comment _comment({
+ required String id,
+ required int collectionID,
+ required int createdAt,
+ bool isDeleted = false,
+}) {
+ return Comment(
+ id: id,
+ collectionID: collectionID,
+ fileID: 100,
+ data: id,
+ isDeleted: isDeleted,
+ userID: 1,
+ createdAt: createdAt,
+ updatedAt: createdAt,
+ );
+}
+
+class _FakePathProvider extends PathProviderPlatform {
+ _FakePathProvider(this.documentsPath);
+
+ final String documentsPath;
+
+ @override
+ Future<String?> getApplicationDocumentsPath() async => documentsPath;
+}
diff --git a/mobile/apps/photos/test/ui/social/file_social_context_test.dart b/mobile/apps/photos/test/ui/social/file_social_context_test.dart
new file mode 100644
index 0000000000..a512aef3cd
--- /dev/null
+++ b/mobile/apps/photos/test/ui/social/file_social_context_test.dart
@@ -0,0 +1,32 @@
+import "package:flutter_test/flutter_test.dart";
+import "package:photos/models/file/file.dart";
+import "package:photos/ui/social/widgets/file_social_overlay.dart";
+
+void main() {
+ test("non-hidden opening context excludes hidden collections", () {
+ expect(fileSocialContextIncludesHiddenCollections(10, {20}), isFalse);
+ });
+
+ test("hidden opening context includes all shared collections", () {
+ expect(fileSocialContextIncludesHiddenCollections(20, {20}), isTrue);
+ });
+
+ test(
+ "widget treats a changed collection ID as a different async context",
+ () {
+ final file = EnteFile()..uploadedFileID = 100;
+ final first = FileSocialOverlay(
+ file: file,
+ currentUserID: 1,
+ openingCollectionID: 10,
+ );
+ final second = FileSocialOverlay(
+ file: file,
+ currentUserID: 1,
+ openingCollectionID: 20,
+ );
+
+ expect(first.contextIdentity, isNot(second.contextIdentity));
+ },
+ );
+}