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

feat(frontend): fix sidebar need reload when first time load #150

Merged
merged 11 commits into from
Mar 5, 2025

Conversation

PengyuChen01
Copy link
Collaborator

@PengyuChen01 PengyuChen01 commented Mar 4, 2025

Summary by CodeRabbit

  • New Features

    • Improved authentication experience with dedicated sign-in and sign-up modals featuring smoother transitions.
    • Conditional data fetching based on user authorization enhances security and performance.
    • Navigation updates now provide clear alerts for upcoming features (e.g., a “Coming Soon” message when selecting specific tabs).
  • Style

    • Enhanced UI responsiveness with adjustments to layouts, flexible component widths, and repositioned notifications for a better visual experience.

@PengyuChen01 PengyuChen01 requested a review from Sma1lboy March 4, 2025 05:02
Copy link
Contributor

coderabbitai bot commented Mar 4, 2025

Warning

Rate limit exceeded

@Sma1lboy has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 11 minutes and 48 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between cc155d2 and 0d5ef8d.

📒 Files selected for processing (1)
  • frontend/src/components/sidebar.tsx (4 hunks)

Walkthrough

The changes uniformly enhance user authentication and conditional data fetching across the application. They introduce delayed transitions for sign-in and sign-up modals, integrate authentication state via a centralized context, and adjust query executions to respect user authorization. Additionally, navigation, UI components, and feedback (toast notifications) have been updated, while minor formatting and logging improvements were applied in authentication and GraphQL schema components.

Changes

File(s) Summary
frontend/src/app/(main)/page.tsx
frontend/src/components/auth-choice-modal.tsx
Integrated new SignIn/SignUp modals with delayed transitions from the AuthChoiceModal and updated comments.
frontend/src/components/chat/chat-layout.tsx
frontend/src/components/chat/code-engine/project-context.tsx
frontend/src/components/chat/index.tsx
frontend/src/hooks/useChatList.ts
frontend/src/hooks/useModels.ts
Introduced authentication state checks via useAuthContext and conditionally skipped queries based on authorization status.
frontend/src/components/root/nav.tsx
frontend/src/components/sidebar.tsx
frontend/src/components/root/prompt-form.tsx
frontend/src/components/sign-in-modal.tsx
Updated navigation actions (e.g., replacing URL opens with alerts and router pushes) and refined UI styling and notification positioning.
frontend/src/graphql/schema.gql Adjusted comment formatting and removed an extraneous newline.
frontend/src/providers/AuthProvider.tsx Streamlined token validation with early returns and added console logging for better traceability.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant AC as AuthChoiceModal
    participant SI as SignInModal
    participant SU as SignUpModal

    U->>AC: Click "Sign In" / "Sign Up" button
    AC->>AC: Execute onClose()
    AC->>AC: setTimeout (100ms delay)
    alt Sign In selected
        AC->>SI: Set showSignIn true
    else Sign Up selected
        AC->>SU: Set showSignUp true
    end
Loading
sequenceDiagram
    participant C as Component
    participant A as AuthContext
    participant Q as Query Hook
    participant S as Server (Data Fetch)

    C->>A: Get isAuthorized state
    C->>Q: Call useQuery with skip condition (!isAuthorized)
    alt isAuthorized true
        Q->>S: Fetch data
        S-->>Q: Return data
    else isAuthorized false
        Q-->>C: Skip fetching
    end
Loading

Possibly related PRs

Suggested reviewers

  • ZHallen122
  • NarwhalChen
  • Sma1lboy

Poem

I'm a hopping rabbit, full of glee,
Watching modals and queries dance so free.
With delays and checks, the code aligns,
Bearing new paths and smoother signs.
A carrot of change, sweet as can be – hooray for code harmony!
🐰🌟


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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai 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.

@PengyuChen01 PengyuChen01 requested review from NarwhalChen and ZHallen122 and removed request for NarwhalChen March 4, 2025 05:13
@Sma1lboy Sma1lboy marked this pull request as ready for review March 5, 2025 02:39
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (3)
frontend/src/components/auth-choice-modal.tsx (1)

