refactor: Pages folder structure

This commit is contained in:
Krille Fear 2021-11-09 21:32:16 +01:00
commit 1abb7310f3
88 changed files with 188 additions and 250 deletions

View file

@ -0,0 +1,524 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:flutter_gen/gen_l10n/l10n.dart';
import 'package:future_loading_dialog/future_loading_dialog.dart';
import 'package:matrix/matrix.dart';
import 'package:receive_sharing_intent/receive_sharing_intent.dart';
import 'package:uni_links/uni_links.dart';
import 'package:vrouter/vrouter.dart';
import 'package:fluffychat/config/app_config.dart';
import 'package:fluffychat/config/setting_keys.dart';
import 'package:fluffychat/pages/chat_list/chat_list_view.dart';
import 'package:fluffychat/utils/fluffy_share.dart';
import 'package:fluffychat/utils/matrix_sdk_extensions.dart/flutter_matrix_hive_database.dart';
import 'package:fluffychat/utils/platform_infos.dart';
import '../../../utils/account_bundles.dart';
import '../../main.dart';
import '../../utils/matrix_sdk_extensions.dart/matrix_file_extension.dart';
import '../../utils/url_launcher.dart';
import '../../widgets/matrix.dart';
import '../bootstrap/bootstrap_dialog.dart';
enum SelectMode { normal, share, select }
enum PopupMenuAction {
settings,
invite,
newGroup,
newSpace,
setStatus,
archive,
}
class ChatList extends StatefulWidget {
const ChatList({Key key}) : super(key: key);
@override
ChatListController createState() => ChatListController();
}
class ChatListController extends State<ChatList> {
StreamSubscription _intentDataStreamSubscription;
StreamSubscription _intentFileStreamSubscription;
StreamSubscription _intentUriStreamSubscription;
String _activeSpaceId;
String get activeSpaceId => _activeSpaceId;
final ScrollController scrollController = ScrollController();
bool scrolledToTop = true;
void _onScroll() {
final newScrolledToTop = scrollController.position.pixels <= 0;
if (newScrolledToTop != scrolledToTop) {
setState(() {
scrolledToTop = newScrolledToTop;
});
}
}
void setActiveSpaceId(BuildContext context, String spaceId) {
Scaffold.of(context).openEndDrawer();
setState(() => _activeSpaceId = spaceId);
}
void editSpace(BuildContext context, String spaceId) async {
Scaffold.of(context).openEndDrawer();
await Matrix.of(context).client.getRoomById(spaceId).postLoad();
VRouter.of(context).toSegments(['spaces', spaceId]);
}
List<Room> get spaces =>
Matrix.of(context).client.rooms.where((r) => r.isSpace).toList();
final selectedRoomIds = <String>{};
Future<bool> crossSigningCachedFuture;
bool crossSigningCached;
bool hideChatBackupBanner = false;
void hideChatBackupBannerAction() =>
setState(() => hideChatBackupBanner = true);
void firstRunBootstrapAction() async {
hideChatBackupBannerAction();
await BootstrapDialog(
client: Matrix.of(context).client,
).show(context);
VRouter.of(context).to('/rooms');
}
String get activeChat => VRouter.of(context).pathParameters['roomid'];
SelectMode get selectMode => Matrix.of(context).shareContent != null
? SelectMode.share
: selectedRoomIds.isEmpty
? SelectMode.normal
: SelectMode.select;
void _processIncomingSharedFiles(List<SharedMediaFile> files) {
if (files?.isEmpty ?? true) return;
VRouter.of(context).to('/rooms');
final file = File(files.first.path);
Matrix.of(context).shareContent = {
'msgtype': 'chat.fluffy.shared_file',
'file': MatrixFile(
bytes: file.readAsBytesSync(),
name: file.path,
).detectFileType,
};
}
void _processIncomingSharedText(String text) {
if (text == null) return;
VRouter.of(context).to('/rooms');
if (text.toLowerCase().startsWith(AppConfig.inviteLinkPrefix) ||
(text.toLowerCase().startsWith(AppConfig.schemePrefix) &&
!RegExp(r'\s').hasMatch(text))) {
return;
}
Matrix.of(context).shareContent = {
'msgtype': 'm.text',
'body': text,
};
}
void _processIncomingUris(String text) async {
if (text == null) return;
VRouter.of(context).to('/rooms');
UrlLauncher(context, text).openMatrixToUrl();
return;
}
void _initReceiveSharingIntent() {
if (!PlatformInfos.isMobile) return;
// For sharing images coming from outside the app while the app is in the memory
_intentFileStreamSubscription = ReceiveSharingIntent.getMediaStream()
.listen(_processIncomingSharedFiles, onError: print);
// For sharing images coming from outside the app while the app is closed
ReceiveSharingIntent.getInitialMedia().then(_processIncomingSharedFiles);
// For sharing or opening urls/text coming from outside the app while the app is in the memory
_intentDataStreamSubscription = ReceiveSharingIntent.getTextStream()
.listen(_processIncomingSharedText, onError: print);
// For sharing or opening urls/text coming from outside the app while the app is closed
ReceiveSharingIntent.getInitialText().then(_processIncomingSharedText);
// For receiving shared Uris
_intentUriStreamSubscription = linkStream.listen(_processIncomingUris);
if (FluffyChatApp.gotInitialLink == false) {
FluffyChatApp.gotInitialLink = true;
getInitialLink().then(_processIncomingUris);
}
}
@override
void initState() {
_initReceiveSharingIntent();
WidgetsBinding.instance.addPostFrameCallback(
(_) => waitForFirstSync.then((_) => checkBootstrap()),
);
scrollController.addListener(_onScroll);
waitForFirstSync = _waitForFirstSync();
super.initState();
}
void checkBootstrap() async {
if (!Matrix.of(context).client.encryptionEnabled) return;
if ((Matrix.of(context).client.database as FlutterMatrixHiveStore)
.get(SettingKeys.dontAskForBootstrapKey) ==
true) {
return;
}
final crossSigning = await crossSigningCachedFuture;
final needsBootstrap =
Matrix.of(context).client.encryption?.crossSigning?.enabled == false ||
crossSigning == false;
final isUnknownSession = Matrix.of(context).client.isUnknownSession;
if (needsBootstrap || isUnknownSession) {
firstRunBootstrapAction();
}
}
@override
void dispose() {
_intentDataStreamSubscription?.cancel();
_intentFileStreamSubscription?.cancel();
_intentUriStreamSubscription?.cancel();
scrollController.removeListener(_onScroll);
super.dispose();
}
bool roomCheck(Room room) {
if (room.isSpace && room.membership == Membership.join && !room.isUnread) {
return false;
}
if (activeSpaceId != null) {
final space = Matrix.of(context).client.getRoomById(activeSpaceId);
if (space.spaceChildren?.any((child) => child.roomId == room.id) ??
false) {
return true;
}
if (room.spaceParents?.any((parent) => parent.roomId == activeSpaceId) ??
false) {
return true;
}
if (room.isDirectChat &&
room.summary?.mHeroes != null &&
room.summary.mHeroes.any((userId) {
final user = space.getState(EventTypes.RoomMember, userId)?.asUser;
return user != null && user.membership == Membership.join;
})) {
return true;
}
return false;
}
return true;
}
void toggleSelection(String roomId) {
setState(() => selectedRoomIds.contains(roomId)
? selectedRoomIds.remove(roomId)
: selectedRoomIds.add(roomId));
}
Future<void> toggleUnread() {
final room = Matrix.of(context).client.getRoomById(selectedRoomIds.single);
return showFutureLoadingDialog(
context: context,
future: () => room.markUnread(!room.isUnread),
);
}
Future<void> toggleFavouriteRoom() {
final room = Matrix.of(context).client.getRoomById(selectedRoomIds.single);
return showFutureLoadingDialog(
context: context,
future: () => room.setFavourite(!room.isFavourite),
);
}
Future<void> toggleMuted() {
final room = Matrix.of(context).client.getRoomById(selectedRoomIds.single);
return showFutureLoadingDialog(
context: context,
future: () => room.setPushRuleState(
room.pushRuleState == PushRuleState.notify
? PushRuleState.mentionsOnly
: PushRuleState.notify),
);
}
Future<void> archiveAction() async {
final confirmed = await showOkCancelAlertDialog(
useRootNavigator: false,
context: context,
title: L10n.of(context).areYouSure,
okLabel: L10n.of(context).yes,
cancelLabel: L10n.of(context).cancel,
) ==
OkCancelResult.ok;
if (!confirmed) return;
await showFutureLoadingDialog(
context: context,
future: () => _archiveSelectedRooms(),
);
setState(() => null);
}
void setStatus() async {
final input = await showTextInputDialog(
useRootNavigator: false,
context: context,
title: L10n.of(context).setStatus,
okLabel: L10n.of(context).ok,
cancelLabel: L10n.of(context).cancel,
textFields: [
DialogTextField(
hintText: L10n.of(context).statusExampleMessage,
),
]);
if (input == null) return;
await showFutureLoadingDialog(
context: context,
future: () => Matrix.of(context).client.setPresence(
Matrix.of(context).client.userID,
PresenceType.online,
statusMsg: input.single,
),
);
}
void onPopupMenuSelect(action) {
switch (action) {
case PopupMenuAction.setStatus:
setStatus();
break;
case PopupMenuAction.settings:
VRouter.of(context).to('/settings');
break;
case PopupMenuAction.invite:
FluffyShare.share(
L10n.of(context).inviteText(Matrix.of(context).client.userID,
'https://matrix.to/#/${Matrix.of(context).client.userID}'),
context);
break;
case PopupMenuAction.newGroup:
VRouter.of(context).to('/newgroup');
break;
case PopupMenuAction.newSpace:
VRouter.of(context).to('/newspace');
break;
case PopupMenuAction.archive:
VRouter.of(context).to('/archive');
break;
}
}
Future<void> _archiveSelectedRooms() async {
final client = Matrix.of(context).client;
while (selectedRoomIds.isNotEmpty) {
final roomId = selectedRoomIds.first;
try {
await client.getRoomById(roomId).leave();
} finally {
toggleSelection(roomId);
}
}
}
Future<void> addOrRemoveToSpace() async {
if (activeSpaceId != null) {
final space = Matrix.of(context).client.getRoomById(activeSpaceId);
final result = await showFutureLoadingDialog(
context: context,
future: () => space.removeSpaceChild(selectedRoomIds.single),
);
if (result.error == null) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(L10n.of(context).chatHasBeenRemovedFromThisSpace),
),
);
}
} else {
final selectedSpace = await showConfirmationDialog<String>(
context: context,
title: L10n.of(context).addToSpace,
actions: Matrix.of(context)
.client
.rooms
.where((r) => r.isSpace)
.map(
(space) => AlertDialogAction(
key: space.id,
label: space.displayname,
),
)
.toList());
if (selectedSpace == null) return;
final result = await showFutureLoadingDialog(
context: context,
future: () => Matrix.of(context)
.client
.getRoomById(selectedSpace)
.setSpaceChild(selectedRoomIds.single),
);
if (result.error == null) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(L10n.of(context).chatHasBeenAddedToThisSpace),
),
);
}
}
setState(() => selectedRoomIds.clear());
}
Future<void> waitForFirstSync;
Future<void> _waitForFirstSync() async {
final client = Matrix.of(context).client;
await client.roomsLoading;
await client.accountDataLoading;
if (client.prevBatch?.isEmpty ?? true) {
await client.onFirstSync.stream.first;
}
// Load space members to display DM rooms
if (activeSpaceId != null) {
final space = client.getRoomById(activeSpaceId);
final localMembers = space.getParticipants().length;
final actualMembersCount = (space.summary?.mInvitedMemberCount ?? 0) +
(space.summary?.mJoinedMemberCount ?? 0);
if (localMembers < actualMembersCount) {
await space.requestParticipants();
}
}
return true;
}
void cancelAction() {
if (selectMode == SelectMode.share) {
setState(() => Matrix.of(context).shareContent = null);
} else {
setState(() => selectedRoomIds.clear());
}
}
void setActiveClient(Client client) {
VRouter.of(context).to('/rooms');
setState(() {
_activeSpaceId = null;
selectedRoomIds.clear();
Matrix.of(context).setActiveClient(client);
});
}
void setActiveBundle(String bundle) {
VRouter.of(context).to('/rooms');
setState(() {
_activeSpaceId = null;
selectedRoomIds.clear();
Matrix.of(context).activeBundle = bundle;
if (!Matrix.of(context)
.currentBundle
.any((client) => client == Matrix.of(context).client)) {
Matrix.of(context)
.setActiveClient(Matrix.of(context).currentBundle.first);
}
});
}
void editBundlesForAccount(String userId) async {
final client = Matrix.of(context)
.widget
.clients[Matrix.of(context).getClientIndexByMatrixId(userId)];
final action = await showConfirmationDialog<EditBundleAction>(
context: context,
title: L10n.of(context).editBundlesForAccount,
actions: [
AlertDialogAction(
key: EditBundleAction.addToBundle,
label: L10n.of(context).addToBundle,
),
if (Matrix.of(context).activeBundle != null)
AlertDialogAction(
key: EditBundleAction.removeFromBundle,
label: L10n.of(context).removeFromBundle,
),
],
);
if (action == null) return;
switch (action) {
case EditBundleAction.addToBundle:
final bundle = await showTextInputDialog(
context: context,
title: L10n.of(context).bundleName,
textFields: [
DialogTextField(hintText: L10n.of(context).bundleName)
]);
if (bundle.isEmpty && bundle.single.isEmpty) return;
await showFutureLoadingDialog(
context: context,
future: () => client.setAccountBundle(bundle.single),
);
break;
case EditBundleAction.removeFromBundle:
await showFutureLoadingDialog(
context: context,
future: () =>
client.removeFromAccountBundle(Matrix.of(context).activeBundle),
);
}
}
bool get displayBundles =>
Matrix.of(context).hasComplexBundles &&
Matrix.of(context).accountBundles.keys.length > 1;
String get secureActiveBundle {
if (Matrix.of(context).activeBundle == null ||
!Matrix.of(context)
.accountBundles
.keys
.contains(Matrix.of(context).activeBundle)) {
return Matrix.of(context).accountBundles.keys.first;
}
return Matrix.of(context).activeBundle;
}
void resetActiveBundle() {
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
setState(() {
Matrix.of(context).activeBundle = null;
});
});
}
@override
Widget build(BuildContext context) {
Matrix.of(context).navigatorContext = context;
crossSigningCachedFuture ??= Matrix.of(context)
.client
.encryption
?.crossSigning
?.isCached()
?.then((c) {
if (mounted) setState(() => crossSigningCached = c);
return c;
});
return ChatListView(this);
}
}
enum EditBundleAction { addToBundle, removeFromBundle }

