Skip to content

fix(chat): Loading a new message page freezes the client - #21521

Merged
ramonlsouza merged 9 commits into
bigbluebutton:v3.0.x-releasefrom
JoVictorNunes:i-21434
Oct 29, 2024
Merged

ramonlsouza merged 9 commits into
bigbluebutton:v3.0.x-releasefrom
JoVictorNunes:i-21434

Conversation

@JoVictorNunes

@JoVictorNunes JoVictorNunes commented Oct 24, 2024 •

Copy link
Copy Markdown
Contributor

What does this PR do?

  • 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 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

  1. Start a session.
  2. Go to the chat.
  3. Type 100+ messages.
  4. Scroll up and click 'Load more messages'.

- 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.
@coderabbitai

coderabbitai Bot commented Oct 24, 2024 •

Copy link
Copy Markdown
Contributor

Walkthrough

The pull request introduces significant enhancements to the ChatMessageList, ChatMessage, and related components within the chat system. Key changes include the integration of new hooks, useMeeting and useCurrentUser, which manage meeting settings and user permissions. Feature flags are added to control the availability of functionalities such as replying, editing, deleting messages, and sending reactions. The ChatMessage component has been refactored to accept a wider array of props, centralizing chat feature management and removing reliance on internal hooks. The mutation functions for handling reactions are now passed as props, enhancing configurability. Additionally, the ChatMessageReactionsProps interface has been updated to include new parameters for handling reactions in the context of specific messages. A new utility function, getValueByPointer, is introduced to improve property comparison logic across chat components. Overall, these changes streamline chat functionality, making it more dynamic and context-aware, while enhancing the structure and maintainability of the code.

Possibly related PRs

Suggested reviewers

  • gustavotrott

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?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. Reduce the number of props being passed
  2. Make it easier to add new features
  3. Improve maintainability
  4. Make testing easier with context mocks

Also applies to: 254-267, 287-299, 342-355

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 67dac35 and b71ec19.

📒 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 getValueByPointer utility is being used appropriately and safely:

  • It's used within memoization comparison functions (areChatPagesEqual and areChatMessagesEqual)
  • 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.tsx

Length 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 chatId and messageId parameters 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:

  1. Use React DevTools to profile the component:

  2. 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:

  1. Locate the ChatMessage component implementation
  2. Find any hook usage within chat message related files
  3. 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 useMemo for complex message content calculations with proper dependencies
  • Implements useCallback for scroll event handlers
  • Employs useImperativeHandle for controlled focus management
  • Properly memoizes the component with memo and custom equality check
  • Event listeners are properly cleaned up in useEffect hooks

The 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:

  1. Message content changes
  2. Visibility/focus state changes
  3. 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 mutations

The imports for useMeeting, useCurrentUser, feature flags, and mutations are correctly added and seem appropriate for the enhancements introduced.

Comment on lines +108 to +110
deleteReaction(details.reactionEmoji, details.reactionEmojiId, chatId, messageId);
} else {
sendReaction(details.reactionEmoji, details.reactionEmojiId);
sendReaction(details.reactionEmoji, details.reactionEmojiId, chatId, messageId);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ 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.

Comment on lines +67 to +102
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;
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ 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:

  1. 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)
  );
};

Comment on lines +570 to +574
'message.recipientHasSeen',
'message.user.currentlyInMeeting',
'message.reactions.length',
'message.replyToMessage.message',
'message.recipientHasSeen',

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

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.

@antobinary antobinary added this to the Release 3.0 milestone Oct 24, 2024
@gustavotrott

Copy link
Copy Markdown
Contributor

does it close the issue #21434?

@JoVictorNunes

Copy link
Copy Markdown
Contributor Author

does it close the issue #21434?

Maybe. I'm not sure yet. Even though they are the same problem, #21434 happens in a different scenario. I'm doing some testing to see if this PR closes it.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. Rename disablePublicChat to isPublicChatDisabled for clarity
  2. 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

📥 Commits

Files that changed from the base of the PR and between b71ec19 and 314081c.

📒 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 getValueByPointer for 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 management

The implementation of useMeeting and useCurrentUser hooks effectively centralizes meeting and user data, improving the component's clarity and maintainability.

Comment on lines 452 to 455
onEmojiSelected={(emoji) => {
sendReaction(emoji.native, emoji.id);
sendReaction(emoji.native, emoji.id, message.chatId, message.messageId);
setIsToolbarReactionPopoverOpen(false);
}}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ 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.

Suggested change
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}

Comment on lines +224 to +244
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,
},
});
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ 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.

Suggested change
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
Arthurk12 self-requested a review October 25, 2024 13:31

@Arthurk12 Arthurk12 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

issue

@@ -202,6 +252,20 @@ const ChatListPage: React.FC<ChatListPageProps> = ({
ref={(ref) => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The callback I mentioned that triggers unnecessary re-renders.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice catch!

@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
C Reliability Rating on New Code (required ≥ A)

See analysis details on SonarCloud

Catch issues before they fail your Quality Gate with our IDE extension SonarLint

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. Loading state during deletion
  2. Success notification
  3. 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:

  1. Split into smaller components:
    • EmojiPicker component
    • MessageInput component
    • MessageForm component
  2. Consolidate state management
  3. 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:

  1. It's not properly cleaned up, which could cause memory leaks
  2. 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

📥 Commits

Files that changed from the base of the PR and between 314081c and 1b29c98.

📒 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:

  1. Core hooks for meeting and user data
  2. Feature flag hooks
  3. Mutation definitions
  4. 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:

  1. Implemented proper memoization at all levels (parent and child components)
  2. Moved state management to parent components
  3. Added explicit prop comparison through propsToCompare array
  4. 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

Comment on lines +225 to +247
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]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ 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

Comment on lines +222 to +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]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ 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.

Comment on lines +202 to +210
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,
}));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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

Comment on lines +454 to +465
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}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ 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.

Comment on lines +558 to +577
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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Update props comparison for complete memoization.

  1. Missing props that could affect rendering:

    • message.editedAt
    • message.deletedAt
    • message.deletedBy
    • message.chatEmphasizedText
    • isPublicChat
    • hasToolbar
  2. Remove redundant prop:

    • message.recipientHasSeen appears 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.

Suggested change
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;

Comment on lines +375 to +382
}).catch((e) => {
logger.error({
logCode: 'chat_edit_message_error',
extraInfo: {
errorName: e?.name,
errorMessage: e?.message,
},
}, `Editing the message failed: ${e?.message}`);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Enhance error handling for message editing.

While the error logging is good, consider these improvements for better error handling:

  1. Update the UI error state to inform users when editing fails
  2. Add correlation data (chatId, messageId) to the error logs
  3. 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.

@github-actions

Copy link
Copy Markdown

Automated tests Summary

✅ All the CI tests have passed!

@Arthurk12
Arthurk12 self-requested a review October 29, 2024 14:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Increasing loading time/client freeze when toggling chat panel

5 participants