Skip to content

feat(chat): Add ability to edit and delete messages - #21355

Merged
ramonlsouza merged 12 commits into
bigbluebutton:v3.0.x-releasefrom
JoVictorNunes:chat-message-edit-and-delete
Oct 14, 2024
Merged

ramonlsouza merged 12 commits into
bigbluebutton:v3.0.x-releasefrom
JoVictorNunes:chat-message-edit-and-delete

Conversation

@JoVictorNunes

Copy link
Copy Markdown
Contributor

What does this PR do?

Add UI support for deleting and editing chat messages.

Screencast.from.2024-10-03.18-32-27.mp4

Closes Issue(s)

n/a

More

Built on top of #21335, so I'll open this PR as draft.

@coderabbitai

coderabbitai Bot commented Oct 3, 2024 •

Copy link
Copy Markdown
Contributor

Walkthrough

The pull request introduces several enhancements to the chat functionality within the BigBlueButton HTML5 application. Key changes include the addition of a new toolbar property in the Chat interface and multiple new properties in the Message interface, which enable features such as message replies, editing, and deletion. The ChatMessageForm component is updated to support replying to messages, while new components for message reactions and toolbars are introduced. Additionally, GraphQL mutations for sending, editing, and deleting messages are defined, and the configuration settings for the chat interface are altered to improve user experience. The backend logic for editing messages is also modified to allow editing when previously disabled.

Possibly related PRs


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

🧹 Outside diff range and nitpick comments (46)
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-form/mutations.tsx (1)

5-10: LGTM! Consider a minor naming improvement.

The changes to the ChatSendMessage mutation look good and align with the PR objective of adding editing and deleting functionality for chat messages. The new optional replyToMessageId parameter allows for replying to specific messages while maintaining backward compatibility.

Consider renaming replyToMessageId to parentMessageId for consistency with common naming conventions in threaded conversations. This might make the code more intuitive for developers familiar with chat systems.