View file

@ -0,0 +1,325 @@
import 'package:flutter/material.dart';
import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:flutter_gen/gen_l10n/l10n.dart';
import 'package:future_loading_dialog/future_loading_dialog.dart';
import 'package:matrix/matrix.dart';
import 'package:pedantic/pedantic.dart';
import 'package:vrouter/vrouter.dart';
import 'package:fluffychat/config/app_config.dart';
import 'package:fluffychat/utils/matrix_sdk_extensions.dart/event_extension.dart';
import 'package:fluffychat/utils/matrix_sdk_extensions.dart/matrix_locals.dart';
import 'package:fluffychat/utils/room_status_extension.dart';
import '../../utils/date_time_extension.dart';
import '../../widgets/avatar.dart';
import '../../widgets/matrix.dart';
import '../new_private_chat/send_file_dialog.dart';
enum ArchivedRoomAction { delete, rejoin }
class ChatListItem extends StatelessWidget {
final Room room;
final bool activeChat;
final bool selected;
final Function onForget;
final Function onTap;
final Function onLongPress;
const ChatListItem(
this.room, {
this.activeChat = false,
this.selected = false,
this.onTap,
this.onLongPress,
this.onForget,
Key key,
}) : super(key: key);
dynamic clickAction(BuildContext context) async {
if (onTap != null) return onTap();
if (!activeChat) {
if (room.membership == Membership.invite &&
(await showFutureLoadingDialog(
context: context,
future: () async {
final joinedFuture = room.client.onSync.stream
.where((u) =>
u.rooms?.join?.containsKey(room.id) ?? false)
.first;
await room.join();
await joinedFuture;
}))
.error !=
null) {
return;
}
if (room.membership == Membership.ban) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(L10n.of(context).youHaveBeenBannedFromThisChat),
),
);
return;
}
if (room.membership == Membership.leave) {
final action = await showModalActionSheet<ArchivedRoomAction>(
context: context,
title: L10n.of(context).archivedRoom,
message: L10n.of(context).thisRoomHasBeenArchived,
actions: [
SheetAction(
label: L10n.of(context).rejoin,
key: ArchivedRoomAction.rejoin,
),
SheetAction(
label: L10n.of(context).delete,
key: ArchivedRoomAction.delete,
isDestructiveAction: true,
),
],
);
if (action != null) {
switch (action) {
case ArchivedRoomAction.delete:
await archiveAction(context);
break;
case ArchivedRoomAction.rejoin:
await showFutureLoadingDialog(
context: context,
future: () => room.join(),
);
break;
}
}
}
if (room.membership == Membership.join) {
if (Matrix.of(context).shareContent != null) {
if (Matrix.of(context).shareContent['msgtype'] ==
'chat.fluffy.shared_file') {
await showDialog(
context: context,
useRootNavigator: false,
builder: (c) => SendFileDialog(
file: Matrix.of(context).shareContent['file'],
room: room,
),
);
} else {
unawaited(room.sendEvent(Matrix.of(context).shareContent));
}
Matrix.of(context).shareContent = null;
}
VRouter.of(context).toSegments(['rooms', room.id]);
}
}
}
Future<void> archiveAction(BuildContext context) async {
{
if ([Membership.leave, Membership.ban].contains(room.membership)) {
final success = await showFutureLoadingDialog(
context: context,
future: () => room.forget(),
);
if (success.error == null) {
if (onForget != null) onForget();
}
return success;
}
final confirmed = await showOkCancelAlertDialog(
useRootNavigator: false,
context: context,
title: L10n.of(context).areYouSure,
okLabel: L10n.of(context).yes,
cancelLabel: L10n.of(context).no,
);
if (confirmed == OkCancelResult.cancel) return;
await showFutureLoadingDialog(
context: context, future: () => room.leave());
return;
}
}
@override
Widget build(BuildContext context) {
final isMuted = room.pushRuleState != PushRuleState.notify;
final typingText = room.getLocalizedTypingText(context);
final ownMessage =
room.lastEvent?.senderId == Matrix.of(context).client.userID;
final unread = room.isUnread || room.membership == Membership.invite;
final unreadBubbleSize = unread
? room.notificationCount > 0
? 20.0
: 14.0
: 0.0;
return ListTile(
selected: selected || activeChat,
selectedTileColor: selected
? Theme.of(context).primaryColor.withAlpha(100)
: Theme.of(context).secondaryHeaderColor,
onLongPress: onLongPress,
leading: selected
? SizedBox(
width: Avatar.defaultSize,
height: Avatar.defaultSize,
child: Material(
color: Theme.of(context).primaryColor,
borderRadius: BorderRadius.circular(Avatar.defaultSize),
child: const Icon(Icons.check, color: Colors.white),
),
)
: Avatar(room.avatar, room.displayname, onTap: onLongPress),
title: Row(
children: <Widget>[
Expanded(
child: Text(
room.getLocalizedDisplayname(MatrixLocals(L10n.of(context))),
maxLines: 1,
overflow: TextOverflow.ellipsis,
softWrap: false,
style: TextStyle(
fontWeight: unread ? FontWeight.bold : null,
color: unread
? Theme.of(context).colorScheme.secondary
: Theme.of(context).textTheme.bodyText1.color,
),
),
),
if (isMuted)
const Padding(
padding: EdgeInsets.only(left: 4.0),
child: Icon(
Icons.notifications_off_outlined,
size: 16,
),
),
if (room.isFavourite)
Padding(
padding: EdgeInsets.only(
right: room.notificationCount > 0 ? 4.0 : 0.0),
child: Icon(
Icons.push_pin_outlined,
size: 16,
color: Theme.of(context).colorScheme.secondary,
),
),
Padding(
padding: const EdgeInsets.only(left: 4.0),
child: Text(
room.timeCreated.localizedTimeShort(context),
style: TextStyle(
fontSize: 13,
color: unread
? Theme.of(context).colorScheme.secondary
: Theme.of(context).textTheme.bodyText2.color,
),
),
),
],
),
subtitle: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
if (typingText.isEmpty && ownMessage) ...{
Icon(
room.lastEvent.statusIcon,
size: 14,
),
const SizedBox(width: 4),
},
AnimatedContainer(
width: typingText.isEmpty ? 0 : 18,
clipBehavior: Clip.hardEdge,
decoration: const BoxDecoration(),
duration: const Duration(milliseconds: 300),
curve: Curves.bounceInOut,
padding: const EdgeInsets.only(right: 4),
child: Icon(
Icons.edit_outlined,
color: Theme.of(context).colorScheme.secondary,
size: 14,
),
),
if (typingText.isEmpty &&
!ownMessage &&
!room.isDirectChat &&
room.lastEvent != null &&
room.lastEvent.type == EventTypes.Message &&
{MessageTypes.Text, MessageTypes.Notice}
.contains(room.lastEvent.messageType))
Text(
'${room.lastEvent.sender.calcDisplayname()}: ',
style: TextStyle(
color: Theme.of(context).textTheme.bodyText1.color,
),
),
Expanded(
child: typingText.isNotEmpty
? Text(
typingText,
style: TextStyle(
color: Theme.of(context).colorScheme.secondary,
),
softWrap: false,
)
: Text(
room.membership == Membership.invite
? L10n.of(context).youAreInvitedToThisChat
: room.lastEvent?.getLocalizedBody(
MatrixLocals(L10n.of(context)),
hideReply: true,
hideEdit: true,
plaintextBody: true,
),
softWrap: false,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: unread
? Theme.of(context).colorScheme.secondary
: Theme.of(context).textTheme.bodyText2.color,
decoration: room.lastEvent?.redacted == true
? TextDecoration.lineThrough
: null,
),
),
),
const SizedBox(width: 8),
AnimatedContainer(
duration: const Duration(milliseconds: 300),
curve: Curves.bounceInOut,
padding: const EdgeInsets.symmetric(horizontal: 7),
height: unreadBubbleSize,
width: room.notificationCount == 0 && !unread
? 0
: (unreadBubbleSize - 9) *
room.notificationCount.toString().length +
9,
decoration: BoxDecoration(
color: room.highlightCount > 0
? Colors.red
: Theme.of(context).primaryColor,
borderRadius: BorderRadius.circular(AppConfig.borderRadius),
),
child: Center(
child: room.notificationCount > 0
? Text(
room.notificationCount.toString(),
style: const TextStyle(
color: Colors.white,
fontSize: 13,
),
)
: Container(),
),
),
],
),
onTap: () => clickAction(context),
);
}
}

