pagination

This commit is contained in:
Christien Rioux 2024-06-06 00:19:07 -04:00
parent 5473bd2ee4
commit 2c38fc6489
22 changed files with 1071 additions and 545 deletions

View file

@ -1,320 +0,0 @@
import 'dart:math';
import 'package:async_tools/async_tools.dart';
import 'package:awesome_extensions/awesome_extensions.dart';
import 'package:fixnum/fixnum.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_chat_types/flutter_chat_types.dart' as types;
import 'package:flutter_chat_ui/flutter_chat_ui.dart';
import 'package:veilid_support/veilid_support.dart';
import '../../account_manager/account_manager.dart';
import '../../chat_list/chat_list.dart';
import '../../contacts/contacts.dart';
import '../../proto/proto.dart' as proto;
import '../../theme/theme.dart';
import '../chat.dart';
const String metadataKeyExpirationDuration = 'expiration';
const String metadataKeyViewLimit = 'view_limit';
const String metadataKeyAttachments = 'attachments';
class ChatComponent extends StatelessWidget {
const ChatComponent._(
{required TypedKey localUserIdentityKey,
required SingleContactMessagesCubit messagesCubit,
required SingleContactMessagesState messagesState,
required types.User localUser,
required types.User remoteUser,
super.key})
: _localUserIdentityKey = localUserIdentityKey,
_messagesCubit = messagesCubit,
_messagesState = messagesState,
_localUser = localUser,
_remoteUser = remoteUser;
final TypedKey _localUserIdentityKey;
final SingleContactMessagesCubit _messagesCubit;
final SingleContactMessagesState _messagesState;
final types.User _localUser;
final types.User _remoteUser;
// Builder wrapper function that takes care of state management requirements
static Widget builder(
{required TypedKey localConversationRecordKey, Key? key}) =>
Builder(builder: (context) {
// Get all watched dependendies
final activeAccountInfo = context.watch<ActiveAccountInfo>();
final accountRecordInfo =
context.watch<AccountRecordCubit>().state.asData?.value;
if (accountRecordInfo == null) {
return debugPage('should always have an account record here');
}
final contactList =
context.watch<ContactListCubit>().state.state.asData?.value;
if (contactList == null) {
return debugPage('should always have a contact list here');
}
final avconversation = context.select<ActiveConversationsBlocMapCubit,
AsyncValue<ActiveConversationState>?>(
(x) => x.state[localConversationRecordKey]);
if (avconversation == null) {
return waitingPage();
}
final conversation = avconversation.asData?.value;
if (conversation == null) {
return avconversation.buildNotData();
}
// Make flutter_chat_ui 'User's
final localUserIdentityKey = activeAccountInfo
.localAccount.identityMaster
.identityPublicTypedKey();
final localUser = types.User(
id: localUserIdentityKey.toString(),
firstName: accountRecordInfo.profile.name,
);
final editedName = conversation.contact.editedProfile.name;
final remoteUser = types.User(
id: conversation.contact.identityPublicKey.toVeilid().toString(),
firstName: editedName);
// Get the messages cubit
final messages = context.select<ActiveSingleContactChatBlocMapCubit,
(SingleContactMessagesCubit, SingleContactMessagesState)?>(
(x) => x.tryOperate(localConversationRecordKey,
closure: (cubit) => (cubit, cubit.state)));
// Get the messages to display
// and ensure it is safe to operate() on the MessageCubit for this chat
if (messages == null) {
return waitingPage();
}
return ChatComponent._(
localUserIdentityKey: localUserIdentityKey,
messagesCubit: messages.$1,
messagesState: messages.$2,
localUser: localUser,
remoteUser: remoteUser,
key: key);
});
/////////////////////////////////////////////////////////////////////
types.Message? messageStateToChatMessage(MessageState message) {
final isLocal = message.content.author.toVeilid() == _localUserIdentityKey;
types.Status? status;
if (message.sendState != null) {
assert(isLocal, 'send state should only be on sent messages');
switch (message.sendState!) {
case MessageSendState.sending:
status = types.Status.sending;
case MessageSendState.sent:
status = types.Status.sent;
case MessageSendState.delivered:
status = types.Status.delivered;
}
}
switch (message.content.whichKind()) {
case proto.Message_Kind.text:
final contextText = message.content.text;
final textMessage = types.TextMessage(
author: isLocal ? _localUser : _remoteUser,
createdAt:
(message.sentTimestamp.value ~/ BigInt.from(1000)).toInt(),
id: message.content.authorUniqueIdString,
text: contextText.text,
showStatus: status != null,
status: status);
return textMessage;
case proto.Message_Kind.secret:
case proto.Message_Kind.delete:
case proto.Message_Kind.erase:
case proto.Message_Kind.settings:
case proto.Message_Kind.permissions:
case proto.Message_Kind.membership:
case proto.Message_Kind.moderation:
case proto.Message_Kind.notSet:
return null;
}
}
void _addTextMessage(
{required String text,
String? topic,
Uint8List? replyId,
Timestamp? expiration,
int? viewLimit,
List<proto.Attachment> attachments = const []}) {
final protoMessageText = proto.Message_Text()..text = text;
if (topic != null) {
protoMessageText.topic = topic;
}
if (replyId != null) {
protoMessageText.replyId = replyId;
}
protoMessageText
..expiration = expiration?.toInt64() ?? Int64.ZERO
..viewLimit = viewLimit ?? 0;
protoMessageText.attachments.addAll(attachments);
_messagesCubit.sendTextMessage(messageText: protoMessageText);
}
void _sendMessage(types.PartialText message) {
final text = message.text;
final replyId = (message.repliedMessage != null)
? base64UrlNoPadDecode(message.repliedMessage!.id)
: null;
Timestamp? expiration;
int? viewLimit;
List<proto.Attachment>? attachments;
final metadata = message.metadata;
if (metadata != null) {
final expirationValue =
metadata[metadataKeyExpirationDuration] as TimestampDuration?;
if (expirationValue != null) {
expiration = Veilid.instance.now().offset(expirationValue);
}
final viewLimitValue = metadata[metadataKeyViewLimit] as int?;
if (viewLimitValue != null) {
viewLimit = viewLimitValue;
}
final attachmentsValue =
metadata[metadataKeyAttachments] as List<proto.Attachment>?;
if (attachmentsValue != null) {
attachments = attachmentsValue;
}
}
_addTextMessage(
text: text,
replyId: replyId,
expiration: expiration,
viewLimit: viewLimit,
attachments: attachments ?? []);
}
void _handleSendPressed(types.PartialText message) {
final text = message.text;
if (text.startsWith('/')) {
_messagesCubit.runCommand(text);
return;
}
_sendMessage(message);
}
// void _handleAttachmentPressed() async {
// //
// }
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final scale = theme.extension<ScaleScheme>()!;
final textTheme = Theme.of(context).textTheme;
final chatTheme = makeChatTheme(scale, textTheme);
final messagesState = _messagesState.asData?.value;
if (messagesState == null) {
return _messagesState.buildNotData();
}
// Convert protobuf messages to chat messages
final chatMessages = <types.Message>[];
final tsSet = <String>{};
for (final message in messagesState.windowMessages) {
final chatMessage = messageStateToChatMessage(message);
if (chatMessage == null) {
continue;
}
chatMessages.insert(0, chatMessage);
if (!tsSet.add(chatMessage.id)) {
// ignore: avoid_print
print('duplicate id found: ${chatMessage.id}:\n'
'Messages:\n${messagesState.windowMessages}\n'
'ChatMessages:\n$chatMessages');
assert(false, 'should not have duplicate id');
}
}
final isLastPage =
(messagesState.windowTail - messagesState.windowMessages.length) <= 0;
final follow = messagesState.windowTail == 0 ||
messagesState.windowTail == messagesState.length; xxx finish calculating pagination and get scroll position here somehow
return DefaultTextStyle(
style: textTheme.bodySmall!,
child: Align(
alignment: AlignmentDirectional.centerEnd,
child: Stack(
children: [
Column(
children: [
Container(
height: 48,
decoration: BoxDecoration(
color: scale.primaryScale.subtleBorder,
),
child: Row(children: [
Align(
alignment: AlignmentDirectional.centerStart,
child: Padding(
padding: const EdgeInsetsDirectional.fromSTEB(
16, 0, 16, 0),
child: Text(_remoteUser.firstName!,
textAlign: TextAlign.start,
style: textTheme.titleMedium!.copyWith(
color: scale.primaryScale.borderText)),
)),
const Spacer(),
IconButton(
icon: Icon(Icons.close,
color: scale.primaryScale.borderText),
onPressed: () async {
context.read<ActiveChatCubit>().setActiveChat(null);
}).paddingLTRB(16, 0, 16, 0)
]),
),
Expanded(
child: DecoratedBox(
decoration: const BoxDecoration(),
child: Chat(
theme: chatTheme,
messages: chatMessages,
onEndReached: () async {
final tail = await _messagesCubit.setWindow(
tail: max(
0,
(messagesState.windowTail -
(messagesState.windowCount ~/ 2))),
count: messagesState.windowCount,
follow: follow);
},
isLastPage: isLastPage,
//onAttachmentPressed: _handleAttachmentPressed,
//onMessageTap: _handleMessageTap,
//onPreviewDataFetched: _handlePreviewDataFetched,
onSendPressed: _handleSendPressed,
//showUserAvatars: false,
//showUserNames: true,
user: _localUser,
emptyState: const EmptyChatWidget()),
),
),
],
),
],
),
));
}
}

