Skip to content

fix(chat): a few adjustments and fixes - #21636

Merged
ramonlsouza merged 9 commits into
bigbluebutton:v3.0.x-releasefrom
JoVictorNunes:chat-fixes-1105
Nov 12, 2024
Merged

ramonlsouza merged 9 commits into
bigbluebutton:v3.0.x-releasefrom
JoVictorNunes:chat-fixes-1105

Conversation

@JoVictorNunes

Copy link
Copy Markdown
Contributor

What does this PR do?

This PR includes a few adjustments and fixes related to the new chat features (reply, edit, delete, reactions).

The most notable ones:

  • 0623457: Tweak message reactions rendering to prevent race conditions.
  • c56df95: Keeps the current message being edited highlighted.
  • d30addc: Automatically focus message input on edit.
  • e3b0fb3: Fixes a bug where the message list scrolling starts at the beginning of the list.
  • 9cb032f: Fixes a bug where the user cannot remove reactions from a private chat message.

Closes Issue(s)

n/a

@coderabbitai

coderabbitai Bot commented Nov 7, 2024 •

Copy link
Copy Markdown
Contributor

Walkthrough

The pull request introduces several enhancements to the chat functionality within the application, primarily focusing on the ChatMessageForm, ChatMessageList, and related components. Key modifications include the addition of message editing and replying capabilities in the ChatMessageForm, where new event listeners handle editing and canceling edits. The ChatMessageList component now features a start sentinel to indicate unread messages above the current scroll position, improving user awareness of message visibility.

Changes to the ChatMessage component include the addition of an editing property to manage rendering based on the editing state of messages. The ChatMessageReactions component has been refactored for improved readability and maintainability, while the ChatMessageReplied component now prevents click events from bubbling up. Additionally, the GraphQL queries have been updated to include new fields for private messages, enhancing the data returned. Overall, these changes aim to improve the user experience by providing more interactive and responsive chat functionalities.

Possibly related PRs

Suggested reviewers

  • ramonlsouza

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.

@sonarqubecloud

sonarqubecloud Bot commented Nov 7, 2024

Copy link
Copy Markdown

@JoVictorNunes JoVictorNunes changed the title Chat fixes 1105 fic(chat): a few adjustments and fixes Nov 7, 2024

@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 (10)
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/queries.ts (1)

Line range hint 112-112: LGTM! Consider caching strategy for read status.

The recipientHasSeen field is a good addition for tracking message read status.

Consider implementing:

  1. Client-side caching of read status to reduce server load
  2. Batch updates for read status to minimize network traffic
  3. Optimistic UI updates for better user experience
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-popup/component.tsx (2)

Line range hint 42-58: Fix potential memory leak and event listener inconsistencies.

There are several issues in the useEffect implementation:

  1. The cleanup function uses global removeEventListener instead of window
  2. Missing dependencies in the useEffect dependency array
  3. Potential memory leak if component unmounts during welcome message state changes

Apply this fix:

  useEffect(() => {
    const eventCallback = () => {
      if (welcomeMessage) {
        setShowWelcomeMessage(true);
        setWelcomeMsgsOnSession(WELCOME_MSG_KEY, true);
      }
      if (welcomeMsgForModerators) {
        setShowWelcomeMessageForModerators(true);
        setWelcomeMsgsOnSession(WELCOME_MSG_FOR_MODERATORS_KEY, true);
      }
    };
    window.addEventListener(ChatCommands.RESTORE_WELCOME_MESSAGES, eventCallback);

    return () => {
-     removeEventListener(ChatCommands.RESTORE_WELCOME_MESSAGES, eventCallback);
+     window.removeEventListener(ChatCommands.RESTORE_WELCOME_MESSAGES, eventCallback);
    };
-  }, []);
+  }, [welcomeMessage, welcomeMsgForModerators]);

Line range hint 89-108: Improve error handling and loading states.

The current implementation has several areas for improvement:

  1. Direct JSON stringification of errors isn't user-friendly
  2. Loading state could benefit from a loading indicator
  3. Consider adding an error boundary

Consider implementing these improvements:

import { ErrorBoundary } from 'react-error-boundary';
import LoadingSpinner from '../../../common/loading-spinner';

