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,6 +1,9 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:veilid_support/veilid_support.dart';
// XXX: if we ever want to have more than one chat 'open', we should put the
// operations and state for that here.
class ActiveChatCubit extends Cubit<TypedKey?> {
ActiveChatCubit(super.initialState);

View file

@ -0,0 +1,272 @@
import 'dart:async';
import 'dart:typed_data';
import 'package:async_tools/async_tools.dart';
import 'package:fast_immutable_collections/fast_immutable_collections.dart';
import 'package:fixnum/fixnum.dart';
import 'package:flutter/widgets.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:scroll_to_index/scroll_to_index.dart';
import 'package:veilid_support/veilid_support.dart';
import '../../account_manager/account_manager.dart';
import '../../chat_list/chat_list.dart';
import '../../proto/proto.dart' as proto;
import '../models/chat_component_state.dart';
import '../models/message_state.dart';
import '../models/window_state.dart';
import 'cubits.dart';
const metadataKeyIdentityPublicKey = 'identityPublicKey';
const metadataKeyExpirationDuration = 'expiration';
const metadataKeyViewLimit = 'view_limit';
const metadataKeyAttachments = 'attachments';
class ChatComponentCubit extends Cubit<ChatComponentState> {
ChatComponentCubit._({
required SingleContactMessagesCubit messagesCubit,
required types.User localUser,
required IMap<TypedKey, types.User> remoteUsers,
}) : _messagesCubit = messagesCubit,
super(ChatComponentState(
chatKey: GlobalKey<ChatState>(),
scrollController: AutoScrollController(),
localUser: localUser,
remoteUsers: remoteUsers,
messageWindow: const AsyncLoading(),
title: '',
)) {
// Async Init
_initWait.add(_init);
}
// ignore: prefer_constructors_over_static_methods
static ChatComponentCubit singleContact(
{required ActiveAccountInfo activeAccountInfo,
required proto.Account accountRecordInfo,
required ActiveConversationState activeConversationState,
required SingleContactMessagesCubit messagesCubit}) {
// Make local 'User'
final localUserIdentityKey =
activeAccountInfo.localAccount.identityMaster.identityPublicTypedKey();
final localUser = types.User(
id: localUserIdentityKey.toString(),
firstName: accountRecordInfo.profile.name,
metadata: {metadataKeyIdentityPublicKey: localUserIdentityKey});
// Make remote 'User's
final remoteUsers = {
activeConversationState.contact.identityPublicKey.toVeilid(): types.User(
id: activeConversationState.contact.identityPublicKey
.toVeilid()
.toString(),
firstName: activeConversationState.contact.editedProfile.name,
metadata: {
metadataKeyIdentityPublicKey:
activeConversationState.contact.identityPublicKey.toVeilid()
})
}.toIMap();
return ChatComponentCubit._(
messagesCubit: messagesCubit,
localUser: localUser,
remoteUsers: remoteUsers,
);
}
Future<void> _init() async {
_messagesSubscription = _messagesCubit.stream.listen((messagesState) {
emit(state.copyWith(
messageWindow: _convertMessages(messagesState),
));
});
emit(state.copyWith(
messageWindow: _convertMessages(_messagesCubit.state),
title: _getTitle(),
));
}
@override
Future<void> close() async {
await _initWait();
await _messagesSubscription.cancel();
await super.close();
}
////////////////////////////////////////////////////////////////////////////
// Public Interface
// Set the tail position of the log for pagination.
// If tail is 0, the end of the log is used.
// If tail is negative, the position is subtracted from the current log
// length.
// If tail is positive, the position is absolute from the head of the log
// If follow is enabled, the tail offset will update when the log changes
Future<void> setWindow(
{int? tail, int? count, bool? follow, bool forceRefresh = false}) async {
//await _initWait();
await _messagesCubit.setWindow(
tail: tail, count: count, follow: follow, forceRefresh: forceRefresh);
}
// Send a message
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 ?? []);
}
// Run a chat command
void runCommand(String command) {
_messagesCubit.runCommand(command);
}
////////////////////////////////////////////////////////////////////////////
// Private Implementation
String _getTitle() {
if (state.remoteUsers.length == 1) {
final remoteUser = state.remoteUsers.values.first;
return remoteUser.firstName ?? '<unnamed>';
} else {
return '<group chat with ${state.remoteUsers.length} users>';
}
}
types.Message? _messageStateToChatMessage(MessageState message) {
final authorIdentityPublicKey = message.content.author.toVeilid();
final author =
state.remoteUsers[authorIdentityPublicKey] ?? state.localUser;
types.Status? status;
if (message.sendState != null) {
assert(author == state.localUser,
'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: author,
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;
}
}
AsyncValue<WindowState<types.Message>> _convertMessages(
AsyncValue<WindowState<MessageState>> avMessagesState) {
final asError = avMessagesState.asError;
if (asError != null) {
return AsyncValue.error(asError.error, asError.stackTrace);
} else if (avMessagesState.asLoading != null) {
return const AsyncValue.loading();
}
final messagesState = avMessagesState.asData!.value;
// Convert protobuf messages to chat messages
final chatMessages = <types.Message>[];
final tsSet = <String>{};
for (final message in messagesState.window) {
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.window}\n'
'ChatMessages:\n$chatMessages');
assert(false, 'should not have duplicate id');
}
}
return AsyncValue.data(WindowState<types.Message>(
window: chatMessages.toIList(),
length: messagesState.length,
windowTail: messagesState.windowTail,
windowCount: messagesState.windowCount,
follow: messagesState.follow));
}
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);
}
////////////////////////////////////////////////////////////////////////////
final _initWait = WaitSet<void>();
final SingleContactMessagesCubit _messagesCubit;
late StreamSubscription<SingleContactMessagesState> _messagesSubscription;
double scrollOffset = 0;
}