- mutation ChatSendMessage($chatId: String!, $chatMessageInMarkdownFormat: String!, $replyToMessageId: String) {
+ mutation ChatSendMessage($chatId: String!, $chatMessageInMarkdownFormat: String!, $parentMessageId: String) {
    chatSendMessage(
      chatId: $chatId,
      chatMessageInMarkdownFormat: $chatMessageInMarkdownFormat,
-     replyToMessageId: $replyToMessageId
+     parentMessageId: $parentMessageId
    )
  }
bigbluebutton-html5/imports/ui/core/enums/chat.ts (1)

4-4: LGTM: New constant for chat reply intention.

The addition of CHAT_REPLY_INTENTION is appropriate and enhances chat functionality. The naming is clear and follows the existing convention.

Consider adding a brief comment explaining the purpose of this constant, as it's not explicitly mentioned in the PR objectives.

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

3-7: LGTM: Well-structured edit message mutation

The CHAT_EDIT_MESSAGE_MUTATION is well-defined with clear parameter names and appropriate use of non-nullable fields. The mutation name 'chatEditMessage' is descriptive and follows the naming convention.

For consistency, consider using multi-line formatting for the mutation parameters:

mutation(
  $chatId: String!,
  $messageId: String!,
  $chatMessageInMarkdownFormat: String!
) {
  chatEditMessage(
    chatId: $chatId,
    messageId: $messageId,
    chatMessageInMarkdownFormat: $chatMessageInMarkdownFormat
  )
}

This improves readability, especially if more parameters are added in the future.


9-13: LGTM: Well-structured delete message mutation

The CHAT_DELETE_MESSAGE_MUTATION is well-defined with clear parameter names and appropriate use of non-nullable fields. The mutation name 'chatDeleteMessage' is descriptive and follows the naming convention.

For consistency with the previous suggestion and improved readability, consider using multi-line formatting for the mutation parameters:

mutation(
  $chatId: String!,
  $messageId: String!
) {
  chatDeleteMessage(
    chatId: $chatId,
    messageId: $messageId
  )
}
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/message-content/text-content/component.tsx (2)

15-15: LGTM: Default value for dataTest prop is appropriate

The addition of a default value 'messageContent' for the dataTest prop is a good practice. It ensures that there's always a data-test attribute available for testing, even when not explicitly provided.

Consider using a constant for the default value to improve maintainability:

const DEFAULT_DATA_TEST = 'messageContent';

// In the component props
dataTest = DEFAULT_DATA_TEST,

This makes it easier to update the default value across the component if needed in the future.


20-20: LGTM: Proper implementation of dataTest prop in data-test attribute

The update to use the dataTest prop in the data-test attribute is correct and consistent with the earlier changes. This implementation allows for more flexible and specific testing.

Consider handling the case where dataTest might be null:

data-test={dataTest || undefined}

This ensures that when dataTest is null, no data-test attribute is rendered at all, which might be preferable in some testing scenarios.

bigbluebutton-html5/imports/ui/Types/message.ts (3)

8-12: LGTM! Consider using a Date type for timestamps.

The new properties editedAt, deletedAt, and deletedBy are well-structured and support the PR objective of adding editing and deleting functionality. Good job on using nullable types to handle cases where these actions haven't occurred.

Consider using a Date type instead of string for editedAt and deletedAt. This would provide stronger type checking and easier date manipulation:

editedAt: Date | null;
deletedAt: Date | null;

This change would require adjusting how these properties are set and read throughout the application, but it could lead to more robust date handling.


23-23: LGTM! Consider adding a comment for clarity.

The messageSequence property is a good addition for maintaining message order.

Consider adding a brief comment to explain the purpose of this property:

/** Represents the sequential order of the message in the conversation */
messageSequence: number;

This would help other developers understand the property's significance at a glance.


24-37: LGTM! Consider improving type consistency and reusability.

The replyToMessage property is a great addition to support reply functionality. Its structure allows for comprehensive tracking of replied messages, including edit and delete information.

Consider the following improvements for better type consistency and reusability:

  1. Create a separate interface for the reply message to improve reusability and maintain DRY principles:
interface ReplyMessage {
  editedAt: string | null;
  deletedAt: string | null;
  deletedBy: {
    name: string;
  } | null;
  messageSequence: number;
  message: string;
  chatEmphasizedText: boolean;
  user: {
    name: string;
    color: string;
  };
}

// Then in the Message interface:
replyToMessage: ReplyMessage | null;
  1. For consistency, consider using the same User type for the user property in ReplyMessage as used in the main Message interface:
import { User } from './user';

interface ReplyMessage {
  // ... other properties
  user: User;
}

These changes would improve code organization, reusability, and type consistency across the application.

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

4-22: LGTM: Well-structured styled component with a minor suggestion.

The EmojiWrapper component is well-implemented, utilizing the imported color constants and a boolean prop for highlighting. The hover effect enhances user interaction, which is great.

Consider using relative units (e.g., em or rem) instead of pixel values for border-radius, margin, and padding to improve responsiveness across different screen sizes:

 const EmojiWrapper = styled.div<{ highlighted: boolean }>`
   background-color: ${colorBlueLightest};
-  border-radius: 10px;
-  margin-left: 3px;
-  margin-top: 3px;
-  padding: 3px;
+  border-radius: 0.625rem;
+  margin-left: 0.1875rem;
+  margin-top: 0.1875rem;
+  padding: 0.1875rem;
   display: flex;
   flex-wrap: nowrap;
   border: 1px solid transparent;
   cursor: pointer;

   ${({ highlighted }) => highlighted && `
     background-color: ${colorBlueLighter};
   `}

   &:hover {
     border: 1px solid ${colorGray};
   }
 `;
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/message-reactions/component.tsx (1)

1-33: Overall, good implementation with room for minor improvements.

The ChatMessageReactions component is well-structured and typed. The main areas for improvement are in the rendering logic, particularly adding keys to mapped elements and fixing the emoji prop usage. These changes will enhance the component's correctness and maintainability.

Would you like assistance in implementing these changes or clarification on any of the suggested improvements?

🧰 Tools
🪛 Biome

[error] 18-18: Missing key property for this element in iterable.

The order of the items may change, and having a key can help React identify which item was moved.
Check the React documentation.

(lint/correctness/useJsxKeyInIterable)

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

6-10: Consider using a variable for the padding value.

The Actions component looks good overall. However, the hardcoded padding value (8px) might be inconsistent with other parts of the application. Consider using a variable from your styling utilities for better maintainability and consistency.

You could refactor it like this:

- padding-top: 8px;
+ padding-top: ${someSpacingVariable};

Make sure to import the appropriate spacing variable from your styling utilities.


12-16: LGTM: Good use of conditional styling. Consider using a variable for the margin value.

The Section component effectively uses a boolean prop for conditional styling, which is a good practice. The use of rem units for the margin is also commendable for accessibility and responsiveness.

However, consider using a variable for the margin value (2.6rem) to maintain consistency across the application.

You could refactor it like this:

- margin-left: 2.6rem;
+ margin-left: ${someMarginVariable};

Make sure to import the appropriate margin variable from your styling utilities.

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

1-45: Great job on the overall structure and organization of the styled components!

The file effectively uses TypeScript and styled-components to create a cohesive styling system for chat messages. The components are well-organized and follow a consistent pattern.

For improved consistency, consider the following suggestion:

Consider using the styled import consistently. For example, change export const DeleteMessage = styled.span to match the pattern used for other components:

const DeleteMessage = styled.span`
  // ... existing styles ...
`;

export default {
  Container,
  Username,
  Message,
  DeleteMessage,
};

This change would make all component declarations consistent throughout the file.

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

43-47: LGTM with suggestion: Conditional rendering of chat time

The conditional rendering of the chat time based on deleteTime is implemented correctly. It ensures that the time is not displayed for deleted messages, which aligns with the PR objective.

Consider enhancing the user experience by displaying the deletion time for deleted messages instead of hiding the time completely. This could provide users with more context about when a message was deleted. Here's a suggested implementation:

- {!deleteTime && (
+ {deleteTime ? (
+   <Styled.ChatTime>
+     Deleted at: <FormattedTime value={deleteTime} />
+   </Styled.ChatTime>
+ ) : (
  <Styled.ChatTime>
    <FormattedTime value={dateTime} />
  </Styled.ChatTime>
- )}
+ )}

This change would display "Deleted at: [time]" for deleted messages, providing more information to users.

bigbluebutton-html5/imports/ui/services/storage/hooks.ts (1)

56-56: LGTM! Consider using object shorthand notation.

The export of the STORAGES constant is a good addition, making it accessible to other modules. This change aligns well with the PR objective of adding UI support for editing and deleting chat messages.

For consistency and to follow modern JavaScript conventions, consider using object shorthand notation in the default export. You can apply this minor change:

export default {
  useStorageKey,
- STORAGES,
+ STORAGES
};

Also applies to: 61-61

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

15-22: LGTM: Well-defined interface with a minor suggestion.

The MessageRepliedProps interface is well-structured and includes all necessary props for the component. The use of TypeScript for prop typing is a good practice.

Consider adding JSDoc comments to describe the purpose of each prop, especially for less obvious ones like sequence and emphasizedMessage. This would improve code documentation and maintainability.

Example:

interface MessageRepliedProps {
  /** The username of the message sender */
  username: string;
  /** The content of the message */
  message: string;
  /** The sequence number of the message */
  sequence: number;
  /** The color associated with the user */
  userColor: string;
  /** Whether the message should be visually emphasized */
  emphasizedMessage: boolean;
  /** The username of the user who deleted the message, or null if not deleted */
  deletedByUser: string | null;
}

31-63: LGTM with suggestions: Well-structured render logic with room for improvement.

The component's render logic is well-implemented, handling both regular and deleted messages appropriately. The use of custom events for focus management is a good approach for component communication.

Consider the following improvements:

  1. Extract the click handler logic into a separate function to improve readability:
const handleClick = () => {
  window.dispatchEvent(
    new CustomEvent(ChatEvents.CHAT_FOCUS_MESSAGE_REQUEST, {
      detail: { sequence },
    })
  );
  Storage.removeItem(ChatEvents.CHAT_FOCUS_MESSAGE_REQUEST);
  Storage.setItem(ChatEvents.CHAT_FOCUS_MESSAGE_REQUEST, sequence);
};
  1. Consider extracting the focus management logic into a custom hook or utility function to improve separation of concerns:
const useFocusManagement = (sequence) => {
  return () => {
    // ... focus management logic
  };
};

// In the component
const handleFocus = useFocusManagement(sequence);
  1. Use React's useCallback hook to memoize the click handler function to optimize performance, especially if this component is rendered frequently:
const handleClick = useCallback(() => {
  // ... click handler logic
}, [sequence]);

These changes would improve the component's maintainability and potentially its performance.

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

11-39: Container styled component looks good, but consider reviewing the z-index.

The Container component is well-structured with appropriate styling and dynamic positioning based on the $sequence prop. The hover effect is implemented correctly. However, the z-index value of 2 might be too low, potentially causing layering issues with other elements.

Consider reviewing and possibly increasing the z-index value to ensure the container appears above other elements when visible:

-  z-index: 2;
+  z-index: 10; // or a higher value that fits your layering strategy

41-68: EmojiPickerWrapper styled component looks good, but consider reviewing the use of !important.

The EmojiPickerWrapper component is well-structured with appropriate styling for positioning and appearance. The z-index of 1000 ensures it appears above other elements.

However, the use of !important in some CSS rules (lines 51, 59, 64, 65) might indicate specificity issues. Consider refactoring these styles to avoid using !important if possible, as it can make styles harder to maintain and override:

-    max-width: 100% !important;
+    max-width: 100%;

-    cursor: pointer !important;
+    cursor: pointer;

-      cursor: pointer !important;
-      display: inline-block !important;
+      cursor: pointer;
+      display: inline-block;

If !important is necessary due to conflicting styles from a third-party library, consider adding a comment explaining why it's needed.


86-88: EmojiPicker styled component is simple and correct.

The EmojiPicker component correctly sets the position to relative, likely to create a new stacking context.

Consider if any additional styling is needed for the EmojiPicker. If not, you might want to add a comment explaining why only the position is set:

const EmojiPicker = styled(EmojiPickerComponent)`
  position: relative; // Creates a new stacking context for child elements
  // Add any additional styles specific to this implementation if needed
`;
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/component.tsx (1)

Line range hint 47-54: LGTM with a minor suggestion for improvement

The ChatLoading component is well-implemented and consistent with the main Chat component. It effectively uses the CircularProgress to indicate the loading state.

However, consider moving the inline style to a styled component or a separate CSS file for better maintainability:

const StyledCircularProgress = styled(CircularProgress)({
  alignSelf: 'center',
});

export const ChatLoading: React.FC<ChatProps> = ({ isRTL }) => {
  const { isChrome } = browserInfo;
  return (
    <Styled.Chat isRTL={isRTL} isChrome={isChrome}>
      <StyledCircularProgress />
    </Styled.Chat>
  );
};

This change would keep your styling consistent with the rest of the component and improve maintainability.

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

29-29: LGTM: New $highlight property added to ChatWrapperProps.

The addition of the $highlight boolean property to the ChatWrapperProps interface is appropriate for implementing conditional styling based on a highlight state.

Consider adding a brief comment explaining the purpose of the $highlight property for better code documentation.


35-35: LGTM: New $highlight property added to ChatContentProps.

The addition of the $highlight boolean property to the ChatContentProps interface is consistent with the change in ChatWrapperProps and will allow for highlight-based styling in the content component.

Consider adding a brief comment explaining the purpose of the $highlight property for better code documentation, similar to the suggestion for ChatWrapperProps.


82-87: LGTM: Conditional hover styling added to ChatWrapper.

The new conditional styling for the hover state when !sameSender && $highlight is a good addition. It enhances the visual feedback for highlighted messages and follows styled-components best practices.

Consider extracting the colorOffWhite value to a constant at the top of the file for easier maintenance and consistency. For example:

const HIGHLIGHT_BACKGROUND_COLOR = colorOffWhite;

Then use this constant in the styled component:

background-color: ${HIGHLIGHT_BACKGROUND_COLOR};

100-105: LGTM: Conditional hover styling added to ChatContent.

The new conditional styling for the hover state when sameSender && $highlight is consistent with the earlier modification to ChatWrapper. It appropriately handles highlight functionality for messages from the same sender.

Similar to the suggestion for ChatWrapper, consider using a constant for the colorOffWhite value:

const HIGHLIGHT_BACKGROUND_COLOR = colorOffWhite;

Then use this constant in the styled component:

background-color: ${HIGHLIGHT_BACKGROUND_COLOR};

This will ensure consistency across both ChatWrapper and ChatContent components.


198-223: LGTM: New styled components added for enhanced chat functionality.

The addition of Container, DeleteMessage, and ChatEditTime components aligns well with the PR objective of adding edit and delete functionality to chat messages. These components provide the necessary styling for the new features.

Consider the following minor improvements:

  1. For Container, add a comment explaining its purpose in the chat message structure.

  2. For DeleteMessage, consider using a semantic HTML element like <del> instead of <span> to improve accessibility:

export const DeleteMessage = styled.del`
  // ... existing styles
`;
  1. For ChatEditTime, consider adding aria-label to improve accessibility:
export const ChatEditTime = styled.time.attrs({
  'aria-label': 'Message edit time',
})`
  // ... existing styles
`;

These suggestions will enhance the semantic meaning and accessibility of the new components.

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

Line range hint 66-84: Remove unnecessary key prop from React.Fragment

The change from a <div> to a <React.Fragment> is a good optimization that reduces DOM depth. However, the key prop on the React.Fragment is unnecessary in this context, as it's not part of a list of sibling elements.

Consider removing the key prop:

- <React.Fragment key={`messagePage-${page}`}>
+ <React.Fragment>

Also, ensure that this change doesn't break any existing CSS styles that might have been targeting the previous div element.


Line range hint 1-1: Consider addressing TypeScript ignore comments

There's a TypeScript ignore comment at the top of the file. While sometimes necessary, these comments can hide potential type-related issues.

If possible, consider addressing the underlying type issues that necessitate these ignore comments. This could involve:

  1. Updating type definitions
  2. Using more specific types
  3. Refactoring code to align with TypeScript's type system

If the ignore comments are absolutely necessary, add explanatory comments detailing why they're needed and any plans to address them in the future.

bigbluebutton-html5/imports/ui/Types/meetingClientSettings.ts (1)

529-529: LGTM! Consider adding a comment for clarity.

The addition of the toolbar property as a string array is a good approach for defining available actions in the chat interface, which aligns with the PR objective of adding edit and delete capabilities for chat messages.

Consider adding a brief comment to explain the purpose of the toolbar property and provide examples of possible values. This would enhance code readability and make it easier for other developers to understand and use this property correctly. For example:

  /** 
   * Defines the available actions in the chat toolbar.
   * Possible values: 'edit', 'delete', etc.
   */
  toolbar: string[]
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-form/component.tsx (2)

286-299: LGTM: Event listener for chat reply intentions

The implementation of the chat reply feature using an effect hook is well-done. It correctly sets up and cleans up the event listener, and the logic is concise and effective.

Consider adding a null check before focusing the text area to prevent potential errors:

- textAreaRef.current?.textarea.focus();
+ textAreaRef.current?.textarea?.focus();

This change adds an additional null check for the textarea property, making the code more robust.


Line range hint 1-624: Overall: Well-implemented reply feature

The changes to implement the reply feature in the chat component are well-done. The new functionality is seamlessly integrated into the existing code, following React best practices and maintaining consistency with the current coding style.

Key points:

  1. Proper state management for the replied message ID.
  2. Effective use of event listeners for handling reply intentions.
  3. Correct integration with the existing GraphQL mutation for sending messages.

The implementation appears robust and shouldn't introduce any significant bugs or performance issues. However, ensure thorough testing of the new feature, especially around edge cases like replying to deleted messages or handling long chains of replies.

Consider adding some comments to explain the logic behind the reply feature, particularly for future maintainers who might not be familiar with the entire codebase.

bigbluebutton-html5/imports/ui/core/initial-values/meetingClientSettings.ts (1)

572-572: Consider additional steps for complete feature implementation.

While adding the toolbar property is a good start, implementing the ability to edit and delete messages likely requires more changes. Consider the following suggestions:

  1. Ensure that appropriate permission checks are implemented for editing and deleting messages.
  2. Update the chat object to include properties for tracking edited messages and deletion status.
  3. Consider adding configuration options for enabling/disabling message editing and deletion.
  4. Update relevant documentation to reflect these new chat features.

Would you like assistance in drafting these additional changes or creating GitHub issues to track these tasks?

bigbluebutton-html5/private/config/settings.yml (1)

771-773: Approve new chat toolbar configuration

The addition of the toolbar option in the chat section is a good implementation for configuring message editing and deleting capabilities. The empty array allows for easy customization of available toolbar options.

Consider setting default values for the toolbar to enable the new features immediately. For example:

    # available options for toolbar: reply, edit, delete
    # example: ['reply', 'delete']
-   toolbar: []
+   toolbar: ['reply', 'edit', 'delete']

This would enable all available options by default, allowing users to immediately benefit from the new features while still providing the flexibility to customize the toolbar as needed.

bigbluebutton-html5/imports/ui/hooks/useStickyScroll.ts (1)

45-49: Ensure timely unobserving in stopObserving

The stopObserving function uses a timeout to delay the unobserving of onResizeOf by 500ms. Verify that this delay is appropriate and does not cause any side effects. If immediate unobserving is acceptable, consider removing the timeout to simplify the logic.

Optionally, you can remove the timeout:

handlers.current.stopObserving = useCallback(() => {
  if (!onResizeOf) return;
- timeout.current = setTimeout(() => {
    observer.unobserve(onResizeOf);
- }, 500);
}, [onResizeOf]);
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-reply-intention/component.tsx (1)

62-65: Reset All Related State Variables on Close

In the close button's onClick handler, you reset message and username to undefined. For consistency and to prevent residual state issues, consider resetting all related state variables, including sequence and emphasizedMessage.

Apply this change to reset all state variables:

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

49-60: Include error in the dependency array of useEffect

The useEffect hook depends on both chatEditMessageError and error. Omitting error from the dependency array might lead to missed updates when error changes. Ensure all dependencies are included for accurate effect execution.

Apply this diff:

-}, [chatEditMessageError]);
+}, [chatEditMessageError, error]);

110-119: Use e.key instead of e.code for key detection

Using e.key is more reliable for detecting key presses across different browsers and user settings. It represents the actual value of the key pressed, accounting for modifier keys and user keyboard layout.

Apply this diff:

