Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@igennova
Copy link
Contributor

@igennova igennova commented Apr 16, 2025

fixes #3681

Summary by CodeRabbit

  • New Features

    • Reactions are now displayed as interactive buttons with counts directly on each message, both for existing and new messages.
    • Quick reaction buttons (👍, ❤️, 😊, 👏, 🔥) are available for easy access if not already used.
  • Improvements

    • The reactions UI updates dynamically and consistently, ensuring a unified experience for all users.
    • Enhanced error handling and debug information for reaction-related actions.
    • The "add reaction" button now uses a plus sign (+) emoji for clarity.
    • Reaction data is embedded in message elements to unify handling between server and client updates.
  • Style

    • Improved layout and styling for the reactions container, including flexible wrapping and minimum height.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 16, 2025

"""

Walkthrough

The changes update the chat message reactions feature in the join_room.html template. Reaction data is now embedded as a JSON string in a data-reactions attribute for each message element. Both server-rendered and dynamically appended messages use this format. The JavaScript logic for updating reactions is revised to dynamically rebuild the reaction buttons, display counts, and add default quick reaction buttons if needed. The UI for adding reactions is unified, the emoji picker button changes from a smiley to a plus sign, and error handling and logging are enhanced. Additional CSS ensures proper layout of the reactions container.

Changes

File(s) Change Summary
website/templates/join_room.html - Embed reactions as JSON in data-reactions for each message
- Major rewrite of updateReactions to dynamically rebuild reaction UI, add quick reactions, and improve error handling
- Update event listeners for new reaction buttons
- Change emoji picker button from smiley to plus sign
- Enhance logging and debug output
- Add CSS for reactions container layout

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant DOM
    participant JS
    participant WebSocket

    User->>DOM: Loads page (messages rendered with data-reactions)
    JS->>DOM: On DOMContentLoaded, setup event listeners
    User->>JS: Clicks reaction button or quick reaction
    JS->>WebSocket: Sends add reaction request
    WebSocket->>JS: Sends reaction update message
    JS->>DOM: Updates data-reactions and calls updateReactions
    JS->>DOM: Rebuilds reaction buttons, updates UI
Loading

Assessment against linked issues

Objective Addressed Explanation
Add emoji reactions to the chat messages (#3681)
"""

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f27a424 and 483545b.

