Skip to content

armgit / ente

Public Imported from GitHub
0

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

[mobile][photos] Add album sharing controls to Family (#11583)

neeraj-pilotcab2856ee3ab
diff --git a/mobile/apps/photos/assets/2.0x/ducky_full_library.png b/mobile/apps/photos/assets/2.0x/ducky_full_library.png
new file mode 100644
index 0000000000..313c4473ef
Binary files /dev/null and b/mobile/apps/photos/assets/2.0x/ducky_full_library.png differ
diff --git a/mobile/apps/photos/assets/3.0x/ducky_full_library.png b/mobile/apps/photos/assets/3.0x/ducky_full_library.png
new file mode 100644
index 0000000000..32102cce07
Binary files /dev/null and b/mobile/apps/photos/assets/3.0x/ducky_full_library.png differ
diff --git a/mobile/apps/photos/assets/ducky_full_library.png b/mobile/apps/photos/assets/ducky_full_library.png
new file mode 100644
index 0000000000..126dcf94b5
Binary files /dev/null and b/mobile/apps/photos/assets/ducky_full_library.png differ
diff --git a/mobile/apps/photos/lib/models/library_sharing/library_sharing_recipient.dart b/mobile/apps/photos/lib/models/library_sharing/library_sharing_recipient.dart
new file mode 100644
index 0000000000..ec47a5067d
--- /dev/null
+++ b/mobile/apps/photos/lib/models/library_sharing/library_sharing_recipient.dart
@@ -0,0 +1,16 @@
+class LibrarySharingRecipient {
+ const LibrarySharingRecipient({
+ required this.userID,
+ required this.email,
+ this.displayName,
+ });
+
+ final int userID;
+ final String email;
+ final String? displayName;
+
+ String get label {
+ final name = displayName?.trim();
+ return name == null || name.isEmpty ? email : name;
+ }
+}
diff --git a/mobile/apps/photos/lib/services/collections_service.dart b/mobile/apps/photos/lib/services/collections_service.dart
index b3d6841c1f..f27f70a021 100644
--- a/mobile/apps/photos/lib/services/collections_service.dart
+++ b/mobile/apps/photos/lib/services/collections_service.dart
@@ -796,6 +796,22 @@ class CollectionsService {
return sharees;
}
+ Future<List<User>> refreshSharees(int collectionID) async {
+ final sharees = await getSharees(collectionID);
+ final collection = _collectionIDToCollections[collectionID];
+ if (collection != null) {
+ _cacheSharees(collection, sharees);
+ }
+ return sharees;
+ }
+
+ void _cacheSharees(Collection collection, List<User> sharees) {
+ final updatedCollection = collection.copyWith(sharees: sharees);
+ _collectionIDToCollections[collection.id] = updatedCollection;
+ Bus.instance.fire(ContactRelationshipsInvalidatedEvent());
+ unawaited(_db.insert([updatedCollection]));
+ }
+
String getCastData(
String castToken,
Collection collection,
@@ -830,10 +846,7 @@ class CollectionsService {
encryptedKey: CryptoUtil.bin2base64(encryptedKey),
role: role.toStringVal(),
);
- _collectionIDToCollections[collectionID] =
- _collectionIDToCollections[collectionID]!.copyWith(sharees: sharees);
- Bus.instance.fire(ContactRelationshipsInvalidatedEvent());
- unawaited(_db.insert([_collectionIDToCollections[collectionID]!]));
+ _cacheSharees(_collectionIDToCollections[collectionID]!, sharees);
RemoteSyncService.instance.sync(silently: true).ignore();
return sharees;
} on DioException catch (e) {
@@ -850,10 +863,7 @@ class CollectionsService {
collectionID: collectionID,
email: email,
);
- _collectionIDToCollections[collectionID] =
- _collectionIDToCollections[collectionID]!.copyWith(sharees: sharees);
- Bus.instance.fire(ContactRelationshipsInvalidatedEvent());
- unawaited(_db.insert([_collectionIDToCollections[collectionID]!]));
+ _cacheSharees(_collectionIDToCollections[collectionID]!, sharees);
RemoteSyncService.instance.sync(silently: true).ignore();
return sharees;
} catch (e) {
diff --git a/mobile/apps/photos/lib/services/library_sharing_service.dart b/mobile/apps/photos/lib/services/library_sharing_service.dart
new file mode 100644
index 0000000000..399a61aec1
--- /dev/null
+++ b/mobile/apps/photos/lib/services/library_sharing_service.dart
@@ -0,0 +1,124 @@
+import 'package:dio/dio.dart';
+import 'package:photos/models/collection/collection.dart';
+import 'package:photos/services/account/user_service.dart';
+import 'package:photos/services/collections_service.dart';
+
+const librarySharingRoles = [
+ CollectionParticipantRole.viewer,
+ CollectionParticipantRole.collaborator,
+ CollectionParticipantRole.admin,
+];
+
+CollectionParticipantRole? librarySharingRoleFor(
+ Collection collection,
+ int userID,
+) {
+ for (final sharee in collection.sharees) {
+ if (sharee.id == userID) {
+ final role = CollectionParticipantRoleExtn.fromString(sharee.role);
+ return librarySharingRoles.contains(role) ? role : null;
+ }
+ }
+ return null;
+}
+
+abstract interface class LibrarySharingRepository {
+ Future<List<Collection>> getEligibleAlbums();
+
+ Future<String?> getPublicKey(String email);
+
+ Future<void> shareAlbum({
+ required Collection collection,
+ required String email,
+ required String publicKey,
+ required CollectionParticipantRole role,
+ });
+
+ Future<void> unshareAlbum({
+ required Collection collection,
+ required int recipientUserID,
+ required String email,
+ });
+}
+
+class LibrarySharingService implements LibrarySharingRepository {
+ LibrarySharingService({
+ CollectionsService? collectionsService,
+ UserService? userService,
+ }) : _collectionsService = collectionsService ?? CollectionsService.instance,
+ _userService = userService ?? UserService.instance;
+
+ final CollectionsService _collectionsService;
+ final UserService _userService;
+
+ @override
+ Future<List<Collection>> getEligibleAlbums() async {
+ final albums = _eligibleAlbums().toList();
+ await _collectionsService.sortCollectionsByAlbumPreferences(albums);
+ return albums;
+ }
+
+ static bool _isEligibleAlbum(Collection collection) {
+ final isShareableAlbum =
+ collection.type == CollectionType.album ||
+ collection.type == CollectionType.folder ||
+ collection.type == CollectionType.favorites;
+ return isShareableAlbum && !collection.isQuickLinkCollection();
+ }
+
+ @override
+ Future<String?> getPublicKey(String email) =>
+ _userService.getPublicKey(email);
+
+ @override
+ Future<void> shareAlbum({
+ required Collection collection,
+ required String email,
+ required String publicKey,
+ required CollectionParticipantRole role,
+ }) async {
+ await _collectionsService.share(collection.id, email, publicKey, role);
+ }
+
+ @override
+ Future<void> unshareAlbum({
+ required Collection collection,
+ required int recipientUserID,
+ required String email,
+ }) async {
+ try {
+ await _collectionsService.unshare(collection.id, email);
+ } on DioException catch (error, stackTrace) {
+ if (error.response?.statusCode != 404) {
+ Error.throwWithStackTrace(error, stackTrace);
+ }
+ // A 404 is idempotent only if fresh sharees confirm they are absent.
+ try {
+ final sharees = await _collectionsService.refreshSharees(collection.id);
+ if (!sharees.any((sharee) => sharee.id == recipientUserID)) {
+ return;
+ }
+ } catch (_) {}
+ Error.throwWithStackTrace(error, stackTrace);
+ }
+ }
+
+ Map<int, int> sharedAlbumCounts(Set<int> recipientUserIDs) {
+ if (recipientUserIDs.isEmpty) {
+ return const {};
+ }
+ final counts = {for (final userID in recipientUserIDs) userID: 0};
+ for (final album in _eligibleAlbums()) {
+ for (final userID in recipientUserIDs) {
+ if (librarySharingRoleFor(album, userID) != null) {
+ counts[userID] = counts[userID]! + 1;
+ }
+ }
+ }
+ return counts;
+ }
+
+ Iterable<Collection> _eligibleAlbums() => _collectionsService
+ .getCollectionsForUI(includeUncategorized: false)
+ .where(_isEligibleAlbum);
+}
diff --git a/mobile/apps/photos/lib/ui/collections/album/list_item.dart b/mobile/apps/photos/lib/ui/collections/album/list_item.dart
index 91257549b8..936017cb79 100644
--- a/mobile/apps/photos/lib/ui/collections/album/list_item.dart
+++ b/mobile/apps/photos/lib/ui/collections/album/list_item.dart
@@ -76,7 +76,7 @@ class AlbumListItemWidget extends StatelessWidget {
onLongPress: onLongPressCallback == null
? null
: () => onLongPressCallback!(collection),
- leading: _AlbumListItemCover(collection: collection),
+ leading: AlbumListItemCover(collection: collection),
title: _buildTitle(
context,
showSharingIndicator: showSharingIndicator,
@@ -267,48 +267,44 @@ class AlbumListItemWidget extends StatelessWidget {
}
}
-class _AlbumListItemCover extends StatelessWidget {
- final Collection collection;
+class AlbumListItemCover extends StatelessWidget {
+ const AlbumListItemCover({
+ required this.collection,
+ this.borderRadius = ThumbnailListItem.defaultLeadingRadius,
+ super.key,
+ });
- const _AlbumListItemCover({required this.collection});
+ final Collection collection;
+ final double borderRadius;
@override
Widget build(BuildContext context) {
- return Stack(
- clipBehavior: Clip.none,
- children: [
- ClipRRect(
- borderRadius: BorderRadius.circular(
- ThumbnailListItem.defaultLeadingRadius,
- ),
- child: SizedBox.expand(
- child: FutureBuilder<EnteFile?>(
- future: CollectionsService.instance.getCover(collection),
- initialData: CollectionsService.instance.getCoverCache(
- collection,
- ),
- builder: (context, snapshot) {
- final thumbnail =
- snapshot.data ??
- CollectionsService.instance.getCoverCache(collection);
- if (thumbnail != null) {
- return ThumbnailWidget(
- thumbnail,
- shouldShowFavoriteIcon: false,
- shouldShowOwnerAvatar: false,
- shouldShowSyncStatus: false,
- key: Key("album_list:${collection.id}:${thumbnail.tag}"),
- );
- }
- return const NoThumbnailWidget(
- borderRadius: ThumbnailListItem.defaultLeadingRadius,
- addBorder: false,
- );
- },
- ),
- ),
+ return ClipRRect(
+ borderRadius: BorderRadius.circular(borderRadius),
+ child: SizedBox.expand(
+ child: FutureBuilder<EnteFile?>(
+ future: CollectionsService.instance.getCover(collection),
+ initialData: CollectionsService.instance.getCoverCache(collection),
+ builder: (context, snapshot) {
+ final thumbnail =
+ snapshot.data ??
+ CollectionsService.instance.getCoverCache(collection);
+ if (thumbnail == null) {
+ return NoThumbnailWidget(
+ borderRadius: borderRadius,
+ addBorder: false,
+ );
+ }
+ return ThumbnailWidget(
+ thumbnail,
+ shouldShowFavoriteIcon: false,
+ shouldShowOwnerAvatar: false,
+ shouldShowSyncStatus: false,
+ key: Key("album_list:${collection.id}:${thumbnail.tag}"),
+ );
+ },
),
- ],
+ ),
);
}
}
diff --git a/mobile/apps/photos/lib/ui/collections/album/row_item.dart b/mobile/apps/photos/lib/ui/collections/album/row_item.dart
index 52b16a600d..552ccbe730 100644
--- a/mobile/apps/photos/lib/ui/collections/album/row_item.dart
+++ b/mobile/apps/photos/lib/ui/collections/album/row_item.dart
@@ -30,11 +30,13 @@ class AlbumRowItemWidget extends StatelessWidget {
final void Function(Collection)? onTapCallback;
final void Function(Collection)? onLongPressCallback;
final SelectedAlbums? selectedAlbums;
+ final bool? isSelected;
+ final Widget? Function(BuildContext, Collection)? topLeftOverlayBuilder;
+ final double titleToSubtitleSpacing;
static const _cornerRadius = 20.0;
static const _cornerSmoothing = 0.6;
static const _overlayPadding = 8.0;
static const _thumbnailToTextSpacing = 8.0;
- static const _titleToSubtitleSpacing = 2.0;
static const _sharePillPadding = EdgeInsets.all(1);
static const _sharedAvatarStrokeWidth = 1.0;
@@ -48,6 +50,9 @@ class AlbumRowItemWidget extends StatelessWidget {
this.onTapCallback,
this.onLongPressCallback,
this.selectedAlbums,
+ this.isSelected,
+ this.topLeftOverlayBuilder,
+ this.titleToSubtitleSpacing = 2,
});
@override
@@ -59,7 +64,10 @@ class AlbumRowItemWidget extends StatelessWidget {
"_" +
c.id.toString();
final componentColors = context.componentColors;
- final bool shouldShowSharePill = isOwner && (c.hasSharees || c.hasLink);
+ final externalSelection = isSelected;
+ final bool shouldShowSharePill =
+ topLeftOverlayBuilder == null && isOwner && (c.hasSharees || c.hasLink);
+ final topLeftOverlay = topLeftOverlayBuilder?.call(context, c);
final Widget? linkIcon = c.hasLink && isOwner
? HugeIcon(
icon: HugeIcons.strokeRoundedLink02,
@@ -71,7 +79,7 @@ class AlbumRowItemWidget extends StatelessWidget {
)
: null;
- return GestureDetector(
+ final row = GestureDetector(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
@@ -105,8 +113,10 @@ class AlbumRowItemWidget extends StatelessWidget {
.getCoverCache(c);
}
if (thumbnail != null) {
- final bool isSelected =
- selectedAlbums?.isAlbumSelected(c) ?? false;
+ final bool isAlbumSelected =
+ externalSelection ??
+ selectedAlbums?.isAlbumSelected(c) ??
+ false;
final String heroTag = tagPrefix + thumbnail.tag;
final thumbnailWidget = ThumbnailWidget(
thumbnail,
@@ -134,7 +144,7 @@ class AlbumRowItemWidget extends StatelessWidget {
fit: StackFit.expand,
children: [
thumbnailWidget,
- if (isSelected)
+ if (isAlbumSelected)
Container(
decoration: BoxDecoration(
color: componentColors.specialScrim
@@ -156,7 +166,13 @@ class AlbumRowItemWidget extends StatelessWidget {
}
},
),
- if (shouldShowSharePill)
+ if (topLeftOverlay != null)
+ Positioned(
+ top: _overlayPadding,
+ left: _overlayPadding,
+ child: topLeftOverlay,
+ )
+ else if (shouldShowSharePill)
Positioned(
top: _overlayPadding,
left: _overlayPadding,
@@ -182,29 +198,22 @@ class AlbumRowItemWidget extends StatelessWidget {
Positioned(
top: _overlayPadding,
right: _overlayPadding,
- child: selectedAlbums == null
- ? const SizedBox.shrink()
- : Hero(
+ child: externalSelection != null
+ ? _selectionBadge(externalSelection)
+ : selectedAlbums != null
+ ? Hero(
tag: tagPrefix + "_album_selection",
transitionOnUserGestures: true,
child: ListenableBuilder(
listenable: selectedAlbums!,
builder: (context, _) {
- final bool isSelected = selectedAlbums!
+ final isAlbumSelected = selectedAlbums!
.isAlbumSelected(c);
- return AnimatedSwitcher(
- duration: const Duration(
- milliseconds: 200,
- ),
- switchInCurve: Curves.easeOut,
- switchOutCurve: Curves.easeIn,
- child: isSelected
- ? const CollectionSelectedBadge()
- : null,
- );
+ return _selectionBadge(isAlbumSelected);
},
),
- ),
+ )
+ : const SizedBox.shrink(),
),
if (!isOwner)
Positioned(
@@ -292,7 +301,7 @@ class AlbumRowItemWidget extends StatelessWidget {
softWrap: false,
overflow: TextOverflow.ellipsis,
),
- const SizedBox(height: _titleToSubtitleSpacing),
+ SizedBox(height: titleToSubtitleSpacing),
Text(
textCount,
style: TextStyles.mini.copyWith(
@@ -353,6 +362,18 @@ class AlbumRowItemWidget extends StatelessWidget {
}
},
);
+ return externalSelection == null
+ ? row
+ : Semantics(button: true, selected: externalSelection, child: row);
+ }
+
+ Widget _selectionBadge(bool isSelected) {
+ return AnimatedSwitcher(
+ duration: const Duration(milliseconds: 200),
+ switchInCurve: Curves.easeOut,
+ switchOutCurve: Curves.easeIn,
+ child: isSelected ? const CollectionSelectedBadge() : null,
+ );
}
Widget _buildAlbumStatusChips({required bool isOwner}) {
diff --git a/mobile/apps/photos/lib/ui/collections/flex_grid_view.dart b/mobile/apps/photos/lib/ui/collections/flex_grid_view.dart
index 1a3fd39eb9..ef5df0e55f 100644
--- a/mobile/apps/photos/lib/ui/collections/flex_grid_view.dart
+++ b/mobile/apps/photos/lib/ui/collections/flex_grid_view.dart
@@ -24,6 +24,38 @@ import "package:photos/ui/components/thumbnail_list_item.dart";
import "package:photos/ui/viewer/gallery/collection_page.dart";
import "package:photos/utils/dialog_util.dart";
+class AlbumGridLayout {
+ const AlbumGridLayout({
+ this.horizontalPadding = 8,
+ this.crossAxisSpacing = 8,
+ this.mainAxisSpacing = 24,
+ this.titleToSubtitleSpacing = 2,
+ });
+
+ static const standard = AlbumGridLayout();
+ static const dense = AlbumGridLayout(
+ horizontalPadding: 16,
+ crossAxisSpacing: 10,
+ mainAxisSpacing: 8,
+ titleToSubtitleSpacing: 4,
+ );
+
+ final double horizontalPadding;
+ final double crossAxisSpacing;
+ final double mainAxisSpacing;
+ final double titleToSubtitleSpacing;
+
+ double thumbnailSideFor({required double width, required int columnCount}) {
+ final totalSpacing = (columnCount - 1) * crossAxisSpacing;
+ return (width - horizontalPadding * 2 - totalSpacing) / columnCount;
+ }
+}
+
+typedef AlbumSelectionCallbacks = ({
+ bool Function(Collection) isSelected,
+ ValueChanged<Collection> toggle,
+});
+
class CollectionsFlexiGridViewWidget extends StatefulWidget {
/*
Aspect ratio 1:1
@@ -31,10 +63,7 @@ class CollectionsFlexiGridViewWidget extends StatefulWidget {
*/
static const maxThumbnailWidth = 224.0;
- static const crossAxisSpacing = 8.0;
- static const horizontalPadding = 16.0;
static const _thumbnailToTextSpacing = 8.0;
- static const _titleToSubtitleSpacing = 2.0;
final List<Collection>? collections;
// If true, the GridView will shrink-wrap its contents.
@@ -46,9 +75,12 @@ class CollectionsFlexiGridViewWidget extends StatefulWidget {
final bool shouldShowCreateAlbum;
final SelectedAlbums? selectedAlbums;
final bool onlyAllowSelection;
+ final AlbumSelectionCallbacks? selectionCallbacks;
+ final Widget? Function(BuildContext, Collection)? gridTopLeftOverlayBuilder;
final UISectionType? sectionType;
final double topPadding;
final double bottomPadding;
+ final AlbumGridLayout gridLayout;
const CollectionsFlexiGridViewWidget(
this.collections, {
@@ -60,10 +92,13 @@ class CollectionsFlexiGridViewWidget extends StatefulWidget {
this.shouldShowCreateAlbum = false,
this.selectedAlbums,
this.onlyAllowSelection = false,
+ this.selectionCallbacks,
+ this.gridTopLeftOverlayBuilder,
this.sectionType,
this.topPadding = 16,
this.bottomPadding = 200,
- });
+ this.gridLayout = AlbumGridLayout.standard,
+ }) : assert(selectedAlbums == null || selectionCallbacks == null);
@override
State<CollectionsFlexiGridViewWidget> createState() =>
@@ -98,12 +133,38 @@ class _CollectionsFlexiGridViewWidgetState
Future<void> _toggleAlbumSelection(Collection c) async {
await HapticFeedback.lightImpact();
+ final callbacks = widget.selectionCallbacks;
+ if (callbacks != null) {
+ callbacks.toggle(c);
+ return;
+ }
widget.selectedAlbums!.toggleSelection(c);
setState(() {
isAnyAlbumSelected = widget.selectedAlbums!.albums.isNotEmpty;
});
}
+ bool get _togglesSelectionOnTap =>
+ widget.selectionCallbacks != null ||
+ isAnyAlbumSelected ||
+ widget.onlyAllowSelection;
+
+ void _handleCollectionTap(Collection collection) {
+ unawaited(
+ _togglesSelectionOnTap
+ ? _toggleAlbumSelection(collection)
+ : _navigateToCollectionPage(collection),
+ );
+ }
+
+ void _handleCollectionLongPress(Collection collection) {
+ unawaited(
+ _togglesSelectionOnTap
+ ? _navigateToCollectionPage(collection)
+ : _toggleAlbumSelection(collection),
+ );
+ }
+
Future<void> _navigateToCollectionPage(Collection c) async {
final thumbnail = await CollectionsService.instance.getCover(c);
final bool isOwner = c.isOwner(Configuration.instance.getUserID()!);
@@ -147,14 +208,15 @@ class _CollectionsFlexiGridViewWidgetState
@override
Widget build(BuildContext context) {
+ final usesExternalSelection = widget.selectionCallbacks != null;
return PopScope(
- canPop: !isAnyAlbumSelected,
+ canPop: usesExternalSelection || !isAnyAlbumSelected,
onPopInvokedWithResult: (didPop, _) {
- if (didPop) {
+ if (didPop || usesExternalSelection) {
return;
}
if (isAnyAlbumSelected) {
- widget.selectedAlbums!.clearAll();
+ widget.selectedAlbums?.clearAll();
setState(() {
isAnyAlbumSelected = false;
});
@@ -167,20 +229,16 @@ class _CollectionsFlexiGridViewWidgetState
}
Widget _buildGridView(BuildContext context, Key key) {
+ final selectionCallbacks = widget.selectionCallbacks;
final double screenWidth = MediaQuery.sizeOf(context).width;
final int albumsCountInCrossAxis = max(
screenWidth ~/ CollectionsFlexiGridViewWidget.maxThumbnailWidth,
3,
);
- final double totalCrossAxisSpacing =
- (albumsCountInCrossAxis - 1) *
- CollectionsFlexiGridViewWidget.crossAxisSpacing;
-
- final double sideOfThumbnail =
- (screenWidth -
- totalCrossAxisSpacing -
- CollectionsFlexiGridViewWidget.horizontalPadding) /
- albumsCountInCrossAxis;
+ final double sideOfThumbnail = widget.gridLayout.thumbnailSideFor(
+ width: screenWidth,
+ columnCount: albumsCountInCrossAxis,
+ );
final double gridItemTextHeight = _gridItemTextHeight(context);
final int totalCollections = widget.collections!.length;
final bool showCreateAlbum = widget.shouldShowCreateAlbum;
@@ -190,8 +248,8 @@ class _CollectionsFlexiGridViewWidgetState
key: key,
padding: EdgeInsets.only(
top: widget.topPadding,
- left: CollectionsFlexiGridViewWidget.horizontalPadding / 2,
- right: CollectionsFlexiGridViewWidget.horizontalPadding / 2,
+ left: widget.gridLayout.horizontalPadding,
+ right: widget.gridLayout.horizontalPadding,
bottom: widget.bottomPadding,
),
sliver: SliverGrid(
@@ -212,24 +270,21 @@ class _CollectionsFlexiGridViewWidgetState
),
tag: widget.tag,
selectedAlbums: widget.selectedAlbums,
- onTapCallback: (c) {
- isAnyAlbumSelected || widget.onlyAllowSelection
- ? _toggleAlbumSelection(c)
- : _navigateToCollectionPage(c);
- },
+ isSelected: selectionCallbacks?.isSelected(
+ widget.collections![collectionIndex],
+ ),
+ topLeftOverlayBuilder: widget.gridTopLeftOverlayBuilder,
+ titleToSubtitleSpacing: widget.gridLayout.titleToSubtitleSpacing,
+ onTapCallback: _handleCollectionTap,
onLongPressCallback: widget.enableSelectionMode
- ? (c) {
- isAnyAlbumSelected || widget.onlyAllowSelection
- ? _navigateToCollectionPage(c)
- : _toggleAlbumSelection(c);
- }
+ ? _handleCollectionLongPress
: null,
);
}, childCount: displayItemCount),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: albumsCountInCrossAxis,
- mainAxisSpacing: 24,
- crossAxisSpacing: CollectionsFlexiGridViewWidget.crossAxisSpacing,
+ mainAxisSpacing: widget.gridLayout.mainAxisSpacing,
+ crossAxisSpacing: widget.gridLayout.crossAxisSpacing,
childAspectRatio:
sideOfThumbnail / (sideOfThumbnail + gridItemTextHeight),
),
@@ -241,7 +296,7 @@ class _CollectionsFlexiGridViewWidgetState
final textScaler = MediaQuery.textScalerOf(context);
return (CollectionsFlexiGridViewWidget._thumbnailToTextSpacing +
_scaledLineHeight(textScaler, TextStyles.body) +
- CollectionsFlexiGridViewWidget._titleToSubtitleSpacing +
+ widget.gridLayout.titleToSubtitleSpacing +
_scaledLineHeight(textScaler, TextStyles.mini))
.ceilToDouble();
}
@@ -252,6 +307,7 @@ class _CollectionsFlexiGridViewWidgetState
}
Widget _buildListView(BuildContext context, Key key) {
+ final selectionCallbacks = widget.selectionCallbacks;
final int totalCollections = widget.collections?.length ?? 0;
final bool showCreateAlbum =
widget.shouldShowCreateAlbum && !isAnyAlbumSelected;
@@ -284,17 +340,10 @@ class _CollectionsFlexiGridViewWidgetState
item = AlbumListItemWidget(
collection,
selectedAlbums: widget.selectedAlbums,
- onTapCallback: (c) {
- isAnyAlbumSelected
- ? _toggleAlbumSelection(c)
- : _navigateToCollectionPage(c);
- },
+ isSelected: selectionCallbacks?.isSelected(collection) ?? false,
+ onTapCallback: _handleCollectionTap,
onLongPressCallback: widget.enableSelectionMode
- ? (c) {
- isAnyAlbumSelected
- ? _navigateToCollectionPage(c)
- : _toggleAlbumSelection(c);
- }
+ ? _handleCollectionLongPress
: null,
);
}
diff --git a/mobile/apps/photos/lib/ui/components/empty_state_component.dart b/mobile/apps/photos/lib/ui/components/empty_state_component.dart
index 93317e85f0..994fcadfc4 100644
--- a/mobile/apps/photos/lib/ui/components/empty_state_component.dart
+++ b/mobile/apps/photos/lib/ui/components/empty_state_component.dart
@@ -8,6 +8,7 @@ class EmptyStateComponent extends StatelessWidget {
this.textWidth = 285,
this.spacing = 20,
this.padding = const EdgeInsets.all(24),
+ this.alignment = Alignment.center,
super.key,
});
@@ -17,10 +18,13 @@ class EmptyStateComponent extends StatelessWidget {
final double spacing;
final EdgeInsetsGeometry padding;
+ final AlignmentGeometry alignment;
+
@override
Widget build(BuildContext context) {
final colors = context.componentColors;
- return Center(
+ return Align(
+ alignment: alignment,
child: Padding(
padding: padding,
child: Column(
diff --git a/mobile/apps/photos/lib/ui/family/family_dashboard.dart b/mobile/apps/photos/lib/ui/family/family_dashboard.dart
index cb6da2549d..af13550250 100644
--- a/mobile/apps/photos/lib/ui/family/family_dashboard.dart
+++ b/mobile/apps/photos/lib/ui/family/family_dashboard.dart
@@ -7,12 +7,14 @@ import 'package:flutter/material.dart';
import 'package:hugeicons/hugeicons.dart';
import 'package:photos/generated/l10n.dart';
import 'package:photos/models/user_details.dart';
+import 'package:photos/ui/sharing/library_sharing/library_sharing_strings.dart';
import 'package:photos/ui/viewer/people/person_face_widget.dart';
import 'package:photos/utils/avatar_util.dart';
enum FamilyMemberAction {
saveContact,
editContact,
+ shareAlbums,
editStorageLimit,
removeMember,
resendInvite,
@@ -30,6 +32,7 @@ List<FamilyMemberAction> familyMemberActions({
required bool isCurrentUser,
required FamilyMember member,
required bool hasSavedContact,
+ bool librarySharingEnabled = false,
}) {
if (isCurrentUser) {
return const [];
@@ -40,10 +43,15 @@ List<FamilyMemberAction> familyMemberActions({
: hasSavedContact
? FamilyMemberAction.editContact
: FamilyMemberAction.saveContact;
+ final shareAction =
+ librarySharingEnabled && member.userID != null && member.isActive
+ ? FamilyMemberAction.shareAlbums
+ : null;
if (isAdmin) {
return [
?contactAction,
+ ?shareAction,
if (member.isPending) ...[
FamilyMemberAction.resendInvite,
FamilyMemberAction.revokeInvite,
@@ -57,7 +65,7 @@ List<FamilyMemberAction> familyMemberActions({
if (!member.isActive || contactAction == null) {
return const [];
}
- return [contactAction];
+ return [contactAction, ?shareAction];
}
class FamilyDashboard extends StatelessWidget {
@@ -69,6 +77,8 @@ class FamilyDashboard extends StatelessWidget {
required this.profilePictureBytesByUserId,
required this.linkedPersonIdsByUserId,
required this.linkedPersonNamesByUserId,
+ this.librarySharingEnabled = false,
+ this.sharedAlbumCountsByUserId = const {},
required this.onMemberTap,
required this.onAddMember,
required this.remainingSlots,
@@ -82,6 +92,8 @@ class FamilyDashboard extends StatelessWidget {
final Map<int, Uint8List?> profilePictureBytesByUserId;
final Map<int, String> linkedPersonIdsByUserId;
final Map<int, String> linkedPersonNamesByUserId;
+ final bool librarySharingEnabled;
+ final Map<int, int> sharedAlbumCountsByUserId;
final void Function(FamilyMember member, String displayName) onMemberTap;
final VoidCallback onAddMember;
final int remainingSlots;
@@ -117,7 +129,11 @@ class FamilyDashboard extends StatelessWidget {
profilePictureBytes: profilePictureBytesByUserId[member.userID],
linkedPersonId: linkedPersonIdsByUserId[member.userID],
hasSavedContact: contactsByUserId[member.userID] != null,
+ librarySharingEnabled: librarySharingEnabled,
avatarColor: _avatarColorFor(member),
+ sharedAlbumCount: librarySharingEnabled
+ ? sharedAlbumCountsByUserId[member.userID]
+ : null,
onTap: () => onMemberTap(member, _displayNameFor(member)),
),
if (index < visibleMembers.length - 1)
@@ -351,7 +367,9 @@ class _FamilyMemberRow extends StatelessWidget {
required this.profilePictureBytes,
required this.linkedPersonId,
required this.hasSavedContact,
+ required this.librarySharingEnabled,
required this.avatarColor,
+ this.sharedAlbumCount,
required this.onTap,
});
@@ -362,7 +380,9 @@ class _FamilyMemberRow extends StatelessWidget {
final Uint8List? profilePictureBytes;
final String? linkedPersonId;
final bool hasSavedContact;
+ final bool librarySharingEnabled;
final AvatarComponentColor avatarColor;
+ final int? sharedAlbumCount;
final VoidCallback onTap;
@override
@@ -373,13 +393,17 @@ class _FamilyMemberRow extends StatelessWidget {
isCurrentUser: isCurrentUser,
member: member,
hasSavedContact: hasSavedContact,
+ librarySharingEnabled: librarySharingEnabled,
);
final isInteractive = actions.isNotEmpty;
+ final storageUsage = l10n.memberStorageUsed(
+ amount: convertBytesToReadableFormat(member.usage),
+ );
final subtitle = member.isPending
? l10n.pending
- : l10n.memberStorageUsed(
- amount: convertBytesToReadableFormat(member.usage),
- );
+ : isCurrentUser || member.userID == null || sharedAlbumCount == null
+ ? storageUsage
+ : LibrarySharingStrings.memberSubtitle(sharedAlbumCount!, storageUsage);
return MenuComponent(
title: displayName,
diff --git a/mobile/apps/photos/lib/ui/family/family_plan_page.dart b/mobile/apps/photos/lib/ui/family/family_plan_page.dart
index c168646399..4535773935 100644
--- a/mobile/apps/photos/lib/ui/family/family_plan_page.dart
+++ b/mobile/apps/photos/lib/ui/family/family_plan_page.dart
@@ -9,14 +9,17 @@ import 'package:ente_pure_utils/ente_pure_utils.dart';
import 'package:flutter/material.dart';
import 'package:hugeicons/hugeicons.dart';
import 'package:photos/core/event_bus.dart';
+import 'package:photos/events/collection_updated_event.dart';
import 'package:photos/events/contacts_changed_event.dart';
import 'package:photos/events/people_changed_event.dart';
import 'package:photos/gateways/billing/models/billing_plan.dart';
import 'package:photos/gateways/billing/models/subscription.dart';
import 'package:photos/generated/l10n.dart';
+import 'package:photos/models/library_sharing/library_sharing_recipient.dart';
import 'package:photos/models/user_details.dart';
import 'package:photos/service_locator.dart';
import 'package:photos/services/family_service.dart';
+import 'package:photos/services/library_sharing_service.dart';
import 'package:photos/services/machine_learning/face_ml/person/person_service.dart';
import 'package:photos/services/photos_contacts_service.dart';
import 'package:photos/theme/ente_theme.dart';
@@ -28,6 +31,8 @@ import 'package:photos/ui/family/family_ui.dart';
import 'package:photos/ui/family/invite_members_page.dart';
import 'package:photos/ui/notification/toast.dart';
import 'package:photos/ui/payment/subscription.dart';
+import 'package:photos/ui/sharing/library_sharing/library_sharing_page.dart';
+import 'package:photos/ui/sharing/library_sharing/library_sharing_strings.dart';
import 'package:photos/ui/viewer/search/result/edit_contact_page.dart';
import 'package:photos/utils/dialog_util.dart';
@@ -54,11 +59,15 @@ class _FamilyPlanPageState extends State<FamilyPlanPage> {
static const double _advertBalancedMinHeight = 560;
late UserDetails _userDetails = widget.initialUserDetails;
+ late final LibrarySharingService _librarySharingService =
+ LibrarySharingService();
final Map<int, contacts.ContactRecord?> _contactsByUserId = {};
final Map<int, Uint8List?> _profilePictureBytesByUserId = {};
+ Map<int, int> _sharedAlbumCountsByUserId = const {};
String? _startingPrice;
bool _isRefreshing = false;
int _memberContactsLoadGeneration = 0;
+ StreamSubscription<CollectionUpdatedEvent>? _collectionUpdatedSubscription;
StreamSubscription<ContactsChangedEvent>? _contactsChangedSubscription;
StreamSubscription<PeopleChangedEvent>? _peopleChangedSubscription;
@@ -78,6 +87,8 @@ class _FamilyPlanPageState extends State<FamilyPlanPage> {
bool get _showsDashboard => _showsAdminDashboard || _showsMemberDashboard;
+ bool get _librarySharingEnabled => flagService.librarySharing;
+
int get _remainingSlots {
final memberCount =
_userDetails.familyData?.members
@@ -96,6 +107,12 @@ class _FamilyPlanPageState extends State<FamilyPlanPage> {
unawaited(_refreshUserDetails());
}
unawaited(_loadMemberContacts());
+ if (_librarySharingEnabled) {
+ _loadSharedAlbumCounts();
+ _collectionUpdatedSubscription = Bus.instance
+ .on<CollectionUpdatedEvent>()
+ .listen(_onCollectionUpdated);
+ }
_contactsChangedSubscription = Bus.instance
.on<ContactsChangedEvent>()
.listen(_onContactsChanged);
@@ -113,6 +130,7 @@ class _FamilyPlanPageState extends State<FamilyPlanPage> {
@override
void dispose() {
+ _collectionUpdatedSubscription?.cancel();
_contactsChangedSubscription?.cancel();
_peopleChangedSubscription?.cancel();
super.dispose();
@@ -128,6 +146,13 @@ class _FamilyPlanPageState extends State<FamilyPlanPage> {
unawaited(_loadMemberContacts());
}
+ void _onCollectionUpdated(CollectionUpdatedEvent event) {
+ if (!mounted || !_showsDashboard || event.updatedFiles.isNotEmpty) {
+ return;
+ }
+ _loadSharedAlbumCounts();
+ }
+
@override
Widget build(BuildContext context) {
final content = _showsAdminDashboard
@@ -357,6 +382,8 @@ class _FamilyPlanPageState extends State<FamilyPlanPage> {
profilePictureBytesByUserId: _profilePictureBytesByUserId,
linkedPersonIdsByUserId: linkedPersons.idsByUserId,
linkedPersonNamesByUserId: linkedPersons.namesByUserId,
+ librarySharingEnabled: _librarySharingEnabled,
+ sharedAlbumCountsByUserId: _sharedAlbumCountsByUserId,
onMemberTap: _showMemberActions,
onAddMember: () => unawaited(_openInvitePage()),
remainingSlots: _remainingSlots,
@@ -448,6 +475,7 @@ class _FamilyPlanPageState extends State<FamilyPlanPage> {
}
setState(() => _userDetails = details);
unawaited(_loadMemberContacts());
+ _loadSharedAlbumCounts();
} catch (error) {
if (mounted && showError) {
await showGenericErrorDialog(context: context, error: error);
@@ -495,6 +523,7 @@ class _FamilyPlanPageState extends State<FamilyPlanPage> {
isCurrentUser: isCurrentUser,
member: member,
hasSavedContact: savedContact != null,
+ librarySharingEnabled: _librarySharingEnabled,
);
if (actions.isEmpty) {
return;
@@ -547,6 +576,8 @@ class _FamilyPlanPageState extends State<FamilyPlanPage> {
final actionLabel = switch (action) {
FamilyMemberAction.saveContact => l10n.saveContact,
FamilyMemberAction.editContact => l10n.editContact,
+ FamilyMemberAction.shareAlbums =>
+ LibrarySharingStrings.internalShareAlbums,
FamilyMemberAction.editStorageLimit => l10n.editStorageLimit,
FamilyMemberAction.removeMember => l10n.removeFromFamily,
FamilyMemberAction.resendInvite => l10n.resendInvite,
@@ -555,6 +586,7 @@ class _FamilyPlanPageState extends State<FamilyPlanPage> {
final icon = switch (action) {
FamilyMemberAction.saveContact => HugeIcons.strokeRoundedUserAdd01,
FamilyMemberAction.editContact => HugeIcons.strokeRoundedEdit03,
+ FamilyMemberAction.shareAlbums => HugeIcons.strokeRoundedAlbum02,
FamilyMemberAction.editStorageLimit =>
HugeIcons.strokeRoundedFilterHorizontal,
FamilyMemberAction.removeMember => HugeIcons.strokeRoundedUserRemove01,
@@ -564,11 +596,18 @@ class _FamilyPlanPageState extends State<FamilyPlanPage> {
final isDestructive =
action == FamilyMemberAction.removeMember ||
action == FamilyMemberAction.revokeInvite;
- final subtitle = action == FamilyMemberAction.editStorageLimit
- ? member.storageLimit == null
- ? l10n.noLimitSet
- : convertBytesToReadableFormat(member.storageLimit!)
- : null;
+ final sharedAlbumCount = _sharedAlbumCountsByUserId[member.userID];
+ final subtitle = switch (action) {
+ FamilyMemberAction.shareAlbums =>
+ sharedAlbumCount == null
+ ? null
+ : LibrarySharingStrings.sharedAlbumCount(sharedAlbumCount),
+ FamilyMemberAction.editStorageLimit =>
+ member.storageLimit == null
+ ? l10n.noLimitSet
+ : convertBytesToReadableFormat(member.storageLimit!),
+ _ => null,
+ };
return MenuComponent(
title: actionLabel,
@@ -584,6 +623,9 @@ class _FamilyPlanPageState extends State<FamilyPlanPage> {
case FamilyMemberAction.editContact:
await _openMemberContact(member);
break;
+ case FamilyMemberAction.shareAlbums:
+ await _openLibrarySharing(member, displayName);
+ break;
case FamilyMemberAction.editStorageLimit:
final updatedUserDetails = await routeToPage<UserDetails>(
context,
@@ -693,6 +735,40 @@ class _FamilyPlanPageState extends State<FamilyPlanPage> {
});
}
+ void _loadSharedAlbumCounts() {
+ if (!mounted || !_showsDashboard || !_librarySharingEnabled) {
+ return;
+ }
+ setState(() {
+ _sharedAlbumCountsByUserId = _librarySharingService.sharedAlbumCounts(
+ _familyMemberUserIDs(),
+ );
+ });
+ }
+
+ Future<void> _openLibrarySharing(
+ FamilyMember member,
+ String displayName,
+ ) async {
+ final userID = member.userID;
+ if (!_librarySharingEnabled || userID == null || !member.isActive) {
+ return;
+ }
+ await routeToPage(
+ context,
+ LibrarySharingPage(
+ recipient: LibrarySharingRecipient(
+ userID: userID,
+ email: member.email,
+ displayName: displayName,
+ ),
+ ),
+ );
+ if (mounted) {
+ _loadSharedAlbumCounts();
+ }
+ }
+
Set<int> _familyMemberUserIDs() =>
_userDetails.familyData?.members
?.map((member) => member.userID)
diff --git a/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_controller.dart b/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_controller.dart
new file mode 100644
index 0000000000..48b01ea079
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_controller.dart
@@ -0,0 +1,341 @@
+import 'package:flutter/foundation.dart';
+import 'package:logging/logging.dart';
+import 'package:photos/models/collection/collection.dart';
+import 'package:photos/models/library_sharing/library_sharing_recipient.dart';
+import 'package:photos/services/library_sharing_service.dart';
+
+enum _LibrarySharingSelectionMode { add, manage }
+
+class LibrarySharingController extends ChangeNotifier {
+ LibrarySharingController({
+ required this.recipient,
+ required LibrarySharingRepository repository,
+ }) : _repository = repository;
+
+ final LibrarySharingRecipient recipient;
+ final LibrarySharingRepository _repository;
+ final _logger = Logger('LibrarySharingController');
+
+ List<Collection> _albums = const [];
+ final Map<int, CollectionParticipantRole> _activeRoles = {};
+ final Map<int, CollectionParticipantRole> _selectedRoles = {};
+ CollectionParticipantRole _defaultRole = CollectionParticipantRole.admin;
+ Object? _loadError;
+ int _failedCount = 0;
+ bool _isLoading = true;
+ bool _isMutating = false;
+ _LibrarySharingSelectionMode? _selectionMode;
+ bool _isDisposed = false;
+
+ int get eligibleAlbumCount => _albums.length;
+ int get selectableAlbumCount => _albums.where(_isVisible).length;
+ List<Collection> get visibleAlbums =>
+ List.unmodifiable(_albums.where(_isVisible));
+ List<Collection> get selectedAlbums => _albums
+ .where((album) => _selectedRoles.containsKey(album.id))
+ .toList(growable: false);
+ int get failedCount => _failedCount;
+ Object? get loadError => _loadError;
+ bool get isLoading => _isLoading;
+ bool get isMutating => _isMutating;
+ bool get isFirstTime => _activeRoles.isEmpty;
+ bool get isAddingAlbums =>
+ isFirstTime || _selectionMode == _LibrarySharingSelectionMode.add;
+ bool get isSelecting =>
+ !_isLoading &&
+ _loadError == null &&
+ (_selectionMode != null || isFirstTime);
+ bool get hasSelection => _selectedRoles.isNotEmpty;
+ int get selectedCount => _selectedRoles.length;
+ int get selectedActiveShareCount =>
+ _selectedRoles.keys.where(_isShared).length;
+ bool get canStopSharing => selectedActiveShareCount > 0 && !_isMutating;
+ bool get canApply => hasSelection && !_isMutating;
+
+ CollectionParticipantRole? get selectedRole {
+ if (_selectedRoles.isEmpty) {
+ return _defaultRole;
+ }
+ final role = _selectedRoles.values.first;
+ return _selectedRoles.values.every((value) => value == role) ? role : null;
+ }
+
+ Future<void> load() async {
+ if (_isDisposed || _isMutating) {
+ return;
+ }
+ _isLoading = true;
+ _loadError = null;
+ _notifyListeners();
+ try {
+ await _reloadAlbums();
+ } catch (error) {
+ _loadError = error;
+ } finally {
+ _isLoading = false;
+ _notifyListeners();
+ }
+ }
+
+ void enterAddMode() => _enterSelectionMode(_LibrarySharingSelectionMode.add);
+
+ void enterManageMode() =>
+ _enterSelectionMode(_LibrarySharingSelectionMode.manage);
+
+ void _enterSelectionMode(_LibrarySharingSelectionMode mode) {
+ if (_isLoading || _loadError != null || _isMutating) {
+ return;
+ }
+ if (_selectionMode != mode) {
+ _clearSelectionState();
+ }
+ _selectionMode = mode;
+ _notifyListeners();
+ }
+
+ void exitSelectionMode() {
+ if (isFirstTime || _isMutating) {
+ return;
+ }
+ _selectionMode = null;
+ _clearSelectionState();
+ _notifyListeners();
+ }
+
+ bool isSelected(Collection collection) =>
+ _selectedRoles.containsKey(collection.id);
+
+ CollectionParticipantRole? activeRoleFor(int collectionID) =>
+ _activeRoles[collectionID];
+
+ CollectionParticipantRole stagedRoleFor(int collectionID) =>
+ _selectedRoles[collectionID] ??
+ activeRoleFor(collectionID) ??
+ _defaultRole;
+
+ void toggleSelection(Collection collection) {
+ if (_isMutating || !isSelecting || !_isVisible(collection)) {
+ return;
+ }
+ final id = collection.id;
+ _failedCount = 0;
+ if (_selectedRoles.remove(id) == null) {
+ _selectedRoles[id] = activeRoleFor(id) ?? _defaultRole;
+ }
+ _exitEmptyManageMode();
+ _notifyListeners();
+ }
+
+ void selectAll() {
+ if (_isMutating || !isSelecting) {
+ return;
+ }
+ for (final album in _albums.where(_isVisible)) {
+ _selectedRoles[album.id] ??= activeRoleFor(album.id) ?? _defaultRole;
+ }
+ _failedCount = 0;
+ _notifyListeners();
+ }
+
+ void clearSelection() {
+ if (_isMutating) {
+ return;
+ }
+ _clearSelectionState();
+ _exitEmptyManageMode();
+ _notifyListeners();
+ }
+
+ void setRoleForSelection(CollectionParticipantRole role) {
+ if (_isMutating) {
+ return;
+ }
+ _defaultRole = role;
+ _selectedRoles.updateAll((_, _) => role);
+ _notifyListeners();
+ }
+
+ void setRoleForAlbum(int collectionID, CollectionParticipantRole role) {
+ if (_isMutating || !_selectedRoles.containsKey(collectionID)) {
+ return;
+ }
+ _selectedRoles[collectionID] = role;
+ _notifyListeners();
+ }
+
+ Future<bool> applySelection() async {
+ if (!canApply) {
+ return false;
+ }
+ final intendedRoles = {
+ for (final entry in _selectedRoles.entries)
+ if (_activeRoles[entry.key] != entry.value) entry.key: entry.value,
+ };
+ if (intendedRoles.isEmpty) {
+ exitSelectionMode();
+ return true;
+ }
+
+ _beginMutation();
+ late final String publicKey;
+ try {
+ final key = await _repository.getPublicKey(recipient.email);
+ if (key == null || key.isEmpty) {
+ throw StateError('No Ente public key found for recipient');
+ }
+ publicKey = key;
+ } catch (error, stackTrace) {
+ _logger.warning(
+ 'Failed to fetch recipient public key',
+ error,
+ stackTrace,
+ );
+ _isMutating = false;
+ _notifyListeners();
+ return false;
+ }
+
+ return _mutateAlbums(
+ intendedRoles.keys.toSet(),
+ (album, collectionID) => _repository.shareAlbum(
+ collection: album,
+ email: recipient.email,
+ publicKey: publicKey,
+ role: intendedRoles[collectionID]!,
+ ),
+ onSucceeded: (collectionID) {
+ _activeRoles[collectionID] = intendedRoles[collectionID]!;
+ },
+ );
+ }
+
+ Future<bool> stopSharingSelected() async {
+ if (!canStopSharing) {
+ return false;
+ }
+ final pendingIDs = _selectedRoles.keys.where(_isShared).toSet();
+ _beginMutation();
+ return _mutateAlbums(
+ pendingIDs,
+ (album, _) => _repository.unshareAlbum(
+ collection: album,
+ recipientUserID: recipient.userID,
+ email: recipient.email,
+ ),
+ onSucceeded: _activeRoles.remove,
+ );
+ }
+
+ void _beginMutation() {
+ _isMutating = true;
+ _failedCount = 0;
+ _notifyListeners();
+ }
+
+ Future<bool> _mutateAlbums(
+ Set<int> collectionIDs,
+ Future<void> Function(Collection album, int collectionID) mutate, {
+ required ValueChanged<int> onSucceeded,
+ }) async {
+ final failedIDs = <int>{};
+ final albumsByID = {for (final album in _albums) album.id: album};
+ for (final collectionID in collectionIDs) {
+ final album = albumsByID[collectionID];
+ if (album == null) {
+ failedIDs.add(collectionID);
+ continue;
+ }
+ try {
+ await mutate(album, collectionID);
+ } catch (error, stackTrace) {
+ _logger.warning(
+ 'Failed to update album $collectionID',
+ error,
+ stackTrace,
+ );
+ failedIDs.add(collectionID);
+ }
+ }
+ return _finishMutation(
+ collectionIDs,
+ failedIDs: failedIDs,
+ onSucceeded: onSucceeded,
+ );
+ }
+
+ Future<bool> _finishMutation(
+ Set<int> attemptedIDs, {
+ required Set<int> failedIDs,
+ required ValueChanged<int> onSucceeded,
+ }) async {
+ final succeededIDs = attemptedIDs.difference(failedIDs);
+ for (final id in succeededIDs) {
+ _selectedRoles.remove(id);
+ onSucceeded(id);
+ }
+ _selectedRoles.removeWhere((id, _) => !failedIDs.contains(id));
+ try {
+ await _reloadAlbums();
+ } catch (error, stackTrace) {
+ _logger.warning(
+ 'Failed to reload albums after sharing update',
+ error,
+ stackTrace,
+ );
+ }
+ failedIDs.removeWhere((id) => !_selectedRoles.containsKey(id));
+ _failedCount = failedIDs.length;
+ _isMutating = false;
+ if (failedIDs.isEmpty) {
+ _selectionMode = null;
+ }
+ _notifyListeners();
+ return failedIDs.isEmpty;
+ }
+
+ Future<void> _reloadAlbums() async {
+ _albums = await _repository.getEligibleAlbums();
+ _activeRoles.clear();
+ for (final album in _albums) {
+ final role = librarySharingRoleFor(album, recipient.userID);
+ if (role != null) {
+ _activeRoles[album.id] = role;
+ }
+ }
+ final selectableIDs = _albums
+ .where(_isVisible)
+ .map((album) => album.id)
+ .toSet();
+ _selectedRoles.removeWhere((id, _) => !selectableIDs.contains(id));
+ _exitEmptyManageMode();
+ }
+
+ bool _isShared(int collectionID) => _activeRoles.containsKey(collectionID);
+
+ bool _isVisible(Collection album) =>
+ isAddingAlbums ? !_isShared(album.id) : _isShared(album.id);
+
+ void _clearSelectionState() {
+ _selectedRoles.clear();
+ _failedCount = 0;
+ }
+
+ void _exitEmptyManageMode() {
+ if (_selectionMode == _LibrarySharingSelectionMode.manage &&
+ _selectedRoles.isEmpty) {
+ _selectionMode = null;
+ }
+ }
+
+ void _notifyListeners() {
+ if (!_isDisposed) {
+ notifyListeners();
+ }
+ }
+
+ @override
+ void dispose() {
+ _isDisposed = true;
+ super.dispose();
+ }
+}
diff --git a/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_page.dart b/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_page.dart
new file mode 100644
index 0000000000..a0bc0a9927
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_page.dart
@@ -0,0 +1,447 @@
+import 'dart:async';
+
+import 'package:ente_components/ente_components.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart' show ScrollDirection;
+import 'package:hugeicons/hugeicons.dart';
+import 'package:photos/models/collection/collection.dart';
+import 'package:photos/models/library_sharing/library_sharing_recipient.dart';
+import 'package:photos/services/library_sharing_service.dart';
+import 'package:photos/ui/collections/flex_grid_view.dart';
+import 'package:photos/ui/components/empty_state_component.dart';
+import 'package:photos/ui/sharing/library_sharing/library_sharing_controller.dart';
+import 'package:photos/ui/sharing/library_sharing/library_sharing_role_badge.dart';
+import 'package:photos/ui/sharing/library_sharing/library_sharing_selection_sheet.dart';
+import 'package:photos/ui/sharing/library_sharing/library_sharing_sheets.dart';
+import 'package:photos/ui/sharing/library_sharing/library_sharing_strings.dart';
+
+class LibrarySharingPage extends StatefulWidget {
+ const LibrarySharingPage({
+ required this.recipient,
+ this.controller,
+ super.key,
+ });
+
+ final LibrarySharingRecipient recipient;
+ final LibrarySharingController? controller;
+
+ @override
+ State<LibrarySharingPage> createState() => _LibrarySharingPageState();
+}
+
+class _LibrarySharingPageState extends State<LibrarySharingPage> {
+ late final LibrarySharingController _controller =
+ widget.controller ??
+ LibrarySharingController(
+ recipient: widget.recipient,
+ repository: LibrarySharingService(),
+ );
+ late final bool _ownsController = widget.controller == null;
+ final ScrollController _scrollController = ScrollController();
+ final GlobalKey _selectionSheetKey = GlobalKey();
+ bool _isSelectionSheetExpanded = true;
+ bool _selectionSheetWasVisible = false;
+ double? _expandedSelectionSheetHeight;
+
+ LibrarySharingRecipient get _recipient => _controller.recipient;
+
+ @override
+ void initState() {
+ super.initState();
+ _selectionSheetWasVisible = _showSelectionSheet;
+ _controller.addListener(_handleControllerChange);
+ unawaited(_controller.load());
+ }
+
+ @override
+ void dispose() {
+ _controller.removeListener(_handleControllerChange);
+ _scrollController.dispose();
+ if (_ownsController) {
+ _controller.dispose();
+ }
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return ListenableBuilder(
+ listenable: _controller,
+ builder: (context, _) => PopScope(
+ canPop:
+ !_controller.isMutating &&
+ (!_controller.isSelecting || _controller.isFirstTime),
+ onPopInvokedWithResult: (didPop, _) {
+ if (!didPop && _controller.isSelecting && !_controller.isMutating) {
+ _controller.exitSelectionMode();
+ }
+ },
+ child: Scaffold(
+ backgroundColor: context.componentColors.backgroundBase,
+ body: _body(context),
+ ),
+ ),
+ );
+ }
+
+ Widget _body(BuildContext context) {
+ final showSelectionSheet = _showSelectionSheet;
+ if (showSelectionSheet && _isSelectionSheetExpanded) {
+ _scheduleSelectionSheetMeasurement();
+ }
+ return Stack(
+ children: [
+ Positioned.fill(
+ child: NotificationListener<UserScrollNotification>(
+ onNotification: _handleUserScroll,
+ child: _content(context),
+ ),
+ ),
+ if (showSelectionSheet)
+ Positioned(
+ left: 0,
+ right: 0,
+ bottom: 0,
+ child: AnimatedSize(
+ duration: Motion.standard,
+ curve: Curves.easeOutCubic,
+ alignment: Alignment.bottomCenter,
+ child: LibrarySharingSelectionSheet(
+ key: _selectionSheetKey,
+ controller: _controller,
+ isExpanded: _isSelectionSheetExpanded,
+ onExpandedChanged: _setSelectionSheetExpanded,
+ onApply: _applySelection,
+ onStopSharing: _stopSharing,
+ onShowMixedRoles: () => unawaited(_showMixedRoles()),
+ ),
+ ),
+ ),
+ ],
+ );
+ }
+
+ Widget _content(BuildContext context) {
+ return AppBarComponent(
+ title: _recipient.label,
+ titleBuilderHeight: _titleBuilderHeight(context),
+ titleBuilder: _titleBuilder,
+ controller: _scrollController,
+ onBack: () => Navigator.of(context).maybePop(),
+ actions: [
+ if (!_controller.isFirstTime && !_controller.isSelecting)
+ IconButtonComponent(
+ tooltip: LibrarySharingStrings.shareAlbums,
+ variant: IconButtonComponentVariant.primary,
+ shouldSurfaceExecutionStates: false,
+ icon: const HugeIcon(
+ icon: HugeIcons.strokeRoundedImageAdd01,
+ size: IconSizes.small,
+ ),
+ onTap: _controller.enterAddMode,
+ ),
+ ],
+ slivers: _slivers(context),
+ );
+ }
+
+ bool get _showSelectionSheet =>
+ _controller.isSelecting && _controller.hasSelection;
+
+ Widget _titleBuilder(BuildContext context, HeaderAppBarTitleState state) {
+ final colors = context.componentColors;
+ return Column(
+ mainAxisAlignment: MainAxisAlignment.center,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ _controller.isAddingAlbums
+ ? LibrarySharingStrings.shareWith
+ : LibrarySharingStrings.sharingWith,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: _librarySharingEyebrowStyle.copyWith(color: colors.textLight),
+ ),
+ Text(
+ _recipient.label,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: state.textStyle.copyWith(color: colors.textBase),
+ ),
+ ],
+ );
+ }
+
+ List<Widget> _slivers(BuildContext context) {
+ if (_controller.isLoading) {
+ return const [
+ SliverFillRemaining(
+ hasScrollBody: false,
+ child: Center(child: CircularProgressIndicator()),
+ ),
+ ];
+ }
+ if (_controller.loadError != null) {
+ return [
+ SliverFillRemaining(
+ hasScrollBody: false,
+ child: Padding(
+ padding: const EdgeInsets.all(Spacing.xl),
+ child: Column(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ Text(
+ LibrarySharingStrings.loadFailed,
+ style: TextStyles.h2,
+ textAlign: TextAlign.center,
+ ),
+ const SizedBox(height: Spacing.lg),
+ ButtonComponent(
+ label: LibrarySharingStrings.retryLoading,
+ onTap: _controller.load,
+ ),
+ ],
+ ),
+ ),
+ ),
+ ];
+ }
+ final albums = _controller.visibleAlbums;
+ final showLibrarySharingBanner =
+ !_controller.isAddingAlbums || _controller.isFirstTime;
+ final leadingSlivers = <Widget>[
+ if (showLibrarySharingBanner) _librarySharingBanner(),
+ ];
+ if (albums.isEmpty) {
+ final isSharingFullLibrary =
+ _controller.isAddingAlbums && _controller.eligibleAlbumCount > 0;
+ return [
+ ...leadingSlivers,
+ SliverFillRemaining(
+ hasScrollBody: false,
+ child: EmptyStateComponent(
+ assetPath: isSharingFullLibrary
+ ? 'assets/ducky_full_library.png'
+ : 'assets/ducky_share.png',
+ title: isSharingFullLibrary
+ ? LibrarySharingStrings.allCurrentAlbumsShared
+ : LibrarySharingStrings.noAlbumsToShare,
+ textWidth: isSharingFullLibrary ? 257 : 285,
+ alignment: isSharingFullLibrary
+ ? Alignment.topCenter
+ : Alignment.center,
+ padding: isSharingFullLibrary
+ ? const EdgeInsets.only(top: _fullLibraryEmptyStateTopPadding)
+ : const EdgeInsets.fromLTRB(
+ Spacing.xl,
+ 0,
+ Spacing.xl,
+ Spacing.xl,
+ ),
+ ),
+ ),
+ ];
+ }
+ return [
+ ...leadingSlivers,
+ CollectionsFlexiGridViewWidget(
+ albums,
+ tag: 'library_sharing_${_recipient.userID}',
+ selectionCallbacks: (
+ isSelected: _controller.isSelected,
+ toggle: _handleAlbumTap,
+ ),
+ gridTopLeftOverlayBuilder: _roleOverlay,
+ topPadding: Spacing.sm,
+ bottomPadding: _gridBottomPadding,
+ gridLayout: AlbumGridLayout.dense,
+ ),
+ ];
+ }
+
+ Widget _librarySharingBanner() {
+ return SliverPadding(
+ padding: const EdgeInsets.fromLTRB(
+ Spacing.lg,
+ Spacing.xl,
+ Spacing.lg,
+ Spacing.md,
+ ),
+ sliver: SliverToBoxAdapter(
+ child: MenuGroupComponent(
+ items: [
+ MenuComponent(
+ title: LibrarySharingStrings.librarySharing,
+ subtitle: LibrarySharingStrings.shareAllYourAlbums,
+ onTap: _showEnableLibrarySharing,
+ trailing: IgnorePointer(
+ child: ExcludeSemantics(
+ child: ToggleSwitchComponent(
+ key: const ValueKey('library-sharing-toggle'),
+ selected: false,
+ onChanged: (_) {},
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ Widget? _roleOverlay(BuildContext context, Collection album) {
+ final role = _controller.activeRoleFor(album.id);
+ return role == null ? null : LibrarySharingRoleBadge(role: role);
+ }
+
+ void _handleAlbumTap(Collection album) {
+ if (_controller.isMutating) {
+ return;
+ }
+ if (!_controller.isSelecting) {
+ _controller.enterManageMode();
+ }
+ _controller.toggleSelection(album);
+ }
+
+ bool _handleUserScroll(UserScrollNotification notification) {
+ if (!_showSelectionSheet ||
+ _controller.isMutating ||
+ notification.metrics.axis != Axis.vertical) {
+ return false;
+ }
+ switch (notification.direction) {
+ case ScrollDirection.reverse:
+ _setSelectionSheetExpanded(false);
+ case ScrollDirection.forward:
+ _setSelectionSheetExpanded(true);
+ case ScrollDirection.idle:
+ break;
+ }
+ return false;
+ }
+
+ void _handleControllerChange() {
+ final isVisible = _showSelectionSheet;
+ if (isVisible && !_selectionSheetWasVisible) {
+ _isSelectionSheetExpanded = true;
+ _expandedSelectionSheetHeight = null;
+ }
+ _selectionSheetWasVisible = isVisible;
+ }
+
+ void _setSelectionSheetExpanded(bool isExpanded) {
+ if (!mounted ||
+ !_showSelectionSheet ||
+ _isSelectionSheetExpanded == isExpanded) {
+ return;
+ }
+ setState(() => _isSelectionSheetExpanded = isExpanded);
+ }
+
+ double get _gridBottomPadding {
+ if (!_showSelectionSheet) {
+ return Spacing.xxl;
+ }
+ return (_expandedSelectionSheetHeight ??
+ _estimatedExpandedSelectionSheetHeight) +
+ Spacing.md;
+ }
+
+ void _scheduleSelectionSheetMeasurement() {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted || !_showSelectionSheet || !_isSelectionSheetExpanded) {
+ return;
+ }
+ final renderObject = _selectionSheetKey.currentContext
+ ?.findRenderObject();
+ final height = renderObject is RenderBox
+ ? renderObject.size.height
+ : null;
+ if (height == null ||
+ (_expandedSelectionSheetHeight != null &&
+ (height - _expandedSelectionSheetHeight!).abs() < 0.5)) {
+ return;
+ }
+ setState(() => _expandedSelectionSheetHeight = height);
+ });
+ }
+
+ double _titleBuilderHeight(BuildContext context) {
+ final textScaler = MediaQuery.textScalerOf(context);
+ return _scaledLineHeight(textScaler, _librarySharingEyebrowStyle) +
+ _scaledLineHeight(textScaler, TextStyles.display2);
+ }
+
+ double _scaledLineHeight(TextScaler textScaler, TextStyle style) {
+ final fontSize = style.fontSize ?? 14;
+ return textScaler.scale(fontSize) * (style.height ?? 1);
+ }
+
+ Future<void> _applySelection() async {
+ await _showFailureIfNeeded(
+ await _controller.applySelection(),
+ _applySelection,
+ );
+ }
+
+ Future<void> _stopSharing() async {
+ final confirmed = await confirmStopLibrarySharing(
+ context: context,
+ count: _controller.selectedActiveShareCount,
+ );
+ if (!confirmed || !mounted) {
+ return;
+ }
+ final success = await _controller.stopSharingSelected();
+ await _showFailureIfNeeded(success, _stopSharing);
+ }
+
+ Future<void> _showMixedRoles() async {
+ final success = await showLibrarySharingRolesSheet(
+ context: context,
+ controller: _controller,
+ );
+ if (success != null) {
+ await _showFailureIfNeeded(success, _applySelection);
+ }
+ }
+
+ Future<void> _showEnableLibrarySharing() async {
+ final shouldEnable = await showEnableLibrarySharingSheet(
+ context: context,
+ recipientLabel: _recipient.label,
+ );
+ if (shouldEnable && mounted) {
+ showToastComponent(context, LibrarySharingStrings.comingSoon);
+ }
+ }
+
+ Future<void> _showFailureIfNeeded(
+ bool success,
+ Future<void> Function() retry,
+ ) async {
+ if (!success && mounted) {
+ await showLibrarySharingFailure(
+ context: context,
+ controller: _controller,
+ onRetry: retry,
+ );
+ }
+ }
+}
+
+/// Positions the 250px empty state group at the reference screen's y=287.
+/// Source: https://www.figma.com/design/BuBNPPytxlVnqfmCUW0mgz/Ente-Visual-Design?node-id=17186-38829&m=dev
+const double _fullLibraryEmptyStateTopPadding = 131;
+
+/// The reference uses an Outfit Semibold 16/32 eyebrow above Display 2.
+/// Source: https://www.figma.com/design/BuBNPPytxlVnqfmCUW0mgz/Ente-Visual-Design?node-id=15782-102259&m=dev
+final TextStyle _librarySharingEyebrowStyle = TextStyles.display2.copyWith(
+ fontSize: 16,
+ height: 2,
+);
+
+// Prevents the final grid row from jumping under the sheet before measurement.
+const double _estimatedExpandedSelectionSheetHeight = 320;
diff --git a/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_role_badge.dart b/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_role_badge.dart
new file mode 100644
index 0000000000..ca45057f1b
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_role_badge.dart
@@ -0,0 +1,131 @@
+import 'package:ente_components/ente_components.dart';
+import 'package:flutter/material.dart';
+import 'package:hugeicons/hugeicons.dart';
+import 'package:photos/generated/l10n.dart';
+import 'package:photos/models/collection/collection.dart';
+import 'package:photos/services/library_sharing_service.dart';
+
+List<EntePopupMenuOption<CollectionParticipantRole>> librarySharingRoleOptions(
+ BuildContext context, {
+ CollectionParticipantRole? activeRole,
+}) {
+ return [
+ for (final role in librarySharingRoles)
+ EntePopupMenuOption(
+ value: role,
+ label: librarySharingRoleLabel(context, role),
+ leadingWidget: HugeIcon(
+ icon: librarySharingRoleIcon(role),
+ size: IconSizes.small,
+ strokeWidth: 1.6,
+ ),
+ isActive: role == activeRole,
+ activeTrailingWidget: const HugeIcon(
+ icon: HugeIcons.strokeRoundedTick02,
+ size: IconSizes.small,
+ ),
+ ),
+ ];
+}
+
+class LibrarySharingRoleBadge extends StatelessWidget {
+ const LibrarySharingRoleBadge({required this.role, super.key});
+
+ final CollectionParticipantRole role;
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = context.componentColors;
+ final label = librarySharingRoleLabel(context, role);
+ return Semantics(
+ label: label,
+ excludeSemantics: true,
+ child: SizedBox.square(
+ dimension: 20,
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ color: colors.fillLight,
+ borderRadius: BorderRadius.circular(40),
+ ),
+ child: Center(
+ child: HugeIcon(
+ icon: librarySharingRoleIcon(role),
+ size: IconSizes.micro,
+ color: colors.textBase,
+ strokeWidth: 1.8,
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+class LibrarySharingRoleSelector extends StatelessWidget {
+ const LibrarySharingRoleSelector({
+ required this.role,
+ this.fallbackLabel,
+ super.key,
+ }) : assert(role != null || fallbackLabel != null);
+
+ final CollectionParticipantRole? role;
+ final String? fallbackLabel;
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = context.componentColors;
+ return Container(
+ height: 40,
+ padding: const EdgeInsets.only(left: Spacing.lg, right: Spacing.md),
+ decoration: BoxDecoration(
+ color: colors.fillDark,
+ borderRadius: BorderRadius.circular(Radii.button),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (role != null) ...[
+ HugeIcon(
+ icon: librarySharingRoleIcon(role!),
+ size: IconSizes.small,
+ color: colors.textBase,
+ strokeWidth: 1.8,
+ ),
+ const SizedBox(width: Spacing.xs),
+ ],
+ Text(
+ role == null
+ ? fallbackLabel!
+ : librarySharingRoleLabel(context, role!),
+ style: TextStyles.mini.copyWith(color: colors.textBase),
+ ),
+ const SizedBox(width: Spacing.sm),
+ const HugeIcon(
+ icon: HugeIcons.strokeRoundedArrowDown01,
+ size: IconSizes.small,
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+List<List<dynamic>> librarySharingRoleIcon(CollectionParticipantRole role) {
+ return switch (role) {
+ CollectionParticipantRole.admin => HugeIcons.strokeRoundedCrown02,
+ CollectionParticipantRole.collaborator => HugeIcons.strokeRoundedUserGroup,
+ _ => HugeIcons.strokeRoundedView,
+ };
+}
+
+String librarySharingRoleLabel(
+ BuildContext context,
+ CollectionParticipantRole role,
+) {
+ final l10n = AppLocalizations.of(context);
+ return switch (role) {
+ CollectionParticipantRole.admin => l10n.admin,
+ CollectionParticipantRole.collaborator => l10n.collaborator,
+ _ => l10n.viewer,
+ };
+}
diff --git a/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_selection_sheet.dart b/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_selection_sheet.dart
new file mode 100644
index 0000000000..55b4f159e7
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_selection_sheet.dart
@@ -0,0 +1,223 @@
+import 'package:ente_components/ente_components.dart';
+import 'package:flutter/material.dart';
+import 'package:hugeicons/hugeicons.dart';
+import 'package:photos/generated/l10n.dart';
+import 'package:photos/models/collection/collection.dart';
+import 'package:photos/ui/sharing/library_sharing/library_sharing_controller.dart';
+import 'package:photos/ui/sharing/library_sharing/library_sharing_role_badge.dart';
+import 'package:photos/ui/sharing/library_sharing/library_sharing_strings.dart';
+
+class LibrarySharingSelectionSheet extends StatelessWidget {
+ const LibrarySharingSelectionSheet({
+ required this.controller,
+ required this.onApply,
+ required this.onStopSharing,
+ required this.onShowMixedRoles,
+ this.isExpanded = true,
+ this.onExpandedChanged,
+ super.key,
+ });
+
+ final LibrarySharingController controller;
+ final Future<void> Function() onApply;
+ final Future<void> Function() onStopSharing;
+ final VoidCallback onShowMixedRoles;
+ final bool isExpanded;
+ final ValueChanged<bool>? onExpandedChanged;
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = context.componentColors;
+ final sheet = BottomSheetComponent(
+ showCloseButton: false,
+ borderSide: BorderSide(color: colors.strokeDark),
+ content: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (isExpanded) ...[
+ _summary(context),
+ const SizedBox(height: Spacing.xl),
+ _roleControl(context),
+ const SizedBox(height: Spacing.md),
+ ],
+ ButtonComponent(
+ label: controller.isAddingAlbums
+ ? LibrarySharingStrings.shareAlbumCount(
+ controller.selectedCount,
+ )
+ : AppLocalizations.of(context).save,
+ density: ButtonComponentDensity.compact,
+ isDisabled: !controller.canApply,
+ onTap: onApply,
+ ),
+ if (isExpanded && controller.canStopSharing) ...[
+ const SizedBox(height: Spacing.md),
+ ButtonComponent(
+ label: LibrarySharingStrings.stopSharing,
+ variant: ButtonComponentVariant.tertiaryCritical,
+ density: ButtonComponentDensity.compact,
+ shouldSurfaceExecutionStates: false,
+ onTap: onStopSharing,
+ ),
+ ],
+ ],
+ ),
+ );
+ final onChanged = onExpandedChanged;
+ if (onChanged == null) {
+ return sheet;
+ }
+ return Semantics(
+ container: true,
+ explicitChildNodes: true,
+ label: LibrarySharingStrings.albumSelectionControls,
+ expanded: isExpanded,
+ onExpand: isExpanded ? null : () => onChanged(true),
+ onCollapse: isExpanded ? () => onChanged(false) : null,
+ child: _ExpansionGestureDetector(
+ isExpanded: isExpanded,
+ onExpandedChanged: onChanged,
+ child: sheet,
+ ),
+ );
+ }
+
+ Widget _summary(BuildContext context) {
+ final l10n = AppLocalizations.of(context);
+ final selectableAlbumCount = controller.selectableAlbumCount;
+ final allSelected =
+ selectableAlbumCount > 0 &&
+ controller.selectedCount == selectableAlbumCount;
+ final canSelectAll =
+ selectableAlbumCount > 0 && !allSelected && !controller.isMutating;
+ final selectionButton = SelectionSummaryChipComponent(
+ key: const ValueKey('library-sharing-select-all'),
+ label: l10n.selectAll,
+ icon: const HugeIcon(
+ icon: HugeIcons.strokeRoundedTick02,
+ size: IconSizes.small,
+ ),
+ semanticLabel: l10n.selectAll,
+ isSelected: allSelected,
+ onTap: canSelectAll ? controller.selectAll : null,
+ );
+ final canClearSelection = controller.hasSelection && !controller.isMutating;
+ final selectedCount = SelectionSummaryChipComponent(
+ key: const ValueKey('library-sharing-selected-count'),
+ label: LibrarySharingStrings.selectedAlbumCount(controller.selectedCount),
+ icon: const HugeIcon(
+ icon: HugeIcons.strokeRoundedCancel01,
+ size: IconSizes.small,
+ ),
+ semanticLabel: canClearSelection
+ ? l10n.unselectAll
+ : LibrarySharingStrings.selectedAlbumCount(controller.selectedCount),
+ isSelected: controller.hasSelection,
+ onTap: canClearSelection ? controller.clearSelection : null,
+ );
+ final useStackedLayout =
+ MediaQuery.textScalerOf(context).scale(TextStyles.body.fontSize ?? 14) >
+ 20;
+ return useStackedLayout
+ ? Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Align(alignment: Alignment.centerLeft, child: selectionButton),
+ const SizedBox(height: Spacing.xs),
+ Align(alignment: Alignment.centerRight, child: selectedCount),
+ ],
+ )
+ : Row(
+ children: [
+ Expanded(
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: selectionButton,
+ ),
+ ),
+ const SizedBox(width: Spacing.sm),
+ Expanded(
+ child: Align(
+ alignment: Alignment.centerRight,
+ child: selectedCount,
+ ),
+ ),
+ ],
+ );
+ }
+
+ Widget _roleControl(BuildContext context) {
+ final selectedRole = controller.selectedRole;
+ final canEditRole = controller.hasSelection && !controller.isMutating;
+ final trailing = LibrarySharingRoleSelector(
+ role: selectedRole,
+ fallbackLabel: LibrarySharingStrings.mixed,
+ );
+ final menu = MenuComponent(
+ title: LibrarySharingStrings.role,
+ trailing: trailing,
+ isDisabled: !canEditRole,
+ onTap: selectedRole == null && canEditRole ? onShowMixedRoles : null,
+ );
+ return MenuGroupComponent(
+ items: [
+ if (selectedRole != null && canEditRole)
+ EntePopupMenuButton<CollectionParticipantRole>(
+ optionsBuilder: () =>
+ librarySharingRoleOptions(context, activeRole: selectedRole),
+ onSelected: controller.setRoleForSelection,
+ child: menu,
+ )
+ else
+ menu,
+ ],
+ );
+ }
+}
+
+class _ExpansionGestureDetector extends StatefulWidget {
+ const _ExpansionGestureDetector({
+ required this.isExpanded,
+ required this.onExpandedChanged,
+ required this.child,
+ });
+
+ final bool isExpanded;
+ final ValueChanged<bool> onExpandedChanged;
+ final Widget child;
+
+ @override
+ State<_ExpansionGestureDetector> createState() =>
+ _ExpansionGestureDetectorState();
+}
+
+class _ExpansionGestureDetectorState extends State<_ExpansionGestureDetector> {
+ double _dragDelta = 0;
+
+ @override
+ Widget build(BuildContext context) {
+ return GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ excludeFromSemantics: true,
+ onVerticalDragStart: (_) => _dragDelta = 0,
+ onVerticalDragUpdate: (details) {
+ _dragDelta += details.primaryDelta ?? 0;
+ },
+ onVerticalDragEnd: (_) => _finishDrag(),
+ onVerticalDragCancel: _resetDrag,
+ child: widget.child,
+ );
+ }
+
+ void _finishDrag() {
+ if (_dragDelta != 0) {
+ final shouldExpand = _dragDelta < 0;
+ if (shouldExpand != widget.isExpanded) {
+ widget.onExpandedChanged(shouldExpand);
+ }
+ }
+ _resetDrag();
+ }
+
+ void _resetDrag() => _dragDelta = 0;
+}
diff --git a/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_sheets.dart b/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_sheets.dart
new file mode 100644
index 0000000000..e18202a9f9
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_sheets.dart
@@ -0,0 +1,224 @@
+import 'package:ente_components/ente_components.dart';
+import 'package:flutter/material.dart';
+import 'package:photos/models/collection/collection.dart';
+import 'package:photos/ui/collections/album/list_item.dart';
+import 'package:photos/ui/components/thumbnail_list_item.dart';
+import 'package:photos/ui/sharing/library_sharing/library_sharing_controller.dart';
+import 'package:photos/ui/sharing/library_sharing/library_sharing_role_badge.dart';
+import 'package:photos/ui/sharing/library_sharing/library_sharing_strings.dart';
+
+typedef LibrarySharingAlbumThumbnailBuilder =
+ Widget Function(BuildContext context, Collection album);
+
+Future<bool> showEnableLibrarySharingSheet({
+ required BuildContext context,
+ required String recipientLabel,
+}) async {
+ var selectedRole = CollectionParticipantRole.admin;
+ return await showBottomSheetComponent<bool>(
+ context: context,
+ builder: (sheetContext) => StatefulBuilder(
+ builder: (context, setState) {
+ final colors = context.componentColors;
+ return BottomSheetComponent(
+ title: LibrarySharingStrings.enableLibrarySharing,
+ borderSide: BorderSide(color: colors.strokeDark),
+ content: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(
+ LibrarySharingStrings.enableLibrarySharingMessage(
+ recipientLabel,
+ ),
+ style: TextStyles.body.copyWith(color: colors.textLight),
+ ),
+ const SizedBox(height: Spacing.lg),
+ Text(
+ LibrarySharingStrings.hiddenAlbumsNotShared,
+ style: TextStyles.body.copyWith(color: colors.textLight),
+ ),
+ const SizedBox(height: Spacing.lg),
+ MenuGroupComponent(
+ items: [
+ EntePopupMenuButton<CollectionParticipantRole>(
+ optionsBuilder: () => librarySharingRoleOptions(
+ context,
+ activeRole: selectedRole,
+ ),
+ onSelected: (role) =>
+ setState(() => selectedRole = role),
+ child: MenuComponent(
+ title: LibrarySharingStrings.role,
+ trailing: LibrarySharingRoleSelector(
+ role: selectedRole,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ],
+ ),
+ actions: [
+ ButtonComponent(
+ label: LibrarySharingStrings.enable,
+ density: ButtonComponentDensity.compact,
+ shouldSurfaceExecutionStates: false,
+ onTap: () => Navigator.of(sheetContext).pop(true),
+ ),
+ ],
+ );
+ },
+ ),
+ ) ??
+ false;
+}
+
+Future<bool?> showLibrarySharingRolesSheet({
+ required BuildContext context,
+ required LibrarySharingController controller,
+ LibrarySharingAlbumThumbnailBuilder? albumThumbnailBuilder,
+}) {
+ return showBottomSheetComponent<bool>(
+ context: context,
+ enableDrag: false,
+ builder: (_) => ListenableBuilder(
+ listenable: controller,
+ builder: (sheetContext, _) => PopScope(
+ canPop: !controller.isMutating,
+ child: Builder(
+ builder: (context) {
+ final colors = context.componentColors;
+ return BottomSheetComponent(
+ title: LibrarySharingStrings.roles,
+ showCloseButton: !controller.isMutating,
+ borderSide: BorderSide(color: colors.strokeDark),
+ content: _LibrarySharingRoleList(
+ controller: controller,
+ thumbnailBuilder: albumThumbnailBuilder,
+ ),
+ actions: [
+ ButtonComponent(
+ label: LibrarySharingStrings.updateRoles,
+ density: ButtonComponentDensity.compact,
+ isDisabled: !controller.canApply,
+ onTap: () async {
+ final success = await controller.applySelection();
+ if (sheetContext.mounted) {
+ Navigator.of(sheetContext).pop(success);
+ }
+ },
+ ),
+ ],
+ );
+ },
+ ),
+ ),
+ ),
+ );
+}
+
+class _LibrarySharingRoleList extends StatelessWidget {
+ const _LibrarySharingRoleList({
+ required this.controller,
+ this.thumbnailBuilder,
+ });
+
+ final LibrarySharingController controller;
+ final LibrarySharingAlbumThumbnailBuilder? thumbnailBuilder;
+
+ @override
+ Widget build(BuildContext context) {
+ final albums = controller.selectedAlbums;
+ return ConstrainedBox(
+ constraints: BoxConstraints(
+ maxHeight: MediaQuery.sizeOf(context).height * 0.5,
+ ),
+ child: Scrollbar(
+ child: ListView.separated(
+ key: const ValueKey('library-sharing-role-list'),
+ primary: false,
+ shrinkWrap: true,
+ itemCount: albums.length,
+ separatorBuilder: (_, _) => const SizedBox(height: Spacing.sm),
+ itemBuilder: (context, index) {
+ final album = albums[index];
+ final role = controller.stagedRoleFor(album.id);
+ return ThumbnailListItem(
+ leading:
+ thumbnailBuilder?.call(context, album) ??
+ AlbumListItemCover(collection: album, borderRadius: Radii.sm),
+ leadingSize: 36,
+ title: Text(
+ album.displayName,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyles.body.copyWith(
+ color: context.componentColors.textBase,
+ ),
+ ),
+ trailing: IgnorePointer(
+ ignoring: controller.isMutating,
+ child: EntePopupMenuButton<CollectionParticipantRole>(
+ optionsBuilder: () =>
+ librarySharingRoleOptions(context, activeRole: role),
+ onSelected: (role) =>
+ controller.setRoleForAlbum(album.id, role),
+ child: LibrarySharingRoleSelector(role: role),
+ ),
+ ),
+ );
+ },
+ ),
+ ),
+ );
+ }
+}
+
+Future<bool> confirmStopLibrarySharing({
+ required BuildContext context,
+ required int count,
+}) async {
+ return await showBottomSheetComponent<bool>(
+ context: context,
+ builder: (sheetContext) {
+ final colors = sheetContext.componentColors;
+ return BottomSheetComponent(
+ title: LibrarySharingStrings.stopSharingTitle(count),
+ message: LibrarySharingStrings.stopSharingMessage(count),
+ illustration: Image.asset('assets/warning-red.png'),
+ borderSide: BorderSide(color: colors.strokeDark),
+ actions: [
+ ButtonComponent(
+ label: LibrarySharingStrings.stopSharing,
+ variant: ButtonComponentVariant.critical,
+ density: ButtonComponentDensity.compact,
+ shouldSurfaceExecutionStates: false,
+ onTap: () => Navigator.of(sheetContext).pop(true),
+ ),
+ ],
+ );
+ },
+ ) ??
+ false;
+}
+
+Future<void> showLibrarySharingFailure({
+ required BuildContext context,
+ required LibrarySharingController controller,
+ required Future<void> Function() onRetry,
+}) {
+ final count = controller.failedCount;
+ return showErrorBottomSheetComponent<void>(
+ context: context,
+ title: LibrarySharingStrings.sharingFailed,
+ message: count > 0
+ ? LibrarySharingStrings.failedAlbumCount(count)
+ : LibrarySharingStrings.sharingFailedMessage,
+ actionLabel: LibrarySharingStrings.retryFailed,
+ onActionTap: () async {
+ Navigator.of(context).pop();
+ await onRetry();
+ },
+ );
+}
diff --git a/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_strings.dart b/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_strings.dart
new file mode 100644
index 0000000000..fbc9c016b2
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/sharing/library_sharing/library_sharing_strings.dart
@@ -0,0 +1,81 @@
+import 'package:photos/utils/pending_translation.dart';
+
+abstract final class LibrarySharingStrings {
+ static String get sharingWith => pendingTranslation('Sharing with');
+ static String get shareWith => pendingTranslation('Share with');
+
+ static String get shareAlbums => pendingTranslation('Share albums');
+ static String get internalShareAlbums =>
+ pendingTranslation('(i) Share albums');
+ static String get librarySharing => pendingTranslation('Library Sharing');
+ static String get shareAllYourAlbums =>
+ pendingTranslation('Share all your albums');
+ static String get enableLibrarySharing =>
+ pendingTranslation('Enable library sharing?');
+ static String enableLibrarySharingMessage(
+ String recipient,
+ ) => pendingTranslation(
+ 'Your existing albums, and the ones you create in the future will be automatically shared with $recipient.',
+ );
+ static String get hiddenAlbumsNotShared => pendingTranslation(
+ 'Hidden albums will not be shared. You can stop sharing any album at any time.',
+ );
+ static String get enable => pendingTranslation('Enable');
+ static String get comingSoon => pendingTranslation('Coming soon');
+
+ static String sharedAlbumCount(int count) => switch (count) {
+ 0 => pendingTranslation('No albums shared'),
+ 1 => pendingTranslation('1 album shared'),
+ _ => pendingTranslation('$count albums shared'),
+ };
+
+ static String memberSubtitle(int count, String storageUsage) =>
+ pendingTranslation('${sharedAlbumCount(count)} \u2022 $storageUsage');
+
+ static String selectedAlbumCount(int count) => switch (count) {
+ 1 => pendingTranslation('1 selected'),
+ _ => pendingTranslation('$count selected'),
+ };
+
+ static String shareAlbumCount(int count) => switch (count) {
+ 1 => pendingTranslation('Share 1 album'),
+ _ => pendingTranslation('Share $count albums'),
+ };
+
+ static String stopSharingTitle(int count) => switch (count) {
+ 1 => pendingTranslation('Stop sharing 1 album?'),
+ _ => pendingTranslation('Stop sharing $count albums?'),
+ };
+
+ static String stopSharingMessage(int count) => switch (count) {
+ 1 => pendingTranslation(
+ "They'll lose this album, and any photos they added leave with them. You can share again later.",
+ ),
+ _ => pendingTranslation(
+ "They'll lose these albums, and any photos they added leave with them. You can share again later.",
+ ),
+ };
+
+ static String failedAlbumCount(int count) => switch (count) {
+ 1 => pendingTranslation('Could not update 1 album.'),
+ _ => pendingTranslation('Could not update $count albums.'),
+ };
+
+ static String get role => pendingTranslation('Role');
+ static String get mixed => pendingTranslation('Mixed');
+ static String get roles => pendingTranslation('Roles');
+ static String get updateRoles => pendingTranslation('Update roles');
+ static String get stopSharing => pendingTranslation('Stop sharing');
+ static String get retryFailed => pendingTranslation('Retry failed albums');
+ static String get retryLoading => pendingTranslation('Try again');
+ static String get noAlbumsToShare =>
+ pendingTranslation('No albums to share yet');
+ static String get allCurrentAlbumsShared =>
+ pendingTranslation('All your current albums are shared');
+ static String get albumSelectionControls =>
+ pendingTranslation('Album selection controls');
+ static String get sharingFailed => pendingTranslation('Sharing failed');
+ static String get sharingFailedMessage =>
+ pendingTranslation('Could not update the selected albums.');
+ static String get loadFailed => pendingTranslation('Could not load albums');
+}
diff --git a/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart b/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart
index 58ff1944d0..eef8f33204 100644
--- a/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart
+++ b/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart
@@ -53,6 +53,8 @@ class FlagService {
return (flags.internalUser || kDebugMode) && !isDisabled;
}
+ bool get librarySharing => internalUser;
+
bool get webGPUEnabled => internalUser;
bool get cloudflareUploadWorker =>
diff --git a/mobile/apps/photos/test/services/library_sharing_service_test.dart b/mobile/apps/photos/test/services/library_sharing_service_test.dart
new file mode 100644
index 0000000000..fadf2b5f06
--- /dev/null
+++ b/mobile/apps/photos/test/services/library_sharing_service_test.dart
@@ -0,0 +1,131 @@
+import 'package:dio/dio.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:mockito/mockito.dart';
+import 'package:photos/models/api/collection/user.dart';
+import 'package:photos/models/collection/collection.dart';
+import 'package:photos/services/collections_service.dart';
+import 'package:photos/services/library_sharing_service.dart';
+
+import '../ui/sharing/library_sharing_test_helpers.dart';
+
+void main() {
+ test('sharedAlbumCounts ignores unsupported participant roles', () {
+ final collectionsService = _MockCollectionsService();
+ final supportedAlbum = librarySharingTestAlbum(
+ 1,
+ recipientRole: CollectionParticipantRole.viewer,
+ );
+ final unsupportedAlbum = librarySharingTestAlbum(
+ 2,
+ recipientRole: CollectionParticipantRole.viewer,
+ );
+ unsupportedAlbum.sharees.single.role = 'EDITOR';
+ collectionsService.collectionsForUI = [supportedAlbum, unsupportedAlbum];
+
+ expect(
+ LibrarySharingService(
+ collectionsService: collectionsService,
+ ).sharedAlbumCounts({librarySharingTestRecipient.userID}),
+ {librarySharingTestRecipient.userID: 1},
+ );
+ });
+
+ group('LibrarySharingService.unshareAlbum', () {
+ late _MockCollectionsService collectionsService;
+ late LibrarySharingService service;
+ late Collection album;
+
+ setUp(() {
+ collectionsService = _MockCollectionsService();
+ service = LibrarySharingService(collectionsService: collectionsService);
+ album = librarySharingTestAlbum(
+ 1,
+ recipientRole: CollectionParticipantRole.viewer,
+ );
+ });
+
+ test('accepts an already-absent recipient after a not-found response', () {
+ final error = _dioException(404);
+ collectionsService.unshareHandler = (_, _) => Future.error(error);
+ collectionsService.refreshShareesHandler = (_) async => const <User>[];
+
+ expect(
+ service.unshareAlbum(
+ collection: album,
+ recipientUserID: librarySharingTestRecipient.userID,
+ email: librarySharingTestRecipient.email,
+ ),
+ completes,
+ );
+ });
+
+ test('preserves non-idempotent unshare failures', () async {
+ final error = _dioException(500);
+ collectionsService.unshareHandler = (_, _) => Future.error(error);
+
+ await expectLater(
+ service.unshareAlbum(
+ collection: album,
+ recipientUserID: librarySharingTestRecipient.userID,
+ email: librarySharingTestRecipient.email,
+ ),
+ throwsA(same(error)),
+ );
+ expect(collectionsService.refreshShareesCalls, 0);
+ });
+
+ test('preserves not-found when the recipient is still present', () async {
+ final error = _dioException(404);
+ collectionsService.unshareHandler = (_, _) => Future.error(error);
+ collectionsService.refreshShareesHandler = (_) async => [
+ User(
+ id: librarySharingTestRecipient.userID,
+ email: librarySharingTestRecipient.email,
+ ),
+ ];
+
+ await expectLater(
+ service.unshareAlbum(
+ collection: album,
+ recipientUserID: librarySharingTestRecipient.userID,
+ email: librarySharingTestRecipient.email,
+ ),
+ throwsA(same(error)),
+ );
+ });
+ });
+}
+
+class _MockCollectionsService extends Mock implements CollectionsService {
+ List<Collection> collectionsForUI = const [];
+ late Future<List<User>> Function(int collectionID, String email)
+ unshareHandler;
+ Future<List<User>> Function(int collectionID)? refreshShareesHandler;
+ int refreshShareesCalls = 0;
+
+ @override
+ List<Collection> getCollectionsForUI({
+ bool includedShared = false,
+ bool includeCollab = false,
+ bool includeUncategorized = false,
+ }) => collectionsForUI;
+
+ @override
+ Future<List<User>> unshare(int collectionID, String email) =>
+ unshareHandler(collectionID, email);
+
+ @override
+ Future<List<User>> refreshSharees(int collectionID) {
+ refreshShareesCalls++;
+ return refreshShareesHandler?.call(collectionID) ??
+ Future.value(const <User>[]);
+ }
+}
+
+DioException _dioException(int statusCode) {
+ final requestOptions = RequestOptions(path: '/collections/unshare');
+ return DioException(
+ requestOptions: requestOptions,
+ response: Response(requestOptions: requestOptions, statusCode: statusCode),
+ );
+}
diff --git a/mobile/apps/photos/test/ui/family/family_dashboard_test.dart b/mobile/apps/photos/test/ui/family/family_dashboard_test.dart
index ea0c10cb91..3cd04f0c00 100644
--- a/mobile/apps/photos/test/ui/family/family_dashboard_test.dart
+++ b/mobile/apps/photos/test/ui/family/family_dashboard_test.dart
@@ -106,6 +106,7 @@ void main() {
isCurrentUser: false,
member: _member(status: FamilyMemberStatus.invited, userID: 42),
hasSavedContact: true,
+ librarySharingEnabled: true,
),
[
FamilyMemberAction.editContact,
@@ -119,6 +120,7 @@ void main() {
isCurrentUser: false,
member: _member(status: FamilyMemberStatus.invited),
hasSavedContact: false,
+ librarySharingEnabled: true,
),
[FamilyMemberAction.resendInvite, FamilyMemberAction.revokeInvite],
);
@@ -153,7 +155,7 @@ void main() {
});
testWidgets(
- 'renders saved contacts and no shared-album content at 375 pixels',
+ 'renders saved contacts and their shared-album counts at 375 pixels',
(tester) async {
await tester.binding.setSurfaceSize(const Size(375, 812));
addTearDown(() => tester.binding.setSurfaceSize(null));
@@ -196,6 +198,8 @@ void main() {
1: 'Person current user',
42: 'Person saved member',
},
+ librarySharingEnabled: true,
+ sharedAlbumCountsByUserId: const {42: 5},
onMemberTap: (member, _) => selectedMember = member,
onAddMember: () {},
remainingSlots: 2,
@@ -210,10 +214,7 @@ void main() {
expect(find.text('Current user'), findsWidgets);
expect(find.text('Saved member'), findsNWidgets(2));
expect(find.text('[email protected]'), findsOneWidget);
- expect(
- find.textContaining(RegExp('shared album', caseSensitive: false)),
- findsNothing,
- );
+ expect(find.textContaining('5 albums shared'), findsOneWidget);
final avatars = tester
.widgetList<AvatarComponent>(find.byType(AvatarComponent))
.where((avatar) => avatar.image == null)
@@ -328,6 +329,49 @@ void main() {
expect(selectedDisplayName, 'Current person');
});
+ testWidgets('does not report zero shared albums before counts are known', (
+ tester,
+ ) async {
+ final currentUser = _member(
+ email: '[email protected]',
+ userID: 1,
+ isAdmin: true,
+ status: FamilyMemberStatus.self,
+ );
+ final otherMember = _member(email: '[email protected]', userID: 42);
+ final members = [currentUser, otherMember];
+
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: lightThemeData,
+ localizationsDelegates: AppLocalizations.localizationsDelegates,
+ supportedLocales: AppLocalizations.supportedLocales,
+ home: Scaffold(
+ body: FamilyDashboard(
+ userDetails: _userDetails(members),
+ members: members,
+ isAdmin: true,
+ contactsByUserId: const {},
+ profilePictureBytesByUserId: const {},
+ linkedPersonIdsByUserId: const {},
+ linkedPersonNamesByUserId: const {},
+ librarySharingEnabled: true,
+ onMemberTap: (_, _) {},
+ onAddMember: () {},
+ remainingSlots: 3,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ expect(find.text('No albums shared'), findsNothing);
+ expect(
+ find.textContaining(RegExp('used', caseSensitive: false)),
+ findsWidgets,
+ );
+ });
+
testWidgets('sorts other members by their displayed name or email', (
tester,
) async {
diff --git a/mobile/apps/photos/test/ui/sharing/library_sharing_controller_test.dart b/mobile/apps/photos/test/ui/sharing/library_sharing_controller_test.dart
new file mode 100644
index 0000000000..5b7a69e3be
--- /dev/null
+++ b/mobile/apps/photos/test/ui/sharing/library_sharing_controller_test.dart
@@ -0,0 +1,203 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:photos/models/collection/collection.dart';
+import 'package:photos/ui/sharing/library_sharing/library_sharing_controller.dart';
+
+import 'library_sharing_test_helpers.dart';
+
+void main() {
+ test('shares a new album and returns to the shared overview', () async {
+ final repository = FakeLibrarySharingRepository([
+ librarySharingTestAlbum(
+ 1,
+ recipientRole: CollectionParticipantRole.viewer,
+ ),
+ librarySharingTestAlbum(2),
+ librarySharingTestAlbum(3),
+ ]);
+ final controller = LibrarySharingController(
+ recipient: librarySharingTestRecipient,
+ repository: repository,
+ );
+ await controller.load();
+ controller.enterAddMode();
+ controller.toggleSelection(repository.albums[1]);
+ controller.setRoleForSelection(CollectionParticipantRole.collaborator);
+
+ expect(await controller.applySelection(), isTrue);
+ expect(repository.publicKeyRequests, 1);
+ expect(repository.sharedIDs, [2]);
+ expect(controller.activeRoleFor(1), CollectionParticipantRole.viewer);
+ expect(controller.activeRoleFor(2), CollectionParticipantRole.collaborator);
+ expect(controller.selectedAlbums, isEmpty);
+ expect(controller.isSelecting, isFalse);
+ expect(controller.visibleAlbums.map((album) => album.id), [1, 2]);
+ });
+
+ test('retains only failed albums for an exact retry', () async {
+ final repository = FakeLibrarySharingRepository([
+ librarySharingTestAlbum(1),
+ librarySharingTestAlbum(2),
+ librarySharingTestAlbum(
+ 3,
+ recipientRole: CollectionParticipantRole.admin,
+ ),
+ ])..shareFailures[2] = StateError('failed');
+ final controller = LibrarySharingController(
+ recipient: librarySharingTestRecipient,
+ repository: repository,
+ );
+ await controller.load();
+ controller.enterAddMode();
+ controller.selectAll();
+
+ expect(await controller.applySelection(), isFalse);
+ expect(controller.selectedAlbums.map((album) => album.id).toSet(), {2});
+ expect(controller.failedCount, 1);
+ expect(controller.activeRoleFor(1), CollectionParticipantRole.admin);
+ expect(controller.activeRoleFor(2), isNull);
+
+ repository.shareFailures.clear();
+ expect(await controller.applySelection(), isTrue);
+ expect(repository.sharedIDs, [1, 2, 2]);
+ });
+
+ test('updates the role of a selected existing share', () async {
+ final repository = FakeLibrarySharingRepository([
+ librarySharingTestAlbum(
+ 1,
+ recipientRole: CollectionParticipantRole.viewer,
+ ),
+ librarySharingTestAlbum(2),
+ ]);
+ final controller = LibrarySharingController(
+ recipient: librarySharingTestRecipient,
+ repository: repository,
+ );
+ await controller.load();
+ controller.enterManageMode();
+ controller.toggleSelection(repository.albums[0]);
+ controller.setRoleForSelection(CollectionParticipantRole.collaborator);
+
+ expect(await controller.applySelection(), isTrue);
+ expect(repository.sharedIDs, [1]);
+ expect(controller.activeRoleFor(1), CollectionParticipantRole.collaborator);
+ expect(controller.visibleAlbums.map((album) => album.id), [1]);
+ });
+
+ test('drops selections that no longer belong to the active mode', () async {
+ final repository = FakeLibrarySharingRepository([
+ librarySharingTestAlbum(1),
+ librarySharingTestAlbum(
+ 2,
+ recipientRole: CollectionParticipantRole.viewer,
+ ),
+ ]);
+ final controller = LibrarySharingController(
+ recipient: librarySharingTestRecipient,
+ repository: repository,
+ );
+ await controller.load();
+ controller.enterAddMode();
+ controller.toggleSelection(repository.albums[0]);
+
+ await repository.shareAlbum(
+ collection: repository.albums[0],
+ email: librarySharingTestRecipient.email,
+ publicKey: 'public-key',
+ role: CollectionParticipantRole.viewer,
+ );
+ await controller.load();
+
+ expect(controller.selectedAlbums, isEmpty);
+ expect(controller.visibleAlbums, isEmpty);
+ });
+
+ test('stops sharing only selected active shares', () async {
+ final repository = FakeLibrarySharingRepository([
+ librarySharingTestAlbum(
+ 1,
+ recipientRole: CollectionParticipantRole.admin,
+ ),
+ librarySharingTestAlbum(2),
+ ]);
+ final controller = LibrarySharingController(
+ recipient: librarySharingTestRecipient,
+ repository: repository,
+ );
+ await controller.load();
+ controller.enterManageMode();
+ controller.selectAll();
+
+ expect(controller.selectedActiveShareCount, 1);
+ expect(await controller.stopSharingSelected(), isTrue);
+ expect(repository.unsharedIDs, [1]);
+ expect(controller.activeRoleFor(1), isNull);
+ expect(controller.isFirstTime, isTrue);
+ });
+
+ test('freezes selection and roles while a batch is running', () async {
+ final gate = Completer<void>();
+ final repository = FakeLibrarySharingRepository([
+ librarySharingTestAlbum(1),
+ librarySharingTestAlbum(2),
+ ])..shareGate = gate;
+ final controller = LibrarySharingController(
+ recipient: librarySharingTestRecipient,
+ repository: repository,
+ );
+ await controller.load();
+ controller.toggleSelection(repository.albums[0]);
+
+ final apply = controller.applySelection();
+ expect(controller.isMutating, isTrue);
+ controller.toggleSelection(repository.albums[1]);
+ controller.selectAll();
+ controller.setRoleForSelection(CollectionParticipantRole.viewer);
+
+ expect(controller.selectedAlbums.map((album) => album.id).toSet(), {1});
+ expect(controller.stagedRoleFor(1), CollectionParticipantRole.admin);
+
+ gate.complete();
+ expect(await apply, isTrue);
+ expect(repository.sharedRoles, [CollectionParticipantRole.admin]);
+ });
+
+ test(
+ 'does not retry successful writes when the local refresh fails',
+ () async {
+ final repository = FakeLibrarySharingRepository([
+ librarySharingTestAlbum(1),
+ ]);
+ final controller = LibrarySharingController(
+ recipient: librarySharingTestRecipient,
+ repository: repository,
+ );
+ await controller.load();
+ controller.selectAll();
+ repository.loadFailure = StateError('refresh failed');
+
+ expect(await controller.applySelection(), isTrue);
+ expect(controller.selectedAlbums, isEmpty);
+ expect(controller.activeRoleFor(1), CollectionParticipantRole.admin);
+ expect(repository.sharedIDs, [1]);
+ },
+ );
+
+ test('can be disposed while an album load is in flight', () async {
+ final loadGate = Completer<List<Collection>>();
+ final repository = FakeLibrarySharingRepository(const [])
+ ..loadGate = loadGate;
+ final controller = LibrarySharingController(
+ recipient: librarySharingTestRecipient,
+ repository: repository,
+ );
+
+ final load = controller.load();
+ controller.dispose();
+ loadGate.complete(const []);
+
+ await expectLater(load, completes);
+ });
+}
diff --git a/mobile/apps/photos/test/ui/sharing/library_sharing_page_test.dart b/mobile/apps/photos/test/ui/sharing/library_sharing_page_test.dart
new file mode 100644
index 0000000000..fcc8ac311f
--- /dev/null
+++ b/mobile/apps/photos/test/ui/sharing/library_sharing_page_test.dart
@@ -0,0 +1,535 @@
+import 'dart:async';
+
+import 'package:ente_components/ente_components.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart' show ScrollDirection;
+import 'package:flutter/semantics.dart' show SemanticsAction, SemanticsFlag;
+import 'package:flutter_test/flutter_test.dart';
+import 'package:photos/ente_theme_data.dart';
+import 'package:photos/generated/l10n.dart';
+import 'package:photos/models/collection/collection.dart';
+import 'package:photos/ui/sharing/library_sharing/library_sharing_controller.dart';
+import 'package:photos/ui/sharing/library_sharing/library_sharing_page.dart';
+import 'package:photos/ui/sharing/library_sharing/library_sharing_selection_sheet.dart';
+import 'package:photos/ui/sharing/library_sharing/library_sharing_sheets.dart';
+
+import 'library_sharing_test_helpers.dart';
+
+void main() {
+ testWidgets('empty first-time flow shows the library sharing banner', (
+ tester,
+ ) async {
+ await tester.binding.setSurfaceSize(const Size(375, 812));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final controller = LibrarySharingController(
+ recipient: librarySharingTestRecipient,
+ repository: FakeLibrarySharingRepository(const []),
+ );
+
+ await tester.pumpWidget(
+ _app(
+ LibrarySharingPage(
+ recipient: librarySharingTestRecipient,
+ controller: controller,
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ expect(find.byType(LibrarySharingSelectionSheet), findsNothing);
+ expect(find.text('No albums to share yet'), findsOneWidget);
+ expect(find.text('Library Sharing'), findsOneWidget);
+ expect(find.byType(ToggleSwitchComponent), findsOneWidget);
+ });
+
+ testWidgets('existing recipient add mode renders the Share with state', (
+ tester,
+ ) async {
+ final controller = LibrarySharingController(
+ recipient: librarySharingTestRecipient,
+ repository: FakeLibrarySharingRepository([
+ librarySharingTestAlbum(
+ 1,
+ recipientRole: CollectionParticipantRole.viewer,
+ ),
+ ]),
+ );
+ await controller.load();
+ controller.enterAddMode();
+
+ await tester.pumpWidget(
+ _app(
+ LibrarySharingPage(
+ recipient: librarySharingTestRecipient,
+ controller: controller,
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ expect(find.text('Share with'), findsOneWidget);
+ expect(find.text('Sharing with'), findsNothing);
+ expect(find.text('All your current albums are shared'), findsOneWidget);
+ expect(find.text('Library Sharing'), findsNothing);
+ expect(find.byType(LibrarySharingSelectionSheet), findsNothing);
+ expect(find.byType(ToggleSwitchComponent), findsNothing);
+ });
+
+ testWidgets('library sharing banner opens the enable preview', (
+ tester,
+ ) async {
+ final controller = _LayoutTestLibrarySharingController();
+
+ await tester.pumpWidget(
+ _app(
+ LibrarySharingPage(
+ recipient: librarySharingTestRecipient,
+ controller: controller,
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ expect(find.text('Library Sharing'), findsOneWidget);
+ expect(find.text('Share all your albums'), findsOneWidget);
+ final toggle = tester.widget<ToggleSwitchComponent>(
+ find.byKey(const ValueKey('library-sharing-toggle')),
+ );
+ expect(toggle.selected, isFalse);
+
+ await tester.tap(find.text('Library Sharing'));
+ await tester.pumpAndSettle();
+
+ expect(find.text('Enable library sharing?'), findsOneWidget);
+ expect(
+ find.text(
+ 'Your existing albums, and the ones you create in the future will be automatically shared with Friend.',
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.text(
+ 'Hidden albums will not be shared. You can stop sharing any album at any time.',
+ ),
+ findsOneWidget,
+ );
+ expect(find.text('Role'), findsOneWidget);
+ expect(find.text('Admin'), findsOneWidget);
+
+ await tester.tap(find.text('Enable'));
+ await tester.pumpAndSettle();
+
+ expect(find.text('Enable library sharing?'), findsNothing);
+ expect(find.text('Coming soon'), findsOneWidget);
+ expect(
+ tester
+ .widget<ToggleSwitchComponent>(
+ find.byKey(const ValueKey('library-sharing-toggle')),
+ )
+ .selected,
+ isFalse,
+ );
+ await tester.pump(const Duration(seconds: 5));
+ });
+
+ testWidgets('keeps the library sharing banner while albums are selected', (
+ tester,
+ ) async {
+ final controller = _LayoutTestLibrarySharingController();
+
+ await tester.pumpWidget(
+ _app(
+ LibrarySharingPage(
+ recipient: librarySharingTestRecipient,
+ controller: controller,
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ expect(find.text('Library Sharing'), findsOneWidget);
+ expect(find.byType(LibrarySharingSelectionSheet), findsNothing);
+
+ controller.enterManageMode();
+ controller.selectAll();
+ await tester.pumpAndSettle();
+ expect(find.text('Library Sharing'), findsOneWidget);
+ expect(find.byType(LibrarySharingSelectionSheet), findsOneWidget);
+
+ controller.clearSelection();
+ await tester.pumpAndSettle();
+ expect(find.text('Library Sharing'), findsOneWidget);
+ expect(find.byType(LibrarySharingSelectionSheet), findsNothing);
+ expect(find.byTooltip('Share albums'), findsOneWidget);
+ });
+
+ testWidgets('mixed selection routes role editing and offers stop sharing', (
+ tester,
+ ) async {
+ await tester.binding.setSurfaceSize(const Size(375, 812));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final repository = FakeLibrarySharingRepository([
+ librarySharingTestAlbum(
+ 1,
+ recipientRole: CollectionParticipantRole.viewer,
+ ),
+ librarySharingTestAlbum(
+ 2,
+ recipientRole: CollectionParticipantRole.admin,
+ ),
+ ]);
+ final controller = LibrarySharingController(
+ recipient: librarySharingTestRecipient,
+ repository: repository,
+ );
+ await controller.load();
+ controller.enterManageMode();
+ controller.selectAll();
+ var mixedRolesOpened = false;
+
+ await tester.pumpWidget(
+ _app(
+ Scaffold(
+ body: Align(
+ alignment: Alignment.bottomCenter,
+ child: LibrarySharingSelectionSheet(
+ controller: controller,
+ onApply: () async {},
+ onStopSharing: () async {},
+ onShowMixedRoles: () => mixedRolesOpened = true,
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ expect(find.text('2 selected'), findsOneWidget);
+ expect(find.text('Mixed'), findsOneWidget);
+ expect(find.text('Stop sharing'), findsOneWidget);
+
+ await tester.tap(find.text('Mixed'));
+ expect(mixedRolesOpened, isTrue);
+ });
+
+ testWidgets('shows loading before the empty add state', (tester) async {
+ final loadGate = Completer<List<Collection>>();
+ final controller = LibrarySharingController(
+ recipient: librarySharingTestRecipient,
+ repository: FakeLibrarySharingRepository(const [], loadGate: loadGate),
+ );
+
+ await tester.pumpWidget(
+ _app(
+ LibrarySharingPage(
+ recipient: librarySharingTestRecipient,
+ controller: controller,
+ ),
+ ),
+ );
+ await tester.pump();
+
+ expect(find.byType(CircularProgressIndicator), findsOneWidget);
+ expect(find.byType(LibrarySharingSelectionSheet), findsNothing);
+
+ loadGate.complete(const []);
+ await tester.pumpAndSettle();
+ expect(find.byType(CircularProgressIndicator), findsNothing);
+ expect(find.text('No albums to share yet'), findsOneWidget);
+ expect(find.byType(LibrarySharingSelectionSheet), findsNothing);
+ });
+
+ testWidgets('roles sheet cannot be dismissed while an update is running', (
+ tester,
+ ) async {
+ final gate = Completer<void>();
+ final repository =
+ FakeLibrarySharingRepository([
+ librarySharingTestAlbum(
+ 1,
+ recipientRole: CollectionParticipantRole.viewer,
+ ),
+ librarySharingTestAlbum(
+ 2,
+ recipientRole: CollectionParticipantRole.admin,
+ ),
+ ])
+ ..shareGate = gate
+ ..shareFailures[1] = StateError('failed');
+ final controller = LibrarySharingController(
+ recipient: librarySharingTestRecipient,
+ repository: repository,
+ );
+ await controller.load();
+ controller.enterManageMode();
+ controller.selectAll();
+ controller.setRoleForAlbum(1, CollectionParticipantRole.collaborator);
+ bool? result;
+
+ await tester.pumpWidget(
+ _app(
+ Builder(
+ builder: (context) => Scaffold(
+ body: TextButton(
+ onPressed: () async {
+ result = await showLibrarySharingRolesSheet(
+ context: context,
+ controller: controller,
+ albumThumbnailBuilder: (_, _) =>
+ const ColoredBox(color: Colors.red),
+ );
+ },
+ child: const Text('Open roles'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('Open roles'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Update roles'));
+ await tester.pump();
+
+ expect(controller.isMutating, isTrue);
+ expect(find.byTooltip('Close'), findsNothing);
+ await tester.tapAt(const Offset(8, 8));
+ await tester.pump();
+ expect(find.text('Roles'), findsOneWidget);
+ await tester.drag(find.byType(BottomSheet), const Offset(0, 500));
+ await tester.pumpAndSettle();
+ expect(find.text('Roles'), findsOneWidget);
+
+ gate.complete();
+ await tester.pumpAndSettle();
+ expect(result, isFalse);
+ expect(find.text('Roles'), findsNothing);
+ });
+
+ testWidgets('supports sheet expansion controls over scrollable content', (
+ tester,
+ ) async {
+ await tester.binding.setSurfaceSize(const Size(375, 812));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final controller = _LayoutTestLibrarySharingController();
+ await controller.load();
+ controller.enterManageMode();
+ controller.selectAll();
+
+ await tester.pumpWidget(
+ _app(
+ LibrarySharingPage(
+ recipient: librarySharingTestRecipient,
+ controller: controller,
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ final scrollView = find.byType(CustomScrollView);
+ final selectionSheet = find.byType(LibrarySharingSelectionSheet);
+ final selectionSheetAnimation = find.ancestor(
+ of: selectionSheet,
+ matching: find.byType(AnimatedSize),
+ );
+ expect(scrollView, findsOneWidget);
+ expect(selectionSheet, findsOneWidget);
+ expect(selectionSheetAnimation, findsOneWidget);
+ bool isExpanded() =>
+ tester.widget<LibrarySharingSelectionSheet>(selectionSheet).isExpanded;
+ expect(isExpanded(), isTrue);
+ final expandedHeight = tester.getSize(selectionSheet).height;
+ expect(
+ tester.getBottomLeft(scrollView).dy,
+ greaterThan(tester.getTopLeft(selectionSheet).dy),
+ );
+
+ await tester.drag(selectionSheet, const Offset(0, 100));
+ await tester.pumpAndSettle();
+ expect(isExpanded(), isFalse);
+ expect(find.text('Role'), findsNothing);
+ expect(find.text('Stop sharing'), findsNothing);
+ expect(find.text('Save'), findsOneWidget);
+
+ await tester.drag(selectionSheet, const Offset(0, -100));
+ await tester.pump();
+ expect(isExpanded(), isTrue);
+ expect(tester.getSize(selectionSheet).height, expandedHeight);
+ expect(
+ tester.getSize(selectionSheetAnimation).height,
+ lessThan(expandedHeight),
+ );
+ await tester.pumpAndSettle();
+
+ final gesture = await tester.startGesture(tester.getCenter(selectionSheet));
+ await gesture.moveBy(const Offset(0, 100));
+ await tester.pump();
+ expect(isExpanded(), isTrue);
+ await gesture.moveBy(const Offset(0, -10));
+ await gesture.up();
+ await tester.pumpAndSettle();
+ expect(isExpanded(), isFalse);
+
+ await tester.drag(selectionSheet, const Offset(0, -100));
+ await tester.pumpAndSettle();
+ expect(isExpanded(), isTrue);
+
+ final scrollContext = tester.element(scrollView);
+ final scrollPosition = tester
+ .state<ScrollableState>(
+ find.descendant(of: scrollView, matching: find.byType(Scrollable)),
+ )
+ .position;
+ UserScrollNotification(
+ metrics: scrollPosition,
+ context: scrollContext,
+ direction: ScrollDirection.reverse,
+ ).dispatch(scrollContext);
+ await tester.pumpAndSettle();
+ expect(isExpanded(), isFalse);
+
+ UserScrollNotification(
+ metrics: scrollPosition,
+ context: scrollContext,
+ direction: ScrollDirection.forward,
+ ).dispatch(scrollContext);
+ await tester.pumpAndSettle();
+ expect(isExpanded(), isTrue);
+
+ final semantics = tester.ensureSemantics();
+ final selectionControls = find.bySemanticsLabel('Album selection controls');
+ var semanticsData = tester
+ .getSemantics(selectionControls)
+ .getSemanticsData();
+ expect(semanticsData.hasFlag(SemanticsFlag.hasExpandedState), isTrue);
+ expect(semanticsData.hasFlag(SemanticsFlag.isExpanded), isTrue);
+ expect(semanticsData.hasAction(SemanticsAction.collapse), isTrue);
+ expect(semanticsData.hasAction(SemanticsAction.expand), isFalse);
+
+ final semanticsNode = tester.getSemantics(selectionControls);
+ semanticsNode.owner!.performAction(
+ semanticsNode.id,
+ SemanticsAction.collapse,
+ );
+ await tester.pumpAndSettle();
+ expect(isExpanded(), isFalse);
+ semanticsData = tester.getSemantics(selectionControls).getSemanticsData();
+ expect(semanticsData.hasFlag(SemanticsFlag.isExpanded), isFalse);
+ expect(semanticsData.hasAction(SemanticsAction.expand), isTrue);
+ expect(semanticsData.hasAction(SemanticsAction.collapse), isFalse);
+ semantics.dispose();
+ });
+
+ testWidgets('fits 2x accessibility text on a 320x568 viewport', (
+ tester,
+ ) async {
+ await tester.binding.setSurfaceSize(const Size(320, 568));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final controller = _LayoutTestLibrarySharingController();
+ await controller.load();
+ controller.enterManageMode();
+ controller.selectAll();
+
+ await tester.pumpWidget(
+ _app(
+ MediaQuery(
+ data: const MediaQueryData(
+ size: Size(320, 568),
+ textScaler: TextScaler.linear(2),
+ ),
+ child: LibrarySharingPage(
+ recipient: librarySharingTestRecipient,
+ controller: controller,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ expect(find.byType(LibrarySharingSelectionSheet), findsOneWidget);
+ expect(find.text('Role'), findsOneWidget);
+ expect(find.text('Stop sharing'), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets('keeps the role action reachable for long selections', (
+ tester,
+ ) async {
+ await tester.binding.setSurfaceSize(const Size(375, 812));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final repository = FakeLibrarySharingRepository([
+ for (var index = 0; index < 16; index++)
+ librarySharingTestAlbum(
+ index + 1,
+ recipientRole: index.isEven
+ ? CollectionParticipantRole.viewer
+ : CollectionParticipantRole.admin,
+ ),
+ ]);
+ final controller = LibrarySharingController(
+ recipient: librarySharingTestRecipient,
+ repository: repository,
+ );
+ await controller.load();
+ controller.enterManageMode();
+ controller.selectAll();
+
+ await tester.pumpWidget(
+ _app(
+ Builder(
+ builder: (context) => Scaffold(
+ body: TextButton(
+ onPressed: () => showLibrarySharingRolesSheet(
+ context: context,
+ controller: controller,
+ albumThumbnailBuilder: (_, album) => ColoredBox(
+ key: ValueKey('album-thumbnail-${album.id}'),
+ color: Colors.red,
+ ),
+ ),
+ child: const Text('Open roles'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('Open roles'));
+ await tester.pumpAndSettle();
+
+ expect(find.byType(DraggableScrollableSheet), findsNothing);
+ expect(find.byKey(const ValueKey('album-thumbnail-1')), findsOneWidget);
+ final roleList = find.byKey(const ValueKey('library-sharing-role-list'));
+ expect(find.text('Update roles'), findsOneWidget);
+ for (var index = 0; index < 6; index++) {
+ await tester.drag(roleList, const Offset(0, -400));
+ await tester.pumpAndSettle();
+ }
+ expect(find.byKey(const ValueKey('album-thumbnail-16')), findsOneWidget);
+ expect(find.text('Update roles'), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ });
+}
+
+Widget _app(Widget home) {
+ return MaterialApp(
+ theme: lightThemeData,
+ localizationsDelegates: AppLocalizations.localizationsDelegates,
+ supportedLocales: AppLocalizations.supportedLocales,
+ home: home,
+ );
+}
+
+class _LayoutTestLibrarySharingController extends LibrarySharingController {
+ _LayoutTestLibrarySharingController()
+ : super(
+ recipient: librarySharingTestRecipient,
+ repository: FakeLibrarySharingRepository([
+ librarySharingTestAlbum(
+ 1,
+ recipientRole: CollectionParticipantRole.viewer,
+ ),
+ ]),
+ );
+
+ @override
+ List<Collection> get visibleAlbums => const [];
+}
diff --git a/mobile/apps/photos/test/ui/sharing/library_sharing_test_helpers.dart b/mobile/apps/photos/test/ui/sharing/library_sharing_test_helpers.dart
new file mode 100644
index 0000000000..4185aeffc4
--- /dev/null
+++ b/mobile/apps/photos/test/ui/sharing/library_sharing_test_helpers.dart
@@ -0,0 +1,108 @@
+import 'dart:async';
+
+import 'package:photos/models/api/collection/user.dart';
+import 'package:photos/models/collection/collection.dart';
+import 'package:photos/models/library_sharing/library_sharing_recipient.dart';
+import 'package:photos/services/library_sharing_service.dart';
+
+const librarySharingTestRecipient = LibrarySharingRecipient(
+ userID: 42,
+ email: '[email protected]',
+ displayName: 'Friend',
+);
+
+class FakeLibrarySharingRepository implements LibrarySharingRepository {
+ FakeLibrarySharingRepository(this.albums, {this.loadGate});
+
+ final List<Collection> albums;
+ final Map<int, Object> shareFailures = {};
+ final List<int> sharedIDs = [];
+ final List<int> unsharedIDs = [];
+ final List<CollectionParticipantRole> sharedRoles = [];
+ Completer<void>? shareGate;
+ Completer<List<Collection>>? loadGate;
+ Object? loadFailure;
+ int publicKeyRequests = 0;
+
+ @override
+ Future<List<Collection>> getEligibleAlbums() async {
+ final gate = loadGate;
+ if (gate != null) {
+ return gate.future;
+ }
+ final failure = loadFailure;
+ if (failure != null) {
+ throw failure;
+ }
+ return albums;
+ }
+
+ @override
+ Future<String?> getPublicKey(String email) async {
+ publicKeyRequests++;
+ return 'public-key';
+ }
+
+ @override
+ Future<void> shareAlbum({
+ required Collection collection,
+ required String email,
+ required String publicKey,
+ required CollectionParticipantRole role,
+ }) async {
+ sharedIDs.add(collection.id);
+ sharedRoles.add(role);
+ await shareGate?.future;
+ final failure = shareFailures[collection.id];
+ if (failure != null) {
+ throw failure;
+ }
+ collection.sharees.removeWhere(
+ (sharee) => sharee.id == librarySharingTestRecipient.userID,
+ );
+ collection.sharees.add(
+ User(
+ id: librarySharingTestRecipient.userID,
+ email: email,
+ role: role.toStringVal(),
+ ),
+ );
+ }
+
+ @override
+ Future<void> unshareAlbum({
+ required Collection collection,
+ required int recipientUserID,
+ required String email,
+ }) async {
+ unsharedIDs.add(collection.id);
+ collection.sharees.removeWhere((sharee) => sharee.id == recipientUserID);
+ }
+}
+
+Collection librarySharingTestAlbum(
+ int id, {
+ CollectionParticipantRole? recipientRole,
+}) {
+ return Collection(
+ id,
+ User(id: 1, email: '[email protected]'),
+ '',
+ null,
+ 'Album $id',
+ null,
+ null,
+ CollectionType.album,
+ CollectionAttributes(),
+ [
+ if (recipientRole != null)
+ User(
+ id: librarySharingTestRecipient.userID,
+ email: librarySharingTestRecipient.email,
+ role: recipientRole.toStringVal(),
+ ),
+ ],
+ [],
+ id,
+ );
+}