Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BA-1912: render newly created chats in chatrooms list #147

Merged
merged 3 commits into from
Dec 12, 2024

Conversation

pt-tsl
Copy link
Contributor

@pt-tsl pt-tsl commented Dec 6, 2024

Acceptance Criteria
Context
Right now, I need to refresh the page in order for a new chat to appear in the chat list. We need to fix it in order to make the experience smoother.

Business Rules

  • Given I create a new chat, when the chat creation is successful, then the new chat should automatically appear at the top of my active chat list without needing a page refresh.

  • Given a new chat is created by another user involving me, when the chat is successfully created, then the new chat should appear in my active chat list automatically.

  • Given there is an issue adding the new chat to my active chat list, when an error occurs, then I should receive an error message prompting me to refresh or retry. (Designs Pending)

  • Create backend automated test for subscription

  • Include test that check permission for the subscription.

  • Fix any backend bugs with this subscription in order to have it work properly.

  • Talk to AA about updating the subscriptions for the messages as well, let me know if more budget will be needed for the messages

Summary by CodeRabbit

  • New Features

    • Enhanced chat room functionality with archiving capabilities.
    • Introduced a new subscription hook for room lists.
    • Updated filtering logic to exclude the current user's profile from chat room lists.
  • Bug Fixes

    • Fixed connection handling in the RoomListSubscription.
  • Documentation

    • Updated changelog for version 0.0.29 to reflect recent changes.
  • Type Updates

    • Added new types and updated existing types to improve clarity and functionality.

Copy link

changeset-bot bot commented Dec 6, 2024

⚠️ No Changeset found

Latest commit: 32c764f

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link

coderabbitai bot commented Dec 6, 2024

Walkthrough

The pull request introduces several updates across various components related to chat room functionality. Key changes include the addition of the useMessageCountUpdate hook in the ChatRoomsList, improved connection handling in the ChatRoomListItem, and the incorporation of the current user's profile in the CreateChatRoomList. Additionally, modifications to GraphQL mutations and subscriptions enhance the management of chat rooms and participants. The overall structure and existing functionalities of components are preserved while refining their operations.

Changes

File Path Change Summary
packages/components/modules/messages/ChatRoomsList/index.tsx Added import for useMessageCountUpdate and updated subscription logic to include it without parameters, maintaining existing structure and control flow.
packages/components/modules/messages/CreateChatRoomList/ChatRoomListItem/index.tsx Updated import for useFragment to include ConnectionHandler, added connections property to commit function, simplified onCompleted callback.
packages/components/modules/messages/CreateChatRoomList/index.tsx Introduced import for useCurrentProfile, modified filtering logic to exclude current user's profile, and adjusted rendering logic accordingly.
packages/components/modules/messages/graphql/mutations/CreateChatRoom.ts Updated CreateChatRoomMutation to include a new $connections parameter and modified type definitions for clarity.
packages/components/modules/messages/graphql/queries/RoomsList.ts Removed unreadMessagesCount and id fields from RoomsListFragment and chatRooms connection.
packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx Renamed subscription query to RoomListSubscriptionQuery, added $connections parameter, and streamlined subscription setup by removing updater logic.
packages/components/modules/messages/index.ts Added default export for useRoomListSubscription function.
packages/components/CHANGELOG.md Updated changelog for version 0.0.29 to reflect changes including RoomListSubscription fix and CreateChatRoom connection addition.
packages/components/modules/messages/CreateChatRoomList/types.ts Introduced new exported type ProfileEdge derived from AllProfilesEdges.
packages/components/package.json Updated version from 0.0.28 to 0.0.29.
packages/components/modules/messages/ChatRoom/index.tsx Modified imports and destructuring for currentProfile, added useRef hooks, and updated useEffect logic for better state management.
packages/components/modules/messages/ChatRoomsList/ChatRoomItem/index.tsx Updated import for useCurrentProfile, renamed destructured profile to currentProfile, and refactored rendering logic for last message.
packages/components/schema.graphql Enhanced GraphQL schema with new fields and input types related to chat room archiving and participant management, including isArchivedByCurrentProfile and ChatRoomArchiveInput.

Possibly related PRs

Suggested reviewers

  • Ronan-Fernandes
  • anicioalexandre
  • deboracosilveira

🐰 In the chat rooms where we play,
New messages count, brightens the day!
With profiles updated, we hop and cheer,
Archiving chats, keeping them near.
Connections enhanced, all clear as a bell,
In our cozy burrow, all is well! 🐇✨


📜 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 e10730f632b56fb9449e6a191cb11725eaca2b81 and 32c764f.

📒 Files selected for processing (2)
  • packages/components/CHANGELOG.md (1 hunks)
  • packages/components/package.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/components/package.json
  • packages/components/CHANGELOG.md

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 generate docstrings to generate docstrings for this PR. (Experiment)
  • @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

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

🧹 Outside diff range and nitpick comments (3)
packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (2)

5-6: Consider renaming the subscription constant for consistency

The constant RoomListSubscriptionQuery could be renamed to useRoomListSubscriptionQuery to match the naming convention of the hook and improve code consistency.

Apply this diff:

-const RoomListSubscriptionQuery = graphql`
+const useRoomListSubscriptionQuery = graphql`

26-28: Enhance error handling in the subscription

Using console.error directly may not provide the best user experience. Consider integrating the error handling with your application's notification system to inform users when subscription errors occur.

Apply this diff to improve error handling:

  return {
    subscription: RoomListSubscriptionQuery,
-   onError: console.error,
+   onError: (error) => {
+     // Replace with your error handling logic
+     console.error(error);
+     // Example: sendToast(error.message, { type: 'error' });
+   },
    variables: {
      profileId,
      connections: [connectionId],
    },
  }
packages/components/modules/messages/graphql/mutations/CreateChatRoom.ts (1)

Line range hint 9-21: Add error handling for mutation response errors

Currently, the onCompleted function does not handle errors returned in response.chatRoomCreate.errors. To ensure proper error reporting, consider checking and handling these errors.