View file

@ -0,0 +1,294 @@
import 'dart:math';
import 'package:async_tools/async_tools.dart';
import 'package:awesome_extensions/awesome_extensions.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_chat_types/flutter_chat_types.dart' as types;
import 'package:flutter_chat_ui/flutter_chat_ui.dart';
import 'package:veilid_support/veilid_support.dart';
import '../../account_manager/account_manager.dart';
import '../../chat_list/chat_list.dart';
import '../../theme/theme.dart';
import '../chat.dart';
const onEndReachedThreshold = 0.75;
class ChatComponentWidget extends StatelessWidget {
const ChatComponentWidget._({required super.key});
// Builder wrapper function that takes care of state management requirements
static Widget builder(
{required TypedKey localConversationRecordKey, Key? key}) =>
Builder(builder: (context) {
// Get all watched dependendies
final activeAccountInfo = context.watch<ActiveAccountInfo>();
final accountRecordInfo =
context.watch<AccountRecordCubit>().state.asData?.value;
if (accountRecordInfo == null) {
return debugPage('should always have an account record here');
}
final avconversation = context.select<ActiveConversationsBlocMapCubit,
AsyncValue<ActiveConversationState>?>(
(x) => x.state[localConversationRecordKey]);
if (avconversation == null) {
return waitingPage();
}
final activeConversationState = avconversation.asData?.value;
if (activeConversationState == null) {
return avconversation.buildNotData();
}
// Get the messages cubit
final messagesCubit = context.select<
ActiveSingleContactChatBlocMapCubit,
SingleContactMessagesCubit?>(
(x) => x.tryOperate(localConversationRecordKey,
closure: (cubit) => cubit));
if (messagesCubit == null) {
return waitingPage();
}
// Make chat component state
return BlocProvider(
create: (context) => ChatComponentCubit.singleContact(
activeAccountInfo: activeAccountInfo,
accountRecordInfo: accountRecordInfo,
activeConversationState: activeConversationState,
messagesCubit: messagesCubit,
),
child: ChatComponentWidget._(key: key));
});
/////////////////////////////////////////////////////////////////////
void _handleSendPressed(
ChatComponentCubit chatComponentCubit, types.PartialText message) {
final text = message.text;
if (text.startsWith('/')) {
chatComponentCubit.runCommand(text);
return;
}
chatComponentCubit.sendMessage(message);
}
// void _handleAttachmentPressed() async {
// //
// }
Future<void> _handlePageForward(
ChatComponentCubit chatComponentCubit,
WindowState<types.Message> messageWindow,
ScrollNotification notification) async {
print(
'_handlePageForward: messagesState.length=${messageWindow.length} messagesState.windowTail=${messageWindow.windowTail} messagesState.windowCount=${messageWindow.windowCount} ScrollNotification=$notification');
// Go forward a page
final tail = min(messageWindow.length,
messageWindow.windowTail + (messageWindow.windowCount ~/ 4)) %
messageWindow.length;
// Set follow
final follow = messageWindow.length == 0 ||
tail == 0; // xxx incorporate scroll position
// final scrollOffset = (notification.metrics.maxScrollExtent -
// notification.metrics.minScrollExtent) *
// (1.0 - onEndReachedThreshold);
// chatComponentCubit.scrollOffset = scrollOffset;
await chatComponentCubit.setWindow(
tail: tail, count: messageWindow.windowCount, follow: follow);
// chatComponentCubit.state.scrollController.position.jumpTo(
// chatComponentCubit.state.scrollController.offset + scrollOffset);
//chatComponentCubit.scrollOffset = 0;
}
Future<void> _handlePageBackward(
ChatComponentCubit chatComponentCubit,
WindowState<types.Message> messageWindow,
ScrollNotification notification,
) async {
print(
'_handlePageBackward: messagesState.length=${messageWindow.length} messagesState.windowTail=${messageWindow.windowTail} messagesState.windowCount=${messageWindow.windowCount} ScrollNotification=$notification');
// Go back a page
final tail = max(
messageWindow.windowCount,
(messageWindow.windowTail - (messageWindow.windowCount ~/ 4)) %
messageWindow.length);
// Set follow
final follow = messageWindow.length == 0 ||
tail == 0; // xxx incorporate scroll position
// final scrollOffset = -(notification.metrics.maxScrollExtent -
// notification.metrics.minScrollExtent) *
// (1.0 - onEndReachedThreshold);
// chatComponentCubit.scrollOffset = scrollOffset;
await chatComponentCubit.setWindow(
tail: tail, count: messageWindow.windowCount, follow: follow);
// chatComponentCubit.scrollOffset = scrollOffset;
// chatComponentCubit.state.scrollController.position.jumpTo(
// chatComponentCubit.state.scrollController.offset + scrollOffset);
//chatComponentCubit.scrollOffset = 0;
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final scale = theme.extension<ScaleScheme>()!;
final textTheme = Theme.of(context).textTheme;
final chatTheme = makeChatTheme(scale, textTheme);
// Get the enclosing chat component cubit that contains our state
// (created by ChatComponentWidget.builder())
final chatComponentCubit = context.watch<ChatComponentCubit>();
final chatComponentState = chatComponentCubit.state;
final messageWindow = chatComponentState.messageWindow.asData?.value;
if (messageWindow == null) {
return chatComponentState.messageWindow.buildNotData();
}
final isLastPage = messageWindow.windowStart == 0;
final isFirstPage = messageWindow.windowEnd == messageWindow.length - 1;
final title = chatComponentState.title;
if (chatComponentCubit.scrollOffset != 0) {
chatComponentState.scrollController.position.correctPixels(
chatComponentState.scrollController.position.pixels +
chatComponentCubit.scrollOffset);
chatComponentCubit.scrollOffset = 0;
}
return DefaultTextStyle(
style: textTheme.bodySmall!,
child: Align(
alignment: AlignmentDirectional.centerEnd,
child: Stack(
children: [
Column(
children: [
Container(
height: 48,
decoration: BoxDecoration(
color: scale.primaryScale.subtleBorder,
),
child: Row(children: [
Align(
alignment: AlignmentDirectional.centerStart,
child: Padding(
padding: const EdgeInsetsDirectional.fromSTEB(
16, 0, 16, 0),
child: Text(title,
textAlign: TextAlign.start,
style: textTheme.titleMedium!.copyWith(
color: scale.primaryScale.borderText)),
)),
const Spacer(),
IconButton(
icon: Icon(Icons.close,
color: scale.primaryScale.borderText),
onPressed: () async {
context.read<ActiveChatCubit>().setActiveChat(null);
}).paddingLTRB(16, 0, 16, 0)
]),
),
Expanded(
child: DecoratedBox(
decoration: const BoxDecoration(),
child: NotificationListener<ScrollNotification>(
onNotification: (notification) {
if (chatComponentCubit.scrollOffset != 0) {
return false;
}
if (!isFirstPage &&
notification.metrics.pixels <=
((notification.metrics.maxScrollExtent -
notification
.metrics.minScrollExtent) *
(1.0 - onEndReachedThreshold) +
notification.metrics.minScrollExtent)) {
//
final scrollOffset = (notification
.metrics.maxScrollExtent -
notification.metrics.minScrollExtent) *
(1.0 - onEndReachedThreshold);
chatComponentCubit.scrollOffset = scrollOffset;
//
singleFuture(chatComponentState.chatKey,
() async {
await _handlePageForward(chatComponentCubit,
messageWindow, notification);
});
} else if (!isLastPage &&
notification.metrics.pixels >=
((notification.metrics.maxScrollExtent -
notification
.metrics.minScrollExtent) *
onEndReachedThreshold +
notification.metrics.minScrollExtent)) {
//
final scrollOffset = -(notification
.metrics.maxScrollExtent -
notification.metrics.minScrollExtent) *
(1.0 - onEndReachedThreshold);
chatComponentCubit.scrollOffset = scrollOffset;
//
singleFuture(chatComponentState.chatKey,
() async {
await _handlePageBackward(chatComponentCubit,
messageWindow, notification);
});
}
return false;
},
child: Chat(
key: chatComponentState.chatKey,
theme: chatTheme,
messages: messageWindow.window.toList(),
scrollToBottomOnSend: isFirstPage,
scrollController:
chatComponentState.scrollController,
// isLastPage: isLastPage,
// onEndReached: () async {
// await _handlePageBackward(
// chatComponentCubit, messageWindow);
// },
//onEndReachedThreshold: onEndReachedThreshold,
//onAttachmentPressed: _handleAttachmentPressed,
//onMessageTap: _handleMessageTap,
//onPreviewDataFetched: _handlePreviewDataFetched,
onSendPressed: (pt) =>
_handleSendPressed(chatComponentCubit, pt),
//showUserAvatars: false,
//showUserNames: true,
user: chatComponentState.localUser,
emptyState: const EmptyChatWidget())),
),
),
],
),
],
),
));
}
}

View file

@ -1,4 +1,4 @@
export 'chat_component.dart';
export 'chat_component_widget.dart';
export 'empty_chat_widget.dart';
export 'new_chat_bottom_sheet.dart';
export 'no_conversation_widget.dart';