💫 Optimize the chat room animation

This commit is contained in:
2026-01-10 16:10:55 +08:00
parent 3847581f1f
commit e36d694397
4 changed files with 209 additions and 180 deletions

View File

@@ -4,11 +4,9 @@ import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/pods/chat/chat_room.dart'; import 'package:island/pods/chat/chat_room.dart';
import 'package:island/database/message.dart'; import 'package:island/database/message.dart';
import 'package:island/pods/chat/messages_notifier.dart'; import 'package:island/pods/chat/messages_notifier.dart';
import 'package:super_sliver_list/super_sliver_list.dart';
class RoomScrollManager { class RoomScrollManager {
final ScrollController scrollController; final ScrollController scrollController;
final ListController listController;
final ValueNotifier<double> bottomGradientOpacity; final ValueNotifier<double> bottomGradientOpacity;
bool isScrollingToMessage; bool isScrollingToMessage;
final void Function({ final void Function({
@@ -19,7 +17,6 @@ class RoomScrollManager {
RoomScrollManager({ RoomScrollManager({
required this.scrollController, required this.scrollController,
required this.listController,
required this.bottomGradientOpacity, required this.bottomGradientOpacity,
required this.scrollToMessage, required this.scrollToMessage,
this.isScrollingToMessage = false, this.isScrollingToMessage = false,
@@ -33,7 +30,6 @@ RoomScrollManager useRoomScrollManager(
AsyncValue<List<LocalChatMessage>> messagesAsync, AsyncValue<List<LocalChatMessage>> messagesAsync,
) { ) {
final scrollController = useScrollController(); final scrollController = useScrollController();
final listController = useMemoized(() => ListController(), []);
final bottomGradientOpacity = useState(ValueNotifier<double>(0.0)); final bottomGradientOpacity = useState(ValueNotifier<double>(0.0));
var isLoading = false; var isLoading = false;
@@ -47,14 +43,23 @@ RoomScrollManager useRoomScrollManager(
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
try { try {
listController.animateToItem( messagesAsync.when(
index: index, data: (messageList) {
scrollController: scrollController, if (!scrollController.hasClients) return;
alignment: 0.5,
duration: (estimatedDistance) => Duration( final messageIndex = index;
milliseconds: (estimatedDistance * 0.5).clamp(200, 800).toInt(), final totalMessages = messageList.length;
),
curve: (estimatedDistance) => Curves.easeOutCubic, if (messageIndex < 0 || messageIndex >= totalMessages) return;
scrollController.animateTo(
messageIndex * 80.0,
duration: const Duration(milliseconds: 300),
curve: Curves.easeOutCubic,
);
},
loading: () {},
error: (_, _) {},
); );
Future.delayed(const Duration(milliseconds: 800), () { Future.delayed(const Duration(milliseconds: 800), () {
@@ -109,7 +114,7 @@ RoomScrollManager useRoomScrollManager(
bottomGradientOpacity.value.value = (pixels / 500.0).clamp(0.0, 1.0); bottomGradientOpacity.value.value = (pixels / 500.0).clamp(0.0, 1.0);
}, },
loading: () {}, loading: () {},
error: (_, _) {}, error: (_, _) => {},
); );
} }
@@ -119,7 +124,6 @@ RoomScrollManager useRoomScrollManager(
return RoomScrollManager( return RoomScrollManager(
scrollController: scrollController, scrollController: scrollController,
listController: listController,
bottomGradientOpacity: bottomGradientOpacity.value, bottomGradientOpacity: bottomGradientOpacity.value,
scrollToMessage: scrollToMessageWrapper, scrollToMessage: scrollToMessageWrapper,
isScrollingToMessage: isScrollingToMessage, isScrollingToMessage: isScrollingToMessage,

View File

@@ -143,7 +143,6 @@ class ChatRoomScreen extends HookConsumerWidget {
final inputKey = useMemoized(() => GlobalKey(), []); final inputKey = useMemoized(() => GlobalKey(), []);
final inputHeight = useState<double>(80.0); final inputHeight = useState<double>(80.0);
final inputManager = useRoomInputManager(ref, id); final inputManager = useRoomInputManager(ref, id);
final roomOpenTime = useMemoized(() => DateTime.now()); final roomOpenTime = useMemoized(() => DateTime.now());
final previousInputHeightRef = useRef<double?>(null); final previousInputHeightRef = useRef<double?>(null);
@@ -372,7 +371,6 @@ class ChatRoomScreen extends HookConsumerWidget {
roomAsync: chatRoom, roomAsync: chatRoom,
chatIdentity: chatIdentity, chatIdentity: chatIdentity,
scrollController: scrollManager.scrollController, scrollController: scrollManager.scrollController,
listController: scrollManager.listController,
isSelectionMode: isSelectionMode.value, isSelectionMode: isSelectionMode.value,
selectedMessages: selectedMessages.value, selectedMessages: selectedMessages.value,
toggleSelectionMode: toggleSelectionMode, toggleSelectionMode: toggleSelectionMode,
@@ -381,10 +379,10 @@ class ChatRoomScreen extends HookConsumerWidget {
onJump: onJump, onJump: onJump,
attachmentProgress: attachmentProgress:
inputManager.attachmentProgress, inputManager.attachmentProgress,
disableAnimation: settings.disableAnimation,
roomOpenTime: roomOpenTime,
inputHeight: inputHeight.value, inputHeight: inputHeight.value,
previousInputHeight: previousInputHeightRef.value, previousInputHeight: previousInputHeightRef.value,
roomOpenTime: roomOpenTime,
disableAnimation: settings.disableAnimation,
), ),
loading: () => const Center( loading: () => const Center(
key: ValueKey('loading-messages'), key: ValueKey('loading-messages'),

View File

@@ -5,23 +5,6 @@ import 'package:island/database/message.dart';
import 'package:island/models/chat.dart'; import 'package:island/models/chat.dart';
import 'package:island/widgets/chat/message_item.dart'; import 'package:island/widgets/chat/message_item.dart';
// Provider to track animated messages to prevent replay
final animatedMessagesProvider =
NotifierProvider<AnimatedMessagesNotifier, Set<String>>(
AnimatedMessagesNotifier.new,
);
class AnimatedMessagesNotifier extends Notifier<Set<String>> {
@override
Set<String> build() {
return {};
}
void addMessage(String messageId) {
state = {...state, messageId};
}
}
class MessageItemWrapper extends ConsumerWidget { class MessageItemWrapper extends ConsumerWidget {
final LocalChatMessage message; final LocalChatMessage message;
final int index; final int index;
@@ -34,8 +17,8 @@ class MessageItemWrapper extends ConsumerWidget {
final Function(String, LocalChatMessage) onMessageAction; final Function(String, LocalChatMessage) onMessageAction;
final Function(String) onJump; final Function(String) onJump;
final Map<String, Map<int, double?>> attachmentProgress; final Map<String, Map<int, double?>> attachmentProgress;
final bool disableAnimation;
final DateTime roomOpenTime; final DateTime roomOpenTime;
final bool disableAnimation;
const MessageItemWrapper({ const MessageItemWrapper({
super.key, super.key,
@@ -50,53 +33,18 @@ class MessageItemWrapper extends ConsumerWidget {
required this.onMessageAction, required this.onMessageAction,
required this.onJump, required this.onJump,
required this.attachmentProgress, required this.attachmentProgress,
required this.disableAnimation,
required this.roomOpenTime, required this.roomOpenTime,
required this.disableAnimation,
}); });
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
// Animation logic return chatIdentity.when(
final animatedMessages = ref.watch(animatedMessagesProvider);
final isNewMessage = message.createdAt.isAfter(roomOpenTime);
final hasAnimated = animatedMessages.contains(message.id);
// Only animate if:
// 1. Animation is enabled
// 2. Message is new (created after room open)
// 3. Has not animated yet
final shouldAnimate = !disableAnimation && isNewMessage && !hasAnimated;
final child = chatIdentity.when(
skipError: true, skipError: true,
data: (identity) => _buildContent(context, identity), data: (identity) => _buildContent(context, identity),
loading: () => _buildLoading(), loading: () => _buildLoading(),
error: (_, _) => const SizedBox.shrink(), error: (_, _) => const SizedBox.shrink(),
); );
if (!shouldAnimate) {
return child;
}
return TweenAnimationBuilder<double>(
key: ValueKey('anim-${message.id}'), // Ensure unique key for animation
tween: Tween<double>(begin: 0.0, end: 1.0),
duration: Duration(milliseconds: 400 + (index % 5) * 50),
curve: Curves.easeOutCubic,
builder: (context, value, child) {
return Transform.translate(
offset: Offset(0, 20 * (1 - value)),
child: Opacity(opacity: value, child: child),
);
},
onEnd: () {
// Mark as animated
WidgetsBinding.instance.addPostFrameCallback((_) {
ref.read(animatedMessagesProvider.notifier).addMessage(message.id);
});
},
child: child,
);
} }
Widget _buildContent(BuildContext context, SnChatMember? identity) { Widget _buildContent(BuildContext context, SnChatMember? identity) {
@@ -116,11 +64,8 @@ class MessageItemWrapper extends ConsumerWidget {
} }
}, },
child: Container( child: Container(
color: color: isSelected
isSelected ? Theme.of(context).colorScheme.primaryContainer.withOpacity(0.3)
? Theme.of(
context,
).colorScheme.primaryContainer.withOpacity(0.3)
: null, : null,
child: Stack( child: Stack(
children: [ children: [
@@ -130,8 +75,7 @@ class MessageItemWrapper extends ConsumerWidget {
key: ValueKey('item-${message.id}'), key: ValueKey('item-${message.id}'),
message: message, message: message,
isCurrentUser: isCurrentUser, isCurrentUser: isCurrentUser,
onAction: onAction: isSelectionMode
isSelectionMode
? null ? null
: (action) => onMessageAction(action, message), : (action) => onMessageAction(action, message),
onJump: onJump, onJump: onJump,

View File

@@ -1,17 +1,15 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/database/message.dart'; import 'package:island/database/message.dart';
import 'package:island/models/chat.dart'; import 'package:island/models/chat.dart';
import 'package:island/pods/config.dart';
import 'package:island/screens/chat/widgets/message_item_wrapper.dart'; import 'package:island/screens/chat/widgets/message_item_wrapper.dart';
import 'package:super_sliver_list/super_sliver_list.dart';
class RoomMessageList extends HookConsumerWidget { class RoomMessageList extends HookConsumerWidget {
final List<LocalChatMessage> messages; final List<LocalChatMessage> messages;
final AsyncValue<SnChatRoom?> roomAsync; final AsyncValue<SnChatRoom?> roomAsync;
final AsyncValue<SnChatMember?> chatIdentity; final AsyncValue<SnChatMember?> chatIdentity;
final ScrollController scrollController; final ScrollController scrollController;
final ListController listController;
final bool isSelectionMode; final bool isSelectionMode;
final Set<String> selectedMessages; final Set<String> selectedMessages;
final VoidCallback toggleSelectionMode; final VoidCallback toggleSelectionMode;
@@ -19,10 +17,10 @@ class RoomMessageList extends HookConsumerWidget {
final void Function(String action, LocalChatMessage message) onMessageAction; final void Function(String action, LocalChatMessage message) onMessageAction;
final void Function(String messageId) onJump; final void Function(String messageId) onJump;
final Map<String, Map<int, double?>> attachmentProgress; final Map<String, Map<int, double?>> attachmentProgress;
final bool disableAnimation;
final DateTime roomOpenTime;
final double inputHeight; final double inputHeight;
final double? previousInputHeight; final double? previousInputHeight;
final DateTime roomOpenTime;
final bool disableAnimation;
const RoomMessageList({ const RoomMessageList({
super.key, super.key,
@@ -30,7 +28,6 @@ class RoomMessageList extends HookConsumerWidget {
required this.roomAsync, required this.roomAsync,
required this.chatIdentity, required this.chatIdentity,
required this.scrollController, required this.scrollController,
required this.listController,
required this.isSelectionMode, required this.isSelectionMode,
required this.selectedMessages, required this.selectedMessages,
required this.toggleSelectionMode, required this.toggleSelectionMode,
@@ -38,45 +35,84 @@ class RoomMessageList extends HookConsumerWidget {
required this.onMessageAction, required this.onMessageAction,
required this.onJump, required this.onJump,
required this.attachmentProgress, required this.attachmentProgress,
required this.disableAnimation,
required this.roomOpenTime,
required this.inputHeight, required this.inputHeight,
required this.roomOpenTime,
required this.disableAnimation,
this.previousInputHeight, this.previousInputHeight,
}); });
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
final settings = ref.watch(appSettingsProvider); final animatedListKey = useMemoized(
() => GlobalKey<SliverAnimatedListState>(),
[],
);
const messageKeyPrefix = 'message-'; const messageKeyPrefix = 'message-';
final bottomPadding = final bottomPadding =
inputHeight + MediaQuery.of(context).padding.bottom + 8; inputHeight + MediaQuery.of(context).padding.bottom + 8;
final listWidget = final listKeys = useRef<List<String>>([]);
previousInputHeight != null && previousInputHeight != inputHeight final messageMap = useRef<Map<String, LocalChatMessage>>({});
? TweenAnimationBuilder<double>(
tween: Tween<double>(begin: previousInputHeight, end: inputHeight), useEffect(() {
duration: const Duration(milliseconds: 200), final currentKeys = messages
curve: Curves.easeOut, .map((m) => '$messageKeyPrefix${m.nonce ?? m.id}')
builder: (context, height, child) => SuperListView.builder( .toList();
listController: listController, final previousKeys = listKeys.value;
final addedKeys = currentKeys
.where((k) => !previousKeys.contains(k))
.toList();
final removedKeys = previousKeys
.where((k) => !currentKeys.contains(k))
.toList();
WidgetsBinding.instance.addPostFrameCallback((_) {
final state = animatedListKey.currentState;
if (state != null) {
for (final key in removedKeys) {
final index = messageMap.value.keys.toList().indexOf(key);
if (index != -1) {
state.removeItem(
index,
(context, animation) => _buildRemovedItem(context, animation),
);
}
}
for (final key in addedKeys) {
final index = currentKeys.indexOf(key);
state.insertItem(
index,
duration: Duration(milliseconds: 300 + (index % 3) * 50),
);
}
}
});
listKeys.value = currentKeys;
messageMap.value = {
for (var m in messages) '$messageKeyPrefix${m.nonce ?? m.id}': m,
};
return null;
}, [messages]);
final listWidget = CustomScrollView(
controller: scrollController, controller: scrollController,
reverse: true, reverse: true,
padding: EdgeInsets.only( slivers: [
top: 8, if (previousInputHeight != null && previousInputHeight != inputHeight)
bottom: height + MediaQuery.of(context).padding.bottom + 8, SliverPadding(
), padding: EdgeInsets.only(top: 8, bottom: bottomPadding),
itemCount: messages.length, sliver: SliverAnimatedList(
findChildIndexCallback: (key) { key: animatedListKey,
if (key is! ValueKey<String>) return null; initialItemCount: messages.length,
final messageId = key.value.substring(messageKeyPrefix.length); itemBuilder: (context, index, animation) {
final index = messages.indexWhere( if (index >= messages.length) {
(m) => (m.nonce ?? m.id) == messageId, return const SizedBox.shrink();
); }
return index >= 0 ? index : null;
},
extentEstimation: (_, _) => 40,
itemBuilder: (context, index) {
final message = messages[index]; final message = messages[index];
final nextMessage = index < messages.length - 1 final nextMessage = index < messages.length - 1
? messages[index + 1] ? messages[index + 1]
@@ -94,7 +130,10 @@ class RoomMessageList extends HookConsumerWidget {
'$messageKeyPrefix${message.nonce ?? message.id}', '$messageKeyPrefix${message.nonce ?? message.id}',
); );
return MessageItemWrapper( return _buildAnimatedItem(
context,
animation,
MessageItemWrapper(
key: key, key: key,
message: message, message: message,
index: index, index: index,
@@ -107,28 +146,24 @@ class RoomMessageList extends HookConsumerWidget {
onMessageAction: onMessageAction, onMessageAction: onMessageAction,
onJump: onJump, onJump: onJump,
attachmentProgress: attachmentProgress, attachmentProgress: attachmentProgress,
disableAnimation: settings.disableAnimation,
roomOpenTime: roomOpenTime, roomOpenTime: roomOpenTime,
disableAnimation: true,
),
); );
}, },
), ),
) )
: SuperListView.builder( else
listController: listController, SliverPadding(
controller: scrollController,
reverse: true,
padding: EdgeInsets.only(top: 8, bottom: bottomPadding), padding: EdgeInsets.only(top: 8, bottom: bottomPadding),
itemCount: messages.length, sliver: SliverAnimatedList(
findChildIndexCallback: (key) { key: animatedListKey,
if (key is! ValueKey<String>) return null; initialItemCount: messages.length,
final messageId = key.value.substring(messageKeyPrefix.length); itemBuilder: (context, index, animation) {
final index = messages.indexWhere( if (index >= messages.length) {
(m) => (m.nonce ?? m.id) == messageId, return const SizedBox.shrink();
); }
return index >= 0 ? index : null;
},
extentEstimation: (_, _) => 40,
itemBuilder: (context, index) {
final message = messages[index]; final message = messages[index];
final nextMessage = index < messages.length - 1 final nextMessage = index < messages.length - 1
? messages[index + 1] ? messages[index + 1]
@@ -146,7 +181,10 @@ class RoomMessageList extends HookConsumerWidget {
'$messageKeyPrefix${message.nonce ?? message.id}', '$messageKeyPrefix${message.nonce ?? message.id}',
); );
return MessageItemWrapper( return _buildAnimatedItem(
context,
animation,
MessageItemWrapper(
key: key, key: key,
message: message, message: message,
index: index, index: index,
@@ -159,12 +197,57 @@ class RoomMessageList extends HookConsumerWidget {
onMessageAction: onMessageAction, onMessageAction: onMessageAction,
onJump: onJump, onJump: onJump,
attachmentProgress: attachmentProgress, attachmentProgress: attachmentProgress,
disableAnimation: settings.disableAnimation,
roomOpenTime: roomOpenTime, roomOpenTime: roomOpenTime,
disableAnimation: true,
),
); );
}, },
),
),
],
); );
return listWidget; return listWidget;
} }
Widget _buildAnimatedItem(
BuildContext context,
Animation<double> animation,
Widget child,
) {
final curvedAnimation = CurvedAnimation(
parent: animation,
curve: Curves.easeOutQuart,
);
final scaleAnimation = Tween<double>(
begin: 0.92,
end: 1.0,
).animate(curvedAnimation);
final slideAnimation = Tween<Offset>(
begin: const Offset(0, 0.12),
end: Offset.zero,
).animate(curvedAnimation);
final fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
CurvedAnimation(
parent: animation,
curve: const Interval(0.1, 1.0, curve: Curves.easeOut),
),
);
return FadeTransition(
opacity: fadeAnimation,
child: ScaleTransition(
scale: scaleAnimation,
child: SlideTransition(position: slideAnimation, child: child),
),
);
}
Widget _buildRemovedItem(BuildContext context, Animation<double> animation) {
return SizeTransition(
sizeFactor: animation,
child: FadeTransition(opacity: animation, child: SizedBox.shrink()),
);
}
} }