const ErrorFallback = ({ error }) => (
  <div role="alert">
    <p>Something went wrong:</p>
    <pre>{error.message}</pre>
  </div>
);

const ChatPopupContainer: React.FC = () => {
  // ... existing query code ...

  if (idChatOpen !== PUBLIC_GROUP_CHAT_KEY) return null;
  if (welcomeLoading) return <LoadingSpinner />;
  if (welcomeError) return <ErrorFallback error={welcomeError} />;
  if (!welcomeData) return null;

  return (
    <ErrorBoundary FallbackComponent={ErrorFallback}>
      <ChatPopup
        welcomeMessage={welcomeData.user_welcomeMsgs[0]?.welcomeMsg}
        welcomeMsgForModerators={welcomeData.user_welcomeMsgs[0]?.welcomeMsgForModerators}
      />
    </ErrorBoundary>
  );
};
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/message-reactions/component.tsx (3)

77-77: Consider using ISO strings for timestamp comparison.

Using new Date(createdAt).getTime() can be problematic if createdAt isn't in a consistent format.

Consider using ISO strings or a date parsing library like date-fns:

- leastRecent: new Date(createdAt).getTime(),
+ leastRecent: new Date(createdAt).toISOString(),

94-101: Optimize sorting performance.

The current implementation chains two sort operations which may impact performance with large reaction sets.

Consider combining the sorts into a single comparison function:

- Object.values(reactionItems).sort(sortByLeastRecent).sort(sortByCount)
+ Object.values(reactionItems).sort((a, b) => {
+   const countDiff = sortByCount(a, b);
+   return countDiff !== 0 ? countDiff : sortByLeastRecent(a, b);
+ })

Line range hint 115-136: Enhance accessibility for emoji reactions.

The emoji wrapper needs proper ARIA attributes for better screen reader support.

Add appropriate ARIA attributes:

  <Styled.EmojiWrapper
    highlighted={reactedByMe}