Apply this diff to handle mutation errors:

  onCompleted: (response, errors) => {
    errors?.forEach((error) => {
      sendToast(error.message, { type: 'error' })
    })
+   if (response.chatRoomCreate.errors) {
+     response.chatRoomCreate.errors.forEach((error) => {
+       sendToast(error.messages.join(', '), { type: 'error' })
+     })
+     return
+   }
    setChatRoom({
      id: response?.chatRoomCreate?.room?.node?.id,
      participants: response?.chatRoomCreate?.room?.node?.participants?.edges?.map(
        (edge: any) => edge?.node?.id,
      ),
    })
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f889c17 and 30f71b42a01f1a91a16ab2c96cffd94825697eaf.

⛔ Files ignored due to path filters (4)
  • packages/components/__generated__/ChatRoomsQuery.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/CreateChatRoomMutation.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/RoomsListFragment.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/useRoomListSubscription.graphql.ts is excluded by !**/__generated__/**
📒 Files selected for processing (7)
  • packages/components/modules/messages/ChatRoomsList/index.tsx (0 hunks)
  • packages/components/modules/messages/CreateChatRoomList/ChatRoomListItem/index.tsx (2 hunks)
  • packages/components/modules/messages/CreateChatRoomList/index.tsx (3 hunks)
  • packages/components/modules/messages/graphql/mutations/CreateChatRoom.ts (3 hunks)
  • packages/components/modules/messages/graphql/queries/RoomsList.ts (0 hunks)
  • packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (1 hunks)
  • packages/components/modules/messages/index.ts (1 hunks)
💤 Files with no reviewable changes (2)
  • packages/components/modules/messages/ChatRoomsList/index.tsx
  • packages/components/modules/messages/graphql/queries/RoomsList.ts
🔇 Additional comments (5)
packages/components/modules/messages/index.ts (1)

30-30: Export useRoomListSubscription

Good job adding the export for useRoomListSubscription. This ensures the subscription hook is accessible throughout the application.

packages/components/modules/messages/CreateChatRoomList/ChatRoomListItem/index.tsx (1)

9-9: Import ConnectionHandler to manage Relay connections

Including ConnectionHandler is essential for properly handling Relay connections and updating the store.

packages/components/modules/messages/CreateChatRoomList/index.tsx (3)

16-16: Import useCurrentProfile to access current user

Good job importing useCurrentProfile to obtain the current user's profile for filtering purposes.


43-44: Ensure currentProfile is defined before usage

While extracting currentProfile, ensure it is not undefined to prevent potential runtime errors.

Would you like to implement a check or fallback in case currentProfile is undefined?


60-63: Exclude current user from the profiles list

Filtering out the current user's profile prevents them from messaging themselves, which is a good user experience practice.

Comment on lines 21 to 26
// TODO: add filter handling (for now we can default 'unreadMessages' to false)
const connectionId = ConnectionHandler.getConnectionID(profileId, 'roomsList_chatRooms', {
unreadMessages: false,
})
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Address the TODO: Implement dynamic filter handling

There's a TODO comment indicating that filter handling should be added. Currently, the unreadMessages filter is hardcoded to false. Implementing dynamic filters will enhance the flexibility of your subscription.

Would you like assistance in implementing dynamic filter handling for the unreadMessages parameter?

Comment on lines +52 to 54
(edge: any) => edge?.node?.id,
),
})
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Avoid using any type for better type safety

Using edge: any reduces the benefits of TypeScript's type safety. Define a specific type for edge to enhance code reliability.

Apply this diff:

-            (edge: any) => edge?.node?.id,
+            (edge: { node: { id: string } }) => edge.node.id,
📝 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
(edge: any) => edge?.node?.id,
),
})
(edge: { node: { id: string } }) => edge.node.id,
),
})

Comment on lines +49 to +54
connections: [
// TODO: add filter handling (for now we can default 'unreadMessages' to false)
ConnectionHandler.getConnectionID(currentProfile.id, 'roomsList_chatRooms', {
unreadMessages: false,
}),
],
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Address the TODO: Implement dynamic filter handling

There's a TODO comment to add filter handling. Currently, unreadMessages is hardcoded to false. Implementing dynamic filters will improve the functionality and user experience.

Would you like assistance in implementing dynamic filter handling for the connections array?

@pt-tsl pt-tsl force-pushed the BA-1912-display-new-chats branch 2 times, most recently from 6efafe5 to 027303b Compare December 6, 2024 15:00
Copy link

@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

🧹 Outside diff range and nitpick comments (3)
packages/components/modules/messages/CreateChatRoomList/types.ts (1)

13-13: LGTM! Consider adding JSDoc documentation.

The new ProfileEdge type correctly represents an edge in the GraphQL connection pattern and supports the filtering functionality needed for chat creation.

Consider adding JSDoc documentation to explain the type's purpose:

+/** Represents an edge in the GraphQL connection for user profiles in the chat creation list */
export type ProfileEdge = AllProfilesEdges[number]
packages/components/CHANGELOG.md (1)

7-9: Enhance changelog entries with additional details.

While the changes are documented, consider adding more context to help other developers:

  • Specify if there are any breaking changes from the subscription connection fixes
  • Add migration steps for teams using the relocated useRoomListSubscription hook
  • List the specific fields removed from RoomsListFragment and RoomListSubscription

Example format:

- Fixed RoomListSubscription connection and added CreateChatRoom mutation connection
- Moved useRoomListSubscription hook to ChatRoom on baseapp-frontend-template
- Removed unused fields on RoomsListFragment and RoomListSubscription
+ Fixed RoomListSubscription connection and added CreateChatRoom mutation connection to support real-time chat updates
+ BREAKING: Moved useRoomListSubscription hook to ChatRoom on baseapp-frontend-template
+   Migration: Update your imports from '@baseapp-frontend/components' to '@baseapp-frontend-template/ChatRoom'
+ Removed unused fields from RoomsListFragment and RoomListSubscription:
+   - Removed: unreadMessagesCount
+   - Reason: Field no longer used in current implementation
packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (1)

19-33: Consider making the subscription more flexible

The current implementation could be more flexible to support different use cases.

Consider these improvements:

- const useRoomListSubscription = (profileId: string) => {
+ type FilterOptions = {
+   unreadMessages?: boolean;
+   // Add other filter options as needed
+ };
+ 
+ const useRoomListSubscription = (
+   profileId: string,
+   filterOptions: FilterOptions = { unreadMessages: false }
+ ) => {
   const config = useMemo(() => {
-    // TODO: add filter handling (for now we can default 'unreadMessages' to false)
     const connectionId = ConnectionHandler.getConnectionID(
       profileId,
       'roomsList_chatRooms',
-      {
-        unreadMessages: false,
-      }
+      filterOptions
     )
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 30f71b42a01f1a91a16ab2c96cffd94825697eaf and 027303b19899a41f10e9dd8705bcbccaa18c66ea.

⛔ Files ignored due to path filters (4)
  • packages/components/__generated__/ChatRoomsQuery.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/CreateChatRoomMutation.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/RoomsListFragment.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/useRoomListSubscription.graphql.ts is excluded by !**/__generated__/**
📒 Files selected for processing (10)
  • packages/components/CHANGELOG.md (1 hunks)
  • packages/components/modules/messages/ChatRoomsList/index.tsx (0 hunks)
  • packages/components/modules/messages/CreateChatRoomList/ChatRoomListItem/index.tsx (2 hunks)
  • packages/components/modules/messages/CreateChatRoomList/index.tsx (3 hunks)
  • packages/components/modules/messages/CreateChatRoomList/types.ts (1 hunks)
  • packages/components/modules/messages/graphql/mutations/CreateChatRoom.ts (3 hunks)
  • packages/components/modules/messages/graphql/queries/RoomsList.ts (0 hunks)
  • packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (1 hunks)
  • packages/components/modules/messages/index.ts (1 hunks)
  • packages/components/package.json (1 hunks)
💤 Files with no reviewable changes (2)
  • packages/components/modules/messages/ChatRoomsList/index.tsx
  • packages/components/modules/messages/graphql/queries/RoomsList.ts
✅ Files skipped from review due to trivial changes (1)
  • packages/components/package.json
🚧 Files skipped from review as they are similar to previous changes (4)
  • packages/components/modules/messages/index.ts
  • packages/components/modules/messages/graphql/mutations/CreateChatRoom.ts
  • packages/components/modules/messages/CreateChatRoomList/index.tsx
  • packages/components/modules/messages/CreateChatRoomList/ChatRoomListItem/index.tsx
🔇 Additional comments (4)
packages/components/CHANGELOG.md (1)

3-10: LGTM! Version history shows consistent development.

The changes in version 0.0.24 align well with the package's development history, particularly building upon previous chat-related features and improvements from versions 0.0.14 and 0.0.18.

packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (3)

5-17: Well-structured subscription query with proper edge handling!

The use of @prependEdge directive is an excellent choice for automatically prepending new chat rooms to the connection, which directly supports the requirement of showing new chats at the top of the list.


21-24: TODO comment needs to be addressed

The hardcoded filter limits the subscription's reusability. This TODO should be addressed to support dynamic filter handling.


6-8: Verify subscription behavior for different user scenarios

Let's verify that the subscription handles all required scenarios from the PR objectives.

✅ Verification successful

Let me try another verification approach with corrected file type flags.


Let me try one final verification approach with simpler commands.


Based on the search results, I can now generate the final response:

Subscription implementation correctly handles chat room updates

The subscription implementation is properly designed to handle chat room updates with:

  • Correct subscription field chatRoomOnRoomUpdate that listens for room updates
  • Proper prepending of new rooms using @prependEdge directive
  • Essential fields included in the subscription: id, unreadMessagesCount, and RoomFragment
  • Error handling via onError callback
  • Proper connection handling for Relay pagination
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if the subscription handles all user scenarios mentioned in PR objectives

# Check for other chat room related subscriptions that might conflict
echo "Checking for other chat room subscriptions:"
rg -l "subscription.*chatRoom" --type ts --type tsx

# Check if there are any permission checks for the subscription
echo "Checking for permission checks:"
rg "chatRoomOnRoomUpdate.*permission" --type ts --type tsx

# Look for error handling patterns in other subscriptions
echo "Checking error handling patterns in other subscriptions:"
ast-grep --pattern 'useSubscription({ $$$, onError: $_ })'

Length of output: 524


Script:

#!/bin/bash
# Search for chat room related subscriptions and their implementations
echo "Checking chat room subscriptions:"
rg -l "subscription.*chatRoom" --type typescript --type typescriptreact

# Look for subscription usage patterns
echo "Checking subscription usage patterns:"
rg "useSubscription.*chatRoom" -A 5 --type typescript --type typescriptreact

# Check for error handling in the component
echo "Checking error handling in the component:"
rg "useRoomListSubscription.*onError" --type typescript --type typescriptreact

# Look for related test files
echo "Looking for related test files:"
fd "useRoomListSubscription.*test" --type f

Length of output: 712


Script:

#!/bin/bash
# Search for all files containing chatRoom related code
echo "Searching for chat room related files:"
rg -l "chatRoom"

# Look for subscription implementation details
echo "Checking subscription implementations:"
rg "subscription" -A 5

# Check the component implementation
echo "Looking at component implementation:"
rg "useRoomListSubscription" -A 10

Length of output: 44812

@pt-tsl pt-tsl force-pushed the BA-1912-display-new-chats branch 2 times, most recently from 47c99b5 to e803ed4 Compare December 6, 2024 20:24
Copy link

@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

🧹 Outside diff range and nitpick comments (1)
packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (1)

21-35: Add type safety to the subscription configuration

Consider enhancing type safety by explicitly typing the subscription configuration object.

+ type RoomListSubscriptionConfig = {
+   subscription: GraphQLTaggedNode;
+   variables: {
+     profileId: string;
+     connections: string[];
+   };
+   onError: (error: Error) => void;
+ };

const useRoomListSubscription = (profileId: string) => {
-  const config = useMemo(() => {
+  const config: RoomListSubscriptionConfig = useMemo(() => {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 47c99b59c01037b54b9ad9b04f2e7fb493a2c1ab and e803ed4f96a39e5fcfaffbb16e4bb475263262c4.

⛔ Files ignored due to path filters (4)
  • packages/components/__generated__/ChatRoomsQuery.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/CreateChatRoomMutation.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/RoomsListFragment.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/useRoomListSubscription.graphql.ts is excluded by !**/__generated__/**
📒 Files selected for processing (10)
  • packages/components/CHANGELOG.md (1 hunks)
  • packages/components/modules/messages/ChatRoomsList/index.tsx (3 hunks)
  • packages/components/modules/messages/CreateChatRoomList/ChatRoomListItem/index.tsx (2 hunks)
  • packages/components/modules/messages/CreateChatRoomList/index.tsx (3 hunks)
  • packages/components/modules/messages/CreateChatRoomList/types.ts (1 hunks)
  • packages/components/modules/messages/graphql/mutations/CreateChatRoom.ts (3 hunks)
  • packages/components/modules/messages/graphql/queries/RoomsList.ts (0 hunks)
  • packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (1 hunks)
  • packages/components/modules/messages/index.ts (1 hunks)
  • packages/components/package.json (1 hunks)
💤 Files with no reviewable changes (1)
  • packages/components/modules/messages/graphql/queries/RoomsList.ts
🚧 Files skipped from review as they are similar to previous changes (8)
  • packages/components/modules/messages/index.ts
  • packages/components/modules/messages/graphql/mutations/CreateChatRoom.ts
  • packages/components/modules/messages/CreateChatRoomList/index.tsx
  • packages/components/modules/messages/ChatRoomsList/index.tsx
  • packages/components/CHANGELOG.md
  • packages/components/package.json
  • packages/components/modules/messages/CreateChatRoomList/types.ts
  • packages/components/modules/messages/CreateChatRoomList/ChatRoomListItem/index.tsx
🔇 Additional comments (3)
packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (3)

7-19: Well-structured subscription query with automatic edge handling!

The use of @prependEdge directive with the $connections parameter is an excellent choice for automatically inserting new chats at the top of the list, which directly fulfills the PR's objective of rendering newly created chats without manual intervention.


23-26: Address the TODO: Implement dynamic filter handling

The hardcoded unreadMessages: false filter limits the subscription's flexibility.


28-29: ⚠️ Potential issue

Critical: Implement error handling to meet PR requirements

The current console.error implementation doesn't fulfill the PR's requirement to show error messages when there are issues with adding new chats. This is critical for user experience.

Consider implementing proper error handling:

- onError: console.error,
+ onError: (error) => {
+   console.error('Chat subscription error:', error);
+   showErrorNotification({
+     message: 'Unable to receive new chat updates. Please refresh the page.',
+     action: {
+       label: 'Refresh',
+       onClick: () => window.location.reload()
+     }
+   });
+ },

Likely invalid or redundant comment.

@pt-tsl pt-tsl force-pushed the BA-1912-display-new-chats branch from e803ed4 to 9639408 Compare December 6, 2024 21:29
Copy link

@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

🧹 Outside diff range and nitpick comments (1)
packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (1)

24-26: Add type safety for connection parameters.

Consider adding type safety for the connection parameters to prevent potential runtime errors:

+ type RoomListConnectionParams = {
+   unreadMessages: boolean;
+ };

  const connectionId = ConnectionHandler.getConnectionID(
    profileId,
    'roomsList_chatRooms',
-   {
-     unreadMessages: false,
-   }
+   { unreadMessages: false } as RoomListConnectionParams
  )
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e803ed4f96a39e5fcfaffbb16e4bb475263262c4 and 9639408989193a75675095999134f615d937c285.

⛔ Files ignored due to path filters (4)
  • packages/components/__generated__/ChatRoomsQuery.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/CreateChatRoomMutation.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/RoomsListFragment.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/useRoomListSubscription.graphql.ts is excluded by !**/__generated__/**
📒 Files selected for processing (10)
  • packages/components/CHANGELOG.md (1 hunks)
  • packages/components/modules/messages/ChatRoomsList/index.tsx (3 hunks)
  • packages/components/modules/messages/CreateChatRoomList/ChatRoomListItem/index.tsx (2 hunks)
  • packages/components/modules/messages/CreateChatRoomList/index.tsx (3 hunks)
  • packages/components/modules/messages/CreateChatRoomList/types.ts (1 hunks)
  • packages/components/modules/messages/graphql/mutations/CreateChatRoom.ts (3 hunks)
  • packages/components/modules/messages/graphql/queries/RoomsList.ts (0 hunks)
  • packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (1 hunks)
  • packages/components/modules/messages/index.ts (1 hunks)
  • packages/components/package.json (1 hunks)
💤 Files with no reviewable changes (1)
  • packages/components/modules/messages/graphql/queries/RoomsList.ts
🚧 Files skipped from review as they are similar to previous changes (8)
  • packages/components/package.json
  • packages/components/modules/messages/CreateChatRoomList/types.ts
  • packages/components/modules/messages/ChatRoomsList/index.tsx
  • packages/components/modules/messages/graphql/mutations/CreateChatRoom.ts
  • packages/components/modules/messages/CreateChatRoomList/ChatRoomListItem/index.tsx
  • packages/components/CHANGELOG.md
  • packages/components/modules/messages/CreateChatRoomList/index.tsx
  • packages/components/modules/messages/index.ts
🔇 Additional comments (3)
packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (3)

23-26: Address the TODO: Implement dynamic filter handling

There's a TODO comment indicating that filter handling should be added. Currently, the unreadMessages filter is hardcoded to false. Implementing dynamic filters will enhance the flexibility of your subscription.


28-29: Enhance error handling to meet UX requirements

The current error handling (onError: console.error) doesn't meet the PR requirement of showing user-friendly error messages when there are issues with adding new chats.


7-19: LGTM! Verify fragment fields completeness.

The subscription is well-structured with the @prependEdge directive correctly implementing the requirement to show new chats at the top of the list.

Let's verify the fragment fields are complete for chat rendering:

✅ Verification successful

RoomFragment fields are complete and well-structured

The fragment includes all necessary fields for chat room rendering:

  • Basic identifiers: id
  • Message status: unreadMessagesCount
  • Visual elements: image, title
  • Latest activity: lastMessageTime, lastMessage (with id and content)
  • Participant information: full participant details including profile images
  • Messages list: includes MessagesListFragment for complete message history

The subscription's usage of this fragment ensures comprehensive data for both initial render and updates.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check RoomFragment fields to ensure all required fields for chat rendering are included
ast-grep --pattern 'fragment RoomFragment on ChatRoom {
  $$$
}'

Length of output: 66


Script:

#!/bin/bash
# Let's try to find the fragment definition using ripgrep
rg "fragment RoomFragment" -A 10

Length of output: 14529

@pt-tsl pt-tsl force-pushed the BA-1912-display-new-chats branch from 9639408 to b62fc60 Compare December 6, 2024 21:39
Copy link

@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

🧹 Outside diff range and nitpick comments (1)
packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (1)

21-37: Consider implementing a subscription error recovery mechanism

To improve reliability, consider implementing a subscription recovery mechanism that automatically resubscribes after connection errors or network issues. This would enhance the user experience by maintaining real-time updates even in unstable network conditions.

Example approach:

const useRoomListSubscription = (profileId: string) => {
  const [retryCount, setRetryCount] = useState(0);
  const MAX_RETRIES = 3;
  
  const config = useMemo(() => ({
    subscription: RoomListSubscriptionQuery,
    onError: (error) => {
      console.error(error);
      if (retryCount < MAX_RETRIES) {
        setTimeout(() => setRetryCount(prev => prev + 1), 1000 * Math.pow(2, retryCount));
      } else {
        showErrorNotification({
          message: 'Failed to receive chat updates. Please refresh the page.',
          action: {
            label: 'Refresh',
            onClick: () => window.location.reload()
          }
        });
      }
    },
    // ... rest of your config
  }), [profileId, retryCount]);

  return useSubscription(config);
};
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9639408989193a75675095999134f615d937c285 and b62fc60d01b955320c00ba7e98958f48970615ea.

⛔ Files ignored due to path filters (4)
  • packages/components/__generated__/ChatRoomsQuery.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/CreateChatRoomMutation.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/RoomsListFragment.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/useRoomListSubscription.graphql.ts is excluded by !**/__generated__/**
📒 Files selected for processing (10)
  • packages/components/CHANGELOG.md (1 hunks)
  • packages/components/modules/messages/ChatRoomsList/index.tsx (3 hunks)
  • packages/components/modules/messages/CreateChatRoomList/ChatRoomListItem/index.tsx (2 hunks)
  • packages/components/modules/messages/CreateChatRoomList/index.tsx (4 hunks)
  • packages/components/modules/messages/CreateChatRoomList/types.ts (1 hunks)
  • packages/components/modules/messages/graphql/mutations/CreateChatRoom.ts (3 hunks)
  • packages/components/modules/messages/graphql/queries/RoomsList.ts (0 hunks)
  • packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (1 hunks)
  • packages/components/modules/messages/index.ts (1 hunks)
  • packages/components/package.json (1 hunks)
💤 Files with no reviewable changes (1)
  • packages/components/modules/messages/graphql/queries/RoomsList.ts
🚧 Files skipped from review as they are similar to previous changes (8)
  • packages/components/modules/messages/index.ts
  • packages/components/package.json
  • packages/components/modules/messages/CreateChatRoomList/types.ts
  • packages/components/modules/messages/CreateChatRoomList/index.tsx
  • packages/components/modules/messages/ChatRoomsList/index.tsx
  • packages/components/modules/messages/CreateChatRoomList/ChatRoomListItem/index.tsx
  • packages/components/CHANGELOG.md
  • packages/components/modules/messages/graphql/mutations/CreateChatRoom.ts
🔇 Additional comments (4)
packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (4)

7-17: LGTM! Excellent use of Relay's @prependEdge directive.

The subscription query has been optimized to use Relay's automatic edge insertion, which eliminates the need for manual store updates and aligns perfectly with the requirement of automatically displaying new chats.


23-26: Address the TODO: Implement dynamic filter handling

There's a TODO comment indicating that filter handling should be added. Currently, the unreadMessages filter is hardcoded to false. Implementing dynamic filters will enhance the flexibility of your subscription.


28-29: Enhance error handling to meet UX requirements

The current error handling (onError: console.error) doesn't meet the PR requirement of showing user-friendly error messages when there are issues with adding new chats.


24-26: Verify connection ID construction and usage

Let's verify that the connection ID is being constructed correctly and that the subscription is working as expected with the Relay store.

Also applies to: 31-32

✅ Verification successful

Based on the results, I can now generate the final response since I have sufficient information about the connection ID construction and usage.

Connection ID construction is consistent across the codebase

The connection ID is being constructed correctly and consistently:

  • The same connection key roomsList_chatRooms is used in the @connection directive in the query
  • The same parameters are used when constructing the connection ID in both locations:
    • useRoomListSubscription.tsx
    • ChatRoomListItem/index.tsx
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the connection ID construction and usage in other files

# Check for other usages of ConnectionHandler.getConnectionID for this connection
rg -A 2 "getConnectionID.*roomsList_chatRooms"

# Check for any potential connection config mismatches
rg -A 5 "@connection.*roomsList_chatRooms"

Length of output: 1420

@pt-tsl pt-tsl force-pushed the BA-1912-display-new-chats branch from b62fc60 to c7ff7c1 Compare December 9, 2024 13:47
Copy link

@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

🧹 Outside diff range and nitpick comments (1)
packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (1)

5-17: LGTM! Smart use of @prependEdge directive.

The subscription structure effectively supports auto-updating the chat list by using the @prependEdge directive, which automatically handles edge insertion without manual updater logic.

Consider adding a comment explaining the @prependEdge directive's purpose for future maintainers:

 subscription useRoomListSubscription($profileId: ID!, $connections: [ID!]!) {
   chatRoomOnRoomUpdate(profileId: $profileId) {
+    # @prependEdge automatically inserts new chat rooms at the beginning of the list
     room @prependEdge(connections: $connections) {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b62fc60d01b955320c00ba7e98958f48970615ea and c7ff7c1e5c63416e07f2662d675af15c9ab6c348.

⛔ Files ignored due to path filters (4)
  • packages/components/__generated__/ChatRoomsQuery.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/CreateChatRoomMutation.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/RoomsListFragment.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/useRoomListSubscription.graphql.ts is excluded by !**/__generated__/**
📒 Files selected for processing (10)
  • packages/components/CHANGELOG.md (1 hunks)
  • packages/components/modules/messages/ChatRoomsList/index.tsx (3 hunks)
  • packages/components/modules/messages/CreateChatRoomList/ChatRoomListItem/index.tsx (2 hunks)
  • packages/components/modules/messages/CreateChatRoomList/index.tsx (4 hunks)
  • packages/components/modules/messages/CreateChatRoomList/types.ts (1 hunks)
  • packages/components/modules/messages/graphql/mutations/CreateChatRoom.ts (3 hunks)
  • packages/components/modules/messages/graphql/queries/RoomsList.ts (0 hunks)
  • packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (1 hunks)
  • packages/components/modules/messages/index.ts (1 hunks)
  • packages/components/package.json (1 hunks)
💤 Files with no reviewable changes (1)
  • packages/components/modules/messages/graphql/queries/RoomsList.ts
🚧 Files skipped from review as they are similar to previous changes (8)
  • packages/components/modules/messages/index.ts
  • packages/components/modules/messages/CreateChatRoomList/types.ts
  • packages/components/modules/messages/ChatRoomsList/index.tsx
  • packages/components/package.json
  • packages/components/CHANGELOG.md
  • packages/components/modules/messages/CreateChatRoomList/index.tsx
  • packages/components/modules/messages/CreateChatRoomList/ChatRoomListItem/index.tsx
  • packages/components/modules/messages/graphql/mutations/CreateChatRoom.ts
🔇 Additional comments (3)
packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (3)

21-24: Address the TODO: Implement dynamic filter handling

The hardcoded filter for unreadMessages limits the subscription's flexibility.


26-27: Enhance error handling to meet UX requirements

The current error handling doesn't meet the PR requirement of showing user-friendly error messages when there are issues with adding new chats.


19-35: LGTM with noted concerns!

The hook implementation correctly uses ConnectionHandler.getConnectionID and properly manages the subscription configuration. However, please address the above concerns about error handling and filter implementation to fully meet the PR requirements.

Let's verify the subscription's usage across the codebase:

@pt-tsl pt-tsl force-pushed the BA-1912-display-new-chats branch from c7ff7c1 to 8db8eef Compare December 9, 2024 14:19
Copy link

@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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c7ff7c1e5c63416e07f2662d675af15c9ab6c348 and 8db8eef6a730da38d4399558cff38398e60fb37d.

⛔ Files ignored due to path filters (4)
  • packages/components/__generated__/ChatRoomsQuery.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/CreateChatRoomMutation.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/RoomsListFragment.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/useRoomListSubscription.graphql.ts is excluded by !**/__generated__/**
📒 Files selected for processing (10)
  • packages/components/CHANGELOG.md (1 hunks)
  • packages/components/modules/messages/ChatRoomsList/index.tsx (3 hunks)
  • packages/components/modules/messages/CreateChatRoomList/ChatRoomListItem/index.tsx (2 hunks)
  • packages/components/modules/messages/CreateChatRoomList/index.tsx (4 hunks)
  • packages/components/modules/messages/CreateChatRoomList/types.ts (1 hunks)
  • packages/components/modules/messages/graphql/mutations/CreateChatRoom.ts (3 hunks)
  • packages/components/modules/messages/graphql/queries/RoomsList.ts (0 hunks)
  • packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (1 hunks)
  • packages/components/modules/messages/index.ts (1 hunks)
  • packages/components/package.json (1 hunks)
💤 Files with no reviewable changes (1)
  • packages/components/modules/messages/graphql/queries/RoomsList.ts
🚧 Files skipped from review as they are similar to previous changes (8)
  • packages/components/modules/messages/index.ts
  • packages/components/modules/messages/ChatRoomsList/index.tsx
  • packages/components/modules/messages/CreateChatRoomList/types.ts
  • packages/components/package.json
  • packages/components/CHANGELOG.md
  • packages/components/modules/messages/CreateChatRoomList/index.tsx
  • packages/components/modules/messages/CreateChatRoomList/ChatRoomListItem/index.tsx
  • packages/components/modules/messages/graphql/mutations/CreateChatRoom.ts
🔇 Additional comments (4)
packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (4)

5-16: LGTM! Well-structured subscription query.

The use of @prependEdge directive efficiently handles new chat rooms by automatically inserting them at the top of the list, which aligns perfectly with the PR requirement of showing newly created chats without manual refresh.


19-25: Consider implementing the unreadMessages filter.

The unreadMessages parameter is added to the interface but not fully implemented yet (as noted in the TODO). Since filtering unread messages could be an important UX feature, this should be addressed.

Would you like help implementing the filter handling for the unreadMessages parameter?


32-33: Enhance error handling to meet UX requirements.

The current error handling doesn't meet the PR requirement of showing user-friendly error messages when there are issues with adding new chats.


28-30: Verify connection handling across components.

Let's verify that the connection ID generation is consistent with how it's used in other components, particularly in the CreateChatRoom mutation.

✅ Verification successful

Let me gather more information about the mutation implementations to verify the connection handling completely.


Let me try one more search with corrected commands:


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

Connection handling is properly implemented and consistent

The connection ID generation in useRoomListSubscription is correctly aligned with the rest of the codebase:

  • The same connection ID format (roomsList_chatRooms) is used in both the subscription and ChatRoomListItem
  • The mutation CreateChatRoomMutation properly accepts the connection ID via the $connections parameter
  • The @prependEdge directive in the mutation ensures proper connection updates
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other uses of ConnectionHandler.getConnectionID
rg -A 2 "ConnectionHandler\.getConnectionID.*roomsList_chatRooms"

# Search for the connection parameter in mutations
ast-grep --pattern 'mutation $_($connections: [ID!]!) {
  $$$
}'

Length of output: 932


Script:

#!/bin/bash
# Search for CreateChatRoom mutation implementation
ast-grep --pattern 'mutation CreateChatRoom($_) {
  $$$
}'

# Search for any other mutations that might affect the chat rooms connection
rg -A 5 "mutation.*chatRoom.*" --type typescript

# Look for connection updates in store updaters
rg -A 5 "store\.get.*roomsList_chatRooms" --type typescript

Length of output: 243


Script:

#!/bin/bash
# Search for CreateChatRoom mutation implementation and store updates
rg -A 5 "mutation CreateChatRoom"

# Look for store updates related to roomsList
rg -A 5 "store\.get.*roomsList"

# Search for any updater functions that might handle the connection
ast-grep --pattern 'function $_($store: RecordSourceSelectorProxy, $_) {
  $$$
}'

Length of output: 2833

@pt-tsl pt-tsl force-pushed the BA-1912-display-new-chats branch 3 times, most recently from e02f466 to 566a854 Compare December 10, 2024 13:11
Copy link

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

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 12

🧹 Outside diff range and nitpick comments (25)
packages/components/modules/messages/MessagesList/MessagesGroup/MessageItem/index.tsx (1)

3-3: LGTM! Good architectural improvement.

Moving the authentication logic to a dedicated package (@baseapp-frontend/authentication) improves code organization and maintainability. This change aligns with the principle of separation of concerns.

packages/components/modules/messages/graphql/subscriptions/useMessageCountUpdateSubscription.tsx (2)

19-26: Consider pagination for allMessages field

While the addition of allMessages field supports read status tracking, fetching all messages could impact performance for chat rooms with extensive message history.

Consider implementing pagination or limiting the number of messages returned. For example:

allMessages(first: $count) {
  edges {
    node {
      id
      isRead
    }
  }
  pageInfo {
    hasNextPage
    endCursor
  }
}

Line range hint 39-46: Enhance error handling for subscription failures

Currently, errors are only logged to console. Consider implementing proper error handling to align with PR objectives regarding error messaging.

 const config = useMemo(
   () => ({
     subscription: MessageCountUpdateSubscription,
-    onError: console.error,
+    onError: (error) => {
+      console.error('Message count subscription error:', error);
+      // Notify user about the error
+      showErrorNotification({
+        message: 'Failed to receive chat updates',
+        description: 'Please refresh the page or try again later'
+      });
+    },
     variables: {
       profileId: profile?.id,
     },
   }),
   [profile?.id],
 )
packages/components/modules/profiles/ProfilePopover/CurrentProfile/index.tsx (1)

27-29: Consider adding type validation for urlPath

While the simplified conditional is cleaner, consider adding type validation to ensure urlPath is always a string when present.

-        {profile.urlPath && (
+        {typeof profile.urlPath === 'string' && profile.urlPath && (
           <Typography variant="body2" sx={{ color: 'text.secondary' }} noWrap>
             {profile.urlPath}
           </Typography>
packages/components/modules/profiles/ProfilePopover/ProfilesList/ProfileMenuItem/types.ts (1)

6-8: LGTM! Consider adding documentation.

The type changes correctly reflect the move from inline fragment to regular fragment, and the removal of redundant props improves the interface design.

Consider adding JSDoc comments to document the purpose of these types:

+/** GraphQL fragment types for profile data */
import type {
  ProfileItemFragment$data,
  ProfileItemFragment$key,
} from '../../../../../__generated__/ProfileItemFragment.graphql'

+/** Props for the ProfileMenuItem component */
export interface ProfileMenuItemProps {
  profileRef: ProfileItemFragment$key
  onProfileChange: (newProfile: ProfileItemFragment$data) => void
  // ...
}

Also applies to: 11-12

packages/components/modules/profiles/ProfilePopover/ProfilesList/index.tsx (2)

5-5: LGTM! Good architectural improvement.

Moving the useCurrentProfile hook to a centralized authentication module improves code organization and reusability.


27-28: Consider moving image path handling to backend.

The TODO comment indicates that image path handling should be moved to the backend. This is the correct approach as:

  1. It centralizes the logic
  2. Makes the frontend more maintainable
  3. Allows for easier CDN integration in the future
packages/components/modules/messages/ChatRoom/index.tsx (1)

45-57: Add braces to if statements for clarity and maintainability

Including braces {} around the if statement enhances readability and prevents potential bugs due to unintended code execution.

 useEffect(() => {
-  if (hasRunRef.current)
+  if (hasRunRef.current) {
     return () => {
       if (prevProfileIdRef.current && prevRoomIdRef.current) {
         commitMutation({
           variables: {
             input: {
               roomId: prevRoomIdRef.current,
               profileId: prevProfileIdRef.current as string,
             },
           },
         })
       }
     }
+  }
   hasRunRef.current = true
   return () => {}
 }, [profile?.id, chatRoom?.id])
packages/authentication/modules/profile/useCurrentProfile/__tests__/__mock__/profiles.ts (1)

1-10: Seed faker for consistent and reproducible test data

To ensure that your tests are reliable and produce consistent results across runs, consider seeding faker.

 import { faker } from '@faker-js/faker'

+faker.seed(42)

 export const mockUserProfileFactory = (id: string) => {
   return {
     id,
     name: faker.person.fullName(),
     image: faker.image.avatar(),
     urlPath: faker.internet.url(),
   }
 }

This will make the generated data deterministic, aiding in debugging and test reliability.

packages/authentication/modules/profile/index.ts (1)

4-5: Avoid exporting test utilities from the main module

Exporting InitialProfileProvider and InitialProfileProp from test utilities introduces test-specific code into your public API, which may not be intended.

Consider:

  • Moving these utilities to a non-test directory if they are meant for public use.
  • Keeping them within the test directory and not exporting them from the main module.
packages/authentication/modules/profile/useCurrentProfile/__tests__/__utils__/InitialProfileProvider/index.tsx (1)

12-17: Fix typo in usage documentation.

There's a typo in the comment: "You're" should be "Your".

-//     // You're component goes here, it is passed the initialProfile
+//     // Your component goes here, it is passed the initialProfile
packages/components/modules/messages/ChatRoomsList/ChatRoomItem/styled.tsx (1)

9-9: LGTM! Consider responsive behavior.

The addition of alignItems: 'center' improves the vertical alignment of grid items. While this is a good improvement, consider testing this alignment on different screen sizes and with varying content lengths to ensure consistent appearance.

Consider adding a comment explaining the grid structure (avatar-content-action) for better maintainability.

packages/authentication/modules/user/useUpdateUser/index.ts (1)

Line range hint 17-32: Consider adding retry mechanism for token refresh.

Since this functionality is critical for maintaining user sessions and chat functionality, consider implementing a retry mechanism before giving up and clearing the profile.

packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (1)

46-52: Consider consolidating connection handling

The current implementation creates two separate connection IDs for active and unread messages. Consider creating a helper function to reduce code duplication:

+const getConnectionId = (profileId: string, unreadMessages: boolean) =>
+  ConnectionHandler.getConnectionID(profileId, 'roomsList_chatRooms', {
+    unreadMessages,
+  })

 const config = useMemo(() => {
   // TODO: add filter handling (for now we can default 'unreadMessages' to false)
-  const connectionIdActive = ConnectionHandler.getConnectionID(profileId, 'roomsList_chatRooms', {
-    unreadMessages: false,
-  })
-  const connectionIdUnread = ConnectionHandler.getConnectionID(profileId, 'roomsList_chatRooms', {
-    unreadMessages: true,
-  })
+  const connectionIdActive = getConnectionId(profileId, false)
+  const connectionIdUnread = getConnectionId(profileId, true)
packages/components/.storybook/decorators/withProviders.tsx (1)

Line range hint 16-18: Address TODO comment regarding Tailwind classes

The TODO indicates potential issues with Tailwind class inclusion in Storybook.

Would you like help investigating and fixing the Tailwind configuration for Storybook?

packages/authentication/modules/profile/useCurrentProfile/index.ts (1)

51-55: Consider adding error handling for profile updates.

The updateProfileIfActive function should handle potential errors during profile updates.

Consider wrapping the update in a try-catch:

  const updateProfileIfActive = (newProfile: MinimalProfile) => {
+   try {
      if (currentProfile?.id === newProfile.id) {
        setCurrentProfile(newProfile)
      }
+   } catch (error) {
+     console.error('Failed to update profile:', error)
+     // Consider adding error reporting here
+   }
  }
packages/components/modules/navigations/Header/AccountMenu/AccountPopover/index.tsx (1)

36-36: Consider adding a default avatar fallback.

While the migration to useCurrentProfile is correct, the avatar fallback could be improved.

Consider adding a default avatar:

- src={profile?.image ?? ''}
+ src={profile?.image ?? '/assets/default-avatar.png'}

Also applies to: 69-69

packages/authentication/modules/access/useLogin/index.ts (1)

58-59: Move image path handling to backend

The TODO comment suggests moving absolute path handling to the backend, which is the correct approach.

Consider:

  1. Backend should return complete URLs
  2. Frontend shouldn't need to manipulate URLs
  3. This prevents issues with different environment configurations

Would you like me to create a GitHub issue to track this backend enhancement?

packages/components/modules/messages/SendMessage/index.tsx (1)

Line range hint 95-108: Improve error handling implementation

The current error handling implementation has several issues:

  1. Multiple TODO comments without implementation
  2. Console.error in production code
  3. No user feedback on errors

Consider implementing proper error handling:

 onCompleted: (response, errors) => {
   if (errors) {
-    // TODO: handle errors
-    console.error(errors)
+    const errorMessage = errors.map(e => e.message).join('. ')
+    toast.error(`Failed to send message: ${errorMessage}`)
+    return
   }
   const mutationErrors = response?.chatRoomSendMessage?.errors
   setFormRelayErrors(form, mutationErrors)

   if (!mutationErrors?.length) {
     form.reset()
   }
 },
-// TODO: handle errors
-onError: console.error,
+onError: (error) => {
+  toast.error('Failed to send message. Please try again.')
+  console.error('SendMessage mutation error:', error)
+},

Don't forget to import and configure a toast notification library for user feedback.

packages/components/modules/messages/ChatRoomsList/ChatRoomItem/index.tsx (1)

Line range hint 38-47: Consider extracting room title logic

The room title and avatar logic is complex and could benefit from extraction into a separate function for better maintainability.

Consider extracting the logic:

+const getRoomData = (room, currentProfile) => {
+  const defaultData = {
+    title: room.title,
+    avatarUrl: room.image?.url,
+  }
+
+  if (
+    !room.participants?.totalCount ||
+    room.participants.totalCount >= MINIMUM_AMOUNT_OF_PARTICIPANTS_TO_SHOW_ROOM_TITLE
+  ) {
+    return defaultData
+  }
+
+  const otherParticipant = room.participants.edges.find(
+    (edge) => edge?.node?.profile?.id && edge?.node?.profile?.id !== currentProfile?.id,
+  )
+
+  return {
+    title: otherParticipant?.node?.profile?.name ?? defaultData.title,
+    avatarUrl: otherParticipant?.node?.profile?.image?.url ?? defaultData.avatarUrl,
+  }
+}

-const roomData = {
-  title: room.title,
-  avatarUrl: room.image?.url,
-}
-
-if (
-  room.participants?.totalCount &&
-  room.participants?.totalCount < MINIMUM_AMOUNT_OF_PARTICIPANTS_TO_SHOW_ROOM_TITLE
-) {
-  const otherParticipant = room.participants.edges.find(
-    (edge) => edge?.node?.profile?.id && edge?.node?.profile?.id !== profile?.id,
-  )
-  roomData.title = otherParticipant?.node?.profile?.name
-  roomData.avatarUrl = otherParticipant?.node?.profile?.image?.url
-}
+const roomData = getRoomData(room, profile)
packages/components/modules/comments/CommentCreate/index.tsx (1)

Line range hint 116-120: Address TODO comments for error handling.

The error handling TODOs should be addressed to ensure proper user feedback when errors occur.

Would you like me to help implement proper error handling for both the mutation errors and network errors? This could include:

  1. Displaying error messages to the user
  2. Logging errors for debugging
  3. Implementing retry logic if needed

Also applies to: 134-135

packages/components/modules/navigations/Header/AccountMenu/AccountPopover/__tests__/AccountPopover.cy.tsx (2)

61-61: Extract magic number to a constant.

The number 6 is used multiple times for creating mock profiles. Consider extracting it to a named constant for better maintainability.

+const MOCK_PROFILES_COUNT = 6;
-const profileListData = mockProfilesListFactory(6, mockUserProfileData)
+const profileListData = mockProfilesListFactory(MOCK_PROFILES_COUNT, mockUserProfileData)

Also applies to: 153-153


74-74: Use test data constants for profile references.

Instead of using array indices directly, consider creating named constants for test profiles to make the tests more maintainable and readable.

+const TEST_PROFILE = {
+  INDEX: 1,
+  getName: (profiles) => profiles.data.me.profiles[TEST_PROFILE.INDEX]?.name
+};
-cy.findByLabelText(`Switch to ${profileListData.data.me.profiles[1]!.name}`)
+cy.findByLabelText(`Switch to ${TEST_PROFILE.getName(profileListData)}`)

Also applies to: 103-103

packages/components/schema.graphql (2)

214-214: LGTM: Archive filtering support

The addition of the archived parameter to the chatRooms query in ChatRoomsInterface enables filtering chat rooms based on their archived status, which is crucial for managing the chat rooms list effectively.

Consider implementing caching for the archived status to improve performance when frequently switching between archived and active chat lists.

Also applies to: 977-977


Schema changes for chat room archiving need implementation

The schema defines new types and mutations for chat room archiving functionality (ChatRoomArchiveInput, ChatRoomArchivePayload, isArchivedByCurrentProfile, hasArchivedRoom), but the corresponding resolvers and frontend implementations are missing. This needs to be addressed to make the feature functional.

  • Missing Python resolver for isArchivedByCurrentProfile field in ChatRoom type
  • Missing Python resolver for hasArchivedRoom field in ChatRoomParticipant type
  • Missing Python implementation for chatRoomArchive mutation
  • Missing frontend components/hooks to utilize the archive functionality
🔗 Analysis chain

Line range hint 75-977: Verify the implementation of archive-related resolvers

The schema changes for chat room archiving are well-designed. Let's verify the implementation of these changes.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for the implementation of archive-related resolvers and components

# Search for archive-related resolver implementations
rg -t py "def resolve_(is_archived_by_current_profile|has_archived_room)"

# Search for archive mutation implementation
rg -t py "class ChatRoomArchive"

# Search for frontend components using the new archive functionality
rg -t tsx -t ts "chatRoomArchive|isArchivedByCurrentProfile|hasArchivedRoom"

Length of output: 515


Script:

#!/bin/bash
# Let's try a different approach to search for the implementation

# Search for Python files containing archive-related code
fd -e py | xargs rg "is_archived_by_current_profile|has_archived_room|ChatRoomArchive"

# Search for TypeScript/JavaScript files containing archive-related code
fd -e ts -e js | xargs rg "chatRoomArchive|isArchivedByCurrentProfile|hasArchivedRoom"

# Search for any files containing archive-related GraphQL operations
rg "mutation chatRoomArchive|isArchivedByCurrentProfile|hasArchivedRoom"

Length of output: 624

🛑 Comments failed to post (12)
packages/test/jest.config.ts (1)

30-30: 🛠️ Refactor suggestion

Consider adjusting the testMatch pattern for nested directories.

The current pattern '<rootDir>/**/*.(spec|test).(ts|tsx)' might not correctly match test files in nested directories. The glob pattern should be:

-  testMatch: ['<rootDir>/**/*.(spec|test).(ts|tsx)'],
+  testMatch: ['<rootDir>/**/*.{spec,test}.{ts,tsx}'],

This change:

  1. Uses curly braces for alternatives (Jest's preferred syntax)
  2. Ensures proper matching of test files in subdirectories
📝 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.

  testMatch: ['<rootDir>/**/*.{spec,test}.{ts,tsx}'],
packages/components/modules/profiles/ProfilePopover/CurrentProfile/index.tsx (1)

3-3: 💡 Codebase verification

Found inconsistent import paths for useCurrentProfile

There are still a few files using different import paths:

  • packages/components/modules/messages/ChatRoom/index.tsx imports from '../../profiles'
  • packages/authentication/modules/access/useLogin/index.ts imports from '../../profile'
  • packages/authentication/modules/user/useUpdateUser/index.ts imports from '../../profile'

Note: The import in authentication package files is expected since that's where the hook is defined, but the ChatRoom component should be updated to use the centralized import.

🔗 Analysis chain

Verify consistent usage of the new authentication import path

The import path change suggests a move towards centralized authentication logic. Let's ensure this change is consistent across the codebase.


Let me try a different search pattern to find any old imports of useCurrentProfile:


Let me try one final search with a corrected command:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining old import paths and verify new import usage
# This helps ensure the migration is complete and consistent

# Search for any remaining old imports of useCurrentProfile
echo "Checking for old import paths:"
rg "import.*useCurrentProfile.*from '(?!@baseapp-frontend/authentication)"

# Verify the new import is used consistently
echo -e "\nVerifying new import usage:"
rg "import.*useCurrentProfile.*from '@baseapp-frontend/authentication'"

Length of output: 2486


Script:

#!/bin/bash
# Search for imports of useCurrentProfile that don't use the new path
rg "import.*useCurrentProfile" --type ts --type tsx | grep -v "@baseapp-frontend/authentication"

Length of output: 124


Script:

#!/bin/bash
# Search for any imports of useCurrentProfile
echo "All useCurrentProfile imports:"
rg --type-add 'ts:*.{ts,tsx}' --type ts "import.*useCurrentProfile"

Length of output: 2473

packages/components/modules/profiles/ProfilePopover/ProfilesList/ProfileMenuItem/index.tsx (1)

20-21: 🛠️ Refactor suggestion

Add error handling for profile loading state.

The current implementation might cause runtime errors if currentProfile is undefined during initial load or error states.

Consider adding error handling:

-  const { currentProfile } = useCurrentProfile()
+  const { currentProfile, loading, error } = useCurrentProfile()
   const profile = useFragment(ProfileItemFragment, profileRef)
+
+  if (loading) {
+    return <StyledMenuItem disabled><Typography>Loading...</Typography></StyledMenuItem>
+  }
+
+  if (error) {
+    return <StyledMenuItem disabled><Typography>Error loading profile</Typography></StyledMenuItem>
+  }

Committable suggestion skipped: line range outside the PR's diff.

packages/components/modules/profiles/ProfilePopover/ProfilesList/index.tsx (2)

28-29: ⚠️ Potential issue

Add null check for environment variable.

The environment variable access needs proper null checking to prevent runtime errors.

-const baseUrl = process.env.NEXT_PUBLIC_API_BASE_URL?.replace('/v1', '')
-const absoluteImagePath = profile.image ? `${baseUrl}${profile.image?.url}` : null
+const baseUrl = process.env.NEXT_PUBLIC_API_BASE_URL?.replace('/v1', '') ?? ''
+const absoluteImagePath = profile.image?.url ? `${baseUrl}${profile.image.url}` : null
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      const baseUrl = process.env.NEXT_PUBLIC_API_BASE_URL?.replace('/v1', '') ?? ''
      const absoluteImagePath = profile.image?.url ? `${baseUrl}${profile.image.url}` : null

31-37: 🛠️ Refactor suggestion

Add error handling for profile switch failures.

The profile switch operation should handle potential failures gracefully.

+  const handleProfileChange = async (profile: ProfileItemFragment$data) => {
     if (currentProfile?.id !== profile.id) {
       const baseUrl = process.env.NEXT_PUBLIC_API_BASE_URL?.replace('/v1', '') ?? ''
       const absoluteImagePath = profile.image?.url ? `${baseUrl}${profile.image.url}` : null

+      try {
         setCurrentProfile({
           id: profile.id,
           name: profile.name ?? null,
           image: absoluteImagePath,
           urlPath: profile.urlPath?.path ?? null,
         })
         sendToast(`Switched to ${profile.name}`)
         handleCloseSubmenu()
+      } catch (error) {
+        sendToast('Failed to switch profile. Please try again.', { type: 'error' })
+        console.error('Profile switch failed:', error)
+      }
     }
   }

Committable suggestion skipped: line range outside the PR's diff.

packages/components/modules/messages/ChatRoom/index.tsx (1)

44-60: 🛠️ Refactor suggestion

Simplify the useEffect logic to ensure correct cleanup behavior

The current implementation of the useEffect hook may not correctly handle the cleanup on unmount or dependency changes. Consider simplifying the logic to ensure commitMutation is called appropriately.

-useEffect(() => {
-  if (hasRunRef.current) {
-    return () => {
-      if (prevProfileIdRef.current && prevRoomIdRef.current) {
-        commitMutation({
-          variables: {
-            input: {
-              roomId: prevRoomIdRef.current,
-              profileId: prevProfileIdRef.current as string,
-            },
-          },
-        })
-      }
-    }
-  }
-  hasRunRef.current = true
-  return () => {}
-}, [profile?.id, chatRoom?.id])
+useEffect(() => {
+  const profileId = profile?.id
+  const roomId = chatRoom?.id
+  return () => {
+    if (profileId && roomId) {
+      commitMutation({
+        variables: {
+          input: {
+            roomId,
+            profileId,
+          },
+        },
+      })
+    }
+  }
+}, [profile?.id, chatRoom?.id])

This revision removes the unnecessary hasRunRef and prev*Ref variables, capturing the profileId and roomId within the effect to ensure they have the correct values during cleanup.

📝 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.

  useEffect(() => {
    const profileId = profile?.id
    const roomId = chatRoom?.id
    return () => {
      if (profileId && roomId) {
        commitMutation({
          variables: {
            input: {
              roomId,
              profileId,
            },
          },
        })
      }
    }
  }, [profile?.id, chatRoom?.id])
packages/authentication/modules/user/useUpdateUser/index.ts (1)

7-7: 🛠️ Refactor suggestion

Improve error handling visibility.

While setting the current profile to null on token refresh failure is appropriate, the current implementation silently fails with only console.error logging. Consider:

  1. Adding more detailed error logging
  2. Implementing a user-facing error notification
  3. Adding error tracking/monitoring

This is particularly important as it affects the chat room rendering functionality, which is core to this PR's objectives.

 try {
   await refreshAccessToken(accessKeyName, refreshKeyName)
 } catch (e) {
-  // silently fail
-  // eslint-disable-next-line no-console
   setCurrentProfile(null)
-  console.error(e)
+  const error = e instanceof Error ? e : new Error('Unknown error during token refresh')
+  console.error('Token refresh failed:', {
+    error: error.message,
+    stack: error.stack,
+    context: 'useUpdateUser'
+  })
+  // TODO: Add error notification
+  options?.onError?.(error)
 }

Also applies to: 17-17, 28-28

packages/authentication/modules/profile/useCurrentProfile/__tests__/useCurrentProfile.test.tsx (2)

14-42: 🛠️ Refactor suggestion

Add test coverage for missing scenarios.

The test suite should include additional test cases:

  1. Initial state verification
  2. Error handling scenarios
  3. Invalid profile data handling
// Add these test cases:

it('initializes with null current profile', () => {
  const { result } = renderHook(() => useCurrentProfile())
  expect(result.current.currentProfile).toBeNull()
})

it('handles invalid profile data', () => {
  const { result } = renderHook(() => useCurrentProfile())
  act(() => result.current.setCurrentProfile(null as any))
  expect(result.current.currentProfile).toBeNull()
})

it('handles cookie parsing errors', () => {
  // Mock implementation to simulate parsing error
  (setCookie as jest.Mock).mockImplementationOnce(() => {
    throw new Error('Cookie parsing error')
  })
  
  const profile = mockUserProfileFactory('error-profile')
  const { result } = renderHook(() => useCurrentProfile())
  
  act(() => result.current.setCurrentProfile(profile))
  expect(result.current.currentProfile!.id).toEqual('error-profile')
})

28-30: ⚠️ Potential issue

Fix incorrect test assertion for profile2.

The setCookie assertion is using profile1 instead of profile2 in the second test case.

    act(() => result.current.setCurrentProfile(profile2))
    expect(result.current.currentProfile!.id).toEqual('profile-id-2')
-   expect(setCookie).toHaveBeenCalledWith(CURRENT_PROFILE_KEY, profile1, { stringfyValue: true })
+   expect(setCookie).toHaveBeenCalledWith(CURRENT_PROFILE_KEY, profile2, { stringfyValue: 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.

    act(() => result.current.setCurrentProfile(profile2))
    expect(result.current.currentProfile!.id).toEqual('profile-id-2')
    expect(setCookie).toHaveBeenCalledWith(CURRENT_PROFILE_KEY, profile2, { stringfyValue: true })
packages/authentication/modules/profile/useCurrentProfile/index.ts (1)

33-78: ⚠️ Potential issue

Fix missing dependencies in useCallback and useEffect hooks.

The static analysis correctly identified missing dependencies that could lead to stale closures.

Apply this fix:

- const removeCurrentProfile = useCallback(() => setCurrentProfile(null), [])
+ const removeCurrentProfile = useCallback(() => setCurrentProfile(null), [setCurrentProfile])

  useEffect(() => {
    eventEmitter.on(LOGOUT_EVENT, removeCurrentProfile)
    return () => {
      eventEmitter.off(LOGOUT_EVENT, removeCurrentProfile)
    }
-  }, [])
+  }, [removeCurrentProfile])
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const useCurrentProfile = ({ noSSR = true }: ServerSideRenderingOption = {}) => {
  const [currentProfile, setProfile] = useAtom(profileAtom)
  const isSSR = typeof window === typeof undefined

  const setCurrentProfile = (newProfile: MinimalProfile | null) => {
    if (newProfile === null) {
      setProfile(() => {
        removeCookie(CURRENT_PROFILE_KEY)
        return null
      })
    } else {
      setProfile(() => {
        setCookie(CURRENT_PROFILE_KEY, newProfile, { stringfyValue: true })
        return newProfile
      })
    }
  }

  const updateProfileIfActive = (newProfile: MinimalProfile) => {
    if (currentProfile?.id === newProfile.id) {
      setCurrentProfile(newProfile)
    }
  }

  const removeCurrentProfile = useCallback(() => setCurrentProfile(null), [setCurrentProfile])

  useEffect(() => {
    eventEmitter.on(LOGOUT_EVENT, removeCurrentProfile)
    return () => {
      eventEmitter.off(LOGOUT_EVENT, removeCurrentProfile)
    }
  }, [removeCurrentProfile])

  if (isSSR) {
    return {
      currentProfile: getProfileFromCookie({ noSSR }),
      setCurrentProfile,
      updateProfileIfActive,
    }
  }
  return {
    currentProfile,
    setCurrentProfile,
    updateProfileIfActive,
  }
}
🧰 Tools
🪛 GitHub Check: Lint

[warning] 57-57:
React Hook useCallback has a missing dependency: 'setCurrentProfile'. Either include it or remove the dependency array


[warning] 64-64:
React Hook useEffect has a missing dependency: 'removeCurrentProfile'. Either include it or remove the dependency array

packages/authentication/modules/access/useLogin/index.ts (1)

58-64: 🛠️ Refactor suggestion

Improve URL construction reliability

The current implementation of constructing the absolute image path has potential reliability issues:

  1. No validation of the base URL format
  2. Hard-coded '/v1' string removal
  3. No URL encoding for the image path

Consider using URL manipulation utilities:

-const baseUrl = process.env.NEXT_PUBLIC_API_BASE_URL?.replace('/v1', '')
-const absoluteImagePath = user.profile.image ? `${baseUrl}${user.profile.image}` : null
+import { URL } from 'url'
+
+const getAbsoluteImagePath = (imagePath: string | null) => {
+  if (!imagePath) return null
+  try {
+    const baseUrl = new URL(process.env.NEXT_PUBLIC_API_BASE_URL || '')
+    baseUrl.pathname = imagePath
+    return baseUrl.toString()
+  } catch {
+    console.error('Invalid base URL or image path')
+    return null
+  }
+}
+const absoluteImagePath = getAbsoluteImagePath(user.profile.image)
📝 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.

      // TODO: handle the absolute image path on the backend
      import { URL } from 'url'

      const getAbsoluteImagePath = (imagePath: string | null) => {
        if (!imagePath) return null
        try {
          const baseUrl = new URL(process.env.NEXT_PUBLIC_API_BASE_URL || '')
          baseUrl.pathname = imagePath
          return baseUrl.toString()
        } catch {
          console.error('Invalid base URL or image path')
          return null
        }
      }
      const absoluteImagePath = getAbsoluteImagePath(user.profile.image)
      setCurrentProfile({
        ...user.profile,
        image: absoluteImagePath,
      })
packages/components/modules/comments/CommentCreate/index.tsx (1)

109-109: ⚠️ Potential issue

Add null check for currentProfile?.id.

The mutation could fail if currentProfile is null. Consider adding validation before submitting the mutation.

-profileId: currentProfile?.id,
+profileId: currentProfile?.id ?? (() => {
+  throw new Error('User profile is required to create a comment')
+})(),
📝 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.

            profileId: currentProfile?.id ?? (() => {
              throw new Error('User profile is required to create a comment')
            })(),

Copy link

@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

🧹 Outside diff range and nitpick comments (1)
packages/components/modules/messages/ChatRoom/index.tsx (1)

41-60: Consider simplifying the cleanup logic.

The current implementation using multiple refs and effects could be simplified. Consider combining the effects and using a single cleanup function.

-  const prevProfileIdRef = useRef<string | undefined>(currentProfile?.id)
-  const prevRoomIdRef = useRef<string | undefined>(chatRoom?.id)
-
-  useEffect(() => {
-    if (hasRunRef.current)
-      return () => {
-        if (prevProfileIdRef.current && prevRoomIdRef.current) {
-          commitMutation({
-            variables: {
-              input: {
-                roomId: prevRoomIdRef.current,
-                profileId: prevProfileIdRef.current as string,
-              },
-            },
-          })
-        }
-      }
-    hasRunRef.current = true
-    return () => {}
-  }, [currentProfile?.id, chatRoom?.id])
-
-  useEffect(() => {
-    prevProfileIdRef.current = currentProfile?.id
-    prevRoomIdRef.current = chatRoom?.id
-  }, [currentProfile?.id, chatRoom?.id])
+  useEffect(() => {
+    const profileId = currentProfile?.id
+    const roomId = chatRoom?.id
+    
+    return () => {
+      if (hasRunRef.current && profileId && roomId) {
+        commitMutation({
+          variables: {
+            input: {
+              roomId,
+              profileId,
+            },
+          },
+        })
+      }
+      hasRunRef.current = true
+    }
+  }, [currentProfile?.id, chatRoom?.id, commitMutation])
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e02f466d6fc82c4a26bcb95beb3c136aa04c13f9 and 566a854b5eac4d72e23e8e0e0006b272c2620796.

⛔ Files ignored due to path filters (7)
  • packages/components/__generated__/ChatRoomsQuery.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/CreateChatRoomMutation.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/NotificationItemFragment.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/NotificationItemWithQuery.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/RoomsListFragment.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/chatRoomsPaginationQuery.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/useRoomListSubscription.graphql.ts is excluded by !**/__generated__/**
📒 Files selected for processing (12)
  • packages/components/CHANGELOG.md (1 hunks)
  • packages/components/modules/messages/ChatRoom/index.tsx (4 hunks)
  • packages/components/modules/messages/ChatRoomsList/index.tsx (2 hunks)
  • packages/components/modules/messages/CreateChatRoomList/ChatRoomListItem/index.tsx (3 hunks)
  • packages/components/modules/messages/CreateChatRoomList/index.tsx (4 hunks)
  • packages/components/modules/messages/CreateChatRoomList/types.ts (1 hunks)
  • packages/components/modules/messages/graphql/mutations/CreateChatRoom.ts (2 hunks)
  • packages/components/modules/messages/graphql/queries/RoomsList.ts (0 hunks)
  • packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (2 hunks)
  • packages/components/modules/messages/index.ts (1 hunks)
  • packages/components/package.json (2 hunks)
  • packages/components/schema.graphql (5 hunks)
💤 Files with no reviewable changes (1)
  • packages/components/modules/messages/graphql/queries/RoomsList.ts
🚧 Files skipped from review as they are similar to previous changes (8)
  • packages/components/package.json
  • packages/components/modules/messages/CreateChatRoomList/types.ts
  • packages/components/modules/messages/index.ts
  • packages/components/modules/messages/ChatRoomsList/index.tsx
  • packages/components/modules/messages/graphql/mutations/CreateChatRoom.ts
  • packages/components/modules/messages/CreateChatRoomList/index.tsx
  • packages/components/CHANGELOG.md
  • packages/components/modules/messages/CreateChatRoomList/ChatRoomListItem/index.tsx
🔇 Additional comments (4)
packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (3)

Line range hint 5-42: LGTM! The subscription query effectively supports auto-updating chat lists.

The GraphQL subscription is well-structured with:

  • Proper handling of connections via the new $connections parameter
  • Use of @prependEdge directive to automatically prepend new rooms
  • Complete room data fragment including essential fields for display

46-46: Address the TODO comment regarding filter handling.

The hardcoded unreadMessages: false filter might limit the subscription's flexibility.


54-55: Enhance error handling to meet UX requirements.

The current console.error doesn't fulfill the PR requirement of showing user-friendly error messages when there are issues with adding new chats.

packages/components/schema.graphql (1)

75-76: LGTM! Well-structured schema changes for chat room archiving.

The additions properly support chat room archiving functionality with:

  • Boolean field for archive status
  • Proper input/payload types for the archive mutation
  • Consistent integration with existing types

Also applies to: 78-83, 85-90, 143-143, 214-214, 584-584, 977-977

@pt-tsl pt-tsl force-pushed the BA-1912-display-new-chats branch from 566a854 to 2e07465 Compare December 10, 2024 17:53
Copy link

@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

🧹 Outside diff range and nitpick comments (4)
packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (1)

20-26: TODO comment needs to be addressed.

The comment indicates that filter handling needs to be implemented, which could affect how unread messages are displayed.

Would you like me to help implement the dynamic filter handling for the unreadMessages parameter?

packages/components/modules/messages/ChatRoom/index.tsx (3)

26-26: Address TODO comment regarding query preloading

The comment indicates a need to preload this query instead of using lazy loading. This could impact performance and user experience.

Would you like me to help implement query preloading to improve the initial load time?


62-65: Consider memoizing the profile and room IDs

While the current implementation works, it could benefit from memoization to prevent unnecessary ref updates.

Consider this optimization:

+ const currentProfileId = currentProfile?.id
+ const currentRoomId = chatRoom?.id

  useEffect(() => {
-   prevProfileIdRef.current = currentProfile?.id
-   prevRoomIdRef.current = chatRoom?.id
+   prevProfileIdRef.current = currentProfileId
+   prevRoomIdRef.current = currentRoomId
- }, [currentProfile?.id, chatRoom?.id])
+ }, [currentProfileId, currentRoomId])

Line range hint 67-69: Enhance error handling and user feedback

The current error handling is minimal and could be improved to align with the PR objectives, which mention showing error messages when there are issues.

Consider implementing a proper error boundary or error state:

- // TODO: handle error for chatRoom
- if (!chatRoom) {
-   return <div>Chat room not found</div>
- }
+ if (!chatRoom) {
+   return (
+     <ErrorMessage
+       title="Chat room not found"
+       message="The requested chat room could not be loaded. Please refresh or try again later."
+       action={{
+         label: 'Refresh',
+         onClick: () => window.location.reload(),
+       }}
+     />
+   )
+ }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 566a854b5eac4d72e23e8e0e0006b272c2620796 and 2e074659d89c7e0e8fe9fc9dbf08b6e1a515bfae.

⛔ Files ignored due to path filters (7)
  • packages/components/__generated__/ChatRoomsQuery.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/CreateChatRoomMutation.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/NotificationItemFragment.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/NotificationItemWithQuery.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/RoomsListFragment.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/chatRoomsPaginationQuery.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/useRoomListSubscription.graphql.ts is excluded by !**/__generated__/**
📒 Files selected for processing (13)
  • packages/components/CHANGELOG.md (1 hunks)
  • packages/components/modules/messages/ChatRoom/index.tsx (4 hunks)
  • packages/components/modules/messages/ChatRoomsList/ChatRoomItem/index.tsx (3 hunks)
  • packages/components/modules/messages/ChatRoomsList/index.tsx (0 hunks)
  • packages/components/modules/messages/CreateChatRoomList/ChatRoomListItem/index.tsx (3 hunks)
  • packages/components/modules/messages/CreateChatRoomList/index.tsx (4 hunks)
  • packages/components/modules/messages/CreateChatRoomList/types.ts (1 hunks)
  • packages/components/modules/messages/graphql/mutations/CreateChatRoom.ts (2 hunks)
  • packages/components/modules/messages/graphql/queries/RoomsList.ts (0 hunks)
  • packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (1 hunks)
  • packages/components/modules/messages/index.ts (1 hunks)
  • packages/components/package.json (2 hunks)
  • packages/components/schema.graphql (5 hunks)
💤 Files with no reviewable changes (2)
  • packages/components/modules/messages/ChatRoomsList/index.tsx
  • packages/components/modules/messages/graphql/queries/RoomsList.ts
🚧 Files skipped from review as they are similar to previous changes (8)
  • packages/components/modules/messages/index.ts
  • packages/components/modules/messages/CreateChatRoomList/types.ts
  • packages/components/package.json
  • packages/components/modules/messages/CreateChatRoomList/ChatRoomListItem/index.tsx
  • packages/components/modules/messages/CreateChatRoomList/index.tsx
  • packages/components/modules/messages/ChatRoomsList/ChatRoomItem/index.tsx
  • packages/components/modules/messages/graphql/mutations/CreateChatRoom.ts
  • packages/components/CHANGELOG.md
🔇 Additional comments (9)
packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (3)

5-15: LGTM! The subscription query is well structured.

The query correctly implements the @prependEdge directive which will automatically handle adding new chat rooms to the top of the list, fulfilling the PR's requirement for automatic updates.


31-33: LGTM! Connection handling is well implemented.

The implementation correctly handles both active and unread message connections, ensuring that new chats will appear in both lists as appropriate.


28-29: ⚠️ Potential issue

Enhance error handling to meet UX requirements.

The current error handling (console.error) doesn't meet the PR requirement of showing user-friendly error messages when there are issues with adding new chats.

- onError: console.error,
+ onError: (error) => {
+   console.error('Chat subscription error:', error);
+   // Show user-friendly error message
+   showErrorNotification({
+     message: 'Unable to receive new chat updates. Please refresh the page or try again.',
+     action: {
+       label: 'Refresh',
+       onClick: () => window.location.reload()
+     }
+   });
+ },

Likely invalid or redundant comment.

packages/components/schema.graphql (4)

75-76: LGTM! ChatRoom type extension is well defined.

The isArchivedByCurrentProfile field is appropriately typed as Boolean and follows GraphQL naming conventions.


78-90: LGTM! Archive mutation types are well structured.

The ChatRoomArchiveInput and ChatRoomArchivePayload types follow GraphQL best practices:

  • Required fields are properly marked with !
  • Includes standard error handling fields
  • Follows consistent naming conventions

143-143: LGTM! ChatRoomParticipant field addition is correct.

The hasArchivedRoom field is properly marked as non-nullable (Boolean!) which ensures consistent behavior.


977-977: LGTM! Interface extension maintains consistency.

The archived parameter addition to the chatRooms query maintains consistency with the new archiving functionality.

packages/components/modules/messages/ChatRoom/index.tsx (2)

Line range hint 3-14: LGTM: Imports are well-organized and appropriate

The new imports support the added functionality for handling message reading on component unmount.


Line range hint 1-85: Verify integration with chat rooms list

While the changes to this component look good, we should verify its integration with the chat rooms list component to ensure it meets the PR objective of automatically displaying newly created chats.

✅ Verification successful

Let's search for any GraphQL subscription related to rooms list to verify the integration:

Let's also check for any room-related mutations that might trigger updates:


Let's also check for any room-related mutations in the codebase:


Based on the search results, I can now generate the final response regarding the integration of the chat room with the chat rooms list:

Integration with chat rooms list is properly implemented

The codebase shows a complete integration between the chat room and chat rooms list through:

  1. A GraphQL subscription useRoomListSubscription that listens for room updates and automatically prepends new rooms to the connection
  2. The subscription is properly used in the ChatRoomsList component: useRoomListSubscription(data.id)
  3. The CreateChatRoom mutation includes the @prependEdge directive to automatically add new rooms to the list
  4. The chat room updates (messages, read status) are handled through additional subscriptions (useMessageCountUpdateSubscription)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for the chat rooms list component and its subscription handling
rg -t typescript -A 10 "useRoomListSubscription|ChatRoomsList" --glob "!**/__generated__/**"

Length of output: 129


Script:

#!/bin/bash
# Search for chat rooms list related components and subscriptions
rg -l "ChatRoomsList|RoomsList|useRoomListSubscription" --type-add 'ts:*.{ts,tsx}' --type ts

# After finding the files, let's examine their content
rg -A 10 "ChatRoomsList|RoomsList|useRoomListSubscription" --type-add 'ts:*.{ts,tsx}' --type ts

Length of output: 35073


Script:

#!/bin/bash
# Look for GraphQL subscription definitions related to rooms
rg -A 5 "subscription.*Room" --type-add 'ts:*.{ts,tsx}' --type ts --type graphql

Length of output: 114


Script:

#!/bin/bash
# Search for room-related mutations
rg -A 5 "mutation.*Room|createRoom|updateRoom" --type-add 'ts:*.{ts,tsx}' --type ts --type graphql

Length of output: 132


Script:

#!/bin/bash
# Search for GraphQL subscription and mutation definitions related to rooms with proper file extensions
rg -A 5 "subscription.*Room|mutation.*Room|createRoom|updateRoom" --glob "*.{ts,tsx,graphql}"

# Let's also check the ChatRoomsList component implementation for subscription usage
rg -A 10 "useRoomListSubscription" packages/components/modules/messages/ChatRoomsList/index.tsx

Length of output: 16094


Script:

#!/bin/bash
# Look for room-related mutation implementations
rg -A 5 "createRoom|updateRoom" --glob "*.{ts,tsx,graphql}"

Length of output: 61

@pt-tsl pt-tsl force-pushed the BA-1912-display-new-chats branch 2 times, most recently from 75e7f9e to 7674772 Compare December 10, 2024 21:01
Copy link

@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

🧹 Outside diff range and nitpick comments (6)
packages/components/modules/messages/ChatRoom/index.tsx (2)

Line range hint 26-37: Consider implementing query preloading as noted in TODO

The current lazy loading approach might impact the initial load performance. Preloading the query would improve the user experience by reducing the initial loading time.

Would you like me to help implement the query preloading optimization or create an issue to track this improvement?


Line range hint 67-69: Enhance error handling for better user experience

The current error handling is minimal. Consider implementing a more informative error state that:

  1. Provides specific error messages based on the failure reason
  2. Offers retry options
  3. Aligns with the PR objective's requirement to "prompt the user to refresh or retry" on errors

Here's a suggested implementation:

- // TODO: handle error for chatRoom
- if (!chatRoom) {
-   return <div>Chat room not found</div>
- }
+ if (!chatRoom) {
+   return (
+     <ErrorContainer>
+       <ErrorMessage>
+         Unable to load chat room. Please try again.
+       </ErrorMessage>
+       <RetryButton onClick={() => window.location.reload()}>
+         Refresh Page
+       </RetryButton>
+     </ErrorContainer>
+   );
+ }
packages/authentication/modules/profile/useCurrentProfile/__tests__/__utils__/InitialProfileProvider/index.tsx (3)

1-6: Consider using path aliases to improve import readability

The deep relative import path (../../../../../../) makes the code harder to maintain and more prone to errors when files are moved. Consider using TypeScript path aliases.

Example configuration in tsconfig.json:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@types/*": ["types/*"],
      "@modules/*": ["packages/authentication/modules/*"]
    }
  }
}

Then imports could be simplified:

import { MinimalProfile } from '@types/profile'

12-18: Enhance documentation with JSDoc format and fix typo

The usage example is helpful but could be improved with proper JSDoc formatting and a typo fix.

-// Use as:
-// <JotaiProvider>
-//   <InitialProfileProvider initialProfile={props.initialProfile}>
-//     // You're component goes here, it is passed the initialProfile
-//   </InitialProfileProvider>
-// </JotaiProvider>
+/**
+ * Provides initial profile state to the Jotai atom system.
+ * @example
+ * <JotaiProvider>
+ *   <InitialProfileProvider initialProfile={props.initialProfile}>
+ *     {/* Your component goes here, it is passed the initialProfile *\/}
+ *   </InitialProfileProvider>
+ * </JotaiProvider>
+ */

19-25: Consider adding error boundary for hydration failures

The implementation is clean and follows best practices. However, given that this component is crucial for chat functionality, consider adding error handling for hydration failures.

import { ErrorBoundary } from 'react-error-boundary'

export const InitialProfileProvider: FC<PropsWithChildren & InitialProfileProp> = ({
  initialProfile,
  children,
}) => {
  useHydrateAtoms([[profileAtom, initialProfile]])
  return (
    <ErrorBoundary fallback={<div>Error initializing profile state</div>}>
      {children}
    </ErrorBoundary>
  )
}
packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (1)

20-23: TODO needs to be addressed for filter handling

The comment indicates that filter handling is not yet implemented, defaulting 'unreadMessages' to false.

Would you like me to help implement the dynamic filter handling for the unreadMessages parameter?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2e074659d89c7e0e8fe9fc9dbf08b6e1a515bfae and 76747727ea2f310d18dd0437d2962f245db9e3be.

⛔ Files ignored due to path filters (8)
  • packages/components/__generated__/ChatRoomsQuery.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/CreateChatRoomMutation.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/NotificationItemFragment.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/NotificationItemWithQuery.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/RoomsListFragment.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/chatRoomsPaginationQuery.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/useMessageCountUpdateSubscription.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/useRoomListSubscription.graphql.ts is excluded by !**/__generated__/**
📒 Files selected for processing (17)
  • packages/authentication/modules/profile/useCurrentProfile/__tests__/__utils__/InitialProfileProvider/index.tsx (1 hunks)
  • packages/components/CHANGELOG.md (1 hunks)
  • packages/components/modules/messages/ChatRoom/index.tsx (4 hunks)
  • packages/components/modules/messages/ChatRoomsList/ChatRoomItem/index.tsx (1 hunks)
  • packages/components/modules/messages/ChatRoomsList/ChatRoomItem/styled.tsx (1 hunks)
  • packages/components/modules/messages/ChatRoomsList/index.tsx (0 hunks)
  • packages/components/modules/messages/CreateChatRoomList/ChatRoomListItem/index.tsx (2 hunks)
  • packages/components/modules/messages/CreateChatRoomList/index.tsx (4 hunks)
  • packages/components/modules/messages/CreateChatRoomList/types.ts (1 hunks)
  • packages/components/modules/messages/MessagesList/index.tsx (0 hunks)
  • packages/components/modules/messages/graphql/mutations/CreateChatRoom.ts (3 hunks)
  • packages/components/modules/messages/graphql/queries/RoomsList.ts (0 hunks)
  • packages/components/modules/messages/graphql/subscriptions/useMessageCountUpdateSubscription.tsx (1 hunks)
  • packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (1 hunks)
  • packages/components/modules/messages/index.ts (1 hunks)
  • packages/components/package.json (1 hunks)
  • packages/components/schema.graphql (5 hunks)
💤 Files with no reviewable changes (3)
  • packages/components/modules/messages/ChatRoomsList/index.tsx
  • packages/components/modules/messages/graphql/queries/RoomsList.ts
  • packages/components/modules/messages/MessagesList/index.tsx
🚧 Files skipped from review as they are similar to previous changes (10)
  • packages/components/modules/messages/index.ts
  • packages/components/modules/messages/ChatRoomsList/ChatRoomItem/styled.tsx
  • packages/components/modules/messages/CreateChatRoomList/types.ts
  • packages/components/package.json
  • packages/components/CHANGELOG.md
  • packages/components/modules/messages/ChatRoomsList/ChatRoomItem/index.tsx
  • packages/components/modules/messages/CreateChatRoomList/index.tsx
  • packages/components/modules/messages/CreateChatRoomList/ChatRoomListItem/index.tsx
  • packages/components/modules/messages/graphql/mutations/CreateChatRoom.ts
  • packages/components/modules/messages/graphql/subscriptions/useMessageCountUpdateSubscription.tsx
🔇 Additional comments (14)
packages/components/modules/messages/ChatRoom/index.tsx (5)

Line range hint 3-17: LGTM! Dependencies are properly organized.

The new imports are correctly added and all are being utilized in the component.


38-40: LGTM! Hooks are properly implemented.

The profile and mutation hooks are correctly placed at the top level following React hooks rules.


41-43: LGTM! Refs are properly typed and initialized.

The refs for tracking profile and room IDs are correctly implemented with appropriate typing.


62-65: LGTM! Ref updates are properly handled.

The effect correctly updates the refs when profile or room ID changes, with appropriate dependencies.


44-60: ⚠️ Potential issue

Simplify cleanup logic and handle potential race conditions

The current implementation has the same concerns as previously identified in the earlier review.

Please implement the improvements suggested in the previous review comment to:

  1. Remove the complex hasRunRef pattern
  2. Add safety checks for stale cleanup
  3. Remove unsafe type assertions
packages/authentication/modules/profile/useCurrentProfile/__tests__/__utils__/InitialProfileProvider/index.tsx (2)

8-10: LGTM! Well-defined type with explicit nullability

The type definition is clear and follows TypeScript best practices.


1-25: Verify integration with chat components

Since this component is crucial for profile state management in chat features, let's verify its integration with chat-related components.

✅ Verification successful

Profile state management is properly integrated with chat components

The verification shows that the InitialProfileProvider and profile state management are correctly integrated:

  • Chat components consistently use useCurrentProfile hook to access profile data
  • The hook is properly used for critical chat features:
    • Message ownership verification in MessageItem
    • User context in SendMessage
    • Chat room state management in ChatRoom
  • The implementation follows a consistent pattern across components, correctly accessing the currentProfile object
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify usage of InitialProfileProvider in chat-related components
# and ensure proper profile state access

# Check for direct usage of InitialProfileProvider in chat components
echo "Checking InitialProfileProvider usage in chat components..."
rg -l "InitialProfileProvider" packages/components/modules/messages

# Check for useCurrentProfile hook usage in chat components
echo "Checking profile state access in chat components..."
rg -l "useCurrentProfile" packages/components/modules/messages

# Check for profileAtom usage to ensure consistent state management
echo "Checking profile atom usage..."
rg -l "profileAtom" packages/components/modules/messages

Length of output: 1095


Script:

#!/bin/bash
# Let's examine how useCurrentProfile is used in chat components to verify proper integration

# Check the implementation in a few key chat components
echo "=== Checking SendMessage implementation ==="
rg -A 5 "useCurrentProfile" "packages/components/modules/messages/SendMessage/index.tsx"

echo -e "\n=== Checking ChatRoom implementation ==="
rg -A 5 "useCurrentProfile" "packages/components/modules/messages/ChatRoom/index.tsx"

echo -e "\n=== Checking MessageItem implementation ==="
rg -A 5 "useCurrentProfile" "packages/components/modules/messages/MessagesList/MessagesGroup/MessageItem/index.tsx"

# Let's also verify the profile type being used matches
echo -e "\n=== Checking MinimalProfile type usage ==="
rg "MinimalProfile" "packages/components/modules/messages/"

Length of output: 2133

packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (3)

5-15: LGTM! Query changes properly handle chat list updates

The subscription query has been correctly updated to use the @prependEdge directive, ensuring new chats appear at the top of the list as required by the PR objectives.


21-26: LGTM! Comprehensive connection handling

The implementation correctly handles both active and unread message connections, ensuring chat updates appear in both filtered views.


28-34: ⚠️ Potential issue

Enhance error handling to meet UX requirements

The current error handling (console.error) doesn't fulfill the PR requirement of showing user-friendly error messages when there are issues with adding new chats.

- onError: console.error,
+ onError: (error) => {
+   console.error('Chat subscription error:', error);
+   showErrorNotification({
+     message: 'Failed to receive chat updates. Please refresh the page or try again.',
+     action: {
+       label: 'Refresh',
+       onClick: () => window.location.reload()
+     }
+   });
+ },

Likely invalid or redundant comment.

packages/components/schema.graphql (4)

75-76: LGTM! Clear and well-typed archive status field

The new isArchivedByCurrentProfile field is appropriately typed and named.


78-90: LGTM! Well-structured archive mutation types

The ChatRoomArchiveInput and ChatRoomArchivePayload types are properly structured with appropriate required fields and error handling.


143-143: LGTM! Appropriate participant archive status field

The hasArchivedRoom field is correctly defined as non-nullable Boolean, ensuring archive status is always available.


214-214: LGTM! Verify archive parameter implementation

The archived parameter is consistently added to the chatRooms query across interfaces.

Also applies to: 977-977

✅ Verification successful

Based on the GraphQL schema output, I can now provide a definitive response about the archived parameter implementation.

Verified: archived parameter is consistently implemented

The archived parameter is properly implemented in the ChatRoomsInterface interface as an optional Boolean parameter in the chatRooms query, which is consistent with the review comment's observation. The interface is implemented by the Profile type, ensuring consistent behavior across the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify consistent implementation of archived parameter
ast-grep --pattern 'chatRooms(
  $$$
  archived: Boolean
  $$$
): ChatRoomConnection'

Length of output: 87


Script:

#!/bin/bash
# Let's try a different approach to find chatRooms query definitions
rg "chatRooms.*\(.*\).*:.*ChatRoomConnection" -A 5

Length of output: 52


Script:

#!/bin/bash
# Search for archived parameter in GraphQL schema
rg "archived.*:.*Boolean" --type graphql

Length of output: 74


Script:

#!/bin/bash
# Find all GraphQL schema files
fd "schema.graphql" --type f --exec cat {}

Length of output: 32329

@pt-tsl pt-tsl changed the base branch from master to BA-1882-FE-packages-Unread-updates December 10, 2024 21:08
@pt-tsl pt-tsl force-pushed the BA-1912-display-new-chats branch from 7674772 to 9a1f958 Compare December 11, 2024 17:24
@Ronan-Fernandes Ronan-Fernandes force-pushed the BA-1882-FE-packages-Unread-updates branch from 5da7599 to 8ff1275 Compare December 11, 2024 17:28
@pt-tsl pt-tsl force-pushed the BA-1912-display-new-chats branch from 9a1f958 to e5d5d76 Compare December 11, 2024 17:33
@Ronan-Fernandes Ronan-Fernandes force-pushed the BA-1882-FE-packages-Unread-updates branch from 0edd25e to 08f9118 Compare December 11, 2024 17:44
Base automatically changed from BA-1882-FE-packages-Unread-updates to master December 11, 2024 18:15
tsl-ps2 and others added 2 commits December 12, 2024 07:20

Unverified

The email in this signature doesn’t match the committer email.
* BA-1809 squash all previous commits

* BA-1809 Replacing catalogs temporarily, revert later

* BA-1809 Fix rebase mistakes

* Revert "BA-1809 Replacing catalogs temporarily, revert later"

This reverts commit 1071e6e2098c27d40eb28bce840c285805db1b80.

* BA-1809 Do not pass currentProfile as props

* BA-1809 Fix component tests

* BA-1809 Remove duplicated try ... catch

* BA-1809 Move useCurrentProfile into authentication package

* BA-1809 Remove profileId from Comment props and use useCurrentProfile instead

* BA-1809 set current profile in useLogin hook

* BA-1809 Fix tests

* BA-1809 changesets

* BA-1809 pnpm-lock.yaml

* BA-1809 Replace catalogs, revert later!

* BA-1809 Remove profile id from comment props

* BA-1809 Make image paths absolute

* BA-1809 Implement remaining gitlab suggestions

* BA-1809 Test whether env variable is undefined before using it

* tweaks

---------

Co-authored-by: Alexandre Anicio <aa@tsl.io>

Unverified

The email in this signature doesn’t match the committer email.
@pt-tsl pt-tsl force-pushed the BA-1912-display-new-chats branch from e5d5d76 to e10730f Compare December 12, 2024 12:21
Copy link

@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

🧹 Outside diff range and nitpick comments (1)
packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (1)

20-20: TODO comment needs to be addressed

The comment indicates that filter handling needs to be implemented. This could affect the functionality of the chat list filtering.

Would you like me to help implement the filter handling logic?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 76747727ea2f310d18dd0437d2962f245db9e3be and e10730f632b56fb9449e6a191cb11725eaca2b81.

⛔ Files ignored due to path filters (7)
  • packages/components/__generated__/ChatRoomsQuery.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/CreateChatRoomMutation.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/NotificationItemFragment.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/NotificationItemWithQuery.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/RoomsListFragment.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/chatRoomsPaginationQuery.graphql.ts is excluded by !**/__generated__/**
  • packages/components/__generated__/useRoomListSubscription.graphql.ts is excluded by !**/__generated__/**
📒 Files selected for processing (13)
  • packages/components/CHANGELOG.md (1 hunks)
  • packages/components/modules/messages/ChatRoom/index.tsx (2 hunks)
  • packages/components/modules/messages/ChatRoomsList/ChatRoomItem/index.tsx (1 hunks)
  • packages/components/modules/messages/ChatRoomsList/index.tsx (0 hunks)
  • packages/components/modules/messages/CreateChatRoomList/ChatRoomListItem/index.tsx (2 hunks)
  • packages/components/modules/messages/CreateChatRoomList/index.tsx (4 hunks)
  • packages/components/modules/messages/CreateChatRoomList/types.ts (1 hunks)
  • packages/components/modules/messages/graphql/mutations/CreateChatRoom.ts (3 hunks)
  • packages/components/modules/messages/graphql/queries/RoomsList.ts (0 hunks)
  • packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (1 hunks)
  • packages/components/modules/messages/index.ts (1 hunks)
  • packages/components/package.json (1 hunks)
  • packages/components/schema.graphql (5 hunks)
💤 Files with no reviewable changes (2)
  • packages/components/modules/messages/ChatRoomsList/index.tsx
  • packages/components/modules/messages/graphql/queries/RoomsList.ts
🚧 Files skipped from review as they are similar to previous changes (8)
  • packages/components/modules/messages/index.ts
  • packages/components/package.json
  • packages/components/modules/messages/CreateChatRoomList/types.ts
  • packages/components/modules/messages/CreateChatRoomList/index.tsx
  • packages/components/modules/messages/CreateChatRoomList/ChatRoomListItem/index.tsx
  • packages/components/CHANGELOG.md
  • packages/components/modules/messages/ChatRoomsList/ChatRoomItem/index.tsx
  • packages/components/modules/messages/ChatRoom/index.tsx
🔇 Additional comments (4)
packages/components/modules/messages/graphql/subscriptions/useRoomListSubscription.tsx (2)

5-15: Subscription query changes look good!

The addition of the $connections parameter and @prependEdge directive properly implements the auto-update functionality for the chat rooms list, ensuring new chats appear at the top.


28-34: ⚠️ Potential issue

Enhance error handling for subscription errors

The current error handling (onError: console.error) doesn't meet the PR requirement of showing user-friendly error messages when there are issues with adding new chats.

Consider implementing proper error handling:

- onError: console.error,
+ onError: (error) => {
+   console.error('Chat subscription error:', error);
+   showErrorNotification({
+     message: 'Failed to receive chat updates. Please refresh the page.',
+     action: {
+       label: 'Refresh',
+       onClick: () => window.location.reload()
+     }
+   });
+ },

Likely invalid or redundant comment.

packages/components/modules/messages/graphql/mutations/CreateChatRoom.ts (1)

52-52: 🛠️ Refactor suggestion

Replace 'any' type with a proper type definition

Using any type reduces type safety. Define a specific type for better reliability.

Apply this change:

- (edge: any) => edge?.node?.id,
+ (edge: { node: { id: string } }) => edge.node.id,

Likely invalid or redundant comment.

packages/components/schema.graphql (1)

110-111: Schema changes are well-structured and complete!

The additions properly support chat room archiving functionality with:

  • New fields for archive status tracking
  • Input/payload types for archive operations
  • Proper integration with existing types

Also applies to: 113-118, 120-125, 192-192, 281-281, 777-777, 1372-1372

Unverified

The email in this signature doesn’t match the committer email.
@pt-tsl pt-tsl force-pushed the BA-1912-display-new-chats branch from e10730f to 32c764f Compare December 12, 2024 12:57
Copy link

Quality Gate Failed Quality Gate failed

Failed conditions
53.4% Duplication on New Code (required ≤ 3%)

See analysis details on SonarQube Cloud

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.

None yet

5 participants