more messages work

This commit is contained in:
Christien Rioux 2024-02-11 14:17:10 -05:00
parent 634543910b
commit ff14969ffa
12 changed files with 226 additions and 192 deletions

View File

@ -18,55 +18,94 @@ import '../../theme/theme.dart';
import '../../tools/tools.dart';
import '../chat.dart';
class ChatComponent extends StatefulWidget {
const ChatComponent({required this.remoteConversationRecordKey, super.key});
class ChatComponent extends StatelessWidget {
const ChatComponent._(
{required TypedKey localUserIdentityKey,
required TypedKey remoteConversationRecordKey,
required IList<proto.Message> messages,
required types.User localUser,
required types.User remoteUser,
super.key})
: _localUserIdentityKey = localUserIdentityKey,
_remoteConversationRecordKey = remoteConversationRecordKey,
_messages = messages,
_localUser = localUser,
_remoteUser = remoteUser;
@override
ChatComponentState createState() => ChatComponentState();
final TypedKey _localUserIdentityKey;
final TypedKey _remoteConversationRecordKey;
final IList<proto.Message> _messages;
final types.User _localUser;
final types.User _remoteUser;
final TypedKey remoteConversationRecordKey;
// Builder wrapper function that takes care of state management requirements
static Widget builder(
{required TypedKey remoteConversationRecordKey, Key? key}) =>
Builder(builder: (context) {
// Get all watched dependendies
final activeAccountInfo = context.watch<ActiveAccountInfo>();
final accountRecordInfo =
context.watch<AccountRecordCubit>().state.data?.value;
if (accountRecordInfo == null) {
return debugPage('should always have an account record here');
}
final contactList = context.watch<ContactListCubit>().state.data?.value;
if (contactList == null) {
return debugPage('should always have a contact list here');
}
final avconversation = context.select<ActiveConversationsCubit,
AsyncValue<ActiveConversationState>?>(
(x) => x.state[remoteConversationRecordKey]);
if (avconversation == null) {
return debugPage('should always have an active conversation here');
}
final conversation = avconversation.data?.value;
if (conversation == null) {
return avconversation.buildNotData();
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<TypedKey>(
'chatRemoteConversationKey', remoteConversationRecordKey));
}
}
// Make flutter_chat_ui 'User's
final localUserIdentityKey = activeAccountInfo
.localAccount.identityMaster
.identityPublicTypedKey();
class ChatComponentState extends State<ChatComponent> {
final _unfocusNode = FocusNode();
late final types.User _localUser;
late final types.User _remoteUser;
final localUser = types.User(
id: localUserIdentityKey.toString(),
firstName: accountRecordInfo.profile.name,
);
final editedName = conversation.contact.editedProfile.name;
final remoteUser = types.User(
id: proto.TypedKeyProto.fromProto(
conversation.contact.identityPublicKey)
.toString(),
firstName: editedName);
@override
void initState() {
super.initState();
// Get the messages to display
// and ensure it is safe to operate() on the MessageCubit for this chat
final avmessages = context.select<ActiveConversationMessagesCubit,
AsyncValue<IList<proto.Message>>?>(
(x) => x.state[remoteConversationRecordKey]);
if (avmessages == null) {
return waitingPage();
}
final messages = avmessages.data?.value;
if (messages == null) {
return avmessages.buildNotData();
}
_localUser = types.User(
id: widget.activeAccountInfo.localAccount.identityMaster
.identityPublicTypedKey()
.toString(),
firstName: widget.activeAccountInfo.account.profile.name,
);
_remoteUser = types.User(
id: proto.TypedKeyProto.fromProto(
widget.activeChatContact.identityPublicKey)
.toString(),
firstName: widget.activeChatContact.remoteProfile.name);
}
return ChatComponent._(
localUserIdentityKey: localUserIdentityKey,
remoteConversationRecordKey: remoteConversationRecordKey,
messages: messages,
localUser: localUser,
remoteUser: remoteUser,
key: key);
});
@override
void dispose() {
_unfocusNode.dispose();
super.dispose();
}
/////////////////////////////////////////////////////////////////////
types.Message protoMessageToMessage(proto.Message message) {
final isLocal = message.author ==
widget.activeAccountInfo.localAccount.identityMaster
.identityPublicTypedKey()
.toProto();
types.Message messageToChatMessage(proto.Message message) {
final isLocal = message.author == _localUserIdentityKey.toProto();
final textMessage = types.TextMessage(
author: isLocal ? _localUser : _remoteUser,
@ -77,142 +116,98 @@ class ChatComponentState extends State<ChatComponent> {
return textMessage;
}
Future<void> _addMessage(proto.Message protoMessage) async {
if (protoMessage.text.isEmpty) {
Future<void> _addMessage(BuildContext context, proto.Message message) async {
if (message.text.isEmpty) {
return;
}
final message = protoMessageToMessage(protoMessage);
// setState(() {
// _messages.insert(0, message);
// });
// Now add the message to the conversation messages
final localConversationRecordKey = proto.TypedKeyProto.fromProto(
widget.activeChatContact.localConversationRecordKey);
final remoteIdentityPublicKey = proto.TypedKeyProto.fromProto(
widget.activeChatContact.identityPublicKey);
await addLocalConversationMessage(
activeAccountInfo: widget.activeAccountInfo,
localConversationRecordKey: localConversationRecordKey,
remoteIdentityPublicKey: remoteIdentityPublicKey,
message: protoMessage);
ref.invalidate(activeConversationMessagesProvider);
await context.read<ActiveConversationMessagesCubit>().operate(
_remoteConversationRecordKey,
closure: (messagesCubit) => messagesCubit.addMessage(message: message));
}
Future<void> _handleSendPressed(types.PartialText message) async {
Future<void> _handleSendPressed(
BuildContext context, types.PartialText message) async {
final protoMessage = proto.Message()
..author = widget.activeAccountInfo.localAccount.identityMaster
.identityPublicTypedKey()
.toProto()
..timestamp = (await eventualVeilid.future).now().toInt64()
..author = _localUserIdentityKey.toProto()
..timestamp = Veilid.instance.now().toInt64()
..text = message.text;
//..signature = signature;
await _addMessage(protoMessage);
await _addMessage(context, protoMessage);
}
void _handleAttachmentPressed() {
Future<void> _handleAttachmentPressed() async {
//
}
@override
// ignore: prefer_expression_function_bodies
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 contactListCubit = context.watch<ContactListCubit>();
// Convert protobuf messages to chat messages
final chatMessages = <types.Message>[];
for (final message in _messages) {
final chatMessage = messageToChatMessage(message);
chatMessages.insert(0, chatMessage);
}
return contactListCubit.state.builder((context, contactList) {
// Get active chat contact profile
final activeChatContactIdx = contactList.indexWhere((c) =>
widget.remoteConversationRecordKey == c.remoteConversationRecordKey);
late final proto.Contact activeChatContact;
if (activeChatContactIdx == -1) {
// xxx: error, no contact for conversation...
return const NoConversationWidget();
} else {
activeChatContact = contactList[activeChatContactIdx];
}
final contactName = activeChatContact.editedProfile.name;
final messages = context.select<ActiveConversationMessagesCubit,
AsyncValue<IList<proto.Message>>?>(
(x) => x.state[widget.remoteConversationRecordKey]);
if (messages == null) {
// xxx: error, no messages for conversation...
return const NoConversationWidget();
}
return messages.builder((context, protoMessages) {
final messages = <types.Message>[];
for (final protoMessage in protoMessages) {
final message = protoMessageToMessage(protoMessage);
messages.insert(0, message);
}
return DefaultTextStyle(
style: textTheme.bodySmall!,
child: Align(
alignment: AlignmentDirectional.centerEnd,
child: Stack(
return DefaultTextStyle(
style: textTheme.bodySmall!,
child: Align(
alignment: AlignmentDirectional.centerEnd,
child: Stack(
children: [
Column(
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(contactName,
textAlign: TextAlign.start,
style: textTheme.titleMedium),
)),
const Spacer(),
IconButton(
icon: const Icon(Icons.close),
onPressed: () async {
context
.read<ActiveChatCubit>()
.setActiveChat(null);
}).paddingLTRB(16, 0, 16, 0)
]),
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),
)),
const Spacer(),
IconButton(
icon: const Icon(Icons.close),
onPressed: () async {
context.read<ActiveChatCubit>().setActiveChat(null);
}).paddingLTRB(16, 0, 16, 0)
]),
),
Expanded(
child: DecoratedBox(
decoration: const BoxDecoration(),
child: Chat(
theme: chatTheme,
messages: chatMessages,
//onAttachmentPressed: _handleAttachmentPressed,
//onMessageTap: _handleMessageTap,
//onPreviewDataFetched: _handlePreviewDataFetched,
onSendPressed: (message) {
singleFuture(this,
() async => _handleSendPressed(context, message));
},
//showUserAvatars: false,
//showUserNames: true,
user: _localUser,
),
Expanded(
child: DecoratedBox(
decoration: const BoxDecoration(),
child: Chat(
theme: chatTheme,
messages: messages,
//onAttachmentPressed: _handleAttachmentPressed,
//onMessageTap: _handleMessageTap,
//onPreviewDataFetched: _handlePreviewDataFetched,
onSendPressed: (message) {
unawaited(_handleSendPressed(message));
},
//showUserAvatars: false,
//showUserNames: true,
user: _localUser,
),
),
),
],
),
),
],
),
));
});
});
],
),
));
}
}