View file

@ -1,2 +1,3 @@
export 'active_chat_cubit.dart';
export 'chat_component_cubit.dart';
export 'single_contact_messages_cubit.dart';

View file

@ -44,7 +44,7 @@ class RenderStateElement {
bool sentOffline;
}
typedef SingleContactMessagesState = AsyncValue<MessagesState>;
typedef SingleContactMessagesState = AsyncValue<WindowState<MessageState>>;
// Cubit that processes single-contact chats
// Builds the reconciled chat record from the local and remote conversation keys
@ -189,6 +189,9 @@ class SingleContactMessagesCubit extends Cubit<SingleContactMessagesState> {
Future<void> setWindow(
{int? tail, int? count, bool? follow, bool forceRefresh = false}) async {
await _initWait();
print('setWindow: tail=$tail count=$count, follow=$follow');
await _reconciledMessagesCubit!.setWindow(
tail: tail, count: count, follow: follow, forceRefresh: forceRefresh);
}
@ -358,8 +361,8 @@ class SingleContactMessagesCubit extends Cubit<SingleContactMessagesState> {
.toIList();
// Emit the rendered state
emit(AsyncValue.data(MessagesState(
windowMessages: messages,
emit(AsyncValue.data(WindowState<MessageState>(
window: messages,
length: reconciledMessages.length,
windowTail: reconciledMessages.windowTail,
windowCount: reconciledMessages.windowCount,

View file

@ -0,0 +1,34 @@
import 'package:async_tools/async_tools.dart';
import 'package:fast_immutable_collections/fast_immutable_collections.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chat_types/flutter_chat_types.dart' show Message, User;
import 'package:flutter_chat_ui/flutter_chat_ui.dart' show ChatState;
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:scroll_to_index/scroll_to_index.dart';
import 'package:veilid_support/veilid_support.dart';
import 'window_state.dart';
part 'chat_component_state.freezed.dart';
@freezed
class ChatComponentState with _$ChatComponentState {
const factory ChatComponentState(
{
// GlobalKey for the chat
required GlobalKey<ChatState> chatKey,
// ScrollController for the chat
required AutoScrollController scrollController,
// Local user
required User localUser,
// Remote users
required IMap<TypedKey, User> remoteUsers,
// Messages state
required AsyncValue<WindowState<Message>> messageWindow,
// Title of the chat
required String title}) = _ChatComponentState;
}
extension ChatComponentStateExt on ChatComponentState {
//
}

View file

@ -0,0 +1,267 @@
// coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'chat_component_state.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
T _$identity<T>(T value) => value;
final _privateConstructorUsedError = UnsupportedError(
'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models');
/// @nodoc
mixin _$ChatComponentState {
// GlobalKey for the chat
GlobalKey<ChatState> get chatKey =>
throw _privateConstructorUsedError; // ScrollController for the chat
AutoScrollController get scrollController =>
throw _privateConstructorUsedError; // Local user
User get localUser => throw _privateConstructorUsedError; // Remote users
IMap<Typed<FixedEncodedString43>, User> get remoteUsers =>
throw _privateConstructorUsedError; // Messages state
AsyncValue<WindowState<Message>> get messageWindow =>
throw _privateConstructorUsedError; // Title of the chat
String get title => throw _privateConstructorUsedError;
@JsonKey(ignore: true)
$ChatComponentStateCopyWith<ChatComponentState> get copyWith =>
throw _privateConstructorUsedError;
}
/// @nodoc
abstract class $ChatComponentStateCopyWith<$Res> {
factory $ChatComponentStateCopyWith(
ChatComponentState value, $Res Function(ChatComponentState) then) =
_$ChatComponentStateCopyWithImpl<$Res, ChatComponentState>;
@useResult
$Res call(
{GlobalKey<ChatState> chatKey,
AutoScrollController scrollController,
User localUser,
IMap<Typed<FixedEncodedString43>, User> remoteUsers,
AsyncValue<WindowState<Message>> messageWindow,
String title});
$AsyncValueCopyWith<WindowState<Message>, $Res> get messageWindow;
}
/// @nodoc
class _$ChatComponentStateCopyWithImpl<$Res, $Val extends ChatComponentState>
implements $ChatComponentStateCopyWith<$Res> {
_$ChatComponentStateCopyWithImpl(this._value, this._then);
// ignore: unused_field
final $Val _value;
// ignore: unused_field
final $Res Function($Val) _then;
@pragma('vm:prefer-inline')
@override
$Res call({
Object? chatKey = null,
Object? scrollController = null,
Object? localUser = null,
Object? remoteUsers = null,
Object? messageWindow = null,
Object? title = null,
}) {
return _then(_value.copyWith(
chatKey: null == chatKey
? _value.chatKey
: chatKey // ignore: cast_nullable_to_non_nullable
as GlobalKey<ChatState>,
scrollController: null == scrollController
? _value.scrollController
: scrollController // ignore: cast_nullable_to_non_nullable
as AutoScrollController,
localUser: null == localUser
? _value.localUser
: localUser // ignore: cast_nullable_to_non_nullable
as User,
remoteUsers: null == remoteUsers
? _value.remoteUsers
: remoteUsers // ignore: cast_nullable_to_non_nullable
as IMap<Typed<FixedEncodedString43>, User>,
messageWindow: null == messageWindow
? _value.messageWindow
: messageWindow // ignore: cast_nullable_to_non_nullable
as AsyncValue<WindowState<Message>>,
title: null == title
? _value.title
: title // ignore: cast_nullable_to_non_nullable
as String,
) as $Val);
}
@override
@pragma('vm:prefer-inline')
$AsyncValueCopyWith<WindowState<Message>, $Res> get messageWindow {
return $AsyncValueCopyWith<WindowState<Message>, $Res>(_value.messageWindow,
(value) {
return _then(_value.copyWith(messageWindow: value) as $Val);
});
}
}
/// @nodoc
abstract class _$$ChatComponentStateImplCopyWith<$Res>
implements $ChatComponentStateCopyWith<$Res> {
factory _$$ChatComponentStateImplCopyWith(_$ChatComponentStateImpl value,
$Res Function(_$ChatComponentStateImpl) then) =
__$$ChatComponentStateImplCopyWithImpl<$Res>;
@override
@useResult
$Res call(
{GlobalKey<ChatState> chatKey,
AutoScrollController scrollController,
User localUser,
IMap<Typed<FixedEncodedString43>, User> remoteUsers,
AsyncValue<WindowState<Message>> messageWindow,
String title});
@override
$AsyncValueCopyWith<WindowState<Message>, $Res> get messageWindow;
}
/// @nodoc
class __$$ChatComponentStateImplCopyWithImpl<$Res>
extends _$ChatComponentStateCopyWithImpl<$Res, _$ChatComponentStateImpl>
implements _$$ChatComponentStateImplCopyWith<$Res> {
__$$ChatComponentStateImplCopyWithImpl(_$ChatComponentStateImpl _value,
$Res Function(_$ChatComponentStateImpl) _then)
: super(_value, _then);
@pragma('vm:prefer-inline')
@override
$Res call({
Object? chatKey = null,
Object? scrollController = null,
Object? localUser = null,
Object? remoteUsers = null,
Object? messageWindow = null,
Object? title = null,
}) {
return _then(_$ChatComponentStateImpl(
chatKey: null == chatKey
? _value.chatKey
: chatKey // ignore: cast_nullable_to_non_nullable
as GlobalKey<ChatState>,
scrollController: null == scrollController
? _value.scrollController
: scrollController // ignore: cast_nullable_to_non_nullable
as AutoScrollController,
localUser: null == localUser
? _value.localUser
: localUser // ignore: cast_nullable_to_non_nullable
as User,
remoteUsers: null == remoteUsers
? _value.remoteUsers
: remoteUsers // ignore: cast_nullable_to_non_nullable
as IMap<Typed<FixedEncodedString43>, User>,
messageWindow: null == messageWindow
? _value.messageWindow
: messageWindow // ignore: cast_nullable_to_non_nullable
as AsyncValue<WindowState<Message>>,
title: null == title
? _value.title
: title // ignore: cast_nullable_to_non_nullable
as String,
));
}
}
/// @nodoc
class _$ChatComponentStateImpl implements _ChatComponentState {
const _$ChatComponentStateImpl(
{required this.chatKey,
required this.scrollController,
required this.localUser,
required this.remoteUsers,
required this.messageWindow,
required this.title});
// GlobalKey for the chat
@override
final GlobalKey<ChatState> chatKey;
// ScrollController for the chat
@override
final AutoScrollController scrollController;
// Local user
@override
final User localUser;
// Remote users
@override
final IMap<Typed<FixedEncodedString43>, User> remoteUsers;
// Messages state
@override
final AsyncValue<WindowState<Message>> messageWindow;
// Title of the chat
@override
final String title;
@override
String toString() {
return 'ChatComponentState(chatKey: $chatKey, scrollController: $scrollController, localUser: $localUser, remoteUsers: $remoteUsers, messageWindow: $messageWindow, title: $title)';
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _$ChatComponentStateImpl &&
(identical(other.chatKey, chatKey) || other.chatKey == chatKey) &&
(identical(other.scrollController, scrollController) ||
other.scrollController == scrollController) &&
(identical(other.localUser, localUser) ||
other.localUser == localUser) &&
(identical(other.remoteUsers, remoteUsers) ||
other.remoteUsers == remoteUsers) &&
(identical(other.messageWindow, messageWindow) ||
other.messageWindow == messageWindow) &&
(identical(other.title, title) || other.title == title));
}
@override
int get hashCode => Object.hash(runtimeType, chatKey, scrollController,
localUser, remoteUsers, messageWindow, title);
@JsonKey(ignore: true)
@override
@pragma('vm:prefer-inline')
_$$ChatComponentStateImplCopyWith<_$ChatComponentStateImpl> get copyWith =>
__$$ChatComponentStateImplCopyWithImpl<_$ChatComponentStateImpl>(
this, _$identity);
}
abstract class _ChatComponentState implements ChatComponentState {
const factory _ChatComponentState(
{required final GlobalKey<ChatState> chatKey,
required final AutoScrollController scrollController,
required final User localUser,
required final IMap<Typed<FixedEncodedString43>, User> remoteUsers,
required final AsyncValue<WindowState<Message>> messageWindow,
required final String title}) = _$ChatComponentStateImpl;
@override // GlobalKey for the chat
GlobalKey<ChatState> get chatKey;
@override // ScrollController for the chat
AutoScrollController get scrollController;
@override // Local user
User get localUser;
@override // Remote users
IMap<Typed<FixedEncodedString43>, User> get remoteUsers;
@override // Messages state
AsyncValue<WindowState<Message>> get messageWindow;
@override // Title of the chat
String get title;
@override
@JsonKey(ignore: true)
_$$ChatComponentStateImplCopyWith<_$ChatComponentStateImpl> get copyWith =>
throw _privateConstructorUsedError;
}

View file

@ -1,27 +0,0 @@
import 'package:fast_immutable_collections/fast_immutable_collections.dart';
import 'package:flutter/foundation.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'message_state.dart';
part 'messages_state.freezed.dart';
part 'messages_state.g.dart';
@freezed
class MessagesState with _$MessagesState {
const factory MessagesState({
// List of messages in the window
required IList<MessageState> windowMessages,
// Total number of messages
required int length,
// One past the end of the last element
required int windowTail,
// The total number of elements to try to keep in 'messages'
required int windowCount,
// If we should have the tail following the array
required bool follow,
}) = _MessagesState;
factory MessagesState.fromJson(dynamic json) =>
_$MessagesStateFromJson(json as Map<String, dynamic>);
}

View file

@ -1,28 +0,0 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'messages_state.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
_$MessagesStateImpl _$$MessagesStateImplFromJson(Map<String, dynamic> json) =>
_$MessagesStateImpl(
windowMessages: IList<MessageState>.fromJson(
json['window_messages'], (value) => MessageState.fromJson(value)),
length: (json['length'] as num).toInt(),
windowTail: (json['window_tail'] as num).toInt(),
windowCount: (json['window_count'] as num).toInt(),
follow: json['follow'] as bool,
);
Map<String, dynamic> _$$MessagesStateImplToJson(_$MessagesStateImpl instance) =>
<String, dynamic>{
'window_messages': instance.windowMessages.toJson(
(value) => value.toJson(),
),
'length': instance.length,
'window_tail': instance.windowTail,
'window_count': instance.windowCount,
'follow': instance.follow,
};

View file

@ -1,2 +1,3 @@
export 'chat_component_state.dart';
export 'message_state.dart';
export 'messages_state.dart';
export 'window_state.dart';

View file

@ -0,0 +1,27 @@
import 'package:fast_immutable_collections/fast_immutable_collections.dart';
import 'package:flutter/foundation.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'window_state.freezed.dart';
@freezed
class WindowState<T> with _$WindowState<T> {
const factory WindowState({
// List of objects in the window
required IList<T> window,
// Total number of objects (windowTail max)
required int length,
// One past the end of the last element
required int windowTail,
// The total number of elements to try to keep in the window
required int windowCount,
// If we should have the tail following the array
required bool follow,
}) = _WindowState;
}
extension WindowStateExt<T> on WindowState<T> {
int get windowEnd => (length == 0) ? -1 : (windowTail - 1) % length;
int get windowStart =>
(length == 0) ? 0 : (windowTail - window.length) % length;
}

View file

@ -3,7 +3,7 @@
// ignore_for_file: type=lint
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'messages_state.dart';
part of 'window_state.dart';
// **************************************************************************
// FreezedGenerator
@ -14,37 +14,32 @@ T _$identity<T>(T value) => value;
final _privateConstructorUsedError = UnsupportedError(
'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models');
MessagesState _$MessagesStateFromJson(Map<String, dynamic> json) {
return _MessagesState.fromJson(json);
}
/// @nodoc
mixin _$MessagesState {
// List of messages in the window
IList<MessageState> get windowMessages =>
throw _privateConstructorUsedError; // Total number of messages
mixin _$WindowState<T> {
// List of objects in the window
IList<T> get window =>
throw _privateConstructorUsedError; // Total number of objects (windowTail max)
int get length =>
throw _privateConstructorUsedError; // One past the end of the last element
int get windowTail =>
throw _privateConstructorUsedError; // The total number of elements to try to keep in 'messages'
throw _privateConstructorUsedError; // The total number of elements to try to keep in the window
int get windowCount =>
throw _privateConstructorUsedError; // If we should have the tail following the array
bool get follow => throw _privateConstructorUsedError;
Map<String, dynamic> toJson() => throw _privateConstructorUsedError;
@JsonKey(ignore: true)
$MessagesStateCopyWith<MessagesState> get copyWith =>
$WindowStateCopyWith<T, WindowState<T>> get copyWith =>
throw _privateConstructorUsedError;
}
/// @nodoc
abstract class $MessagesStateCopyWith<$Res> {
factory $MessagesStateCopyWith(
MessagesState value, $Res Function(MessagesState) then) =
_$MessagesStateCopyWithImpl<$Res, MessagesState>;
abstract class $WindowStateCopyWith<T, $Res> {
factory $WindowStateCopyWith(
WindowState<T> value, $Res Function(WindowState<T>) then) =
_$WindowStateCopyWithImpl<T, $Res, WindowState<T>>;
@useResult
$Res call(
{IList<MessageState> windowMessages,
{IList<T> window,
int length,
int windowTail,
int windowCount,
@ -52,9 +47,9 @@ abstract class $MessagesStateCopyWith<$Res> {
}
/// @nodoc
class _$MessagesStateCopyWithImpl<$Res, $Val extends MessagesState>
implements $MessagesStateCopyWith<$Res> {
_$MessagesStateCopyWithImpl(this._value, this._then);
class _$WindowStateCopyWithImpl<T, $Res, $Val extends WindowState<T>>
implements $WindowStateCopyWith<T, $Res> {
_$WindowStateCopyWithImpl(this._value, this._then);
// ignore: unused_field
final $Val _value;
@ -64,17 +59,17 @@ class _$MessagesStateCopyWithImpl<$Res, $Val extends MessagesState>
@pragma('vm:prefer-inline')
@override
$Res call({
Object? windowMessages = null,
Object? window = null,
Object? length = null,
Object? windowTail = null,
Object? windowCount = null,
Object? follow = null,
}) {
return _then(_value.copyWith(
windowMessages: null == windowMessages
? _value.windowMessages
: windowMessages // ignore: cast_nullable_to_non_nullable
as IList<MessageState>,
window: null == window
? _value.window
: window // ignore: cast_nullable_to_non_nullable
as IList<T>,
length: null == length
? _value.length
: length // ignore: cast_nullable_to_non_nullable
@ -96,15 +91,15 @@ class _$MessagesStateCopyWithImpl<$Res, $Val extends MessagesState>
}
/// @nodoc
abstract class _$$MessagesStateImplCopyWith<$Res>
implements $MessagesStateCopyWith<$Res> {
factory _$$MessagesStateImplCopyWith(
_$MessagesStateImpl value, $Res Function(_$MessagesStateImpl) then) =
__$$MessagesStateImplCopyWithImpl<$Res>;
abstract class _$$WindowStateImplCopyWith<T, $Res>
implements $WindowStateCopyWith<T, $Res> {
factory _$$WindowStateImplCopyWith(_$WindowStateImpl<T> value,
$Res Function(_$WindowStateImpl<T>) then) =
__$$WindowStateImplCopyWithImpl<T, $Res>;
@override
@useResult
$Res call(
{IList<MessageState> windowMessages,
{IList<T> window,
int length,
int windowTail,
int windowCount,
@ -112,27 +107,27 @@ abstract class _$$MessagesStateImplCopyWith<$Res>
}
/// @nodoc
class __$$MessagesStateImplCopyWithImpl<$Res>
extends _$MessagesStateCopyWithImpl<$Res, _$MessagesStateImpl>
implements _$$MessagesStateImplCopyWith<$Res> {
__$$MessagesStateImplCopyWithImpl(
_$MessagesStateImpl _value, $Res Function(_$MessagesStateImpl) _then)
class __$$WindowStateImplCopyWithImpl<T, $Res>
extends _$WindowStateCopyWithImpl<T, $Res, _$WindowStateImpl<T>>
implements _$$WindowStateImplCopyWith<T, $Res> {
__$$WindowStateImplCopyWithImpl(
_$WindowStateImpl<T> _value, $Res Function(_$WindowStateImpl<T>) _then)
: super(_value, _then);
@pragma('vm:prefer-inline')
@override
$Res call({
Object? windowMessages = null,
Object? window = null,
Object? length = null,
Object? windowTail = null,
Object? windowCount = null,
Object? follow = null,
}) {
return _then(_$MessagesStateImpl(
windowMessages: null == windowMessages
? _value.windowMessages
: windowMessages // ignore: cast_nullable_to_non_nullable
as IList<MessageState>,
return _then(_$WindowStateImpl<T>(
window: null == window
? _value.window
: window // ignore: cast_nullable_to_non_nullable
as IList<T>,
length: null == length
? _value.length
: length // ignore: cast_nullable_to_non_nullable
@ -154,30 +149,27 @@ class __$$MessagesStateImplCopyWithImpl<$Res>
}
/// @nodoc
@JsonSerializable()
class _$MessagesStateImpl
class _$WindowStateImpl<T>
with DiagnosticableTreeMixin
implements _MessagesState {
const _$MessagesStateImpl(
{required this.windowMessages,
implements _WindowState<T> {
const _$WindowStateImpl(
{required this.window,
required this.length,
required this.windowTail,
required this.windowCount,
required this.follow});
factory _$MessagesStateImpl.fromJson(Map<String, dynamic> json) =>
_$$MessagesStateImplFromJson(json);
// List of messages in the window
// List of objects in the window
@override
final IList<MessageState> windowMessages;
// Total number of messages
final IList<T> window;
// Total number of objects (windowTail max)
@override
final int length;
// One past the end of the last element
@override
final int windowTail;
// The total number of elements to try to keep in 'messages'
// The total number of elements to try to keep in the window
@override
final int windowCount;
// If we should have the tail following the array
@ -186,15 +178,15 @@ class _$MessagesStateImpl
@override
String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) {
return 'MessagesState(windowMessages: $windowMessages, length: $length, windowTail: $windowTail, windowCount: $windowCount, follow: $follow)';
return 'WindowState<$T>(window: $window, length: $length, windowTail: $windowTail, windowCount: $windowCount, follow: $follow)';
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties
..add(DiagnosticsProperty('type', 'MessagesState'))
..add(DiagnosticsProperty('windowMessages', windowMessages))
..add(DiagnosticsProperty('type', 'WindowState<$T>'))
..add(DiagnosticsProperty('window', window))
..add(DiagnosticsProperty('length', length))
..add(DiagnosticsProperty('windowTail', windowTail))
..add(DiagnosticsProperty('windowCount', windowCount))
@ -205,9 +197,8 @@ class _$MessagesStateImpl
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _$MessagesStateImpl &&
const DeepCollectionEquality()
.equals(other.windowMessages, windowMessages) &&
other is _$WindowStateImpl<T> &&
const DeepCollectionEquality().equals(other.window, window) &&
(identical(other.length, length) || other.length == length) &&
(identical(other.windowTail, windowTail) ||
other.windowTail == windowTail) &&
@ -216,11 +207,10 @@ class _$MessagesStateImpl
(identical(other.follow, follow) || other.follow == follow));
}
@JsonKey(ignore: true)
@override
int get hashCode => Object.hash(
runtimeType,
const DeepCollectionEquality().hash(windowMessages),
const DeepCollectionEquality().hash(window),
length,
windowTail,
windowCount,
@ -229,40 +219,31 @@ class _$MessagesStateImpl
@JsonKey(ignore: true)
@override
@pragma('vm:prefer-inline')
_$$MessagesStateImplCopyWith<_$MessagesStateImpl> get copyWith =>
__$$MessagesStateImplCopyWithImpl<_$MessagesStateImpl>(this, _$identity);
@override
Map<String, dynamic> toJson() {
return _$$MessagesStateImplToJson(
this,
);
}
_$$WindowStateImplCopyWith<T, _$WindowStateImpl<T>> get copyWith =>
__$$WindowStateImplCopyWithImpl<T, _$WindowStateImpl<T>>(
this, _$identity);
}
abstract class _MessagesState implements MessagesState {
const factory _MessagesState(
{required final IList<MessageState> windowMessages,
abstract class _WindowState<T> implements WindowState<T> {
const factory _WindowState(
{required final IList<T> window,
required final int length,
required final int windowTail,
required final int windowCount,
required final bool follow}) = _$MessagesStateImpl;
required final bool follow}) = _$WindowStateImpl<T>;
factory _MessagesState.fromJson(Map<String, dynamic> json) =
_$MessagesStateImpl.fromJson;
@override // List of messages in the window
IList<MessageState> get windowMessages;
@override // Total number of messages
@override // List of objects in the window
IList<T> get window;
@override // Total number of objects (windowTail max)
int get length;
@override // One past the end of the last element
int get windowTail;
@override // The total number of elements to try to keep in 'messages'
@override // The total number of elements to try to keep in the window
int get windowCount;
@override // If we should have the tail following the array
bool get follow;
@override
@JsonKey(ignore: true)
_$$MessagesStateImplCopyWith<_$MessagesStateImpl> get copyWith =>
_$$WindowStateImplCopyWith<T, _$WindowStateImpl<T>> get copyWith =>
throw _privateConstructorUsedError;
}

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';