View file

@ -0,0 +1,508 @@
import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:async/async.dart';
import 'package:flutter_gen/gen_l10n/l10n.dart';
import 'package:matrix/matrix.dart';
import 'package:vrouter/vrouter.dart';
import 'package:fluffychat/config/app_config.dart';
import 'package:fluffychat/config/themes.dart';
import 'package:fluffychat/pages/chat_list/chat_list.dart';
import 'package:fluffychat/pages/chat_list/chat_list_item.dart';
import 'package:fluffychat/widgets/avatar.dart';
import 'package:fluffychat/widgets/connection_status_header.dart';
import '../../utils/account_bundles.dart';
import '../../utils/stream_extension.dart';
import '../../widgets/matrix.dart';
class ChatListView extends StatelessWidget {
final ChatListController controller;
const ChatListView(this.controller, {Key key}) : super(key: key);
List<BottomNavigationBarItem> getBottomBarItems(BuildContext context) {
final displayClients = Matrix.of(context).currentBundle;
if (displayClients.isEmpty) {
displayClients.addAll(Matrix.of(context).widget.clients);
controller.resetActiveBundle();
}
final items = displayClients.map((client) {
return BottomNavigationBarItem(
label: client.userID,
icon: FutureBuilder<Profile>(
future: client.ownProfile,
builder: (context, snapshot) {
return InkWell(
borderRadius: BorderRadius.circular(32),
onTap: () => controller.setActiveClient(client),
onLongPress: () =>
controller.editBundlesForAccount(client.userID),
child: Avatar(
snapshot.data?.avatarUrl,
snapshot.data?.displayName ?? client.userID.localpart,
size: 32,
),
);
}),
);
}).toList();
if (controller.displayBundles && false) {
items.insert(
0,
BottomNavigationBarItem(
label: 'Bundles',
icon: PopupMenuButton(
icon: Icon(
Icons.menu,
color: Theme.of(context).textTheme.bodyText1.color,
),
onSelected: controller.setActiveBundle,
itemBuilder: (context) => Matrix.of(context)
.accountBundles
.keys
.map(
(bundle) => PopupMenuItem(
value: bundle,
child: Text(bundle),
),
)
.toList(),
)));
}
return items;
}
@override
Widget build(BuildContext context) {
return StreamBuilder<Object>(
stream: Matrix.of(context).onShareContentChanged.stream,
builder: (_, __) {
final selectMode = controller.selectMode;
return VWidgetGuard(
onSystemPop: (redirector) async {
final selMode = controller.selectMode;
if (selMode != SelectMode.normal) controller.cancelAction();
if (selMode == SelectMode.select) redirector.stopRedirection();
},
child: Scaffold(
appBar: AppBar(
elevation: controller.scrolledToTop ? 0 : null,
actionsIconTheme: IconThemeData(
color: controller.selectedRoomIds.isEmpty
? null
: Theme.of(context).colorScheme.primary,
),
leading: selectMode == SelectMode.normal
? controller.spaces.isEmpty
? null
: Builder(
builder: (context) => IconButton(
icon: const Icon(Icons.group_work_outlined),
onPressed: Scaffold.of(context).openDrawer,
))
: IconButton(
tooltip: L10n.of(context).cancel,
icon: const Icon(Icons.close_outlined),
onPressed: controller.cancelAction,
color: Theme.of(context).colorScheme.primary,
),
centerTitle: false,
titleSpacing: controller.spaces.isEmpty ? null : 0,
actions: selectMode == SelectMode.share
? null
: selectMode == SelectMode.select
? [
if (controller.selectedRoomIds.length == 1 &&
controller.spaces.isNotEmpty &&
!Matrix.of(context)
.client
.getRoomById(
controller.selectedRoomIds.single)
.isDirectChat)
IconButton(
tooltip: L10n.of(context).addToSpace,
icon: const Icon(Icons.group_work_outlined),
onPressed: controller.addOrRemoveToSpace,
),
if (controller.selectedRoomIds.length == 1)
IconButton(
tooltip: L10n.of(context).toggleUnread,
icon: Icon(Matrix.of(context)
.client
.getRoomById(
controller.selectedRoomIds.single)
.isUnread
? Icons.mark_chat_read_outlined
: Icons.mark_chat_unread_outlined),
onPressed: controller.toggleUnread,
),
if (controller.selectedRoomIds.length == 1)
IconButton(
tooltip: L10n.of(context).toggleFavorite,
icon: const Icon(Icons.push_pin_outlined),
onPressed: controller.toggleFavouriteRoom,
),
if (controller.selectedRoomIds.length == 1)
IconButton(
icon: Icon(Matrix.of(context)
.client
.getRoomById(controller
.selectedRoomIds.single)
.pushRuleState ==
PushRuleState.notify
? Icons.notifications_off_outlined
: Icons.notifications_outlined),
tooltip: L10n.of(context).toggleMuted,
onPressed: controller.toggleMuted,
),
IconButton(
icon: const Icon(Icons.delete_outlined),
tooltip: L10n.of(context).archive,
onPressed: controller.archiveAction,
),
]
: [
IconButton(
icon: const Icon(Icons.search_outlined),
tooltip: L10n.of(context).search,
onPressed: () =>
VRouter.of(context).to('/search'),
),
PopupMenuButton<PopupMenuAction>(
onSelected: controller.onPopupMenuSelect,
itemBuilder: (_) => [
PopupMenuItem(
value: PopupMenuAction.setStatus,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.edit_outlined),
const SizedBox(width: 12),
Text(L10n.of(context).setStatus),
],
),
),
PopupMenuItem(
value: PopupMenuAction.newGroup,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.group_add_outlined),
const SizedBox(width: 12),
Text(L10n.of(context).createNewGroup),
],
),
),
PopupMenuItem(
value: PopupMenuAction.newSpace,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.group_work_outlined),
const SizedBox(width: 12),
Text(L10n.of(context).createNewSpace),
],
),
),
PopupMenuItem(
value: PopupMenuAction.invite,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.share_outlined),
const SizedBox(width: 12),
Text(L10n.of(context).inviteContact),
],
),
),
PopupMenuItem(
value: PopupMenuAction.archive,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.archive_outlined),
const SizedBox(width: 12),
Text(L10n.of(context).archive),
],
),
),
PopupMenuItem(
value: PopupMenuAction.settings,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.settings_outlined),
const SizedBox(width: 12),
Text(L10n.of(context).settings),
],
),
),
],
),
],
title: Text(selectMode == SelectMode.share
? L10n.of(context).share
: selectMode == SelectMode.select
? controller.selectedRoomIds.length.toString()
: controller.activeSpaceId == null
? AppConfig.applicationName
: Matrix.of(context)
.client
.getRoomById(controller.activeSpaceId)
.displayname),
),
body: Column(children: [
const ConnectionStatusHeader(),
Expanded(child: _ChatListViewBody(controller)),
]),
floatingActionButton: selectMode == SelectMode.normal
? controller.scrolledToTop
? FloatingActionButton.extended(
heroTag: 'main_fab',
onPressed: () =>
VRouter.of(context).to('/newprivatechat'),
icon: const Icon(CupertinoIcons.chat_bubble),
label: Text(L10n.of(context).newChat),
)
: FloatingActionButton(
heroTag: 'main_fab',
onPressed: () =>
VRouter.of(context).to('/newprivatechat'),
child: const Icon(CupertinoIcons.chat_bubble),
)
: null,
bottomNavigationBar: Matrix.of(context).isMultiAccount
? StreamBuilder(
stream: StreamGroup.merge(Matrix.of(context)
.widget
.clients
.map((client) => client.onSync.stream.where((s) =>
s.accountData != null &&
s.accountData
.any((e) => e.type == accountBundlesType)))),
builder: (context, _) => Material(
color: Theme.of(context)
.bottomNavigationBarTheme
.backgroundColor,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Divider(height: 1),
Builder(builder: (context) {
final items = getBottomBarItems(context);
if (items.length == 1) {
return Padding(
padding: const EdgeInsets.all(7.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
items.single.icon,
Text(items.single.label),
],
),
);
}
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: SizedBox(
width: max(
FluffyThemes.isColumnMode(context)
? FluffyThemes.columnWidth
: MediaQuery.of(context).size.width,
Matrix.of(context).widget.clients.length *
84.0,
),
child: BottomNavigationBar(
elevation: 0,
onTap: (i) => controller.setActiveClient(
Matrix.of(context).currentBundle[i]),
currentIndex: Matrix.of(context)
.currentBundle
.indexWhere(
(client) =>
client ==
Matrix.of(context).client,
),
showUnselectedLabels: false,
showSelectedLabels: true,
type: BottomNavigationBarType.shifting,
selectedItemColor:
Theme.of(context).colorScheme.secondary,
items: items,
),
),
);
}),
if (controller.displayBundles)
Padding(
padding: const EdgeInsets.symmetric(
vertical: 4.0,
horizontal: 12,
),
child: SizedBox(
width: double.infinity,
child: CupertinoSlidingSegmentedControl(
groupValue: controller.secureActiveBundle,
onValueChanged: controller.setActiveBundle,
children: Map.fromEntries(Matrix.of(context)
.accountBundles
.keys
.map((bundle) =>
MapEntry(bundle, Text(bundle)))),
),
),
),
],
),
),
)
: null,
drawer: controller.spaces.isEmpty
? null
: Drawer(
child: SafeArea(
child: ListView.builder(
itemCount: controller.spaces.length + 1,
itemBuilder: (context, i) {
if (i == 0) {
return ListTile(
selected: controller.activeSpaceId == null,
selectedTileColor:
Theme.of(context).secondaryHeaderColor,
leading: CircleAvatar(
foregroundColor: Colors.white,
backgroundColor:
Theme.of(context).primaryColor,
radius: Avatar.defaultSize / 2,
child: const Icon(Icons.home_outlined),
),
title: Text(L10n.of(context).allChats),
onTap: () =>
controller.setActiveSpaceId(context, null),
);
}
final space = controller.spaces[i - 1];
return ListTile(
selected: controller.activeSpaceId == space.id,
selectedTileColor:
Theme.of(context).secondaryHeaderColor,
leading: Avatar(space.avatar, space.displayname),
title: Text(space.displayname, maxLines: 1),
subtitle: Text(L10n.of(context).countParticipants(
(space.summary.mJoinedMemberCount +
space.summary.mInvitedMemberCount)
.toString())),
onTap: () => controller.setActiveSpaceId(
context, space.id),
trailing: IconButton(
icon: const Icon(Icons.edit_outlined),
onPressed: () =>
controller.editSpace(context, space.id),
),
);
},
),
),
),
),
);
});
}
}
class _ChatListViewBody extends StatelessWidget {
final ChatListController controller;
const _ChatListViewBody(this.controller, {Key key}) : super(key: key);
@override
Widget build(BuildContext context) => StreamBuilder(
stream: Matrix.of(context)
.client
.onSync
.stream
.where((s) => s.hasRoomUpdate)
.rateLimit(const Duration(seconds: 1)),
builder: (context, snapshot) {
return FutureBuilder<void>(
future: controller.waitForFirstSync,
builder: (BuildContext context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
final rooms = Matrix.of(context)
.client
.rooms
.where(controller.roomCheck)
.toList();
if (rooms.isEmpty) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const Icon(
Icons.maps_ugc_outlined,
size: 80,
color: Colors.grey,
),
Center(
child: Text(
L10n.of(context).startYourFirstChat,
textAlign: TextAlign.start,
style: const TextStyle(
color: Colors.grey,
fontSize: 16,
),
),
),
],
);
}
return ListView.builder(
controller: controller.scrollController,
itemCount: rooms.length,
itemBuilder: (BuildContext context, int i) {
return ChatListItem(
rooms[i],
selected: controller.selectedRoomIds.contains(rooms[i].id),
onTap: controller.selectMode == SelectMode.select
? () => controller.toggleSelection(rooms[i].id)
: null,
onLongPress: () => controller.toggleSelection(rooms[i].id),
activeChat: controller.activeChat == rooms[i].id,
);
},
);
} else {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Image.asset(
'assets/private_chat_wallpaper.png',
width: 100,
),
Text(
L10n.of(context).yourChatsAreBeingSynced,
textAlign: TextAlign.center,
),
],
),
);
}
},
);
});
}
enum ChatListPopupMenuItemActions {
createGroup,
createSpace,
discover,
setStatus,
inviteContact,
settings,
}