View File

@ -100,6 +100,8 @@ class ActiveConversationMessagesCubit extends BlocMapCubit<TypedKey,
localMessagesRecordKey: localConversation.messages,
remoteMessagesRecordKey: remoteConversation.messages)));
////
final ActiveAccountInfo _activeAccountInfo;
ActiveConversationsBlocMapState _lastActiveConversationsState =
ActiveConversationsBlocMapState();

View File

@ -25,10 +25,6 @@ class ChatSingleContactItemWidget extends StatelessWidget {
final scale = theme.extension<ScaleScheme>()!;
final activeChatCubit = context.watch<ActiveChatCubit>();
// final activeConversation = context.select<ActiveConversationsCubit, >();
// final activeConversationMessagesCubit =
// context.watch<ActiveConversationMessagesCubit>(); xxx does this need to be here?
final remoteConversationRecordKey =
proto.TypedKeyProto.fromProto(_contact.remoteConversationRecordKey);
final selected = activeChatCubit.state == remoteConversationRecordKey;

View File

@ -89,7 +89,7 @@ class ContactInvitationDisplayDialogState
minHeight: cardsize,
maxHeight: cardsize),
child: signedContactInvitationBytesV.when(
loading: () => buildProgressIndicator(context),
loading: buildProgressIndicator,
data: (data) => Form(
key: formKey,
child: Column(children: [

View File

@ -242,7 +242,7 @@ class InviteDialogState extends State<InviteDialog> {
return SizedBox(
height: 300,
width: 300,
child: buildProgressIndicator(context).toCenter())
child: buildProgressIndicator().toCenter())
.paddingAll(16);
}
return ConstrainedBox(
@ -258,7 +258,7 @@ class InviteDialogState extends State<InviteDialog> {
Column(children: [
Text(translate('invite_dialog.validating'))
.paddingLTRB(0, 0, 0, 16),
buildProgressIndicator(context).paddingAll(16),
buildProgressIndicator().paddingAll(16),
]).toCenter(),
if (_validInvitation == null &&
!_isValidating &&

View File

@ -56,8 +56,8 @@ class HomePageState extends State<HomePage> with TickerProviderStateMixin {
case AccountInfoStatus.accountLocked:
return const HomeAccountLocked();
case AccountInfoStatus.accountReady:
return Provider.value(
value: accountInfo.activeAccountInfo,
return Provider<ActiveAccountInfo>.value(
value: accountInfo.activeAccountInfo!,
child: BlocProvider(
create: (context) => AccountRecordCubit(
record: accountInfo.activeAccountInfo!.accountRecord),

View File

@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../chat/chat.dart';
import '../../../tools/tools.dart';
@ -31,10 +32,20 @@ class ChatOnlyPageState extends State<ChatOnlyPage>
super.dispose();
}
Widget buildChatComponent(BuildContext context) {
final activeChatRemoteConversationKey =
context.watch<ActiveChatCubit>().state;
if (activeChatRemoteConversationKey == null) {
return const EmptyChatWidget();
}
return ChatComponent.builder(
remoteConversationRecordKey: activeChatRemoteConversationKey);
}
@override
Widget build(BuildContext context) => SafeArea(
child: GestureDetector(
onTap: () => FocusScope.of(context).requestFocus(_unfocusNode),
child: const ChatComponent(),
child: buildChatComponent(context),
));
}

View File

@ -74,7 +74,15 @@ class HomeAccountReadyState extends State<HomeAccountReady>
builder: (context) =>
Material(color: Colors.transparent, child: buildUserPanel()));
Widget buildTabletRightPane(BuildContext context) => const ChatComponent();
Widget buildTabletRightPane(BuildContext context) {
final activeChatRemoteConversationKey =
context.watch<ActiveChatCubit>().state;
if (activeChatRemoteConversationKey == null) {
return const EmptyChatWidget();
}
return ChatComponent.builder(
remoteConversationRecordKey: activeChatRemoteConversationKey);
}
// ignore: prefer_expression_function_bodies
Widget buildTablet(BuildContext context) {
@ -106,7 +114,7 @@ class HomeAccountReadyState extends State<HomeAccountReady>
final accountData = context.watch<AccountRecordCubit>().state.data;
if (accountData == null) {
return waitingPage(context);
return waitingPage();
}
return MultiBlocProvider(

View File

@ -143,7 +143,7 @@ class MainPagerState extends State<MainPager> with TickerProviderStateMixin {
return _onNewChatBottomSheetBuilder(context);
} else {
// Unknown error
return waitingPage(context);
return debugPage('unknown page');
}
}

View File

@ -21,5 +21,5 @@ class HomeNoActiveState extends State<HomeNoActive> {
}
@override
Widget build(BuildContext context) => waitingPage(context);
Widget build(BuildContext context) => waitingPage();
}

View File

@ -24,56 +24,72 @@ extension ModalProgressExt on Widget {
return BlurryModalProgressHUD(
inAsyncCall: isLoading,
blurEffectIntensity: 4,
progressIndicator: buildProgressIndicator(context),
progressIndicator: buildProgressIndicator(),
color: scale.tertiaryScale.appBackground.withAlpha(64),
child: this);
}
}
Widget buildProgressIndicator(BuildContext context) {
final theme = Theme.of(context);
final scale = theme.extension<ScaleScheme>()!;
return SpinKitFoldingCube(
color: scale.tertiaryScale.background,
size: 80,
);
}
Widget buildProgressIndicator() => Builder(builder: (context) {
final theme = Theme.of(context);
final scale = theme.extension<ScaleScheme>()!;
return SpinKitFoldingCube(
color: scale.tertiaryScale.background,
size: 80,
);
});
Widget waitingPage(BuildContext context) => ColoredBox(
color: Theme.of(context).scaffoldBackgroundColor,
child: Center(child: buildProgressIndicator(context)));
Widget waitingPage({String? text}) => Builder(
builder: (context) => ColoredBox(
color: Theme.of(context).scaffoldBackgroundColor,
child: Center(
child: Column(children: [
buildProgressIndicator(),
if (text != null) Text(text)
]))));
Widget errorPage(BuildContext context, Object err, StackTrace? st) =>
ColoredBox(
Widget debugPage(String text) => Builder(
builder: (context) => ColoredBox(
color: Theme.of(context).colorScheme.error,
child: Center(child: Text(err.toString())));
child: Center(child: Text(text))));
Widget errorPage(Object err, StackTrace? st) => Builder(
builder: (context) => ColoredBox(
color: Theme.of(context).colorScheme.error,
child: Center(child: ErrorWidget(err))));
Widget asyncValueBuilder<T>(
AsyncValue<T> av, Widget Function(BuildContext, T) builder) =>
av.when(
loading: () => const Builder(builder: waitingPage),
error: (e, st) =>
Builder(builder: (context) => errorPage(context, e, st)),
loading: waitingPage,
error: errorPage,
data: (d) => Builder(builder: (context) => builder(context, d)));
extension AsyncValueBuilderExt<T> on AsyncValue<T> {
Widget builder(Widget Function(BuildContext, T) builder) =>
asyncValueBuilder<T>(this, builder);
Widget buildNotData(
{Widget Function()? loading,
Widget Function(Object, StackTrace?)? error}) =>
when(
loading: () => (loading ?? waitingPage)(),
error: (e, st) => (error ?? errorPage)(e, st),
data: (d) => debugPage('AsyncValue should not be data here'));
}
class AsyncBlocBuilder<B extends StateStreamable<AsyncValue<S>>, S>
extends BlocBuilder<B, AsyncValue<S>> {
AsyncBlocBuilder({
required BlocWidgetBuilder<S> builder,
Widget Function(BuildContext)? loading,
Widget Function(BuildContext, Object, StackTrace?)? error,
Widget Function()? loading,
Widget Function(Object, StackTrace?)? error,
super.key,
super.bloc,
super.buildWhen,
}) : super(
builder: (context, state) => state.when(
loading: () => (loading ?? waitingPage)(context),
error: (e, st) => (error ?? errorPage)(context, e, st),
loading: () => (loading ?? waitingPage)(),
error: (e, st) => (error ?? errorPage)(e, st),
data: (d) => builder(context, d)));
}

View File

@ -4,8 +4,8 @@ import 'async_tag_lock.dart';
AsyncTagLock<Object> _keys = AsyncTagLock();
void singleFuture(Object tag, Future<void> Function() closure,
{void Function()? onBusy}) {
void singleFuture<T>(Object tag, Future<T> Function() closure,
{void Function()? onBusy, void Function(T)? onDone}) {
if (!_keys.tryLock(tag)) {
if (onBusy != null) {
onBusy();
@ -13,7 +13,13 @@ void singleFuture(Object tag, Future<void> Function() closure,
return;
}
unawaited(() async {
await closure();
_keys.unlockTag(tag);
try {
final out = await closure();
if (onDone != null) {
onDone(out);
}
} finally {
_keys.unlockTag(tag);
}
}());
}