📒 Files selected for processing (1)
  • website/templates/join_room.html (10 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • website/templates/join_room.html
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Run Tests
  • GitHub Check: Analyze (python)
  • GitHub Check: docker-test

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

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

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (5)
website/templates/join_room.html (5)

28-28: Ensure safe JSON encoding for data attributes.

Embedding reactions as a JSON string in data-reactions is a good approach for synchronizing state. However, ensure that the escapejs filter is always used and that the data is never too large to fit comfortably in a data attribute. If reactions grow large, consider a more scalable approach (e.g., fetching on demand).


35-67: Server-rendered reactions logic is robust and user-friendly.

The template logic for rendering both existing reactions and default quick reactions is clear and matches the new client-side approach. Good use of accessibility features (button, span, title). Consider adding aria-label attributes for better screen reader support.


406-467: updateReactions function is robust, but consider accessibility and performance.

  • The function now robustly clears and rebuilds the reactions container, handling both existing and quick reactions.
  • Good use of logging and error handling.
  • Consider adding aria-label to dynamically created buttons for accessibility.
  • If the number of reactions grows, rebuilding the entire container on every update could be inefficient; consider diffing or partial updates if performance becomes an issue.

529-530: Debug logging for WebSocket messages is helpful for development.

Consider gating these logs behind a debug flag or removing them in production for cleaner console output.


636-637: Console log on DOMContentLoaded is useful for debugging.

As with other logs, consider removing or gating in production.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1a4840a and 3008a43.

📒 Files selected for processing (1)
  • website/templates/join_room.html (10 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run Tests
  • GitHub Check: docker-test
🔇 Additional comments (6)
website/templates/join_room.html (6)

69-69: Emoji picker button change is clear and intuitive.

Switching from a smiley to a "+" for the add reaction button is a sensible UI choice, making the action clearer to users.


475-476: Correct use of JSON.stringify for embedding reactions in new messages.

This ensures consistency between server-rendered and client-side messages. Good practice.


522-523: Immediate initialization of reactions for new messages is correct.

Calling updateReactions right after appending a new message ensures the UI is always in sync.


545-550: Synchronizing data-reactions attribute on reaction updates is correct.

This ensures the DOM always reflects the latest state, which is important for consistency and debugging.


667-677: Event listeners for server-rendered reaction buttons are correctly set up.

This ensures that all reaction buttons, even those rendered on page load, are interactive. No issues found.


705-721: CSS for reactions container improves layout and usability.

The new styles ensure reactions are always visible and wrap as needed. Good use of flexbox.

coderabbitai[bot]
coderabbitai bot previously approved these changes Apr 16, 2025
DonnieBLT
DonnieBLT previously approved these changes Apr 22, 2025
@DonnieBLT DonnieBLT added this pull request to the merge queue Apr 22, 2025
@github-merge-queue github-merge-queue bot removed this pull request from the merge queue due to failed status checks Apr 22, 2025
@igennova igennova dismissed stale reviews from coderabbitai[bot] and DonnieBLT via 61450a9 May 2, 2025 08:02
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (6)
website/templates/join_room.html (6)

408-424: Review debug logging and early exit checks in updateReactions
You’ve added console.log and two console.warn calls to trace missing elements, then clear the container. For production, consider gating verbose logs behind a debug flag or removing them to avoid console clutter. The early returns are a good safety net.


451-462: DRY up common quick reaction button creation
The loop for commonEmojis duplicates markup found elsewhere (e.g., in appendMessage). Extract a helper function or template to reduce duplication. Also, switch from innerHTML to textContent when inserting the emoji to further mitigate XSS concerns.


465-468: Enhance error messaging in the catch block
The catch logs the raw error and shows a generic notification. Consider including messageId or more context in the notification (e.g., "Failed to update reactions for message ${messageId}") to aid debugging.


531-531: Remove or gate raw WebSocket message logging
console.log('Received websocket message:', data); is useful for debugging but may expose sensitive chat payloads in production. Wrap it in a debug check or remove once validated.


638-638: Remove initialization debug log
The console.log('DOM loaded, initializing chat room...'); is helpful during development but should be removed or wrapped under a verbose/debug flag in production.


680-687: Bind click handlers to “add reaction” buttons
Setting up the .add-reaction-btn event listeners for pre-rendered messages duplicates logic in appendMessage. Extract this into a shared initializer to avoid drift if the handler signature changes.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3008a43 and 61450a9.

📒 Files selected for processing (1)
  • website/templates/join_room.html (10 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run Tests
  • GitHub Check: docker-test
🔇 Additional comments (10)
website/templates/join_room.html (10)

27-28: Embed reaction metadata on each message element
You’ve added data-message-id and data-reactions attributes to the .message-item div, embedding the JSON‐escaped reactions payload directly into the DOM. This aligns server‐rendered messages with the client‐side update logic.


35-36: Define a dedicated reactions container with min-height
The new <div class="reactions-container … min-h-[28px]"> ensures consistent layout even when no reactions are present. This change stabilizes the UI across messages of varying reaction counts.


38-48: Render existing reactions server‐side
Looping over message.reactions.items to output buttons with counts puts initial state directly in the template, reducing the flash of empty state before JS hydrates. Ensure that the emoji and users|length values are always safe (they are internal, so risk is low).


50-65: Provide default quick‐reaction buttons when no reactions exist
Good fallback logic. Note that the server‐rendered defaults are 👍, ❤️, 😊, whereas the client’s commonEmojis array includes 👏 and 🔥 as well. Please verify that this divergence is intentional for UX consistency.


69-69: Switch “add reaction” icon from smiley to plus
Updating the emoji‐picker trigger to “+” simplifies the action affordance. This is a clear UX improvement.


477-478: Embed reactions dataset for dynamically appended messages
Mirroring the server rendering by setting messageDiv.dataset.reactions = JSON.stringify(data.reactions || {}); ensures that newly received messages have the same data structure for hydration. Well done.


525-526: Initialize reactions UI immediately after appending a message
Calling updateReactions(data.message_id, data.reactions || {}); right after insertion ensures the UI is up-to-date without waiting for a separate WS update. Clean and effective.


547-554: Fully handle reaction_update events
You correctly update the element’s data-reactions attribute and then call updateReactions. This keeps both the DOM and JS state synchronized. Ensure incoming data.reactions is always a valid object to avoid JSON‐parsing errors.


669-677: Bind click handlers to existing reaction buttons
Attaching listeners to .reaction-btn elements at DOMContentLoaded ensures server‐rendered buttons work without additional calls to updateReactions. Good use of addEventListener.


719-723: Append CSS to support flexible wrapping of reactions
Your injected style ensures .reactions-container flex‐wraps and honors a minimum height, preventing layout shifts. This is a solid fix for responsive behavior.

coderabbitai[bot]
coderabbitai bot previously approved these changes May 2, 2025
@igennova igennova requested a review from DonnieBLT May 2, 2025 08:10
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (2)
website/templates/join_room.html (2)

441-447: Avoid innerHTML to prevent XSS.

Building reactionButton.innerHTML with ${emoji} and ${users.length} can introduce XSS risks if these values are ever user-controlled. Instead, create child <span> elements and assign .textContent to emoji and the count to ensure safe insertion.


456-460: Sanitize quick reaction button labels.

Similar to existing reactions, using innerHTML for <span>${emoji}</span> could pose injection risks. Construct the <span> via document.createElement('span') and set .textContent = emoji. This change eliminates any potential for HTML injection.

🧹 Nitpick comments (6)
website/templates/join_room.html (6)

50-65: Fallback to default quick reactions.

Providing default emojis when there are no reactions improves discoverability. However, the list here (👍, ❤️, 😊) differs from the JS-side commonEmojis (['👍','❤️','😊','👏','🔥']). Consider centralizing the default emoji list in a shared context variable or constant to avoid discrepancies.


69-69: Improve accessibility for “add reaction” button.

Changing the span from “😀” to “+” clarifies intent. To further improve accessibility, add an aria-label="Add reaction" or visually hidden text so screen readers announce the button’s purpose.


408-415: Review debug logging in production.

The initial console.log and console.warn calls help during development but may clutter the console in production. Consider gating these logs behind a debug flag or using a logging library that can adjust verbosity levels.


638-639: Remove or guard initial debug log.

console.log('DOM loaded, initializing chat room...') is useful for debuggers. In production, wrap such logs under a debug condition or remove them to avoid unnecessary console noise.


669-677: Deduplicate event listener setup.

Event listeners for .reaction-btn and .add-reaction-btn are registered both here and in appendMessage. Consider extracting this into a helper (e.g., initReactionButtons(container)) and calling it in both places to adhere to DRY principles.


719-723: Move inline style injection to a CSS file.

Injecting styles via JavaScript can complicate maintenance and make them harder to override. It would be cleaner to place these .reactions-container styles in your Tailwind config or a dedicated CSS file, leveraging existing build tooling.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 61450a9 and f27a424.

📒 Files selected for processing (1)
  • website/templates/join_room.html (9 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Run Tests
  • GitHub Check: docker-test
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (4)
website/templates/join_room.html (4)

35-47: Server-render existing reaction buttons.

This block directly renders existing reactions with counts, reducing the flash-of-unstyled-content before JS kicks in. The logic correctly skips empty user lists. Ensure CSS (min-h-[28px]) and layout handle multiple reaction buttons gracefully.


477-478: Embed reactions for new messages.

Embedding data-reactions on dynamically added messages ensures that updateReactions has the necessary initial state. Confirm that data.reactions from the WebSocket payload is always a well-formed object to prevent runtime errors.


524-526: Initialize reactions after appending messages.

Calling updateReactions immediately after adding the new message populates both existing and quick-reaction buttons without additional logic elsewhere. This is concise and aligns with the server-rendered flow.


547-553: Synchronize dataset on reaction updates.

Updating messageElement.dataset.reactions before calling updateReactions keeps the DOM attribute in sync with the latest state. This is helpful if any other logic relies on the attribute. Ensure JSON is stringified consistently.

coderabbitai[bot]
coderabbitai bot previously approved these changes May 2, 2025
@DonnieBLT DonnieBLT enabled auto-merge May 2, 2025 19:51
@DonnieBLT DonnieBLT added this pull request to the merge queue May 2, 2025
Merged via the queue into OWASP-BLT:main with commit ef7668b May 2, 2025
12 checks passed
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.

Add emoji reactions to the chat messages

2 participants