- if (e.code === 'Enter' && !e.shiftKey) {
+ if (e.key === 'Enter' && !e.shiftKey) {

152-153: Correct the event type in the onClick handler

The onClick handler for the Save button specifies the event type as React.MouseEvent<HTMLInputElement, MouseEvent>, but the button is a Button component, not an input element. Update the event type to match the correct element.

Apply this diff:

- onClick={(e: React.MouseEvent<HTMLInputElement, MouseEvent>) => e.stopPropagation()}
+ onClick={(e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => e.stopPropagation()}

126-136: Avoid inline styles for better maintainability

Using inline styles can make the component harder to maintain and override. Consider moving these styles to a styled component or a CSS class for better scalability and readability.

Apply this diff:

- style={{
-   width: '100%',
-   minWidth: 0,
- }}
+ className="edit-message-input"

Then, in your styles file (./styles), add:

.edit-message-input {
  width: 100%;
  min-width: 0;
}

62-70: Simplify message handling logic

In handleMessageChange, you can streamline the assignment of newMessage by using a ternary operator, improving code readability.

Apply this diff:

-let newMessage = null;
-if (AUTO_CONVERT_EMOJI) {
-  newMessage = checkText(e.target.value);
-} else {
-  newMessage = e.target.value;
-}
+const newMessage = AUTO_CONVERT_EMOJI ? checkText(e.target.value) : e.target.value;
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/message-toolbar/component.tsx (1)

215-215: Consider using a named export for consistency

Currently, the component is exported as a default export. Using a named export can enhance consistency and clarity, especially in larger codebases.

Apply this diff:

-export default ChatMessageToolbar;
+export { ChatMessageToolbar };
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/component.tsx (1)

164-178: Specify the correct event type in the handler function

In the useEffect hook starting at line 164, the handler function accepts an event parameter typed as Event, but you are checking if it's an instance of CustomEvent. For better type safety and readability, consider typing the e parameter directly as CustomEvent.

Apply this diff to adjust the event type:

-    const handler = (e: Event) => {
+    const handler = (e: CustomEvent) => {
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/component.tsx (3)

146-154: Optimize Animation Functions and Dependencies

Ensure that the startScrollAnimation and animate functions handle their dependencies correctly. Currently, animate is defined with an empty dependency array, but it uses containerRef and animationInitialTimestamp.

While refs do not need to be in the dependency array, consider adding comments to clarify this and ensure future maintainability.

Also applies to: 177-186


Line range hint 295-296: Avoid Parsing Message Metadata Without Checks

In currentPluginMessageMetadata = message.messageType === ChatMessageType.PLUGIN && JSON.parse(message.messageMetadata);, ensure that message.messageMetadata is a valid JSON string before parsing to prevent errors.

Add a try-catch block or validation:

-let currentPluginMessageMetadata = message.messageType === ChatMessageType.PLUGIN && JSON.parse(message.messageMetadata);
+let currentPluginMessageMetadata = null;
+if (message.messageType === ChatMessageType.PLUGIN) {
+  try {
+    currentPluginMessageMetadata = JSON.parse(message.messageMetadata);
+  } catch (e) {
+    console.error('Invalid messageMetadata JSON:', e);
+  }
+}

124-139: Clarify Locking Logic for Chat

The locking logic for the chat might be complex and could benefit from simplification or additional comments for clarity.

Consider refactoring the locking conditions or adding comments to explain the logic.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 60e0de1 and 0699456.

📒 Files selected for processing (30)
  • bigbluebutton-html5/imports/ui/Types/meetingClientSettings.ts (1 hunks)
  • bigbluebutton-html5/imports/ui/Types/message.ts (2 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-form/component.tsx (3 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-form/mutations.tsx (1 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/component.tsx (6 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/component.tsx (6 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/message-content/text-content/component.tsx (1 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/message-edit-form/component.tsx (1 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/message-edit-form/styles.ts (1 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/message-header/component.tsx (2 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/message-reactions/component.tsx (1 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/message-reactions/styles.ts (1 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/message-replied/styles.tsx (1 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/message-toolbar/component.tsx (1 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/message-toolbar/styles.ts (1 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/mutations.ts (1 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/styles.ts (5 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/component.tsx (2 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 (1 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-reply-intention/component.tsx (1 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-reply-intention/styles.tsx (1 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/component.tsx (1 hunks)
  • bigbluebutton-html5/imports/ui/core/enums/chat.ts (1 hunks)
  • bigbluebutton-html5/imports/ui/core/initial-values/meetingClientSettings.ts (1 hunks)
  • bigbluebutton-html5/imports/ui/hooks/useStickyScroll.ts (3 hunks)
  • bigbluebutton-html5/imports/ui/services/storage/hooks.ts (1 hunks)
  • bigbluebutton-html5/private/config/settings.yml (2 hunks)
  • bigbluebutton-html5/public/locales/en.json (2 hunks)
🧰 Additional context used
🪛 Biome
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/component.tsx

[error] 317-317: Missing key property for this element in iterable.

The order of the items may change, and having a key can help React identify which item was moved.
Check the React documentation.

(lint/correctness/useJsxKeyInIterable)

bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/message-reactions/component.tsx

[error] 18-18: Missing key property for this element in iterable.

The order of the items may change, and having a key can help React identify which item was moved.
Check the React documentation.

(lint/correctness/useJsxKeyInIterable)

🔇 Additional comments (70)
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-form/mutations.tsx (1)

Line range hint 1-24: Summary: Changes align with PR objectives and follow best practices

The modifications to the ChatSendMessage mutation in this file are well-implemented and directly support the PR's objective of adding editing and deleting functionality for chat messages. The new optional replyToMessageId parameter allows for replying to specific messages while maintaining backward compatibility with existing code.

These changes lay the groundwork for implementing threaded conversations or message editing features in the BigBlueButton chat system. The focused nature of these changes aligns well with the PR best practices mentioned in the PR description.

bigbluebutton-html5/imports/ui/core/enums/chat.ts (3)

3-3: LGTM: New constant for focusing on a chat message.

The addition of CHAT_FOCUS_MESSAGE_REQUEST is appropriate and aligns with the PR objective of enhancing chat message interactions. The naming is clear and follows the existing convention.


5-5: LGTM: New constant for chat edit request.

The addition of CHAT_EDIT_REQUEST directly supports the PR objective of adding the ability to edit messages. The naming is clear and follows the existing convention.


6-6: LGTM: New constant for chat delete request.

The addition of CHAT_DELETE_REQUEST directly supports the PR objective of adding the ability to delete messages. The naming is clear and follows the existing convention.

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

1-1: LGTM: Correct import for GraphQL mutations

The import of gql from '@apollo/client' is correct and necessary for defining GraphQL mutations.


15-23: LGTM: Correct and flexible export statements

The export statements are well-structured, providing both default and named exports for the mutations. This approach offers flexibility for importing these mutations in other parts of the application.


1-23: Overall assessment: Well-implemented GraphQL mutations for chat message management

This new file successfully introduces GraphQL mutations for editing and deleting chat messages, aligning with the PR objectives. The code is clean, well-organized, and follows GraphQL and TypeScript conventions. The mutations are correctly defined, and the export statements provide flexibility for importing.

Minor suggestions were made for improving readability through consistent multi-line formatting of mutation parameters. These changes are not critical but would enhance code maintainability.

Great job on implementing these new features while adhering to best practices!

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

9-9: LGTM: Addition of dataTest prop enhances testability

The new optional dataTest prop of type string | null is a good addition. It allows for more flexible and specific testing by enabling custom data-test attributes. The type and optional nature are correctly implemented.


Line range hint 1-33: Overall assessment: Changes improve component testability

The modifications to this file enhance the testability of the ChatMessageTextContent component by introducing a flexible dataTest prop. The implementation is correct, maintains backwards compatibility, and follows React best practices. The suggestions provided are minor optimizations that could further improve the code quality and flexibility.

bigbluebutton-html5/imports/ui/Types/message.ts (1)

Line range hint 1-37: Great job on implementing the new message properties!

The changes to the Message interface align well with the PR objective of adding support for editing and deleting messages. The new properties (editedAt, deletedAt, deletedBy, messageSequence, and replyToMessage) provide a comprehensive structure for implementing these features.

The additions are well-thought-out and use appropriate types. They lay a solid foundation for the new chat functionality. The suggestions provided in the review are minor improvements that could enhance type safety, consistency, and code organization, but they don't detract from the overall quality of the implementation.

Great work on keeping the changes focused and aligned with the PR objectives!

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

1-2: LGTM: Imports are correct and well-organized.

The imports for styled-components and color constants are appropriate for the styled components defined in this file. Using specific color imports from a shared palette file promotes consistency and maintainability across the application.


32-35: LGTM: Clean and standard export of styled components.

The default export of an object containing both styled components is a clean and standard approach. This allows for easy and flexible importing of the components in other files.


1-35: Overall: Well-implemented styled components for chat message reactions.

This new file successfully implements styled components for chat message reactions, aligning with the PR objectives. The code is clean, modular, and follows React and styled-components best practices. The EmojiWrapper and ReactionsWrapper components provide a solid foundation for the UI support of editing and deleting chat messages.

A few minor suggestions and verifications have been made to further improve the implementation:

  1. Consider using relative units for better responsiveness in the EmojiWrapper component.
  2. Verify the positioning of the parent component using ReactionsWrapper to ensure correct layout.

Great job on implementing this feature!


24-30: LGTM: Simple and effective wrapper component with a note on positioning.

The ReactionsWrapper component is well-implemented, using flexbox for a flexible layout of reaction emojis.

Note that the absolute positioning of this component assumes that its parent container has a relative positioning. To ensure this component is used correctly, let's verify the parent component's positioning:

This will help us confirm that the parent component is set up correctly to handle the absolute positioning of ReactionsWrapper.

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

1-9: LGTM: Imports and interface declaration are well-structured.

The imports are appropriate, and the use of a TypeScript interface for prop types enhances code reliability and maintainability.


11-13: LGTM: Component declaration and props handling are correct.

The functional component is properly typed with TypeScript, and props are efficiently destructured. This approach enhances code readability and type safety.


33-33: LGTM: Component export is correct.

The default export of the component follows React best practices and common conventions.

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

1-4: LGTM: Imports are appropriate and consistent.

The imports are well-organized and include necessary styling utilities from both external and local sources. The use of absolute paths for local imports is consistent with the project structure.


1-34: Overall, good implementation with minor suggestions for improvement.

This new file for styling the chat message editing interface is well-structured and follows good practices for using styled-components. The components are clearly defined and make appropriate use of existing styling variables.

Key points:

  1. Consider using variables for hardcoded values (padding, margins) to improve consistency and maintainability.
  2. The duplicate color property in ChatMessageError should be removed.
  3. The use of TypeScript for prop typing ($sameSender in Section) is commendable.

These minor adjustments will further enhance the code quality and maintainability of this styling module.

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

1-3: LGTM: Imports are appropriate and well-organized.

The imports are correctly set up for styled-components, and the use of a separate palette file for colors is a good practice for maintaining consistency across the application.


15-18: LGTM: Typography component provides a good base for text styling.

The Typography component is a simple yet effective base for text-related components. It handles overflow, which is crucial for maintaining layout consistency.


19-26: LGTM: Username component is well-designed with appropriate styling.

The Username component extends Typography and adds specific styles for usernames. The use of a prop for user color allows for dynamic styling, and the text overflow handling is appropriate for usernames.


28-32: LGTM: Message component handles text display effectively.

The Message component extends Typography and adds appropriate styles for message text. The max-height, line-height, and overflow handling are well-suited for displaying chat messages.


34-38: LGTM: DeleteMessage component is appropriately styled for deleted messages.

The DeleteMessage component uses appropriate styles to differentiate deleted messages. The use of colorText from the palette ensures consistency with the overall design.


40-45: LGTM: Default export provides easy access to all components.

The default export includes all the styled components, making them easily accessible when importing this file. This approach promotes clean and organized imports in other parts of the application.


4-13: LGTM: Container component is well-structured. Verify clickable behavior.

The Container component is well-designed with dynamic styling based on user color. The styles are appropriate for a chat message container.

The cursor: pointer style suggests that the container is clickable. Please verify if this is the intended behavior and if there's a corresponding click handler in the parent component.

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

17-17: LGTM: Addition of deleteTime property

The new deleteTime property in the ChatMessageHeaderProps interface is well-defined and aligns with the PR objective of adding message deletion functionality. The optional Date | null type is appropriate and maintains backward compatibility.


25-25: LGTM: Destructuring of deleteTime prop

The addition of deleteTime to the component's props destructuring is consistent with the interface update and allows the component to access this new prop.


Line range hint 1-52: Overall assessment: Well-implemented feature addition

The changes in this file successfully implement the ability to handle deleted messages in the chat message header component. The code is clean, consistent, and aligns well with the PR objective. The addition of the deleteTime prop and its usage in conditional rendering is appropriate.

While the current implementation is good, consider the suggestion to display deletion time for enhanced user information. This could provide a better user experience by offering more context about message deletions.

Great job on maintaining code quality while adding this new feature!

bigbluebutton-html5/imports/ui/services/storage/hooks.ts (1)

Line range hint 1-61: Verify the usage of STORAGES constant in related components.

The changes in this file are minimal and focused, which aligns well with the PR best practices mentioned in the objectives. Exporting the STORAGES constant doesn't introduce any breaking changes to existing functionality and enables other parts of the application to use it.

To ensure that this change is utilized effectively, please verify that the STORAGES constant is imported and used correctly in the components responsible for editing and deleting chat messages. Run the following script to check for its usage:

If the script doesn't find any usage, consider adding appropriate imports and utilizing the STORAGES constant in the relevant components for editing and deleting chat messages.

✅ Verification successful

STORAGES constant is correctly utilized in relevant components.

The STORAGES constant is imported and used in bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/component.tsx, confirming that it is being used as intended.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for the usage of STORAGES constant in related components

# Search for imports of STORAGES
echo "Searching for imports of STORAGES:"
rg --type typescript --type typescript "import.*STORAGES.*from.*storage/hooks" -g '!hooks.ts'

# Search for usage of STORAGES constant
echo "Searching for usage of STORAGES constant:"
rg --type typescript --type typescript "STORAGES\.(LOCAL|SESSION|IN_MEMORY)" -g '!hooks.ts'

Length of output: 431


Script:

#!/bin/bash
# Description: Check for the usage of STORAGES constant in related components

# Search for imports of STORAGES
echo "Searching for imports of STORAGES:"
rg "import.*STORAGES.*from.*storage/hooks" -g '*.ts' -g '*.tsx' --glob '!hooks.ts'

# Search for usage of STORAGES constant
echo "Searching for usage of STORAGES constant:"
rg "STORAGES\.(LOCAL|SESSION|IN_MEMORY)" -g '*.ts' -g '*.tsx' --glob '!hooks.ts'

Length of output: 745

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

14-14: LGTM: Addition of messageSequence field

The addition of the messageSequence field is a good improvement. It likely provides a unique identifier or order for messages, which is essential for implementing editing and deleting functionality as per the PR objectives.


15-27: LGTM: Addition of replyToMessage field and its nested structure

The addition of the replyToMessage field with its comprehensive nested structure is a valuable enhancement. It supports more complex chat interactions, such as threaded conversations, by providing detailed information about the message being replied to. This aligns well with the PR's objective of improving chat functionality.

The inclusion of fields like deletedAt and deletedBy within replyToMessage is particularly noteworthy, as it allows for proper handling of scenarios where a replied-to message has been deleted.


34-38: LGTM: Addition of editing and deletion-related fields

The addition of editedAt, deletedAt, and deletedBy fields is excellent and directly supports the PR objective of adding editing and deleting functionality for chat messages. These fields will allow the application to:

  1. Track when a message was last edited (editedAt).
  2. Determine if and when a message was deleted (deletedAt).
  3. Identify who deleted a message (deletedBy).

This information is crucial for implementing a robust chat system with edit and delete capabilities, enhancing the overall user experience.


Line range hint 1-73: Overall assessment: Changes align well with PR objectives

The modifications to the CHAT_MESSAGE_PUBLIC_SUBSCRIPTION query in this file are well-structured and directly support the PR's objective of adding editing and deleting functionality for chat messages. The additions include:

  1. A messageSequence field for unique message identification.
  2. A comprehensive replyToMessage structure for supporting threaded conversations.
  3. Fields for tracking edits (editedAt) and deletions (deletedAt, deletedBy).

These changes provide the necessary data structure to implement robust chat message editing and deleting features, enhancing the overall functionality of the chat system.

bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-reply-intention/styles.tsx (2)

1-6: LGTM: Imports are appropriate for styled components.

The imports include necessary modules from styled-components, color constants from a palette, and a Button component. These are suitable for creating styled components for the chat reply intention feature.


8-54: LGTM: Well-structured styled components with appropriate styling techniques.

The styled components (Container, Typography, Username, Message) are well-defined and make good use of styled-components features. The conditional styling based on props in the Container component is particularly well-implemented.

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

1-13: LGTM: Imports and message definitions are well-structured.

The imports are appropriate for the component's functionality, and the use of react-intl for internationalization is a good practice. The intlMessages object is correctly defined using defineMessages.


24-29: LGTM: Component definition and prop handling are well-implemented.

The ChatMessageReplied component is correctly defined as a React functional component with proper TypeScript typing. The destructuring of props in the function parameters improves code readability. The use of the useIntl hook for internationalization is also correct.


66-66: LGTM: Correct component export.

The component is properly exported as the default export, following common React component export practices.


1-66: Overall assessment: Well-implemented component with minor improvement opportunities.

The ChatMessageReplied component is a well-structured and functional implementation for displaying replied chat messages. It successfully handles both regular and deleted messages, uses TypeScript for type safety, and implements internationalization.

Key strengths:

  1. Proper use of TypeScript for prop typing.
  2. Effective use of react-intl for internationalization.
  3. Conditional rendering to handle different message states.

Suggestions for improvement:

  1. Add JSDoc comments to the MessageRepliedProps interface for better documentation.
  2. Extract click handler and focus management logic into separate functions or hooks for better separation of concerns.
  3. Consider using useCallback for performance optimization.

These improvements would enhance the component's maintainability and potentially its performance. Overall, the implementation is solid and adheres to React best practices.

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

1-9: Imports look good and are appropriate for the file's purpose.

The imports cover all necessary styling utilities, color palettes, and components needed for creating the styled components in this file. The use of absolute import paths is consistent with the project structure.


90-95: Exports are correct and follow good practices.

All styled components defined in the file are exported using named exports. This approach allows for selective importing in other parts of the application, which is a good practice for maintaining clean and efficient imports.

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

2-2: LGTM: Good choice for loading indicator

The addition of CircularProgress from Material-UI is a good choice for implementing a loading indicator. It's a widely-used and well-designed component that will enhance the user experience during chat loading.


Line range hint 1-54: Clarification needed on PR objectives

The changes in this file improve the chat loading experience, which is a positive addition. However, the main PR objective of adding the ability to edit and delete messages is not addressed in this file.

Could you please clarify:

  1. Is this change a prerequisite for the message editing and deleting functionality?
  2. Are there other files in this PR that implement the core objectives?
  3. If not, what are the next steps to implement the message editing and deleting features?

This information will help ensure that the PR meets its stated objectives and follows the best practice of focusing on a single functionality.

To help verify the implementation of message editing and deleting functionality, you can run the following script:

✅ Verification successful

To effectively search for implementations of message editing and deleting, please run the following revised script:


Verified: Editing and Deleting Implementations Found

The PR includes implementations for editing and deleting messages in multiple files, such as:

  • imports/ui/components/breakout-room/breakout-room/components/messageForm.tsx
  • imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/component.tsx
  • imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/message-replied/component.tsx

These additions address the PR's objectives to enhance chat functionality by enabling message editing and deleting.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for potential implementations of message editing and deleting

echo "Searching for potential message editing implementations:"
rg --type typescript --type javascript 'edit.*message|message.*edit' -g '!*test*'

echo "\nSearching for potential message deleting implementations:"
rg --type typescript --type javascript 'delete.*message|message.*delete' -g '!*test*'

Length of output: 493


Script:

#!/bin/bash
# Description: Search for potential implementations of message editing and deleting

echo "Searching for potential message editing implementations:"
rg 'edit.*message|message.*edit' -g '*.ts' -g '*.tsx' --ignore-file .gitignore

echo "\nSearching for potential message deleting implementations:"
rg 'delete.*message|message.*delete' -g '*.ts' -g '*.tsx' --ignore-file .gitignore

Length of output: 1854

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

17-19: LGTM: New color imports added.

The new color imports (colorOffWhite, colorText, palettePlaceholderText) are consistent with the existing import style and will be used in the new styled components.


Line range hint 1-223: Overall assessment: Changes align well with PR objectives.

The modifications and additions to this file effectively support the new edit and delete functionality for chat messages, as outlined in the PR objectives. The changes include:

  1. New color imports for enhanced styling.
  2. Addition of $highlight property to relevant interfaces for conditional styling.
  3. Implementation of highlight-based hover effects in ChatWrapper and ChatContent.
  4. Introduction of new styled components (Container, DeleteMessage, and ChatEditTime) to support edit and delete features.

These changes maintain consistency with the existing codebase while introducing the necessary elements for the new functionality. The suggested minor improvements, if implemented, will further enhance maintainability and accessibility.

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

Line range hint 1-134: LGTM with minor suggestions

The changes in this file are minimal and generally improve the code by reducing unnecessary DOM elements. The rest of the file remains unchanged and follows good practices for React and GraphQL usage.

Please consider the suggestions about removing the unnecessary key prop from the React.Fragment and addressing the TypeScript ignore comments if possible. Once these minor issues are addressed, the changes look good to merge.

bigbluebutton-html5/imports/ui/Types/meetingClientSettings.ts (2)

Line range hint 1-1000: Overall assessment: Good addition, well-scoped change

The addition of the toolbar property to the Chat interface is a well-scoped change that aligns with the PR objectives. The modification is minimal and doesn't introduce any breaking changes to the existing structure of the MeetingClientSettings interface.

The file maintains good organization and follows TypeScript best practices. No other parts of the file seem to require changes related to this PR.

To ensure a smooth integration of the new feature:

  1. Consider adding a brief comment to explain the purpose and possible values of the toolbar property, as suggested earlier.
  2. Verify the integration with existing chat features using the provided script.
  3. Ensure that the implementation of the edit and delete functionality in other parts of the codebase (not visible in this file) is consistent with the types defined here.

Great job on keeping the change focused and maintaining the overall structure of the configuration file!


529-529: Verify integration with existing chat features

While the addition of the toolbar property is a good start for implementing edit and delete functionality, it's important to ensure that this new feature integrates well with existing chat-related properties and settings.

Please run the following script to check for any potential interactions or conflicts with existing chat features:

This script will help identify any existing code that might need to be updated to support the new toolbar functionality fully. Please review the results and ensure that all necessary changes have been made to integrate the new feature seamlessly.

✅ Verification successful

Integration of toolbar Property Verified

The toolbar property has been successfully integrated with existing chat features. References to toolbar are consistently used across relevant chat components, ensuring that the new edit and delete functionalities are supported without affecting other chat-related settings.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential interactions between the new toolbar and existing chat features

# Search for references to chat settings in the codebase
echo "Searching for references to chat settings:"
rg --type typescript --type javascript 'chat\.(enabled|itemsPerPage|timeBetweenFetchs|enableSaveAndCopyPublicChat|bufferChatInsertsMs|startClosed|min_message_length|max_message_length|grouping_messages_window|type_system|type_public|type_private|system_userid|system_username|public_id|public_group_id|public_userid|public_username|storage_key|system_messages_keys|typingIndicator|moderatorChatEmphasized|privateMessageReadFeedback|autoConvertEmoji|emojiPicker|disableEmojis|allowedElements|toolbar)'

# Search for potential toolbar-related logic
echo "\nSearching for potential toolbar-related logic:"
rg --type typescript --type javascript '(chat|message)\s*(toolbar|edit|delete|modify)'

Length of output: 863


Script:

#!/bin/bash
# Description: Check for potential interactions between the new toolbar and existing chat features

# Search for references to chat settings in TypeScript and JavaScript files
echo "Searching for references to chat settings in .ts and .tsx files:"
rg --type-add 'ts=*.ts' --type-add 'tsx=*.tsx' 'chat\.(enabled|itemsPerPage|timeBetweenFetchs|enableSaveAndCopyPublicChat|bufferChatInsertsMs|startClosed|min_message_length|max_message_length|grouping_messages_window|type_system|type_public|type_private|system_userid|system_username|public_id|public_group_id|public_userid|public_username|storage_key|system_messages_keys|typingIndicator|moderatorChatEmphasized|privateMessageReadFeedback|autoConvertEmoji|emojiPicker|disableEmojis|allowedElements|toolbar)' -g '*.ts' -g '*.tsx'

# Search for potential toolbar-related logic in TypeScript and JavaScript files
echo "\nSearching for potential toolbar-related logic in .ts and .tsx files:"
rg --type-add 'ts=*.ts' --type-add 'tsx=*.tsx' '(chat|message)\s*(toolbar|edit|delete|modify)' -g '*.ts' -g '*.tsx'

Length of output: 1059


Script:

#!/bin/bash
# Description: Check for potential interactions between the new toolbar and existing chat features

# Search for references to chat settings in TypeScript and JavaScript files
echo "Searching for references to chat settings in .ts and .tsx files:"
rg 'chat\.(enabled|itemsPerPage|timeBetweenFetchs|enableSaveAndCopyPublicChat|bufferChatInsertsMs|startClosed|min_message_length|max_message_length|grouping_messages_window|type_system|type_public|type_private|system_userid|system_username|public_id|public_group_id|public_userid|public_username|storage_key|system_messages_keys|typingIndicator|moderatorChatEmphasized|privateMessageReadFeedback|autoConvertEmoji|emojiPicker|disableEmojis|allowedElements|toolbar)' -g '*.ts' -g '*.tsx'

# Search for potential toolbar-related logic in TypeScript and JavaScript files
echo "\nSearching for potential toolbar-related logic in .ts and .tsx files:"
rg '(chat|message)\s*(toolbar|edit|delete|modify)' -g '*.ts' -g '*.tsx'

Length of output: 2624


Script:

#!/bin/bash
# Description: Further check for potential interactions between the new toolbar and existing chat/message features

# Search for enhanced references to chat settings and toolbar in TypeScript and JavaScript files
echo "Searching for enhanced references to chat settings and toolbar in .ts and .tsx files:"
rg 'window\.meetingClientSettings\.public\.chat\.toolbar' -g '*.ts' -g '*.tsx'

# Search for functions or components that utilize the toolbar, edit, delete, or modify in chat or message contexts
echo "\nSearching for functions or components utilizing toolbar, edit, delete, or modify in chat/message contexts in .ts and .tsx files:"
rg '(toolbar|edit|delete|modify)\b.*\b(chat|message)' -g '*.ts' -g '*.tsx'

# Search for imports or dependencies related to the toolbar in chat/message components
echo "\nSearching for imports or dependencies related to toolbar in chat/message components in .ts and .tsx files:"
rg 'import.*toolbar' -g '*.ts' -g '*.tsx'

Length of output: 2205

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

137-137: LGTM: New state variable for reply feature

The addition of the repliedMessageId state variable is a good approach for implementing the reply feature. It's correctly typed and uses the appropriate React hook.


322-335: LGTM: Updated message submission with reply feature

The addition of replyToMessageId to the chatSendMessage mutation is correct for implementing the reply feature. The custom event dispatch after sending the message is a good way to reset the reply intention.

However, could you clarify the purpose of the undefined properties in the event payload? If they're intentional, consider adding a comment explaining why. If not, you might want to remove them or set appropriate values.

window.dispatchEvent(
  new CustomEvent(ChatEvents.CHAT_REPLY_INTENTION, {
    detail: {
      username: undefined,
      message: undefined,
      messageId: undefined,
      chatId: undefined,
    },
  }),
);
bigbluebutton-html5/imports/ui/core/initial-values/meetingClientSettings.ts (2)

572-572: Verify alignment with existing chat configurations.

While the addition of the toolbar property is straightforward, it's important to ensure that the new edit and delete functionality aligns with existing chat configurations. Please verify:

  1. The new functionality respects the chat.enabled setting.
  2. Consider how the new feature interacts with chat.startClosed and chat.autoConvertEmoji settings.
  3. Ensure that message editing and deleting respect the chat.min_message_length and chat.max_message_length constraints.
  4. Verify that the new functionality works correctly with the chat.typingIndicator feature.

To assist in this verification, you can run the following script to gather relevant chat configuration:

#!/bin/bash
# Extract chat-related configuration
echo "Current chat configuration:"
sed -n '/chat: {/,/},/p' bigbluebutton-html5/imports/ui/core/initial-values/meetingClientSettings.ts

572-572: LGTM. Verify toolbar implementation in related files.

The addition of the toolbar property to the chat object is a good starting point for implementing the ability to edit and delete messages. The empty array allows for flexible configuration of toolbar items.

To ensure this change is properly utilized, please verify the implementation of the chat toolbar in related files:

bigbluebutton-html5/private/config/settings.yml (2)

62-62: Summary of configuration changes

The changes in this configuration file lay the groundwork for implementing message editing and deletion features:

  1. Disabling the leave confirmation prompt simplifies the user experience but may increase the risk of accidental exits.
  2. The new toolbar option in the chat section provides a flexible way to configure message interaction options.

These changes align well with the PR objectives. However, consider enabling some default toolbar options to immediately provide users with the new functionality.

Also applies to: 771-773


62-62: Consider the implications of disabling leave confirmation

The askForConfirmationOnLeave setting has been changed from true to false. This change will remove the confirmation prompt when users attempt to leave a session, which can streamline the user experience. However, it may also increase the risk of accidental session exits.

To ensure this change doesn't conflict with any other parts of the application, please run the following command:

✅ Verification successful

Verification Successful: No Conflicts Found with askForConfirmationOnLeave

The askForConfirmationOnLeave setting has been consistently updated to false across the codebase. No conflicting references or unintended side effects were detected in the search results.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any references to askForConfirmationOnLeave in the codebase
rg "askForConfirmationOnLeave" --type js --type jsx --type ts --type tsx

Length of output: 100


Script:

#!/bin/bash
# Search for any references to askForConfirmationOnLeave in the codebase
rg "askForConfirmationOnLeave" --type js --type ts --type tsx

Length of output: 89


Script:

#!/bin/bash
# Search for any references to askForConfirmationOnLeave in the entire codebase
rg "askForConfirmationOnLeave"

Length of output: 578

bigbluebutton-html5/public/locales/en.json (7)

8-8: New error message for chat update looks good.

The new entry "app.chat.errorOnUpdateMessage" is clear, concise, and follows the existing naming convention for error messages. It appropriately handles the scenario of an error occurring during a chat message update.


43-43: New entry for displaying edit time is appropriate.

The new entry "app.chat.editTime" with the value "Last edited at {0}" is well-formatted and uses a placeholder for the time value. This approach allows for easy localization and is consistent with other time-related entries in the file.


44-44: New entry for deleted messages is clear and informative.

The new entry "app.chat.deleteMessage" with the value "This message was deleted by {0}" is well-structured. It provides clear information about the deletion action and includes a placeholder for the user who performed the deletion, which is consistent with the application's localization approach.


45-45: New entry for reply action in chat toolbar is well-formed.

The new entry "app.chat.toolbar.reply" with the value "Reply to message {0}" is clear and action-oriented. It appropriately uses a placeholder, likely for the username or message identifier, which is consistent with the localization approach used throughout the file.


46-46: New entry for edit action in chat toolbar is concise and clear.

The new entry "app.chat.toolbar.edit" with the simple value "Edit" is appropriately concise for a toolbar action. It follows the pattern of other similar entries in the file and clearly conveys its purpose.


47-47: New entry for delete action in chat toolbar is succinct and clear.

The new entry "app.chat.toolbar.delete" with the value "Delete" is appropriately brief for a toolbar action. It maintains consistency with other toolbar entries and clearly communicates its function.


Line range hint 1-1239: New chat-related entries are well-integrated and enhance functionality.

The six new entries added to the localization file are all related to chat functionality, specifically for editing and deleting messages. These additions are consistent with the existing file structure and naming conventions. They provide clear and concise messages for error handling, displaying edit times, showing deleted message information, and new toolbar actions (reply, edit, delete).

These changes align well with the PR objective of introducing user interface support for editing and deleting chat messages. The new entries will allow for proper localization of these new features, ensuring a consistent user experience across different languages.

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

11-13: Definition of MessageListProps is correct

The MessageListProps interface is properly defined with the isRTL boolean property, facilitating RTL support.

bigbluebutton-html5/imports/ui/hooks/useStickyScroll.ts (1)

10-10: ⚠️ Potential issue

Ensure all usages of useStickyScroll are updated to the new signature

The useStickyScroll hook now accepts two parameters: stickyElement and onResizeOf, which is a breaking change. Please ensure that all instances where useStickyScroll is used have been updated to match the new signature to prevent runtime errors.

To verify all usages of useStickyScroll in the codebase, you can run the following script:

✅ Verification successful

All usages of useStickyScroll have been updated to the new signature.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all calls to useStickyScroll and confirm they have two arguments.

# Search for all occurrences of useStickyScroll and display the lines with context.
rg --type-add 'tsx:*.{tsx,ts}' -t tsx -A 2 'useStickyScroll\('

Length of output: 433

bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-reply-intention/component.tsx (1)

1-76: Overall, Good Implementation of ChatReplyIntention Component

The ChatReplyIntention component is well-structured and effectively manages state and side effects using React hooks. The use of Styled components enhances readability, and the event handling logic is appropriately set up with cleanup in the useEffect hook.

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

103-104: Handle empty or undefined CHAT_TOOLBAR_CONFIG properly

Returning null when CHAT_TOOLBAR_CONFIG is empty might prevent the toolbar from rendering even when it's needed. Ensure that the component renders appropriately based on the application's requirements.


118-130: Verify that event listeners for custom events are properly implemented

Dispatching a custom event ChatEvents.CHAT_REPLY_INTENTION relies on appropriate event listeners elsewhere in the application. Ensure that these listeners are set up correctly to handle the event.

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

299-299: ⚠️ Potential issue

Correct the setLastSender prop to avoid unintended function nesting

At line 299, you're passing a function that returns another function to the setLastSender prop. This could lead to unexpected behavior if ChatListPage expects a function with the signature (page: number, sender: string) => void. You should pass the function directly without wrapping it in an additional arrow function.

Apply this diff to pass the correct function:

-                      setLastSender={() => setLastSender(lastSenderPerPage.current)}
+                      setLastSender={setLastSender(lastSenderPerPage.current)}

Likely invalid or redundant comment.

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

231-232: Check for Null Values Before Formatting Dates

When using intl.formatTime(editTime), ensure that editTime is not null to prevent runtime errors.

Confirm that editTime is always a valid Date object before formatting.


395-396: Ensure Consistent Rendering Based on 'editing' State

Verify that the conditional rendering between editing and !editing correctly handles all possible states and that there are no unintended overlaps or missing UI elements.

Review the rendering logic to ensure user experience is seamless.

Also applies to: 466-477

Comment on lines +3 to +6
CHAT_FOCUS_MESSAGE_REQUEST = 'ChatFocusMessageRequest',
CHAT_REPLY_INTENTION = 'ChatReplyIntention',
CHAT_EDIT_REQUEST = 'ChatEditRequest',
CHAT_DELETE_REQUEST = 'ChatDeleteRequest',

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

New chat event constants are not used in the codebase.

The constants ChatFocusMessageRequest, ChatReplyIntention, ChatEditRequest, and ChatDeleteRequest are only defined in bigbluebutton-html5/imports/ui/core/enums/chat.ts but are not referenced anywhere else in the codebase. Please verify if these constants are intended to be used in the current implementation or if they are unnecessary and should be removed.

🔗 Analysis chain

Overall assessment: Excellent additions to support new chat features.

The new constants added to the ChatEvents enum are well-named, consistent with the existing code style, and directly support the PR objectives of adding the ability to edit and delete messages. The additional constant for reply intention, while not explicitly mentioned in the objectives, is a valuable enhancement to the chat functionality.

To ensure these new events are properly utilized, please run the following script to check for their usage across the codebase:

This will help confirm that the new events are being used appropriately in the implementation of the new chat features.


To accurately verify the usage of the new chat events, please run the following script which targets .ts files directly:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of new chat events across the codebase.

echo "Checking usage of new chat events:"
for event in ChatFocusMessageRequest ChatReplyIntention ChatEditRequest ChatDeleteRequest
do
    echo "Usage of $event:"
    rg --type typescript "$event"
    echo "---"
done

Length of output: 1085


Script:

#!/bin/bash
# Description: Verify the usage of new chat events across the codebase.

echo "Checking usage of new chat events:"
for event in ChatFocusMessageRequest ChatReplyIntention ChatEditRequest ChatDeleteRequest
do
    echo "Usage of $event:"
    rg --glob '*.ts' "$event"
    echo "---"
done

Length of output: 1320

Comment on lines +14 to +30
return (
<Styled.ReactionsWrapper>
{reactions.map((emoji) => {
return (
<Styled.EmojiWrapper highlighted={false}>
<em-emoji
emoji={emoji}
size={parseFloat(
window.getComputedStyle(document.documentElement).fontSize,
)}
native={emoji.native}
/>
</Styled.EmojiWrapper>
);
})}
</Styled.ReactionsWrapper>
);

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

⚠️ Potential issue

Improve rendering logic and fix potential issues.

The component's structure is good, but there are a few points to address:

  1. Add a key prop to the mapped elements to help React efficiently update the list:
- <Styled.EmojiWrapper highlighted={false}>
+ <Styled.EmojiWrapper key={emoji.id} highlighted={false}>
  1. Consider making the highlighted prop dynamic, possibly based on user interaction:
- <Styled.EmojiWrapper key={emoji.id} highlighted={false}>
+ <Styled.EmojiWrapper key={emoji.id} highlighted={emoji.isHighlighted}>
  1. Fix the emoji prop passed to em-emoji. It should be the emoji's native representation:
- emoji={emoji}
+ emoji={emoji.native}
  1. Remove the redundant native prop from em-emoji as it's already provided in the emoji prop:
- native={emoji.native}

These changes will improve the component's correctness and flexibility.

Committable suggestion was skipped due to low confidence.

🧰 Tools
🪛 Biome

[error] 18-18: Missing key property for this element in iterable.

The order of the items may change, and having a key can help React identify which item was moved.
Check the React documentation.

(lint/correctness/useJsxKeyInIterable)

Comment on lines +18 to +34
const ChatMessageError = styled.div`
color: ${colorDanger};
font-size: calc(${fontSizeBase} * .75);
color: ${colorGrayDark};
text-align: left;
padding: ${borderSize} 0;
word-break: break-word;
position: relative;
margin-right: 0.05rem;
margin-left: 0.05rem;
`;

export default {
Actions,
Section,
ChatMessageError,
};

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

Fix duplicate color property in ChatMessageError component.

The ChatMessageError component is well-styled and makes good use of existing variables. However, there's a duplicate color property that needs to be addressed.

Please apply the following fix:

const ChatMessageError = styled.div`
  color: ${colorDanger};
  font-size: calc(${fontSizeBase} * .75);
- color: ${colorGrayDark};
  text-align: left;
  padding: ${borderSize} 0;
  word-break: break-word;
  position: relative;
  margin-right: 0.05rem;
  margin-left: 0.05rem;
`;

Also, consider using variables for the small margin values (0.05rem) to maintain consistency.

The export method looks good and appropriate for named exports.

📝 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 ChatMessageError = styled.div`
color: ${colorDanger};
font-size: calc(${fontSizeBase} * .75);
color: ${colorGrayDark};
text-align: left;
padding: ${borderSize} 0;
word-break: break-word;
position: relative;
margin-right: 0.05rem;
margin-left: 0.05rem;
`;
export default {
Actions,
Section,
ChatMessageError,
};
const ChatMessageError = styled.div`
color: ${colorDanger};
font-size: calc(${fontSizeBase} * .75);
text-align: left;
padding: ${borderSize} 0;
word-break: break-word;
position: relative;
margin-right: 0.05rem;
margin-left: 0.05rem;
`;
export default {
Actions,
Section,
ChatMessageError,
};

Comment on lines +56 to +61
// @ts-ignore
const CloseBtn = styled(Button)`
position: absolute;
top: 2px;
right: 2px;
`;

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

Address TypeScript ignore comment for CloseBtn.

The @ts-ignore comment suggests there might be a type issue with the Button component being used. It's generally better to fix type issues rather than ignoring them.

Consider addressing the underlying type issue. If the Button component is incorrectly typed, you might need to create a proper type definition or adjust how it's imported. If you need assistance with this, please let me know.

Comment on lines +63 to +68
export default {
Container,
Username,
CloseBtn,
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.

🛠️ Refactor suggestion

Consider using named exports for better tree-shaking.

While the current default export is concise, using named exports could provide better tree-shaking opportunities and more explicit imports in other files.

Consider refactoring to named exports:

-export default {
-  Container,
-  Username,
-  CloseBtn,
-  Message,
-};
+export {
+  Container,
+  Username,
+  CloseBtn,
+  Message,
+};

This change would allow for more granular imports in other files, potentially improving bundle size through better tree-shaking.

📝 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
export default {
Container,
Username,
CloseBtn,
Message,
};
export {
Container,
Username,
CloseBtn,
Message,
};

const messageRef = React.createRef<HTMLDivElement>();

const ANIMATION_DURATION = 2000;

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

Correct the Component Name Typo

The component is named ChatMesssage with an extra 's'. This may lead to confusion and import errors.

Apply this diff to correct the component name:

-const ChatMesssage: React.FC<ChatMessageProps> = ({
+const ChatMessage: React.FC<ChatMessageProps> = ({

...

-export default ChatMesssage;
+export default ChatMessage;

Also applies to: 479-479

Comment on lines +456 to +457
{`(${intl.formatMessage(intlMessages.editTime, { 0: intl.formatTime(editTime) })})`}
</ChatEditTime>

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

Ensure Proper Usage of 'intl.formatMessage' with Correct Variables

The intl.formatMessage function uses { 0: value } as variables, which is unconventional. It's better to use meaningful variable names matching the placeholders in your messages.

Modify the code to use appropriate variable names:

{editTime && (
  <ChatEditTime>
-    {`(${intl.formatMessage(intlMessages.editTime, { 0: intl.formatTime(editTime) })})`}
+    {`(${intl.formatMessage(intlMessages.editTime, { time: intl.formatTime(editTime) })})`}
  </ChatEditTime>
)}

...

{deleteTime && (
  <DeleteMessage>
-    {intl.formatMessage(intlMessages.deleteMessage, { 0: message.deletedBy?.name })}
+    {intl.formatMessage(intlMessages.deleteMessage, { username: message.deletedBy?.name })}
  </DeleteMessage>
)}

Also, update the defaultMessage in your messages to include these placeholders:

   editTime: {
     id: 'app.chat.editTime',
     description: '',
     defaultMessage: 'Edited at {time}'
   },
   deleteMessage: {
     id: 'app.chat.deleteMessage',
     description: '',
     defaultMessage: 'Message deleted by {username}'
   },

Also applies to: 461-462

const containerRef = React.useRef<HTMLDivElement>(null);
const animationInitialTimestamp = React.useRef(0);

const CHAT_TOOLBAR_CONFIG = window.meetingClientSettings.public.chat.toolbar;

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

Handle Undefined 'window.meetingClientSettings' Safely

Accessing window.meetingClientSettings.public.chat.toolbar without checking if window.meetingClientSettings exists may cause runtime errors if it's undefined.

Add a nullish coalescing operator to provide a default value:

-const CHAT_TOOLBAR_CONFIG = window.meetingClientSettings.public.chat.toolbar;
+const CHAT_TOOLBAR_CONFIG = window.meetingClientSettings?.public?.chat?.toolbar || [];
📝 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 CHAT_TOOLBAR_CONFIG = window.meetingClientSettings.public.chat.toolbar;
const CHAT_TOOLBAR_CONFIG = window.meetingClientSettings?.public?.chat?.toolbar || [];

Comment on lines +64 to +71
editTime: {
id: 'app.chat.editTime',
description: '',
},
deleteMessage: {
id: 'app.chat.deleteMessage',
description: '',
},

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

Add 'defaultMessage' to Internationalization Messages

The messages editTime and deleteMessage lack a defaultMessage property, which is necessary for internationalization using react-intl. Ensure that each message includes a defaultMessage for fallback purposes.

Apply this diff to add defaultMessage:

   editTime: {
     id: 'app.chat.editTime',
     description: '',
+    defaultMessage: 'Edited at {time}'
   },
   deleteMessage: {
     id: 'app.chat.deleteMessage',
     description: '',
+    defaultMessage: 'Message deleted by {username}'
   },

Committable suggestion was skipped due to low confidence.

Comment on lines +14 to +16
Container,
DeleteMessage,
ChatEditTime,

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

Imports from './styles' do not export the required components

  • The components Container, DeleteMessage, and ChatEditTime are exported from different styles.ts files, not from './styles' within the chat message component directory.
  • Update the import paths in component.tsx to reference the correct styles.ts files that export these components.
🔗 Analysis chain

Import Missing Default Exports or Named Exports

The imports Container, DeleteMessage, and ChatEditTime from './styles' may cause issues if they are not properly exported in './styles'. Ensure that these components are correctly exported as named exports in the './styles' file.

Run the following script to check the exports in './styles':

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that 'Container', 'DeleteMessage', and 'ChatEditTime' are exported from './styles'

# Test: Search for the export statements of the components in styles.tsx
ast-grep --lang typescript --pattern 'export const $_ = styled.$_$' ./styles.tsx

Length of output: 142


Script:

#!/bin/bash
# Description: Locate exports of 'Container', 'DeleteMessage', and 'ChatEditTime' across the codebase

# Search for 'Container' export
ast-grep --lang typescript --pattern 'export const Container = $_' 

# Search for 'DeleteMessage' export
ast-grep --lang typescript --pattern 'export const DeleteMessage = $_' 

# Search for 'ChatEditTime' export
ast-grep --lang typescript --pattern 'export const ChatEditTime = $_' 

Length of output: 6412

@antobinary

Copy link
Copy Markdown
Member

@JoVictorNunes do we currently satisfy the requirements in #21357 (comment) ? Do you have any written requirements somewhere?

@JoVictorNunes
JoVictorNunes marked this pull request as draft October 4, 2024 12:38
@gustavotrott

gustavotrott commented Oct 4, 2024 •

Copy link
Copy Markdown
Contributor

The target message should keep highlighted somehow to avoid confusing!
And the toolbar kept visible while navigating in three dots menu!

image

@gustavotrott

Copy link
Copy Markdown
Contributor

IMO the delete button should require a confirmation step!

@JoVictorNunes

JoVictorNunes commented Oct 4, 2024 •

Copy link
Copy Markdown
Contributor Author

TODO:

  • Add disabledFeatures handling.
  • Do not allow moderators to delete in Breakouts.

@github-actions

github-actions Bot commented Oct 9, 2024

Copy link
Copy Markdown

This pull request has conflicts ☹
Please resolve those so we can review the pull request.
Thanks.

@JoVictorNunes
JoVictorNunes marked this pull request as ready for review October 14, 2024 13:21

@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: 11

🧹 Outside diff range and nitpick comments (9)
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/message-toolbar/styles.ts (1)

11-11: Approved: Good enhancement to Container visibility control

The addition of the $menuIsOpen prop and corresponding CSS rules improves the flexibility of the Container component. This change allows the component to be displayed based on both hover and the $menuIsOpen state, providing more granular control over its visibility.

For improved clarity, consider adding a comment explaining the interaction between the hover state and the $menuIsOpen prop. For example:

// Display flex when hovered or when menu is open
${({ $menuIsOpen }) => ($menuIsOpen && css`
  display: flex;
`)}

This will help future developers understand the component's behavior more quickly.

Also applies to: 29-31

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/groupchats/EditGroupChatMessageReqMsgHdlr.scala (1)

Line range hint 28-28: Variable userIsModerator may be misnamed leading to confusion

The variable userIsModerator is assigned as:

val userIsModerator = user.role != Roles.MODERATOR_ROLE

This means userIsModerator is true when the user is not a moderator, which is counterintuitive and could cause confusion or logical errors.

Consider:

  • Renaming the variable to userIsNotModerator or userIsParticipant for clarity.

  • Alternatively, if the intention is to check if the user is a moderator, assign:

    val userIsModerator = user.role == Roles.MODERATOR_ROLE
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/styles.ts (4)

29-30: Consider marking new properties as optional if appropriate

The properties $highlight and $toolbarMenuIsOpen are added as required in the ChatWrapperProps interface. If these properties are not always provided, consider marking them as optional to enhance flexibility and prevent potential issues.

You can modify the interface as follows:

interface ChatWrapperProps {
  sameSender: boolean;
  isSystemSender: boolean;
  isPresentationUpload?: boolean;
  isCustomPluginMessage: boolean;
- $highlight: boolean;
- $toolbarMenuIsOpen: boolean;
+ $highlight?: boolean;
+ $toolbarMenuIsOpen?: boolean;
}

36-37: Consider marking new properties as optional if appropriate

Similarly, in the ChatContentProps interface, the properties $highlight and $toolbarMenuIsOpen are added as required. If they might not be provided in all cases, marking them as optional could be beneficial.

You can modify the interface as follows:

interface ChatContentProps {
  sameSender: boolean;
  isCustomPluginMessage: boolean;
- $highlight: boolean;
- $toolbarMenuIsOpen: boolean;
+ $highlight?: boolean;
+ $toolbarMenuIsOpen?: boolean;
}

219-223: Reevaluate styling choices for DeleteMessage component

Applying both font-style: italic; and font-weight: bold; to the DeleteMessage component may impact readability. It's uncommon to use italic and bold styles together, and it might be worth reconsidering to enhance clarity.

Consider if one style suffices or if an alternative styling approach would better convey the intended emphasis.


225-234: Ensure consistency in font sizing for ChatEditTime

The font-size is set to 75% in the ChatEditTime component. Verify that this sizing aligns with the application's typography guidelines and maintains readability across different devices and screen resolutions.

If a standard font size is used elsewhere, consider using that for consistency:

- font-size: 75%;
+ font-size: ${someStandardFontSizeVariable};

Ensure that someStandardFontSizeVariable matches the design system's defined sizes.

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

44-45: Consider renaming props 'own' and 'amIModerator' for clarity

Using more descriptive prop names enhances code readability and maintainability. Consider renaming own to isMessageOwner and amIModerator to isModerator for clearer intent and consistency with common naming conventions.

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

147-151: Simplify the 'hasToolbar' condition

To ensure that hasToolbar accurately reflects when the toolbar should be displayed, consider simplifying the check for message.deletedAt. Checking for falsiness will cover both null and undefined values.

Modify the condition as follows:

const hasToolbar = CHAT_TOOLBAR_CONFIG.length > 0
-   && message.deletedAt === null
+   && !message.deletedAt
    && !editing
    && !!message.user
    && !locked;

499-500: Include all relevant properties in 'areChatMessagesEqual' comparison

In the areChatMessagesEqual function, you compare several properties of prevMessage and nextMessage. Consider including additional properties that might affect the rendering, such as message.editedAt and message.deletedAt, to ensure the memoization is accurate.

Update the comparison:

return prevMessage?.createdAt === nextMessage?.createdAt
  && prevMessage?.user?.currentlyInMeeting === nextMessage?.user?.currentlyInMeeting
  && prevMessage?.recipientHasSeen === nextMessage.recipientHasSeen
  && prevMessage?.message === nextMessage.message
+ && prevMessage?.editedAt === nextMessage?.editedAt
+ && prevMessage?.deletedAt === nextMessage?.deletedAt;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0699456 and f0f87b9.

📒 Files selected for processing (9)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/groupchats/EditGroupChatMessageReqMsgHdlr.scala (1 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/component.tsx (14 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/message-toolbar/component.tsx (6 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/message-toolbar/styles.ts (3 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/styles.ts (5 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/component.tsx (2 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/queries.ts (3 hunks)
  • bigbluebutton-html5/private/config/settings.yml (2 hunks)
  • bigbluebutton-html5/public/locales/en.json (2 hunks)
🧰 Additional context used
🔇 Additional comments (17)
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-message-list/page/chat-message/message-toolbar/styles.ts (1)

Line range hint 70-82: Fix TypeScript issue in EmojiButton component

The @ts-ignore comment is still present, indicating that the TypeScript issue hasn't been addressed. It's important to resolve this for better type safety and maintainability.

To fix this, please follow these steps:

  1. Create an interface for the EmojiButton props that extends the Button component's props:
interface EmojiButtonProps extends React.ComponentProps<typeof Button> {
  // Add any additional props used in EmojiButton
}
  1. Use this interface in the styled component definition:
const EmojiButton = styled(Button)<EmojiButtonProps>`
  // ... existing styles
`;
  1. Remove the @ts-ignore comment.

This approach will improve type safety and make the code more maintainable.

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

53-53: Improved memoization logic for chat messages.

The addition of prevMessage?.message === nextMessage?.message to the equality check enhances the memoization logic. This change ensures that the component only re-renders when the actual content of the messages changes, not just when other properties are updated. This optimization can lead to better performance, especially in chat rooms with frequent updates to message metadata.


133-133: Verify the impact of removing the third argument in useCreateUseSubscription.

The removal of the third argument (true) from the useCreateUseSubscription hook call may affect how the subscription handles updates or initial data fetching. Please clarify the reasoning behind this change and confirm that it doesn't negatively impact the subscription behavior.

To ensure this change doesn't introduce any regressions, please run the following verification steps:

  1. Test the chat functionality thoroughly, paying special attention to message updates and initial loading.
  2. Verify that real-time updates are still working as expected.
  3. Check if there are any performance implications, especially for large chat rooms.
bigbluebutton-html5/private/config/settings.yml (2)

Line range hint 1-1103: Overall assessment of configuration changes

The changes in this configuration file partially support the PR objectives of adding the ability to edit and delete messages. However, there are a couple of points to consider:

  1. The askForConfirmationOnLeave setting change might need further discussion to ensure it aligns with the desired user experience.
  2. The chat toolbar configuration needs to be updated to actually enable the new edit and delete features.

Please review these suggestions and make the necessary adjustments to fully implement the intended functionality.


62-62: Consider the implications of disabling leave confirmation

The askForConfirmationOnLeave setting has been changed from true to false. This means users will no longer be prompted for confirmation when leaving a session. While this can improve user experience by reducing friction, it may also lead to accidental exits.

To ensure this change aligns with the intended user experience, please run the following verification:

Consider adding a comment explaining the rationale behind this change.

✅ Verification successful

Leave Confirmation Behavior Verified

The change to set askForConfirmationOnLeave to false has been verified. Users will no longer be prompted for confirmation when leaving a session, aligning with the desired user experience improvements.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if this change is mentioned in any recent pull requests or issues

gh pr list --search "askForConfirmationOnLeave" --limit 5
gh issue list --search "askForConfirmationOnLeave" --limit 5

Length of output: 434

bigbluebutton-html5/public/locales/en.json (6)

8-8: New error message for chat update looks good.

The addition of "app.chat.errorOnUpdateMessage" provides a clear error message for users when there's an issue updating a chat message. This aligns well with the new edit functionality being implemented.


43-43: New localization string for edit time is appropriate.

The addition of "app.chat.editTime" provides a clear way to display when a message was last edited. The use of a placeholder for the time value is good for localization purposes.


44-44: New localization string for deleted messages is well-formed.

The addition of "app.chat.deleteMessage" provides a clear placeholder for deleted messages, including information about who deleted it. This supports the new delete functionality and maintains transparency in the chat.


46-46: Updated localization string for edit action is concise.

The update to "app.chat.toolbar.edit" simplifies the text to just "Edit". This is clear and concise, which is good for UI elements like toolbar buttons.


47-47: Updated localization string for delete action is appropriate.

The update to "app.chat.toolbar.delete" simplifies the text to just "Delete". This is clear and concise, which is good for UI elements like toolbar buttons.


Line range hint 1-1024: Localization updates for chat edit and delete features are comprehensive.

The changes to this localization file adequately support the new chat message editing and deleting functionalities. New strings have been added for error handling, displaying edit times, and showing placeholders for deleted messages. The toolbar action strings have been updated to be more concise. These changes align well with the PR objectives and should provide a good user experience for the new features.

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

62-75: Ensure 'replyToMessage' fields are consistent

In the CHAT_MESSAGE_PRIVATE_SUBSCRIPTION, the replyToMessage includes several fields. Confirm that these fields are consistent with those in the public subscription, and that the client components can handle them appropriately. Consistency helps prevent unexpected bugs and simplifies maintenance.

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

90-93: 🛠️ Refactor suggestion

Remove redundant styling inside combined conditional

Since the styles for $toolbarMenuIsOpen are now included in the combined condition, the separate conditional block can be removed to prevent redundancy.

You can remove the redundant block:

- ${({ sameSender, $toolbarMenuIsOpen }) => !sameSender && $toolbarMenuIsOpen && `
-   background-color: ${colorOffWhite};
-   border-radius: 6px;
- `}

Likely invalid or redundant comment.

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

20-21: Ensure 'DeleteMessage' and 'ChatEditTime' are exported from './styles'

The imports DeleteMessage and ChatEditTime should be correctly exported from the ./styles file. Verify that these components are exported as named exports to prevent import errors.


469-470: Correct the usage of 'intl.formatMessage' with proper variable names

Using { 0: value } in intl.formatMessage is unconventional. It's better to use meaningful variable names matching the placeholders in your messages to improve readability and maintainability.

Also applies to: 474-475


123-124: Use 'useRef' instead of 'createRef' in functional components

The messageRef and messageContentRef are defined using React.createRef(), which is intended for class components. In functional components, it's recommended to use useRef to create refs.


479-488: Ensure 'ChatEditMessageForm' receives all necessary props

When rendering the ChatEditMessageForm, make sure that all required props are provided and correctly typed. This ensures that the form functions properly and avoids potential runtime errors.

Please confirm that ChatEditMessageForm accepts these props and that their types match the expected definitions.

Comment on lines +771 to +772
# available options for toolbar: reply, edit, delete
# example: ['reply', 'delete']

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

Update chat toolbar configuration to enable new features

The comment for chat toolbar options has been updated to include "edit" and "delete" capabilities. However, the actual configuration (toolbar: []) remains empty. To fully implement the new features mentioned in the PR objectives, consider updating the configuration as follows:

-    toolbar: []
+    toolbar: ['reply', 'edit', 'delete']

This change will enable the new editing and deleting functionalities for chat messages, aligning with the PR's objectives.

Committable suggestion was skipped due to low confidence.

Comment on lines +16 to +19
deletedAt
deletedBy {
name
}

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 including 'userId' in 'deletedBy' for consistency

In the replyToMessage, you've added deletedBy { name }. To maintain consistency with other user objects and to uniquely identify users, consider including userId within deletedBy. This will help in accurately identifying the user who deleted the message.

Apply this diff to include userId:

      replyToMessage {
        deletedAt
        deletedBy {
          name
+         userId
        }
        chatEmphasizedText
        messageSequence
        message
        user {
          name
          color
        }
      }
📝 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
deletedAt
deletedBy {
name
}
deletedAt
deletedBy {
name
userId
}

Comment on lines +34 to 38
deletedAt
deletedBy {
name
}
messageMetadata

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

Include 'userId' in 'deletedBy' for better identification

Similarly, in the main message object, including userId in deletedBy { name } would facilitate better user identification and maintain consistency across your data structures.

Apply this diff:

      deletedAt
      deletedBy {
        name
+       userId
      }
📝 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
editedAt
deletedAt
deletedBy {
name
}
editedAt
deletedAt
deletedBy {
name
userId
}

🛠️ Refactor suggestion

Consider adding 'editedBy' field for completeness

While you've added editedAt to indicate when a message was edited, consider adding an editedBy field to record who performed the edit. This enhances traceability and can be useful for audit purposes or displaying editor information in the UI.

Update the subscription to include editedBy:

      editedAt
+     editedBy {
+       name
+       userId
+     }
      deletedAt

Committable suggestion was skipped due to low confidence.

Comment on lines +82 to 86
deletedAt
deletedBy {
name
}
messageMetadata

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

Include 'userId' in 'deletedBy' and consider adding 'editedBy'

As with the public subscription, consider including userId in deletedBy and adding an editedBy field to the private subscription. This ensures consistency and provides complete information for user identification.

Apply this diff:

      deletedAt
      deletedBy {
        name
+       userId
      }
+     editedBy {
+       name
+       userId
+     }
📝 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
editedAt
deletedAt
deletedBy {
name
}
editedAt
deletedAt
deletedBy {
name
userId
}
editedBy {
name
userId
}

}

if (!chatDisabled && editChatMessageDisabled && !(applyPermissionCheck && chatLocked) && !chatLockedForUser) {
if (!chatDisabled && !editChatMessageDisabled && !(applyPermissionCheck && chatLocked) && !chatLockedForUser) {

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 simplifying the conditional statement for better readability

The conditional logic at line 48 is complex. Extracting it into a well-named Boolean variable can improve readability and maintainability.

For example:

val canEditMessage = !chatDisabled && !editChatMessageDisabled && !(applyPermissionCheck && chatLocked) && !chatLockedForUser

if (canEditMessage) {
  // existing code
}

Comment on lines +113 to +116
${({ sameSender, $toolbarMenuIsOpen }) => sameSender && $toolbarMenuIsOpen && `
background-color: ${colorOffWhite};
border-radius: 6px;
`}

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

Eliminate redundant styling due to refactoring

After combining the conditional styles, the separate block for $toolbarMenuIsOpen becomes unnecessary and can be removed to avoid redundancy.

You can remove the redundant block:

- ${({ sameSender, $toolbarMenuIsOpen }) => sameSender && $toolbarMenuIsOpen && `
-   background-color: ${colorOffWhite};
-   border-radius: 6px;
- `}
📝 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
${({ sameSender, $toolbarMenuIsOpen }) => sameSender && $toolbarMenuIsOpen && `
background-color: ${colorOffWhite};
border-radius: 6px;
`}

Comment on lines +106 to +116
${({ sameSender, $highlight }) => sameSender && $highlight && `
&:hover {
background-color: ${colorOffWhite};
}
border-radius: 6px;
`}

${({ sameSender, $toolbarMenuIsOpen }) => sameSender && $toolbarMenuIsOpen && `
background-color: ${colorOffWhite};
border-radius: 6px;
`}

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

Refactor to combine similar conditional styles in ChatContent

In ChatContent, the conditional styling for $highlight and $toolbarMenuIsOpen can also be combined to eliminate duplication and streamline the code.

You can refactor as follows:

${({ sameSender, $highlight, $toolbarMenuIsOpen }) => sameSender && ($highlight || $toolbarMenuIsOpen) && `
-  &:hover {
-    background-color: ${colorOffWhite};
-  }
+  background-color: ${colorOffWhite};
  border-radius: 6px;
`}

This approach consolidates the styles for when either $highlight or $toolbarMenuIsOpen is true.

📝 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
${({ sameSender, $highlight }) => sameSender && $highlight && `
&:hover {
background-color: ${colorOffWhite};
}
border-radius: 6px;
`}
${({ sameSender, $toolbarMenuIsOpen }) => sameSender && $toolbarMenuIsOpen && `
background-color: ${colorOffWhite};
border-radius: 6px;
`}
${({ sameSender, $highlight, $toolbarMenuIsOpen }) => sameSender && ($highlight || $toolbarMenuIsOpen) && `
background-color: ${colorOffWhite};
border-radius: 6px;
`}

Comment on lines +84 to +93
${({ sameSender, $highlight }) => !sameSender && $highlight && `
&:hover {
background-color: ${colorOffWhite};
}
border-radius: 6px;
`}
${({ sameSender, $toolbarMenuIsOpen }) => !sameSender && $toolbarMenuIsOpen && `
background-color: ${colorOffWhite};
border-radius: 6px;
`}

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

Refactor to reduce code duplication in conditional styles

The conditional styling blocks for $highlight and $toolbarMenuIsOpen in ChatWrapper are similar and can be combined to reduce duplication and improve maintainability.

You can refactor the code as follows:

${({ sameSender, $highlight, $toolbarMenuIsOpen }) => !sameSender && ($highlight || $toolbarMenuIsOpen) && `
-  &:hover {
-    background-color: ${colorOffWhite};
-  }
+  background-color: ${colorOffWhite};
  border-radius: 6px;
`}

This ensures that the background color and border radius are applied when either $highlight or $toolbarMenuIsOpen is true.

Committable suggestion was skipped due to low confidence.

Comment on lines +93 to +109
if (CHAT_DELETE_ENABLED && (own || amIModerator)) {
const customStyles = { background: colorDanger, color: colorWhite };
actions.push({
key: 'delete',
icon: 'delete',
label: 'Delete',
onClick: () => null,
label: intl.formatMessage(intlMessages.delete),
customStyles,
onClick: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
e.stopPropagation();

chatDeleteMessage({
variables: {
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.

⚠️ Potential issue

Add confirmation prompt before deleting messages

Deleting a message without user confirmation may lead to accidental deletions. To enhance user experience and prevent unintended data loss, consider adding a confirmation dialog before executing the delete action.

Apply this diff to add a confirmation prompt:

 onClick: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
   e.stopPropagation();
+  if (window.confirm('Are you sure you want to delete this message?')) {
     chatDeleteMessage({
       variables: {
         chatId,
         messageId,
       },
     });
+  }
 },
📝 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
if (CHAT_DELETE_ENABLED && (own || amIModerator)) {
const customStyles = { background: colorDanger, color: colorWhite };
actions.push({
key: 'delete',
icon: 'delete',
label: 'Delete',
onClick: () => null,
label: intl.formatMessage(intlMessages.delete),
customStyles,
onClick: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
e.stopPropagation();
chatDeleteMessage({
variables: {
chatId,
messageId,
},
});
},
if (CHAT_DELETE_ENABLED && (own || amIModerator)) {
const customStyles = { background: colorDanger, color: colorWhite };
actions.push({
key: 'delete',
icon: 'delete',
label: intl.formatMessage(intlMessages.delete),
customStyles,
onClick: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
e.stopPropagation();
if (window.confirm('Are you sure you want to delete this message?')) {
chatDeleteMessage({
variables: {
chatId,
messageId,
},
});
}
},

};
}
}, []);
}, [message.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

Include all used 'message' properties in useMemo dependencies

The useMemo hook depends on several properties of the message object inside its calculation. Currently, the dependencies array only includes message.message. This can lead to stale memoized values if other properties of message change.

Update the dependencies array to include all the message properties used within the useMemo:

- }, [message.message]);
+ }, [
+   message.message,
+   message.messageType,
+   message.messageMetadata,
+   message.user,
+   message.replyToMessage,
+   message.chatEmphasizedText,
+ ]);
📝 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
}, [message.message]);
}, [
message.message,
message.messageType,
message.messageMetadata,
message.user,
message.replyToMessage,
message.chatEmphasizedText,
]);

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

attempting to copy or save the chat from the chat menu causes an error if any message has been deleted

Screenshot from 2024-10-14 14-40-56

@sonarqubecloud

Copy link
Copy Markdown

@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: 0

🧹 Outside diff range and nitpick comments (3)
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-header/chat-actions/queries.ts (1)

Line range hint 6-9: Update the getChatMessageHistory type definition.

The getChatMessageHistory type should be updated to include the new deletedBy field in the Message type. This ensures type safety and consistency with the GraphQL query.

Consider updating the type definition as follows:

export type getChatMessageHistory = {
  chat_message_public: Array<Message & { deletedBy?: { name: string } }>;
  meeting: Array<Meeting>;
  user_welcomeMsgs: Array<{welcomeMsg: string, welcomeMsgForModerators: string | null}>;
};

Alternatively, if the Message type is defined elsewhere, update it to include the deletedBy field.

bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-header/chat-actions/services.ts (2)

24-27: LGTM! Consider adding a description for the new message.

The new deleteMessage entry is correctly formatted and follows the existing pattern. However, the description field is empty. Consider adding a brief description to maintain consistency with other entries and improve code documentation.

 deleteMessage: {
   id: 'app.chat.deleteMessage',
-  description: '',
+  description: 'Message displayed when a chat message has been deleted',
 },

77-79: LGTM! Consider adding a comment for clarity.

The changes effectively handle deleted messages in the chat export. The conditional check for message.message and the use of the new deleteMessage entry improve the functionality.

Consider adding a brief comment to explain the purpose of this conditional check:

+ // Handle deleted messages
 messageText = message.message
   ? htmlDecode(message.message)
   : intl.formatMessage(intlMessages.deleteMessage, { 0: message.deletedBy?.name });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f0f87b9 and 2315887.

📒 Files selected for processing (2)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-header/chat-actions/queries.ts (1 hunks)
  • bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-header/chat-actions/services.ts (2 hunks)
🧰 Additional context used
🔇 Additional comments (3)
bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-header/chat-actions/queries.ts (2)

27-29: LGTM! The addition of deletedBy field enhances message deletion tracking.

The inclusion of the deletedBy field in the chat_message_public selection set is a good addition. It aligns with the PR objective of adding message deletion functionality and will allow the UI to display information about who deleted a message.


27-29: Verify the impact on components consuming this query.

The addition of the deletedBy field may affect components that use the results of this query. Ensure that these components are updated to handle the new field appropriately.

Run the following script to identify components that might be affected:

Please review the output and update the affected components to handle the new deletedBy field.

✅ Verification successful

Please run the following updated script to identify components that might be affected:


Impact Verified

No components currently consume the GET_CHAT_MESSAGE_HISTORY query. Therefore, the addition of the deletedBy field does not affect any components.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find components that import and use the GET_CHAT_MESSAGE_HISTORY query

# Search for files that import the GET_CHAT_MESSAGE_HISTORY query
echo "Files importing GET_CHAT_MESSAGE_HISTORY:"
rg --type typescript --type typescript "import.*GET_CHAT_MESSAGE_HISTORY" bigbluebutton-html5/imports/ui/components/

# Search for usage of chat_message_public in components
echo "\nUsage of chat_message_public in components:"
rg --type typescript --type typescript "chat_message_public" bigbluebutton-html5/imports/ui/components/

Length of output: 486


Script:

#!/bin/bash
# Description: Find components that import and use the GET_CHAT_MESSAGE_HISTORY query

# Search for files that import the GET_CHAT_MESSAGE_HISTORY query
echo "Files importing GET_CHAT_MESSAGE_HISTORY:"
rg "import.*GET_CHAT_MESSAGE_HISTORY" bigbluebutton-html5/imports/ui/components/ --glob "*.ts" --glob "*.tsx"

# Search for usage of chat_message_public in components
echo "\nUsage of chat_message_public in components:"
rg "chat_message_public" bigbluebutton-html5/imports/ui/components/ --glob "*.ts" --glob "*.tsx"

Length of output: 1398

bigbluebutton-html5/imports/ui/components/chat/chat-graphql/chat-header/chat-actions/services.ts (1)

Line range hint 1-103: Overall, the changes effectively implement deleted message handling.

The modifications to this file align well with the PR objectives of adding support for deleting messages. The implementation is focused and maintains the existing code structure while enhancing the chat export functionality to handle deleted messages appropriately.

@github-actions

Copy link
Copy Markdown

Automated tests Summary

✅ All the CI tests have passed!

@ramonlsouza
ramonlsouza merged commit d2afb28 into bigbluebutton:v3.0.x-release Oct 14, 2024
JoVictorNunes added a commit to JoVictorNunes/bigbluebutton that referenced this pull request Oct 15, 2024
ramonlsouza pushed a commit that referenced this pull request Oct 16, 2024
* feat(chat): message reactions

* fix: Revert settings.yml change introduced in #21355
@antobinary antobinary added this to the Release 3.0 milestone Oct 21, 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