38-48: Good implementation of modal transition delay

The new implementation now properly separates the modal closing and the sign-in action with a brief delay, which helps prevent UI conflicts when transitioning between modals. The comments also clearly explain the sequence of operations.

Consider extracting this pattern into a reusable helper function since it's used for both buttons:

-                onClick={() => {
-                  // 1) Close current modal
-                  onClose();
-                  // 2) After a brief delay, call onSignInClick
-                  setTimeout(() => {
-                    onSignInClick();
-                  }, 100);
-                }}
+                onClick={() => handleModalTransition(onSignInClick)}

And add this function at the top of your component:

const handleModalTransition = (callback: () => void) => {
  // 1) Close current modal
  onClose();
  // 2) After a brief delay, call the callback
  setTimeout(() => {
    callback();
  }, 100);
};
frontend/src/providers/AuthProvider.tsx (1)

142-149: Good optimization for auth flow

The early return when no token is found improves performance by avoiding unnecessary validation attempts. The code properly manages state by setting the appropriate values before returning.

Consider using the logout() function to set the auth state since it already contains the same state reset logic:

      if (!storedToken) {
        console.log('No stored token found, skip checkToken');
-        setIsAuthorized(false);
-        setUser(null);
+        logout();
        setIsLoading(false);
        return;
      }
frontend/src/app/(main)/page.tsx (1)

17-19: Verify unused router import

The useRouter hook is imported and initialized but not used in the visible code. If this is intentional for upcoming features, consider adding a TODO comment. Otherwise, remove the unused import.

Add a comment explaining the intention or remove the unused router:

-  const router = useRouter();
+  // TODO: Router will be used for navigation after successful authentication
+  const router = useRouter();

Or if unused:

-  const router = useRouter();
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7136304 and c0eb2c7.

📒 Files selected for processing (13)
  • frontend/src/app/(main)/page.tsx (3 hunks)
  • frontend/src/components/auth-choice-modal.tsx (3 hunks)
  • frontend/src/components/chat/chat-layout.tsx (1 hunks)
  • frontend/src/components/chat/code-engine/project-context.tsx (3 hunks)
  • frontend/src/components/chat/index.tsx (2 hunks)
  • frontend/src/components/root/nav.tsx (1 hunks)
  • frontend/src/components/root/prompt-form.tsx (1 hunks)
  • frontend/src/components/sidebar.tsx (4 hunks)
  • frontend/src/components/sign-in-modal.tsx (1 hunks)
  • frontend/src/graphql/schema.gql (2 hunks)
  • frontend/src/hooks/useChatList.ts (1 hunks)
  • frontend/src/hooks/useModels.ts (2 hunks)
  • frontend/src/providers/AuthProvider.tsx (2 hunks)
✅ Files skipped from review due to trivial changes (2)
  • frontend/src/components/sign-in-modal.tsx
  • frontend/src/graphql/schema.gql
🧰 Additional context used
🪛 GitHub Actions: Frontend CI
frontend/src/components/sidebar.tsx

[error] 8-11: The name useRouter is defined multiple times.


[error] 50-53: The name router is defined multiple times.

🔇 Additional comments (22)
frontend/src/components/root/prompt-form.tsx (1)

214-214: Good improvement to the SelectTrigger width handling.

Changing from a fixed width (w-[117px]) to a flexible width with minimum bounds (min-w-max) is a good approach. This ensures that the dropdown trigger will properly accommodate longer model names without truncation, while still maintaining appropriate spacing in the UI.

frontend/src/components/chat/chat-layout.tsx (1)

18-20: Efficient query optimization with authorization check.

Adding the skip: !isAuthorized condition to the useQuery hook ensures that the application doesn't waste resources by fetching user projects when the user isn't authorized. This is aligned with best practices for performance and security.

frontend/src/hooks/useModels.ts (2)

14-14: Good addition of authentication context.

