Repository navigation
fix(chat): Loading a new message page freezes the client - #21521
Conversation
- When the user clicks 'Load more messages' the client freezes for a few seconds before rendering the new page. This was happening because the message component was overheaded with hook calls and data access. In order to fix that, all those hook calls within the message component were placed in the parent component (more stable, doesn't rerender frequently) and passed as props to the message component.
WalkthroughThe pull request introduces significant enhancements to the Possibly related PRs
Suggested reviewers
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 9
🧹 Outside diff range and nitpick comments (2)
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/component.tsx (2)
32-63: Add JSDoc comments to document interface properties.The new interface structure is well-organized, but would benefit from JSDoc documentation to explain the purpose and expected values of each property, especially for boolean flags that control features.
Example documentation format:
/** * Common properties shared between ChatListPage container and presentation components */ interface ChatListPageCommonProps { /** ID of the first page to load in the chat history */ firstPageToLoad: number; /** ID of the currently focused message, if any */ focusedId: number | null; // ... add similar documentation for other properties }
114-127: Consider using React Context to reduce prop drilling.The component is passing numerous props through multiple levels, which could make maintenance more challenging. Consider using React Context for commonly shared props like user permissions and chat feature flags.
Example implementation:
// chatFeatureContext.ts interface ChatFeatureContext { meetingDisablePrivateChat: boolean; meetingDisablePublicChat: boolean; currentUserIsModerator: boolean; // ... other feature flags and permissions } const ChatFeatureContext = React.createContext<ChatFeatureContext>(defaultValues); // In parent component: const ChatFeatureProvider: React.FC = ({ children }) => { const value = { meetingDisablePrivateChat, meetingDisablePublicChat, currentUserIsModerator, // ... other values }; return ( <ChatFeatureContext.Provider value={value}> {children} </ChatFeatureContext.Provider> ); };This would:
- Reduce the number of props being passed
- Make it easier to add new features
- Improve maintainability
- Make testing easier with context mocks
Also applies to: 254-267, 287-299, 342-355
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (5)
- bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/component.tsx (3 hunks)
- bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/component.tsx (7 hunks)
- bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/message-reactions/component.tsx (3 hunks)
- bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/component.tsx (5 hunks)
- bigbluebutton-html5/imports/utils/object-utils.js (1 hunks)
🔇 Additional comments (5)
bigbluebutton-html5/imports/utils/object-utils.js (1)
1-13: Verify usage patterns across the codebase.Let's ensure this utility function is being used appropriately in the chat components and doesn't introduce performance bottlenecks.
✅ Verification successful
Let me analyze the usage patterns further by checking the specific context where these function calls are made.
Function usage is safe and optimized for chat performance
The
getValueByPointerutility is being used appropriately and safely:
- It's used within memoization comparison functions (
areChatPagesEqualandareChatMessagesEqual)- Both components using it are wrapped with React.memo for performance optimization
- The function is only called during prop comparison, not during rendering
- No usage found in performance-critical loops
The implementation aligns well with the chat performance improvements context, as it's part of the optimization strategy to prevent unnecessary re-renders.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Analyze usage patterns of getValueByPointer # Find direct imports of the function echo "=== Direct imports ===" rg "import.*getValueByPointer.*from.*object-utils" # Find actual usage of the function echo -e "\n=== Function usage patterns ===" rg "getValueByPointer\(" -A 2 # Look for potential performance-critical loops echo -e "\n=== Usage in loops ===" ast-grep --pattern 'for ($_) { $$$ getValueByPointer($$$) $$$ }'Length of output: 2439
Script:
#!/bin/bash # Get more context around the usage in chat components # Check the full context of usage in chat message list component echo "=== Chat Message List Component Usage ===" rg "getValueByPointer" bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/component.tsx -B 5 -A 5 # Check the full context of usage in chat message component echo -e "\n=== Chat Message Component Usage ===" rg "getValueByPointer" bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/component.tsx -B 5 -A 5 # Look for any performance-related comments or memoization patterns echo -e "\n=== Performance Related Context ===" rg "memo|useMemo|React.memo" bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/component.tsx rg "memo|useMemo|React.memo" bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/component.tsxLength of output: 3179
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/message-reactions/component.tsx (2)
32-35: LGTM! Interface changes improve type safety and component composition.The addition of
chatIdandmessageIdparameters to the reaction handlers aligns well with moving state management to the parent component, which should help reduce unnecessary re-renders.
51-53: LGTM! Clean props destructuring.The destructuring is well-organized and consistent with the interface definition.
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/component.tsx (1)
Line range hint
1-355: Verify performance improvement with React DevTools.The changes align well with the PR objectives by moving data access to the parent component and optimizing re-renders. To ensure the changes effectively resolve the freezing issue:
Use React DevTools to profile the component:
Verify that the message component only re-renders when necessary by checking the React DevTools Profiler during the "Load more messages" action.
✅ Verification successful
Let me try a different approach to verify the hook usage and potential performance implications.
This will help us:
- Locate the ChatMessage component implementation
- Find any hook usage within chat message related files
- Better understand the component's render behavior
Based on the search results, I can now provide a conclusive analysis of the hook usage and performance implications.
Hook usage in ChatMessage component is well-optimized
The code shows proper optimization techniques:
- Uses
useMemofor complex message content calculations with proper dependencies- Implements
useCallbackfor scroll event handlers- Employs
useImperativeHandlefor controlled focus management- Properly memoizes the component with
memoand custom equality check- Event listeners are properly cleaned up in
useEffecthooksThe changes have successfully moved data fetching to the parent component while keeping render-specific hooks in the message component. The component will only re-render when:
- Message content changes
- Visibility/focus state changes
- User interactions occur (reactions, editing, etc.)
The code demonstrates good React performance practices:
- Data fetching is separated from presentation
- Heavy computations are memoized
- Event handlers are properly memoized
- Component updates are optimized through proper prop comparison
- DOM manipulation is handled through refs instead of direct state updates
No further performance verification is needed as the code structure follows React best practices for preventing unnecessary re-renders.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Search for any remaining hook calls in the ChatMessage component # that might cause unnecessary re-renders # Look for useEffect, useState, or other hook calls in ChatMessage ast-grep --pattern 'const $_ = use$_($$$)'Length of output: 44
Script:
#!/bin/bash # Search for the ChatMessage component definition and its hooks ast-grep --pattern 'const ChatMessage = $$$' # Also search for any hook patterns in files containing "chat-message" fd "chat-message" --type f --exec rg -l "use[A-Z]|useState|useEffect|useRef|useContext"Length of output: 84211
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/component.tsx (1)
31-39: Imports added correctly for new hooks and mutationsThe imports for
useMeeting,useCurrentUser, feature flags, and mutations are correctly added and seem appropriate for the enhancements introduced.
| deleteReaction(details.reactionEmoji, details.reactionEmojiId, chatId, messageId); | ||
| } else { | ||
| sendReaction(details.reactionEmoji, details.reactionEmojiId); | ||
| sendReaction(details.reactionEmoji, details.reactionEmojiId, chatId, messageId); |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Consider memoizing the click handler for better performance.
While the implementation is correct, the click handler is recreated on each render. Consider extracting it to a memoized callback using useCallback.
Here's how you could optimize it:
+ const handleReactionClick = React.useCallback((
+ reactionEmoji: string,
+ reactionEmojiId: string,
+ isReacted: boolean
+ ) => {
+ if (isReacted) {
+ deleteReaction(reactionEmoji, reactionEmojiId, chatId, messageId);
+ } else {
+ sendReaction(reactionEmoji, reactionEmojiId, chatId, messageId);
+ }
+ }, [deleteReaction, sendReaction, chatId, messageId]);
// In the JSX
- onClick={() => {
- if (details.reactedByMe) {
- deleteReaction(details.reactionEmoji, details.reactionEmojiId, chatId, messageId);
- } else {
- sendReaction(details.reactionEmoji, details.reactionEmojiId, chatId, messageId);
- }
- }}
+ onClick={() => handleReactionClick(
+ details.reactionEmoji,
+ details.reactionEmojiId,
+ details.reactedByMe
+ )}Committable suggestion was skipped due to low confidence.
| const propsToCompare = [ | ||
| 'focusedId', | ||
| 'meetingDisablePublicChat', | ||
| 'meetingDisablePrivateChat', | ||
| 'currentUserDisablePublicChat', | ||
| 'currentUserId', | ||
| 'currentUserIsLocked', | ||
| 'currentUserIsModerator', | ||
| 'chatDeleteEnabled', | ||
| 'chatEditEnabled', | ||
| 'chatReactionsEnabled', | ||
| 'chatReplyEnabled', | ||
| ] as const; | ||
| const messagePropsToCompare = [ | ||
| 'messageId', | ||
| 'createdAt', | ||
| 'user.currentlyInMeeting', | ||
| 'recipientHasSeen', | ||
| 'message', | ||
| 'reactions.length', | ||
| ] as const; | ||
| const nextMessages = nextProps?.messages || []; | ||
| const prevMessages = prevProps?.messages || []; | ||
| if (nextMessages.length !== prevMessages.length) return false; | ||
| return nextMessages.every((nextMessage, idx) => { | ||
| const prevMessage = prevMessages[idx]; | ||
| return (prevMessage.messageId === nextMessage.messageId | ||
| && prevMessage.createdAt === nextMessage.createdAt | ||
| && prevMessage?.user?.currentlyInMeeting === nextMessage?.user?.currentlyInMeeting | ||
| && prevMessage?.recipientHasSeen === nextMessage?.recipientHasSeen | ||
| && prevMessage?.message === nextMessage?.message | ||
| && prevMessage?.reactions?.length === nextMessage?.reactions?.length | ||
| ); | ||
| }) && prevProps.focusedId === nextProps.focusedId; | ||
| return messagePropsToCompare.every((pointer) => { | ||
| const previousValue = getValueByPointer(prevMessage, pointer); | ||
| const nextValue = getValueByPointer(nextMessage, pointer); | ||
| return previousValue === nextValue; | ||
| }); | ||
| }) && propsToCompare.every((pointer) => { | ||
| const previousValue = getValueByPointer(prevProps, pointer); | ||
| const nextValue = getValueByPointer(nextProps, pointer); | ||
| return previousValue === nextValue; | ||
| }); |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Consider memoizing comparison arrays and optimizing deep comparisons.
While the new comparison logic using getValueByPointer is more maintainable, there are opportunities for optimization:
- Move the comparison arrays outside the function to prevent recreation on each comparison:
const PROPS_TO_COMPARE = [
'focusedId',
'meetingDisablePublicChat',
// ... other props
] as const;
const MESSAGE_PROPS_TO_COMPARE = [
'messageId',
'createdAt',
// ... other message props
] as const;
const areChatPagesEqual = (prevProps: ChatListPageProps, nextProps: ChatListPageProps) => {
const nextMessages = nextProps?.messages || [];
const prevMessages = prevProps?.messages || [];
if (nextMessages.length !== prevMessages.length) return false;
return nextMessages.every((nextMessage, idx) => {
const prevMessage = prevMessages[idx];
return MESSAGE_PROPS_TO_COMPARE.every((pointer) =>
getValueByPointer(prevMessage, pointer) === getValueByPointer(nextMessage, pointer)
);
}) && PROPS_TO_COMPARE.every((pointer) =>
getValueByPointer(prevProps, pointer) === getValueByPointer(nextProps, pointer)
);
};| 'message.recipientHasSeen', | ||
| 'message.user.currentlyInMeeting', | ||
| 'message.reactions.length', | ||
| 'message.replyToMessage.message', | ||
| 'message.recipientHasSeen', |
There was a problem hiding this comment.
Remove duplicate 'message.recipientHasSeen' from 'propsToCompare' array
The property 'message.recipientHasSeen' appears twice in the propsToCompare array. This duplication is unnecessary and may lead to confusion.
Apply this diff to remove the duplicate entry:
const propsToCompare = [
'message.replyToMessage.message',
- 'message.recipientHasSeen',
];Committable suggestion was skipped due to low confidence.
|
does it close the issue #21434? |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Outside diff range and nitpick comments (1)
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/component.tsx (1)
155-164: Consider improving lock status determination.The current implementation could be more maintainable with these improvements:
- Rename
disablePublicChattoisPublicChatDisabledfor clarity- Consider extracting the lock logic into a separate function or useMemo hook
Apply this diff to improve readability:
- const disablePublicChat = meetingDisablePublicChat || currentUserDisablePublicChat; + const isPublicChatDisabled = meetingDisablePublicChat || currentUserDisablePublicChat; - let locked = false; - if (!currentUserIsModerator) { - if (isPublicChat) { - locked = currentUserIsLocked && disablePublicChat; - } else { - locked = currentUserIsLocked && meetingDisablePrivateChat; - } - } + const locked = !currentUserIsModerator && currentUserIsLocked && ( + isPublicChat ? isPublicChatDisabled : meetingDisablePrivateChat + );
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (3)
- bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/component.tsx (3 hunks)
- bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/component.tsx (7 hunks)
- bigbluebutton-html5/imports/utils/object-utils.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- bigbluebutton-html5/imports/utils/object-utils.js
🔇 Additional comments (4)
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/component.tsx (2)
35-35: LGTM! Props interface changes align with performance objectives.The expanded interface properly encapsulates all necessary data and callbacks previously managed by hooks, which should help reduce unnecessary re-renders.
Also applies to: 48-61
576-580: LGTM! Efficient prop comparison implementation.The use of
getValueByPointerfor deep prop comparison is a good approach to optimize re-renders. The implementation correctly handles nested properties and undefined values.bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/component.tsx (2)
31-39: LGTM!The new imports correctly integrate the necessary hooks and feature flags to enhance the chat functionality.
201-220: Efficient use of hooks for data managementThe implementation of
useMeetinganduseCurrentUserhooks effectively centralizes meeting and user data, improving the component's clarity and maintainability.
| onEmojiSelected={(emoji) => { | ||
| sendReaction(emoji.native, emoji.id); | ||
| sendReaction(emoji.native, emoji.id, message.chatId, message.messageId); | ||
| setIsToolbarReactionPopoverOpen(false); | ||
| }} |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Consider memoizing the emoji selection handler.
The onEmojiSelected callback is recreated on every render. Consider using useCallback to memoize it.
+ const handleEmojiSelected = useCallback((emoji) => {
+ sendReaction(emoji.native, emoji.id, message.chatId, message.messageId);
+ setIsToolbarReactionPopoverOpen(false);
+ }, [message.chatId, message.messageId, sendReaction]);
- onEmojiSelected={(emoji) => {
- sendReaction(emoji.native, emoji.id, message.chatId, message.messageId);
- setIsToolbarReactionPopoverOpen(false);
- }}
+ onEmojiSelected={handleEmojiSelected}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| onEmojiSelected={(emoji) => { | |
| sendReaction(emoji.native, emoji.id); | |
| sendReaction(emoji.native, emoji.id, message.chatId, message.messageId); | |
| setIsToolbarReactionPopoverOpen(false); | |
| }} | |
| const handleEmojiSelected = useCallback((emoji) => { | |
| sendReaction(emoji.native, emoji.id, message.chatId, message.messageId); | |
| setIsToolbarReactionPopoverOpen(false); | |
| }, [message.chatId, message.messageId, sendReaction]); | |
| onEmojiSelected={handleEmojiSelected} |
| const sendReaction = (reactionEmoji: string, reactionEmojiId: string, chatId: string, messageId: string) => { | ||
| chatSendReaction({ | ||
| variables: { | ||
| chatId, | ||
| messageId, | ||
| reactionEmoji, | ||
| reactionEmojiId, | ||
| }, | ||
| }); | ||
| }; | ||
|
|
||
| const deleteReaction = (reactionEmoji: string, reactionEmojiId: string, chatId: string, messageId: string) => { | ||
| chatDeleteReaction({ | ||
| variables: { | ||
| chatId, | ||
| messageId, | ||
| reactionEmoji, | ||
| reactionEmojiId, | ||
| }, | ||
| }); | ||
| }; |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Optimize functions with 'useCallback' to prevent unnecessary re-renders
Wrapping sendReaction and deleteReaction in useCallback can enhance performance by memoizing these functions, especially since they are passed as props to child components.
Apply this diff to implement the optimization:
+ const sendReaction = useCallback((reactionEmoji: string, reactionEmojiId: string, chatId: string, messageId: string) => {
chatSendReaction({
variables: {
chatId,
messageId,
reactionEmoji,
reactionEmojiId,
},
});
+ }, [chatSendReaction]);
+ const deleteReaction = useCallback((reactionEmoji: string, reactionEmojiId: string, chatId: string, messageId: string) => {
chatDeleteReaction({
variables: {
chatId,
messageId,
reactionEmoji,
reactionEmojiId,
},
});
+ }, [chatDeleteReaction]);📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const sendReaction = (reactionEmoji: string, reactionEmojiId: string, chatId: string, messageId: string) => { | |
| chatSendReaction({ | |
| variables: { | |
| chatId, | |
| messageId, | |
| reactionEmoji, | |
| reactionEmojiId, | |
| }, | |
| }); | |
| }; | |
| const deleteReaction = (reactionEmoji: string, reactionEmojiId: string, chatId: string, messageId: string) => { | |
| chatDeleteReaction({ | |
| variables: { | |
| chatId, | |
| messageId, | |
| reactionEmoji, | |
| reactionEmojiId, | |
| }, | |
| }); | |
| }; | |
| const sendReaction = useCallback((reactionEmoji: string, reactionEmojiId: string, chatId: string, messageId: string) => { | |
| chatSendReaction({ | |
| variables: { | |
| chatId, | |
| messageId, | |
| reactionEmoji, | |
| reactionEmojiId, | |
| }, | |
| }); | |
| }, [chatSendReaction]); | |
| const deleteReaction = useCallback((reactionEmoji: string, reactionEmojiId: string, chatId: string, messageId: string) => { | |
| chatDeleteReaction({ | |
| variables: { | |
| chatId, | |
| messageId, | |
| reactionEmoji, | |
| reactionEmojiId, | |
| }, | |
| }); | |
| }, [chatDeleteReaction]); |
Arthurk12
left a comment
There was a problem hiding this comment.
The performance when toggling the chat panel and loading previous chat pages has significantly improved, reducing loading time. However, I've noticed that when a new message is sent, all messages on the last page are being re-rendered (see gif below). It seems the trigger for this issue might be the callback ref passed to the ChatMessage component, which is instantiated each time the component renders.
| @@ -202,6 +252,20 @@ const ChatListPage: React.FC<ChatListPageProps> = ({ | |||
| ref={(ref) => { | |||
There was a problem hiding this comment.
The callback I mentioned that triggers unnecessary re-renders.
|
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Outside diff range and nitpick comments (5)
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/message-toolbar/component.tsx (1)
84-99: Consider enhancing user feedback for delete operations.
The delete operation implementation is solid with good error logging, but could benefit from improved user feedback.
Consider adding:
- Loading state during deletion
- Success notification
- Error feedback to the user
const onDeleteConfirmation = useCallback(() => {
+ setIsDeleting(true);
chatDeleteMessage({
variables: {
chatId,
messageId,
},
- }).catch((e) => {
+ }).then(() => {
+ setIsDeleting(false);
+ // Show success toast/notification
+ }).catch((e) => {
+ setIsDeleting(false);
+ // Show error toast/notification
logger.error({
logCode: 'chat_delete_message_error',
extraInfo: {
errorName: e?.name,
errorMessage: e?.message,
},
}, `Deleting the message failed: ${e?.message}`);
});
-}, [chatDeleteMessage, chatId, messageId]);
+}, [chatDeleteMessage, chatId, messageId, setIsDeleting]);bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/component.tsx (2)
33-53: Consider adding JSDoc comments to document the interface properties.
The new ChatListPageCommonProps interface effectively consolidates common props, but would benefit from documentation explaining the purpose and usage of each property.
Add JSDoc comments like this:
/**
* Common properties shared between ChatListPage components
*/
interface ChatListPageCommonProps {
/** The first page number to load in the chat history */
firstPageToLoad: number;
/** ID of the currently focused message */
focusedId: number | null;
// ... add documentation for other properties
}Line range hint 332-336: Consider consolidating null checks for better readability.
The multiple conditions for rendering loading state or null could be simplified for better maintainability.
Consider consolidating the checks like this:
- if (!chatMessageData) return null;
- if (chatMessageData.length > 0 && chatId !== chatMessageData[0].chatId) return <ChatLoading isRTL={document.dir === 'rtl'} />;
+ if (!chatMessageData?.length) return null;
+ if (chatId !== chatMessageData[0].chatId) return <ChatLoading isRTL={document.dir === 'rtl'} />;bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-form/component.tsx (2)
Line range hint 1-24: Consider splitting the component for better performance and maintainability.
Given that this PR aims to fix client freezing issues, consider these architectural improvements:
- Split into smaller components:
- EmojiPicker component
- MessageInput component
- MessageForm component
- Consolidate state management
- Optimize event listeners
Here's a suggested component structure:
// EmojiPicker.tsx
interface EmojiPickerProps {
onSelect: (emoji: { native: string }) => void;
buttonRef: React.RefObject<HTMLButtonElement>;
pickerRef: React.RefObject<HTMLDivElement>;
}
// MessageInput.tsx
interface MessageInputProps {
value: string;
onChange: (value: string) => void;
onKeyDown: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void;
disabled: boolean;
}
// MessageForm.tsx (main component)
const MessageForm: React.FC<ChatMessageFormProps> = () => {
const [formState, setFormState] = useReducer(formReducer, initialState);
// ... rest of the code
}This refactoring would:
- Reduce re-renders by isolating state changes
- Improve code maintainability
- Make it easier to test individual components
Also applies to: 32-70
Line range hint 492-501: Fix potential memory leak and optimize click handling.
The document click listener has two issues:
- It's not properly cleaned up, which could cause memory leaks
- It unnecessarily focuses the textarea on every click within the chat list
Apply this diff to fix these issues:
- document.addEventListener('click', (event) => {
- const chatList = document.getElementById('chat-list');
- if (chatList?.contains(event.target as Node)) {
- const selection = window.getSelection()?.toString();
- if (selection?.length === 0) {
- textAreaRef.current?.textarea.focus();
- }
- }
- });
+ useEffect(() => {
+ const handleChatListClick = (event: MouseEvent) => {
+ const chatList = document.getElementById('chat-list');
+ if (chatList?.contains(event.target as Node) && !isTextAreaFocused) {
+ const selection = window.getSelection()?.toString();
+ if (selection?.length === 0) {
+ textAreaRef.current?.textarea.focus();
+ }
+ }
+ };
+
+ document.addEventListener('click', handleChatListClick);
+ return () => document.removeEventListener('click', handleChatListClick);
+ }, [isTextAreaFocused]);📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (5)
- bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-form/component.tsx (1 hunks)
- bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/component.tsx (3 hunks)
- bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/component.tsx (7 hunks)
- bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/message-toolbar/component.tsx (4 hunks)
- bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/component.tsx (7 hunks)
🔇 Additional comments (11)
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/message-toolbar/component.tsx (3)
1-1: LGTM: Good use of performance optimization and error tracking.
The addition of useCallback and logger utilities demonstrates good practices for:
- Optimizing performance through callback memoization
- Implementing proper error tracking
Also applies to: 19-19
233-233: LGTM: Clean integration with delete confirmation flow.
The ConfirmationModal correctly uses the new callback function.
Line range hint 1-245: Verify impact on message loading performance.
While the code changes improve organization and error handling, let's verify their relationship to the PR's main objective of fixing client freezing during message loading.
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/component.tsx (3)
67-104: Well-structured comparison logic for optimizing re-renders.
The comparison logic effectively uses getValueByPointer with type-safe constant arrays, providing a maintainable solution for deep prop comparison.
234-237: Properly memoized ref update callback.
The updateMessageRef callback is correctly memoized using useCallback, which helps prevent unnecessary re-renders.
Line range hint 1-364: Verify performance improvement with the new implementation.
The changes align well with the PR objectives by moving hook calls to the parent and optimizing re-renders. However, let's verify the impact on performance.
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/component.tsx (3)
31-40: LGTM: Clean import organization
The new imports are well-organized and follow a logical grouping:
- Core hooks for meeting and user data
- Feature flag hooks
- Mutation definitions
- Logger for error handling
211-220: LGTM: Well-structured feature flags
Good practice using feature flags to control chat functionality. The messageToolbarIsEnabled computation is clean and efficient.
465-477: 🛠️ Refactor suggestion
Consider grouping related props
The props passed to ChatListPage could be better organized for improved maintainability.
Group related props into logical objects:
+ const userProps = {
+ currentUserId: currentUser?.userId ?? '',
+ currentUserIsLocked: !!currentUser?.locked,
+ currentUserIsModerator: !!currentUser?.isModerator,
+ currentUserDisablePublicChat: !!currentUser?.userLockSettings?.disablePublicChat,
+ };
+ const meetingProps = {
+ meetingDisablePublicChat: !!meeting?.lockSettings?.disablePublicChat,
+ meetingDisablePrivateChat: !!meeting?.lockSettings?.disablePrivateChat,
+ };
+ const featureProps = {
+ messageToolbarIsEnabled,
+ chatDeleteEnabled: CHAT_DELETE_ENABLED,
+ chatEditEnabled: CHAT_EDIT_ENABLED,
+ chatReactionsEnabled: CHAT_REACTIONS_ENABLED,
+ chatReplyEnabled: CHAT_REPLY_ENABLED,
+ };
+ const reactionHandlers = {
+ deleteReaction,
+ sendReaction,
+ };
<ChatListPage
{...userProps}
{...meetingProps}
{...featureProps}
{...reactionHandlers}
// ... other props
/>Likely invalid or redundant comment.
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/component.tsx (2)
48-61: LGTM: Props interface changes align with PR objectives.
The new props effectively centralize chat feature management and user permissions in the parent component, which should help reduce unnecessary re-renders as intended.
Line range hint 1-584: Verify performance improvement in high-message scenarios.
The changes look good and should improve performance by reducing re-renders. However, let's verify the impact in the scenario described in the PR.
✅ Verification successful
The shell script results show that the child components (message-toolbar, message-replied, message-reactions, etc.) are properly memoized using React.FC and receive their props directly. The main ChatMessage component also implements proper memoization through React.forwardRef and the propsToCompare array.
Performance optimizations are properly implemented
The changes have successfully:
- Implemented proper memoization at all levels (parent and child components)
- Moved state management to parent components
- Added explicit prop comparison through propsToCompare array
- Used useCallback/useMemo hooks appropriately for expensive operations
The component should now avoid unnecessary re-renders in high-message scenarios since:
- Child components only re-render when their specific props change
- The parent component only re-renders when the essential props defined in propsToCompare change
- Event handlers are memoized with useCallback
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for potential performance bottlenecks in parent components
# that might still cause unnecessary re-renders
# Look for useState/useEffect hooks in parent components
ast-grep --pattern 'const [$_] = (useState|useEffect)($$$)'
# Look for potential prop drilling
rg -n "ChatMessage.*props" -A 3
Length of output: 15326
| const sendReaction = useCallback(( | ||
| reactionEmoji: string, | ||
| reactionEmojiId: string, | ||
| chatId: string, | ||
| messageId: string, | ||
| ) => { | ||
| chatSendReaction({ | ||
| variables: { | ||
| chatId, | ||
| messageId, | ||
| reactionEmoji, | ||
| reactionEmojiId, | ||
| }, | ||
| }).catch((e) => { | ||
| logger.error({ | ||
| logCode: 'chat_send_message_reaction_error', | ||
| extraInfo: { | ||
| errorName: e?.name, | ||
| errorMessage: e?.message, | ||
| }, | ||
| }, `Sending reaction failed: ${e?.message}`); | ||
| }); | ||
| }, [chatSendReaction]); |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Optimize reaction handlers with useCallback
Good use of useCallback for memoization. However, consider extracting the error handling logic to reduce duplication.
+ const handleReactionError = useCallback((error: Error, action: 'send' | 'delete') => {
+ logger.error({
+ logCode: `chat_${action}_message_reaction_error`,
+ extraInfo: {
+ errorName: error?.name,
+ errorMessage: error?.message,
+ },
+ }, `${action === 'send' ? 'Sending' : 'Deleting'} reaction failed: ${error?.message}`);
+ }, []);
const sendReaction = useCallback((
reactionEmoji: string,
reactionEmojiId: string,
chatId: string,
messageId: string,
) => {
chatSendReaction({
variables: {
chatId,
messageId,
reactionEmoji,
reactionEmojiId,
},
- }).catch((e) => {
- logger.error({...});
- });
+ }).catch((e) => handleReactionError(e, 'send'));
}, [chatSendReaction, handleReactionError]);Also applies to: 249-271
| const [chatSendReaction] = useMutation(CHAT_SEND_REACTION_MUTATION); | ||
| const [chatDeleteReaction] = useMutation(CHAT_DELETE_REACTION_MUTATION); | ||
|
|
||
| const sendReaction = useCallback(( | ||
| reactionEmoji: string, | ||
| reactionEmojiId: string, | ||
| chatId: string, | ||
| messageId: string, | ||
| ) => { | ||
| chatSendReaction({ | ||
| variables: { | ||
| chatId, | ||
| messageId, | ||
| reactionEmoji, | ||
| reactionEmojiId, | ||
| }, | ||
| }).catch((e) => { | ||
| logger.error({ | ||
| logCode: 'chat_send_message_reaction_error', | ||
| extraInfo: { | ||
| errorName: e?.name, | ||
| errorMessage: e?.message, | ||
| }, | ||
| }, `Sending reaction failed: ${e?.message}`); | ||
| }); | ||
| }, [chatSendReaction]); | ||
|
|
||
| const deleteReaction = useCallback(( | ||
| reactionEmoji: string, | ||
| reactionEmojiId: string, | ||
| chatId: string, | ||
| messageId: string, | ||
| ) => { | ||
| chatDeleteReaction({ | ||
| variables: { | ||
| chatId, | ||
| messageId, | ||
| reactionEmoji, | ||
| reactionEmojiId, | ||
| }, | ||
| }).catch((e) => { | ||
| logger.error({ | ||
| logCode: 'chat_delete_message_reaction_error', | ||
| extraInfo: { | ||
| errorName: e?.name, | ||
| errorMessage: e?.message, | ||
| }, | ||
| }, `Deleting reaction failed: ${e?.message}`); | ||
| }); | ||
| }, [chatDeleteReaction]); |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Enhance error handling in reaction mutations
The error handling is good but could be improved for better debugging and user feedback.
Consider these enhancements:
chatSendReaction({
variables: {
chatId,
messageId,
reactionEmoji,
reactionEmojiId,
},
+ onError: (error) => {
+ // Log the full error stack for debugging
+ logger.error({
+ logCode: 'chat_send_message_reaction_error',
+ extraInfo: {
+ errorName: error?.name,
+ errorMessage: error?.message,
+ errorStack: error?.stack,
+ },
+ }, `Sending reaction failed: ${error?.message}`);
+ // Optionally dispatch an event for UI feedback
+ window.dispatchEvent(new CustomEvent('reaction-error', {
+ detail: { error: error?.message },
+ }));
+ },
})Committable suggestion was skipped due to low confidence.
| const { data: meeting } = useMeeting((m) => ({ | ||
| lockSettings: m?.lockSettings, | ||
| })); | ||
| const { data: currentUser } = useCurrentUser((c) => ({ | ||
| isModerator: c?.isModerator, | ||
| userLockSettings: c?.userLockSettings, | ||
| locked: c?.locked, | ||
| userId: c?.userId, | ||
| })); |
There was a problem hiding this comment.
💡 Codebase verification
🛠️ Refactor suggestion
Based on the search results, I can now generate the final response:
Optional chaining is appropriately used, but default values could be improved
The codebase shows consistent use of optional chaining, and there are already some instances of nullish coalescing operator (??) being used. However, the current implementation could be improved for better type safety.
currentUser?.userId ?? ''is already using the recommended pattern- Other properties should follow the same pattern with appropriate default values based on their types:
const { data: meeting } = useMeeting((m) => ({ - lockSettings: m?.lockSettings, + lockSettings: m?.lockSettings ?? null, })); const { data: currentUser } = useCurrentUser((c) => ({ - isModerator: c?.isModerator, - userLockSettings: c?.userLockSettings, - locked: c?.locked, - userId: c?.userId, + isModerator: c?.isModerator ?? false, + userLockSettings: c?.userLockSettings ?? null, + locked: c?.locked ?? false, + userId: c?.userId ?? '', }));
🔗 Analysis chain
Verify null safety in user data access
While the hook usage is correct, there are potential null safety concerns when accessing nested properties.
Consider using the nullish coalescing operator consistently:
const { data: meeting } = useMeeting((m) => ({
- lockSettings: m?.lockSettings,
+ lockSettings: m?.lockSettings ?? null,
}));
const { data: currentUser } = useCurrentUser((c) => ({
- isModerator: c?.isModerator,
- userLockSettings: c?.userLockSettings,
- locked: c?.locked,
- userId: c?.userId,
+ isModerator: c?.isModerator ?? false,
+ userLockSettings: c?.userLockSettings ?? null,
+ locked: c?.locked ?? false,
+ userId: c?.userId ?? '',
}));🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for similar patterns of nested property access without null checks
rg -U "(\?\.)|(&&)" --type typescript
Length of output: 74
Script:
#!/bin/bash
# Search for similar patterns of nested property access without null checks in TypeScript files
rg -t ts -t tsx -U "(\?\.)|(&&)" ./bigbluebutton-html5/imports/ui/components/
# Also check the specific component's type definitions and usage
ast-grep --pattern 'interface $_ {
$$$
}' ./bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/component.tsx
# Look for useMeeting and useCurrentUser hook definitions
ast-grep --pattern 'const $_ = $_ => ({
$$$
})' ./bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/component.tsx
Length of output: 1973
Script:
#!/bin/bash
# Let's try a different approach to search for optional chaining patterns
find ./bigbluebutton-html5/imports/ui/components/chat/chat-graphql/ -type f -name "*.ts*" -exec grep -l "?." {} \;
# Look for the hook definitions and their return types
ast-grep --pattern 'export const use$_ = '
# Check how these properties are used later in the component
ast-grep --pattern 'const { data: $_ } = use$_($$$)' ./bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/component.tsx
# Look for any existing null checks or default values
ast-grep --pattern '$_ ?? $_' ./bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/component.tsx
Length of output: 18609
| own={message.user?.userId === currentUserId} | ||
| amIModerator={currentUserIsModerator} | ||
| message={message.message} | ||
| messageSequence={message.messageSequence} | ||
| emphasizedMessage={message.chatEmphasizedText} | ||
| onEmojiSelected={(emoji) => { | ||
| sendReaction(emoji.native, emoji.id); | ||
| setIsToolbarReactionPopoverOpen(false); | ||
| }} | ||
| onEmojiSelected={onEmojiSelected} | ||
| onReactionPopoverOpenChange={setIsToolbarReactionPopoverOpen} | ||
| reactionPopoverIsOpen={isToolbarReactionPopoverOpen} | ||
| chatDeleteEnabled={CHAT_DELETE_ENABLED} | ||
| chatEditEnabled={CHAT_EDIT_ENABLED} | ||
| chatReactionsEnabled={CHAT_REACTIONS_ENABLED} | ||
| chatReplyEnabled={CHAT_REPLY_ENABLED} | ||
| chatDeleteEnabled={chatDeleteEnabled} | ||
| chatEditEnabled={chatEditEnabled} | ||
| chatReactionsEnabled={chatReactionsEnabled} | ||
| chatReplyEnabled={chatReplyEnabled} |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Consider memoizing toolbar props object.
To prevent unnecessary re-renders of ChatMessageToolbar, consider extracting these props into a memoized object.
+ const toolbarProps = useMemo(() => ({
+ own: message.user?.userId === currentUserId,
+ amIModerator: currentUserIsModerator,
+ message: message.message,
+ messageSequence: message.messageSequence,
+ emphasizedMessage: message.chatEmphasizedText,
+ chatDeleteEnabled,
+ chatEditEnabled,
+ chatReactionsEnabled,
+ chatReplyEnabled,
+ }), [
+ message.user?.userId,
+ currentUserId,
+ currentUserIsModerator,
+ message.message,
+ message.messageSequence,
+ message.chatEmphasizedText,
+ chatDeleteEnabled,
+ chatEditEnabled,
+ chatReactionsEnabled,
+ chatReplyEnabled,
+ ]);
<ChatMessageToolbar
keyboardFocused={keyboardFocused}
hasToolbar={hasToolbar && messageContent.showToolbar}
locked={locked}
deleted={!!deleteTime}
messageId={message.messageId}
chatId={message.chatId}
username={message.user?.name}
- own={message.user?.userId === currentUserId}
- amIModerator={currentUserIsModerator}
- message={message.message}
- messageSequence={message.messageSequence}
- emphasizedMessage={message.chatEmphasizedText}
onEmojiSelected={onEmojiSelected}
onReactionPopoverOpenChange={setIsToolbarReactionPopoverOpen}
reactionPopoverIsOpen={isToolbarReactionPopoverOpen}
- chatDeleteEnabled={chatDeleteEnabled}
- chatEditEnabled={chatEditEnabled}
- chatReactionsEnabled={chatReactionsEnabled}
- chatReplyEnabled={chatReplyEnabled}
+ {...toolbarProps}
/>Committable suggestion was skipped due to low confidence.
| const propsToCompare = [ | ||
| 'meetingDisablePublicChat', | ||
| 'meetingDisablePrivateChat', | ||
| 'currentUserDisablePublicChat', | ||
| 'currentUserId', | ||
| 'currentUserIsLocked', | ||
| 'currentUserIsModerator', | ||
| 'chatDeleteEnabled', | ||
| 'chatEditEnabled', | ||
| 'chatReactionsEnabled', | ||
| 'chatReplyEnabled', | ||
| 'focused', | ||
| 'keyboardFocused', | ||
| 'message.createdAt', | ||
| 'message.message', | ||
| 'message.recipientHasSeen', | ||
| 'message.user.currentlyInMeeting', | ||
| 'message.reactions.length', | ||
| 'message.replyToMessage.message', | ||
| ] as const; |
There was a problem hiding this comment.
Update props comparison for complete memoization.
-
Missing props that could affect rendering:
message.editedAtmessage.deletedAtmessage.deletedBymessage.chatEmphasizedTextisPublicChathasToolbar
-
Remove redundant prop:
message.recipientHasSeenappears to be unused in the component
Apply this diff to update the comparison array:
const propsToCompare = [
'meetingDisablePublicChat',
'meetingDisablePrivateChat',
'currentUserDisablePublicChat',
'currentUserId',
'currentUserIsLocked',
'currentUserIsModerator',
'chatDeleteEnabled',
'chatEditEnabled',
'chatReactionsEnabled',
'chatReplyEnabled',
'focused',
'keyboardFocused',
'message.createdAt',
'message.message',
- 'message.recipientHasSeen',
'message.user.currentlyInMeeting',
'message.reactions.length',
'message.replyToMessage.message',
+ 'message.editedAt',
+ 'message.deletedAt',
+ 'message.deletedBy',
+ 'message.chatEmphasizedText',
+ 'isPublicChat',
+ 'hasToolbar',
] as const;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const propsToCompare = [ | |
| 'meetingDisablePublicChat', | |
| 'meetingDisablePrivateChat', | |
| 'currentUserDisablePublicChat', | |
| 'currentUserId', | |
| 'currentUserIsLocked', | |
| 'currentUserIsModerator', | |
| 'chatDeleteEnabled', | |
| 'chatEditEnabled', | |
| 'chatReactionsEnabled', | |
| 'chatReplyEnabled', | |
| 'focused', | |
| 'keyboardFocused', | |
| 'message.createdAt', | |
| 'message.message', | |
| 'message.recipientHasSeen', | |
| 'message.user.currentlyInMeeting', | |
| 'message.reactions.length', | |
| 'message.replyToMessage.message', | |
| ] as const; | |
| const propsToCompare = [ | |
| 'meetingDisablePublicChat', | |
| 'meetingDisablePrivateChat', | |
| 'currentUserDisablePublicChat', | |
| 'currentUserId', | |
| 'currentUserIsLocked', | |
| 'currentUserIsModerator', | |
| 'chatDeleteEnabled', | |
| 'chatEditEnabled', | |
| 'chatReactionsEnabled', | |
| 'chatReplyEnabled', | |
| 'focused', | |
| 'keyboardFocused', | |
| 'message.createdAt', | |
| 'message.message', | |
| 'message.user.currentlyInMeeting', | |
| 'message.reactions.length', | |
| 'message.replyToMessage.message', | |
| 'message.editedAt', | |
| 'message.deletedAt', | |
| 'message.deletedBy', | |
| 'message.chatEmphasizedText', | |
| 'isPublicChat', | |
| 'hasToolbar', | |
| ] as const; |
| }).catch((e) => { | ||
| logger.error({ | ||
| logCode: 'chat_edit_message_error', | ||
| extraInfo: { | ||
| errorName: e?.name, | ||
| errorMessage: e?.message, | ||
| }, | ||
| }, `Editing the message failed: ${e?.message}`); |
There was a problem hiding this comment.
Enhance error handling for message editing.
While the error logging is good, consider these improvements for better error handling:
- Update the UI error state to inform users when editing fails
- Add correlation data (chatId, messageId) to the error logs
- Consider retrying the operation for transient failures
Apply this diff to enhance the error handling:
}).catch((e) => {
logger.error({
logCode: 'chat_edit_message_error',
extraInfo: {
errorName: e?.name,
errorMessage: e?.message,
+ chatId: editingMessage.chatId,
+ messageId: editingMessage.messageId,
},
}, `Editing the message failed: ${e?.message}`);
+ setError(intl.formatMessage(messages.errorOnSendMessage));
+ setHasErrors(true);
});Committable suggestion was skipped due to low confidence.
Automated tests Summary✅ All the CI tests have passed! |





What does this PR do?
Load more messagesthe client freezes for a few seconds before rendering the new page. This was happening because the message component was overheaded with hook calls and data access which were triggering an additional render. In order to fix that, all those hook calls within the message component were placed in the parent component (more stable, doesn't rerender frequently) and passed as props to the message component.Closes Issue(s)
Closes #21434
How to test