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 '../../tools/tools.dart';
import '../chat.dart'; import '../chat.dart';
class ChatComponent extends StatefulWidget { class ChatComponent extends StatelessWidget {
const ChatComponent({required this.remoteConversationRecordKey, super.key}); 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 final TypedKey _localUserIdentityKey;
ChatComponentState createState() => ChatComponentState(); 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 // Make flutter_chat_ui 'User's
void debugFillProperties(DiagnosticPropertiesBuilder properties) { final localUserIdentityKey = activeAccountInfo
super.debugFillProperties(properties); .localAccount.identityMaster
properties.add(DiagnosticsProperty<TypedKey>( .identityPublicTypedKey();
'chatRemoteConversationKey', remoteConversationRecordKey));
}
}
class ChatComponentState extends State<ChatComponent> { final localUser = types.User(
final _unfocusNode = FocusNode(); id: localUserIdentityKey.toString(),
late final types.User _localUser; firstName: accountRecordInfo.profile.name,
late final types.User _remoteUser; );
final editedName = conversation.contact.editedProfile.name;
final remoteUser = types.User(
id: proto.TypedKeyProto.fromProto(
conversation.contact.identityPublicKey)
.toString(),
firstName: editedName);
@override // Get the messages to display
void initState() { // and ensure it is safe to operate() on the MessageCubit for this chat
super.initState(); 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( return ChatComponent._(
id: widget.activeAccountInfo.localAccount.identityMaster localUserIdentityKey: localUserIdentityKey,
.identityPublicTypedKey() remoteConversationRecordKey: remoteConversationRecordKey,
.toString(), messages: messages,
firstName: widget.activeAccountInfo.account.profile.name, localUser: localUser,
); remoteUser: remoteUser,
_remoteUser = types.User( key: key);
id: proto.TypedKeyProto.fromProto( });
widget.activeChatContact.identityPublicKey)
.toString(),
firstName: widget.activeChatContact.remoteProfile.name);
}
@override /////////////////////////////////////////////////////////////////////
void dispose() {
_unfocusNode.dispose();
super.dispose();
}
types.Message protoMessageToMessage(proto.Message message) { types.Message messageToChatMessage(proto.Message message) {
final isLocal = message.author == final isLocal = message.author == _localUserIdentityKey.toProto();
widget.activeAccountInfo.localAccount.identityMaster
.identityPublicTypedKey()
.toProto();
final textMessage = types.TextMessage( final textMessage = types.TextMessage(
author: isLocal ? _localUser : _remoteUser, author: isLocal ? _localUser : _remoteUser,
@ -77,142 +116,98 @@ class ChatComponentState extends State<ChatComponent> {
return textMessage; return textMessage;
} }
Future<void> _addMessage(proto.Message protoMessage) async { Future<void> _addMessage(BuildContext context, proto.Message message) async {
if (protoMessage.text.isEmpty) { if (message.text.isEmpty) {
return; return;
} }
await context.read<ActiveConversationMessagesCubit>().operate(
final message = protoMessageToMessage(protoMessage); _remoteConversationRecordKey,
closure: (messagesCubit) => messagesCubit.addMessage(message: message));
// 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);
} }
Future<void> _handleSendPressed(types.PartialText message) async { Future<void> _handleSendPressed(
BuildContext context, types.PartialText message) async {
final protoMessage = proto.Message() final protoMessage = proto.Message()
..author = widget.activeAccountInfo.localAccount.identityMaster ..author = _localUserIdentityKey.toProto()
.identityPublicTypedKey() ..timestamp = Veilid.instance.now().toInt64()
.toProto()
..timestamp = (await eventualVeilid.future).now().toInt64()
..text = message.text; ..text = message.text;
//..signature = signature; //..signature = signature;
await _addMessage(protoMessage); await _addMessage(context, protoMessage);
} }
void _handleAttachmentPressed() { Future<void> _handleAttachmentPressed() async {
// //
} }
@override @override
// ignore: prefer_expression_function_bodies
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context); final theme = Theme.of(context);
final scale = theme.extension<ScaleScheme>()!; final scale = theme.extension<ScaleScheme>()!;
final textTheme = Theme.of(context).textTheme; final textTheme = Theme.of(context).textTheme;
final chatTheme = makeChatTheme(scale, 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) { return DefaultTextStyle(
// Get active chat contact profile style: textTheme.bodySmall!,
final activeChatContactIdx = contactList.indexWhere((c) => child: Align(
widget.remoteConversationRecordKey == c.remoteConversationRecordKey); alignment: AlignmentDirectional.centerEnd,
late final proto.Contact activeChatContact; child: Stack(
if (activeChatContactIdx == -1) { children: [
// xxx: error, no contact for conversation... Column(
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(
children: [ children: [
Column( Container(
children: [ height: 48,
Container( decoration: BoxDecoration(
height: 48, color: scale.primaryScale.subtleBorder,
decoration: BoxDecoration( ),
color: scale.primaryScale.subtleBorder, child: Row(children: [
), Align(
child: Row(children: [ alignment: AlignmentDirectional.centerStart,
Align( child: Padding(
alignment: AlignmentDirectional.centerStart, padding: const EdgeInsetsDirectional.fromSTEB(
child: Padding( 16, 0, 16, 0),
padding: const EdgeInsetsDirectional.fromSTEB( child: Text(_remoteUser.firstName!,
16, 0, 16, 0), textAlign: TextAlign.start,
child: Text(contactName, style: textTheme.titleMedium),
textAlign: TextAlign.start, )),
style: textTheme.titleMedium), const Spacer(),
)), IconButton(
const Spacer(), icon: const Icon(Icons.close),
IconButton( onPressed: () async {
icon: const Icon(Icons.close), context.read<ActiveChatCubit>().setActiveChat(null);
onPressed: () async { }).paddingLTRB(16, 0, 16, 0)
context ]),
.read<ActiveChatCubit>() ),
.setActiveChat(null); Expanded(
}).paddingLTRB(16, 0, 16, 0) 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, localMessagesRecordKey: localConversation.messages,
remoteMessagesRecordKey: remoteConversation.messages))); remoteMessagesRecordKey: remoteConversation.messages)));
////
final ActiveAccountInfo _activeAccountInfo; final ActiveAccountInfo _activeAccountInfo;
ActiveConversationsBlocMapState _lastActiveConversationsState = ActiveConversationsBlocMapState _lastActiveConversationsState =
ActiveConversationsBlocMapState(); ActiveConversationsBlocMapState();

View File

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

View File

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

View File

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

View File

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

View File

@ -1,4 +1,5 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../chat/chat.dart'; import '../../../chat/chat.dart';
import '../../../tools/tools.dart'; import '../../../tools/tools.dart';
@ -31,10 +32,20 @@ class ChatOnlyPageState extends State<ChatOnlyPage>
super.dispose(); super.dispose();
} }
Widget buildChatComponent(BuildContext context) {
final activeChatRemoteConversationKey =
context.watch<ActiveChatCubit>().state;
if (activeChatRemoteConversationKey == null) {
return const EmptyChatWidget();
}
return ChatComponent.builder(
remoteConversationRecordKey: activeChatRemoteConversationKey);
}
@override @override
Widget build(BuildContext context) => SafeArea( Widget build(BuildContext context) => SafeArea(
child: GestureDetector( child: GestureDetector(
onTap: () => FocusScope.of(context).requestFocus(_unfocusNode), 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) => builder: (context) =>
Material(color: Colors.transparent, child: buildUserPanel())); 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 // ignore: prefer_expression_function_bodies
Widget buildTablet(BuildContext context) { Widget buildTablet(BuildContext context) {
@ -106,7 +114,7 @@ class HomeAccountReadyState extends State<HomeAccountReady>
final accountData = context.watch<AccountRecordCubit>().state.data; final accountData = context.watch<AccountRecordCubit>().state.data;
if (accountData == null) { if (accountData == null) {
return waitingPage(context); return waitingPage();
} }
return MultiBlocProvider( return MultiBlocProvider(

View File

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

View File

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

View File

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

View File

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