Adding the isAuthorized state from the auth context provides the necessary information for conditional query execution. This is consistent with the authorization pattern implemented across the application.


53-53: Improved query control flow with authorization check.

Adding the authorization condition to the skip logic ensures that model data is only fetched when the user is authenticated. This prevents unnecessary API calls and potential errors when a user isn't logged in, which is aligned with the PR's goal of fixing first-time load issues.

frontend/src/components/chat/index.tsx (3)

20-20: Good addition of auth context import.

Adding the import for the authentication context provider is necessary for the authorization check implemented in this file.


24-24: Proper extraction of authorization state.

Extracting the isAuthorized state from the authentication context provides the necessary information for conditional query execution.


41-41: Enhanced query control with authorization check.

Adding the !isAuthorized condition to the skip logic ensures that chat history is only fetched when the user is authenticated. This prevents unnecessary API calls and potential errors for unauthenticated users, which directly addresses the issue mentioned in the PR title about needing to reload the sidebar on first load.

frontend/src/components/sidebar.tsx (4)

87-120: Good interactive navigation improvement with Button component.

Replacing a non-interactive div with a Button component that navigates to the home page improves both functionality and accessibility. The Button component provides proper keyboard navigation and screen reader support.

However, consider adding an aria-label to make the button's purpose clearer for screen reader users, especially since it contains an image.

<Button
  onClick={() => router.push('/')}
  variant="ghost"
+ aria-label="Return to home"
  className="
    w-full
    h-14
    flex
    items-center
    justify-start
    px-4
    gap-2
    text-sm
    xl:text-lg
    font-normal
    rounded-md
    hover:bg-yellow-50
    transition-all
    duration-200
    ease-in-out
  "
>

123-123: Full-width divider improvement.

Changing the divider width from partial (w-[85%]) to full width (w-full) creates a more consistent visual separation across the entire sidebar width.


52-52:

✅ Verification successful

Resolve duplicate router definition error.

The CI pipeline indicates that router is defined multiple times. You need to check if there's another router variable defined elsewhere in the component.


🏁 Script executed:

#!/bin/bash
# Check for all router definitions in the file
cat frontend/src/components/sidebar.tsx | grep -n "const router"

Length of output: 99


No duplicate router definition found in sidebar.tsx.
After running the verification script, only one occurrence of const router = useRouter(); exists at line 52. There isn’t an additional declaration elsewhere in the component. This suggests that the CI pipeline’s duplicate router error may be caused by an external factor (such as a build caching issue or a naming conflict in a different file). Please double-check the broader build configuration if the error persists.


11-11:

✅ Verification successful

Check for duplicate imports of useRouter.

The CI pipeline has detected that useRouter is defined multiple times. This likely indicates that another import for useRouter exists somewhere else in the codebase or in this file that's not visible in the provided snippet.


🏁 Script executed:

#!/bin/bash
# Search for all useRouter imports in the file
cat frontend/src/components/sidebar.tsx | grep -n "import.*useRouter"

Length of output: 119


Duplicate Import Check – Sidebar Verified

After reviewing frontend/src/components/sidebar.tsx, we confirmed that there is only one import of useRouter from 'next/navigation' (line 11). The CI pipeline’s duplicate import warning might be caused by another file or a re-export. Please verify elsewhere in the codebase if the issue persists.

🧰 Tools
🪛 GitHub Actions: Frontend CI

[error] 8-11: The name useRouter is defined multiple times.

frontend/src/hooks/useChatList.ts (2)

5-9: Good integration of authentication context.

Adding the useAuthContext hook and extracting isAuthorized is a good practice for components that need to respect the user's authentication state.


16-17: Performance improvement by conditionally skipping queries.

Adding the skip: !isAuthorized condition ensures that the GraphQL query to fetch user chats doesn't execute when the user isn't authenticated. This prevents unnecessary network requests and potential authorization errors.

This change aligns well with the authentication flow and follows recommended patterns for conditional data fetching in Apollo Client.