+   role="button"
+   aria-label={`${label}. Click to ${reactedByMe ? 'remove' : 'add'} reaction`}
+   aria-pressed={reactedByMe}
    onClick={() => {

Also, consider adding keyboard support:

    onClick={() => {
+   onKeyDown={(e) => {
+     if (e.key === 'Enter' || e.key === ' ') {
+       e.preventDefault();
        if (reactedByMe) {
          deleteReaction(reactionEmoji, reactionEmojiId, chatId, messageId);
        } else {
          sendReaction(reactionEmoji, reactionEmojiId, chatId, messageId);
        }
+     }
+   }}
+   tabIndex={0}
🧰 Tools
🪛 Biome

[error] 61-61: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)

bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/component.tsx (2)

465-470: Consider debouncing the scroll handler for better performance.

While the scroll logic is correct, scroll events can fire frequently and impact performance.

Consider using a debounced version of the scroll handler:

+ const debouncedSetShowStartSentinel = useCallback(
+   _.debounce((value: boolean) => setShowStartSentinel(value), 150),
+   []
+ );
+
  onScroll={(e) => {
    if (e.target instanceof HTMLDivElement) {
      const userScrolledUp = Math.ceil(e.target.scrollTop + e.target.clientHeight) < e.target.scrollHeight;
-     setShowStartSentinel(userScrolledUp);
+     debouncedSetShowStartSentinel(userScrolledUp);
    }
  }}

487-495: Consider enhancing keyboard navigation feedback.

While the keyboard navigation implementation is good, users might benefit from visual feedback when navigating through messages.

Consider adding visual focus indicators:

  role="listbox"
  ref={messageListRef}
  tabIndex={hasMessageToolbar ? 0 : -1}
  onKeyDown={rove}
+ className={selectedMessage ? 'keyboard-navigating' : ''}
  onBlur={() => {
    setSelectedMessage(null);
  }}

Then add appropriate CSS styles to highlight the selected message when using keyboard navigation.

bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/component.tsx (1)

577-577: LGTM! Props comparison update is correct.

Adding 'editing' to the comparison array ensures proper re-rendering when the editing state changes. This aligns with the PR's editing feature improvements.

Consider improving type safety by using a type-safe approach for the props comparison array:

-const propsToCompare = [
+const propsToCompare = <const>[
   'meetingDisablePublicChat',
   // ... other props
   'editing',
   // ... remaining props
-] as const;
+];

This provides the same type safety but is more idiomatic TypeScript, making the const assertion at the array creation rather than after.

bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-form/component.tsx (1)

310-310: Simplify code by removing redundant null check on textAreaRef.current

Since textAreaRef.current is already checked and confirmed to be not null in the preceding condition, you can remove the optional chaining operator when accessing textarea.focus(). This makes the code cleaner and slightly more efficient.

Apply this diff:

-            textAreaRef.current?.textarea.focus();
+            textAreaRef.current.textarea.focus();
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9ac70b5 and 9cb032f.

📒 Files selected for processing (10)
  • 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 (2 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/message-reactions/component.tsx (2 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/message-replied/component.tsx (1 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/styles.ts (1 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/queries.ts (1 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/styles.ts (0 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-popup/component.tsx (3 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-popup/styles.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/styles.ts
🧰 Additional context used
🪛 Biome
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/message-reactions/component.tsx

[error] 61-61: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)

🔇 Additional comments (10)
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-popup/styles.ts (1)

8-8: Verify z-index hierarchy across components.

The z-index increase from 3 to 20 looks intentional to ensure proper layering of chat popups. However, let's verify this doesn't create any stacking context conflicts with other UI components.

✅ Verification successful

Let me generate another script to search for z-index values more effectively:

The previous search had issues with file type recognition. This script uses multiple approaches to find z-index values across different file types to help us analyze the z-index hierarchy.


Based on the z-index analysis, I can now provide a final response:

The z-index value of 20 for chat popup is appropriate within the application's stacking context.

The z-index hierarchy shows that:

  • Most UI components use z-index values between 0-5
  • Navigation and dropdowns use values between 3-15
  • Modals and overlays use values between 998-1015
  • The chat popup's z-index of 20 places it above regular UI components but below modals/overlays

This ensures the chat popup will:

  • Appear above regular content and other UI elements
  • Not interfere with higher-priority elements like modals (z-index: 998+)
  • Maintain proper stacking with other chat components (z-index: 10-20)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Analyze z-index values across the codebase to ensure proper layering
# Expected: No components that should be above chat popups have lower z-index values

# Search for z-index declarations in styled-components and CSS files
echo "Analyzing z-index values in styled-components:"
rg "z-index:?\s*\d+" --type ts --type tsx -A 1 -B 1

echo -e "\nAnalyzing z-index values in CSS files:"
rg "z-index:?\s*\d+" --type css -A 1 -B 1

Length of output: 252411


Script:

#!/bin/bash
# Search for z-index values in TypeScript/JavaScript files
echo "Z-index values in TS/JS files:"
rg "z-index:?\s*\d+" --type ts --type js -A 1 -B 1

# Search for styled-components z-index declarations
echo -e "\nZ-index in styled-components:"
rg "z-index:?\s*\d+" --type ts --type js --glob "**/styles.*" -A 1 -B 1

# Search for z-index values in SCSS/CSS files
echo -e "\nZ-index values in SCSS/CSS files:"
rg "z-index:?\s*\d+" --type scss --type css -A 1 -B 1

Length of output: 46211

bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/message-replied/component.tsx (1)

32-32: LGTM! Verify parent click handler behavior.

The addition of e.stopPropagation() is a good fix to prevent click event bubbling, which could interfere with editing or reaction handling in parent components.

Let's verify if any parent components rely on click event bubbling:

✅ Verification successful

Event propagation is correctly handled across the chat components

The verification shows that parent components already implement e.stopPropagation() in their click handlers:

  • Message toolbar buttons (reply, reactions, edit, delete) all use stopPropagation()
  • The only parent click handler without stopPropagation() is for scroll behavior in the message list component, which is unrelated to message interactions

The added stopPropagation() in the replied message component aligns with the existing event handling pattern in the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for click handlers in parent components that might be affected
# by stopping event propagation

# Look for onClick handlers in parent components
rg -A 5 "onClick" ./bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/

Length of output: 7039

bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/queries.ts (1)

89-89: LGTM! Consistent reaction schema across message types.

The addition of reactionEmojiId to private chat messages aligns the reaction schema with public messages, which is essential for consistent reaction handling.

Let's verify the reaction schema consistency:

✅ Verification successful

Let me gather more specific information about the reaction handling in the chat components.


Based on the comprehensive results, I can now provide the final response:

Verified: Reaction handling is consistent between public and private messages

The addition of reactionEmojiId to private chat messages is correctly implemented and maintains consistency with public messages. The evidence shows:

  • The field is used consistently in both message types in the GraphQL queries
  • The reaction handling logic in message-reactions/component.tsx processes reactions uniformly
  • The mutations (chatSendMessageReaction and chatDeleteMessageReaction) handle both message types with identical parameters
  • The type definitions and interfaces are shared between public and private messages
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that reaction handling is consistent across the codebase
# Expected: All reaction-related code should handle both message types similarly

# Search for reaction-related code
rg -l 'reaction' --type ts --type tsx

# Look for any inconsistencies in reaction handling between public and private messages
ast-grep --pattern 'reaction' 

Length of output: 3664


Script:

#!/bin/bash
# Check the reaction handling implementation in chat components
rg -A 5 "reactionEmojiId" --type ts

# Check for any GraphQL fragments or types related to reactions
rg -A 5 "type.*Reaction" --type ts

# Look for message reaction component implementation
ast-grep --pattern 'interface MessageReaction {
  $$$
}'

Length of output: 23821

bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-popup/component.tsx (2)

11-14: LGTM! Clean interface definition.

The simplified ChatPopupProps interface follows the single responsibility principle by focusing only on welcome message functionality.


Line range hint 63-84: LGTM! Clean and well-structured JSX implementation.

The PopupContainer implementation is clear and maintains a good separation of concerns between regular and moderator welcome messages.

bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/styles.ts (1)

232-234: LGTM! Verify spacing with different message types.

The change from :first-child to :first-of-type is a good improvement as it makes the margin application more robust when different element types are present in the container.

Let's verify the impact on message spacing:

✅ Verification successful

The selector change is correct and safe

The change from :first-child to :first-of-type is appropriate for this context. The component structure shows that:

  • The Container only wraps ChatWrapper components
  • Each message type (text, poll, presentation, etc.) renders through the same ChatWrapper component
  • The margin spacing is consistently applied between messages regardless of their type
  • No other element types are rendered within the Container that could affect the spacing
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for different message types that might affect spacing
# Look for components rendered within the Container component

# Search for Container usage and its children
ast-grep --pattern 'const $_ = styled($_)`
  $$$
  &:not(:first-of-type) {
    $$$
  }
  $$$
`'

# Search for different message type components
rg -l "MessageType|MessageItem|SystemMessage|CustomMessage" --type ts

Length of output: 674


Script:

#!/bin/bash
# Let's examine the component structure and message types

# Check the message types enum
cat bigbluebutton-html5/imports/ui/core/enums/chat.ts

# Look at the chat message component implementation
cat bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/component.tsx

# Check if there are any other styled components in the same container
rg -A 5 "styled\." bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/styles.ts

Length of output: 22749

bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/component.tsx (2)

195-195: LGTM! Clean state management implementation.

The new state variable follows React best practices and clearly indicates its purpose.


Line range hint 476-486: LGTM! Excellent accessibility implementation.

The start sentinel implementation is clean and follows accessibility best practices with proper ARIA attributes and tab management.

bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/component.tsx (2)

Line range hint 1-594: Verify concurrent operations handling.

While the implementation looks solid, we should ensure proper handling of concurrent operations (editing messages while reactions are being added/removed) to prevent race conditions mentioned in the PR objectives.

Let's check for potential race conditions in the message update logic:

#!/bin/bash
# Search for message update handlers to verify concurrent operation handling
rg -g '*.{tsx,ts,js,jsx}' -A 5 'handleEdit|handleReaction|updateMessage'

# Search for any mutex or lock implementations that might be relevant
rg -g '*.{tsx,ts,js,jsx}' 'mutex|lock|concurrent|race'

180-183: LGTM! Scroll optimization looks good.

The condition properly prevents unnecessary scroll animations when the message is already visible in the viewport, falling back to just the background highlight animation. This should fix the scrolling issues mentioned in the PR objectives.

Let's verify the scroll behavior implementation across the codebase:

Comment on lines +60 to +90
const reactionItems = reactions.reduce((previousValue, reaction) => {
const newValue = { ...previousValue };
const {
createdAt,
reactionEmoji,
reactionEmojiId,
user,
} = reaction;

reactions.forEach((reaction) => {
if (!reactionItems[reaction.reactionEmojiId]) {
const reactedByMe = reaction.user.userId === currentUser?.userId;
reactionItems[reaction.reactionEmojiId] = {
if (!newValue[reactionEmojiId]) {
const reactedByMe = user.userId === currentUser?.userId;
newValue[reactionEmojiId] = {
count: 1,
userNames: reactedByMe ? [] : [reaction.user.name],
userNames: reactedByMe ? [] : [user.name],
reactedByMe,
reactionEmoji: reaction.reactionEmoji,
reactionEmojiId: reaction.reactionEmojiId,
leastRecent: new Date(reaction.createdAt).getTime(),
reactionEmoji,
reactionEmojiId,
leastRecent: new Date(createdAt).getTime(),
};
return;
return newValue;
}

reactionItems[reaction.reactionEmojiId].count += 1;
if (reaction.user.userId === currentUser?.userId) {
reactionItems[reaction.reactionEmojiId].reactedByMe = true;
newValue[reactionEmojiId].count += 1;
if (user.userId === currentUser?.userId) {
newValue[reactionEmojiId].reactedByMe = true;
} else {
reactionItems[reaction.reactionEmojiId].userNames.push(reaction.user.name);
newValue[reactionEmojiId].userNames.push(user.name);
}
});

return newValue;
}, {} as Record<string, ReactionItem>);

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

Optimize reducer implementation to avoid O(n²) complexity.

The current implementation uses spread operator on the accumulator which can lead to O(n²) time complexity as the reactions array grows.

Consider this more efficient approach:

- const reactionItems = reactions.reduce((previousValue, reaction) => {
-   const newValue = { ...previousValue };
+ const reactionItems = reactions.reduce((acc, reaction) => {
    const {
      createdAt,
      reactionEmoji,
      reactionEmojiId,
      user,
    } = reaction;

-   if (!newValue[reactionEmojiId]) {
+   if (!acc[reactionEmojiId]) {
      const reactedByMe = user.userId === currentUser?.userId;
-     newValue[reactionEmojiId] = {
+     acc[reactionEmojiId] = {
        count: 1,
        userNames: reactedByMe ? [] : [user.name],
        reactedByMe,
        reactionEmoji,
        reactionEmojiId,
        leastRecent: new Date(createdAt).getTime(),
      };
-     return newValue;
+     return acc;
    }

-   newValue[reactionEmojiId].count += 1;
+   acc[reactionEmojiId].count += 1;
    if (user.userId === currentUser?.userId) {
-     newValue[reactionEmojiId].reactedByMe = true;
+     acc[reactionEmojiId].reactedByMe = true;
    } else {
-     newValue[reactionEmojiId].userNames.push(user.name);
+     acc[reactionEmojiId].userNames.push(user.name);
    }

-   return newValue;
+   return acc;
  }, {} as Record<string, ReactionItem>);
📝 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 reactionItems = reactions.reduce((previousValue, reaction) => {
const newValue = { ...previousValue };
const {
createdAt,
reactionEmoji,
reactionEmojiId,
user,
} = reaction;
reactions.forEach((reaction) => {
if (!reactionItems[reaction.reactionEmojiId]) {
const reactedByMe = reaction.user.userId === currentUser?.userId;
reactionItems[reaction.reactionEmojiId] = {
if (!newValue[reactionEmojiId]) {
const reactedByMe = user.userId === currentUser?.userId;
newValue[reactionEmojiId] = {
count: 1,
userNames: reactedByMe ? [] : [reaction.user.name],
userNames: reactedByMe ? [] : [user.name],
reactedByMe,
reactionEmoji: reaction.reactionEmoji,
reactionEmojiId: reaction.reactionEmojiId,
leastRecent: new Date(reaction.createdAt).getTime(),
reactionEmoji,
reactionEmojiId,
leastRecent: new Date(createdAt).getTime(),
};
return;
return newValue;
}
reactionItems[reaction.reactionEmojiId].count += 1;
if (reaction.user.userId === currentUser?.userId) {
reactionItems[reaction.reactionEmojiId].reactedByMe = true;
newValue[reactionEmojiId].count += 1;
if (user.userId === currentUser?.userId) {
newValue[reactionEmojiId].reactedByMe = true;
} else {
reactionItems[reaction.reactionEmojiId].userNames.push(reaction.user.name);
newValue[reactionEmojiId].userNames.push(user.name);
}
});
return newValue;
}, {} as Record<string, ReactionItem>);
const reactionItems = reactions.reduce((acc, reaction) => {
const {
createdAt,
reactionEmoji,
reactionEmojiId,
user,
} = reaction;
if (!acc[reactionEmojiId]) {
const reactedByMe = user.userId === currentUser?.userId;
acc[reactionEmojiId] = {
count: 1,
userNames: reactedByMe ? [] : [user.name],
reactedByMe,
reactionEmoji,
reactionEmojiId,
leastRecent: new Date(createdAt).getTime(),
};
return acc;
}
acc[reactionEmojiId].count += 1;
if (user.userId === currentUser?.userId) {
acc[reactionEmojiId].reactedByMe = true;
} else {
acc[reactionEmojiId].userNames.push(user.name);
}
return acc;
}, {} as Record<string, ReactionItem>);
🧰 Tools
🪛 Biome

[error] 61-61: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)

Comment on lines +488 to +489
role="listbox"
ref={messageListRef}

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

ARIA listbox implementation needs correction

The current implementation has the following issues:

  • The parent element uses role="listbox" but child elements (ChatListPage components) don't implement the required role="option"
  • According to ARIA patterns, listbox items must be direct descendants of the listbox container
  • The current keyboard navigation implementation suggests this should be using a different ARIA pattern, likely role="list" with role="listitem" for messages

Locations needing attention:

  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/component.tsx: Change role="listbox" to role="list"
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/component.tsx: Add appropriate role="listitem" to message containers
🔗 Analysis chain

Verify ARIA listbox implementation.

The role="listbox" implies that the children should have role="option". Let's verify this implementation across child components.


Let me check the specific roles being used in the chat message components to better understand the ARIA implementation.


Let me check the actual message item components to see their structure and any role assignments.


Let me check the actual implementation of the chat message list to understand how messages are rendered.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if child components implement role="option"
# Expected: Each ChatListPage or its message items should have role="option"

# Search for role assignments in related components
rg -l 'role=' --glob 'bigbluebutton-html5/imports/ui/components/chat/**'

# Search specifically for option role in chat components
ast-grep --pattern 'role="option"' --lang tsx

Length of output: 524


Script:

#!/bin/bash
# Let's examine the actual roles used in the chat message components
rg 'role=' -A 2 bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/component.tsx

# Also check the structure of message items
ast-grep --pattern 'const ChatMessage = ($_) => {
  $$$
}' --lang tsx

Length of output: 295


Script:

#!/bin/bash
# Check the chat message component files and their role assignments
fd 'chat-message' bigbluebutton-html5/imports/ui/components/chat/ --exec rg -l 'role='

# Get content of the main message component to understand its structure
fd 'chat-message.tsx' bigbluebutton-html5/imports/ui/components/chat/ --exec cat {}

Length of output: 514


Script:

#!/bin/bash
# Check the structure of the chat message list component
cat bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/component.tsx

# Also check if there are any other ARIA-related attributes in message components
rg 'aria-' --glob 'bigbluebutton-html5/imports/ui/components/chat/**/*.tsx'

Length of output: 21344

@github-actions

github-actions Bot commented Nov 7, 2024

Copy link
Copy Markdown

Automated tests Summary

✅ All the CI tests have passed!

@antobinary antobinary added this to the Release 3.0 milestone Nov 7, 2024
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.

4 participants