frontend/src/components/chat/code-engine/project-context.tsx (3)

21-21: Good integration of authentication context.

Adding the useAuthContext import establishes a connection to the centralized authentication state, which is a good architectural pattern.


52-52: Properly accessing authentication state.

Extracting isAuthorized from the auth context is the correct approach to access the user's authentication status.


88-89: Performance optimization with conditional query execution.

Adding the skip: !isAuthorized condition to the useQuery hook prevents fetching user projects when the user isn't authenticated. This is an important optimization that:

  1. Prevents unnecessary API calls
  2. Avoids potential authorization errors
  3. Improves performance by not loading data that can't be accessed

This change aligns with the similar modifications in other components, creating a consistent pattern throughout the application.

frontend/src/components/root/nav.tsx (2)

176-177: Feature placeholder implementation.

Changing the behavior from opening a GitHub URL to showing a "Coming Soon" alert indicates this feature is planned but not yet implemented. This is an appropriate temporary solution for an upcoming feature.

Consider adding a more informative message in the alert to provide users with context about when this feature might be available:

- alert('Coming Soon');
+ alert('Codefox Journey feature is coming soon! Stay tuned for updates.');

184-185:

❓ Verification inconclusive

Layout positioning change.

Removing the fixed class from the container div changes how the navigation bar is positioned in the document flow. This might be intentional if the navigation bar should now scroll with the content rather than remain fixed at the top.

Verify that this change doesn't negatively impact the user experience on different screen sizes and when scrolling through content:


🏁 Script executed:

#!/bin/bash
# Check if there are any responsive positioning classes or scroll handlers
# related to this navigation component in the codebase
rg -A 3 -B 3 "fixed.*top-5" --type=tsx frontend/

Length of output: 78


Please re-run the above script to verify that no residual “fixed” class strings remain in the navigation component.

Based on the intended change:

  • The removal of the fixed class should let the navigation bar scroll with the content.
  • It’s important to ensure that this change doesn't negatively impact layout responsiveness on different screen sizes.

Once the updated search confirms that the “fixed” class is completely removed—and after manually verifying that the navigation’s behavior on various devices is as expected—this change can be merged.


🏁 Script executed:

#!/bin/bash
# Use rg with custom TSX type definition to search for the 'fixed' class
rg --type-add "tsx:*.tsx" -A 3 -B 3 "fixed" frontend/src/components/root/nav.tsx

Length of output: 202


Navigation Bar Positioning Change – Please Verify Responsiveness

The removal of the fixed class from the container div (frontend/src/components/root/nav.tsx, lines 184-185) means the navigation bar will now scroll with the content. However, the automated search for residual fixed positioning produced an error. Please take the following actions:

  • Manually verify that no instances of the fixed class remain in this file (especially in responsive states).
  • Confirm that the navigation behaves as expected on different screen sizes and that scrolling doesn’t introduce layout issues.

Once you’ve confirmed through manual or corrected script verification that the layout and scrolling behavior are as intended, this change can be merged.

frontend/src/components/auth-choice-modal.tsx (1)

57-62: Consistent implementation for Sign Up button

The Sign Up button correctly implements the same pattern as the Sign In button, providing a consistent user experience.

frontend/src/app/(main)/page.tsx (3)

11-13: Good component organization

The new imports for authentication-related modals are appropriately placed together for improved code organization.


97-106: Consistent modal transition implementation

The setTimeout pattern matches the implementation in the AuthChoiceModal component, ensuring a consistent modal transition experience.


109-111: Modal components correctly integrated

The SignInModal and SignUpModal components are properly integrated into the page with appropriate props for open state control and close handling.

PengyuChen01 and others added 2 commits March 4, 2025 21:47
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@Sma1lboy Sma1lboy changed the title Feat fix sidebar need reload when first time load feat(frontend): fix sidebar need reload when first time load Mar 5, 2025
@Sma1lboy Sma1lboy merged commit 4ca3a2c into main Mar 5, 2025
3 of 4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants