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

fix: display same Avatar from WalletButton in dashboard page #939

Merged
merged 4 commits into from
Nov 10, 2024

Conversation

wheval
Copy link
Contributor

@wheval wheval commented Nov 7, 2024

Added alt text for the avatar image and displayed the avatar on the dashboard page.

Please add the labels corresponding to the type of changes your PR introduces:

  • Bugfix

Resolves: #928

Other information

Here's how it looks.
Screenshot (44)

Summary by CodeRabbit

  • New Features

    • Enhanced accessibility for the Avatar component with an alt attribute for user profile images.
    • Updated ProfileCard component to simplify data flow by directly using the user's address for rendering profile pictures.
  • Bug Fixes

    • Improved conditional rendering for profile pictures in the ProfileCard, ensuring default icons are displayed when necessary.

Copy link

vercel bot commented Nov 7, 2024

@wheval is attempting to deploy a commit to the LFG Labs Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor

coderabbitai bot commented Nov 7, 2024

Walkthrough

The changes in this pull request involve modifications to the Avatar and ProfileCard components. The Avatar component now includes an alt attribute for the image, enhancing accessibility by providing descriptive text. In the ProfileCard, the data retrieval method has shifted from using useStarkProfile to directly using formattedAddress, leading to changes in how user profile information is managed and displayed. The profile picture rendering logic has been updated to utilize the Avatar component, improving the integration of user account data.

Changes

File Path Change Summary
components/UI/avatar.tsx Added an alt attribute to the <img> element for accessibility, conditionally set to user’s name or "User".
components/UI/profileCard/profileCard.tsx Removed useStarkProfile import and profileData, updated profile picture rendering logic to use formattedAddress and conditionally display Avatar or default icon.

Assessment against linked issues

Objective Addressed Explanation
Ensure profile picture is defined (928)

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8d2fd03 and e4e7a60.

📒 Files selected for processing (1)
  • components/UI/profileCard/profileCard.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • components/UI/profileCard/profileCard.tsx

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (6)
components/UI/avatar.tsx (3)

35-35: Good addition of accessible alt text!

The dynamic alt text improves accessibility. However, consider making it more descriptive for screen readers.

-          alt={`${profile?.name?.length !== 0 ? profile?.name : "User"}'s avatar`}
+          alt={`Profile picture for ${profile?.name?.length !== 0 ? profile?.name : "User"}`}

Line range hint 19-24: Consider adding error handling for profile data fetching

The profile data fetching in useEffect should include error handling to gracefully handle API failures.

   useEffect(() => {
     if (!starknetIdNavigator) return;
-    starknetIdNavigator.getProfileData(address).then((profile) => {
-      setProfile(profile);
-    });
+    starknetIdNavigator.getProfileData(address)
+      .then((profile) => {
+        setProfile(profile);
+      })
+      .catch((error) => {
+        console.error('Failed to fetch profile:', error);
+        setProfile(null);
+      });
   }, [starknetIdNavigator, address]);

Line range hint 8-13: Strengthen type safety for the StarkProfile interface

The component relies on optional chaining for profile properties. Consider defining stricter types.

 type AvatarProps = {
   address: string;
   width?: string;
+  onError?: (error: Error) => void;
 };

+interface ProfileData extends StarkProfile {
+  name: string | null;
+  profilePicture: string | null;
+}
components/UI/profileCard/profileCard.tsx (3)

51-51: Consider removing unused accountStatus variable.

The accountStatus is destructured from useAccount but never used in the component.

-  const { address, status: accountStatus } = useAccount();
+  const { address } = useAccount();

116-117: Consider type improvements for the width prop.

The Avatar implementation successfully achieves the PR objective of consistent avatar display. However, consider passing the width as a number instead of a string for better type safety.

-            <Avatar width="120" address={formattedAddress} />
+            <Avatar width={120} address={formattedAddress} />

Line range hint 62-83: Consider optimizing the retry logic.

The current implementation has the following concerns:

  1. The while(true) loop with MAX_RETRIES=1000 could lead to excessive retries
  2. No exponential backoff strategy for retries
  3. No break condition in the catch block despite reaching max retries

Consider implementing exponential backoff and proper loop termination:

  const fetchTotalBalance = async () => {
    let attempts = 0;
-   while (true) {
+   while (attempts < MAX_RETRIES) {
      try {
        const balance = await calculateTotalBalance(formattedAddress, "USD", {signal});
        setTotalBalance(balance);
-       return; // Exit if successful
+       break;
      } catch (err) {
        attempts++;
        console.error(`Attempt ${attempts} - Error fetching total balance:`, err);
        
-       if (attempts >= MAX_RETRIES) {
+       if (attempts === MAX_RETRIES) {
          console.error("Failed to fetch total balance after multiple attempts.");
+         break;
        } else {
-         await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY));
+         await new Promise((resolve) => 
+           setTimeout(resolve, RETRY_DELAY * Math.pow(2, attempts - 1))
+         );
        }
      }
    }
  };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ad77f2c and 5e8a404.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (2)
  • components/UI/avatar.tsx (1 hunks)
  • components/UI/profileCard/profileCard.tsx (4 hunks)
🔇 Additional comments (3)
components/UI/avatar.tsx (1)

Line range hint 15-41: Verify profile picture loading behavior

Since this component is central to fixing the avatar display issue (#928), we should verify its usage across the application.

✅ Verification successful

Avatar component implementation is consistently used across the application

The verification shows that:

  • The Avatar component is properly imported and used across 7 different components/pages
  • All instances use the component with the correct props (address and optional width)
  • There are no direct img tag implementations for profile pictures that bypass the Avatar component
  • The component is used in key UI areas including:
    • Leaderboard (RankCard, RankingsTable, page)
    • Navigation (walletButton)
    • Profile displays (profileCard)
    • Quest-related UI (questTag)

The profile picture loading behavior is consistently implemented through this centralized Avatar component, which aligns with the fix for issue #928.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all instances where Avatar component is used
# to ensure consistent implementation across the application

echo "Searching for Avatar component usage..."
rg -l "import.*Avatar.*from.*components/UI/avatar" --type tsx

echo "\nChecking for direct img tag usage that might need to be replaced with Avatar..."
rg -l "img.*src=.*profile.*picture" --type tsx

Length of output: 430


Script:

#!/bin/bash
# Let's try without file type restriction since tsx might not be recognized
# First, find all potential Avatar component imports
echo "Searching for Avatar component usage..."
rg -l "import.*Avatar.*from.*['\"].*avatar['\"]"

echo "\nChecking for direct img tag usage with profile pictures..."
rg -l "img.*src.*profile.*picture"

# Let's also check for the actual component usage
echo "\nChecking for Avatar component usage in JSX..."
rg "<Avatar"

Length of output: 1255

components/UI/profileCard/profileCard.tsx (2)

10-10: LGTM! Import changes align with the PR objectives.

The switch from useStarkProfile to useAccount and the addition of the Avatar component import support the goal of consistent avatar display across the application.

Also applies to: 26-26


Line range hint 1-249: Implementation successfully meets PR objectives.

The changes effectively resolve issue #928 by:

  1. Using the same Avatar component across the application
  2. Properly handling the profile picture display on the dashboard
  3. Maintaining consistent UI elements with appropriate fallbacks

The code is well-structured and maintains good error handling and loading states.

Copy link

vercel bot commented Nov 8, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
sepolia-starknet-quest ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 8, 2024 8:04am
starknet-quest ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 8, 2024 8:04am

Copy link
Contributor

@fricoben fricoben left a comment

Choose a reason for hiding this comment

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

lgtm

Copy link
Contributor

@fricoben fricoben left a comment

Choose a reason for hiding this comment

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

Some small changes

@@ -47,7 +48,7 @@ const ProfileCard: FunctionComponent<ProfileCardProps> = ({
const formattedAddress = (
identity.owner.startsWith("0x") ? identity.owner : `0x${identity.owner}`
) as Address;
const { data: profileData } = useStarkProfile({ address: formattedAddress });
const { address, status: accountStatus } = useAccount();
Copy link
Contributor

Choose a reason for hiding this comment

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

You don't use address or accountStatus here, do you ?

@@ -112,8 +113,8 @@ const ProfileCard: FunctionComponent<ProfileCardProps> = ({
<div className={styles.dashboard_profile_card}>
<div className={styles.left}>
<div className={styles.profile_picture_div}>
{profileData?.profilePicture ? (
<img src={profileData.profilePicture} className="rounded-full" />
{ formattedAddress && formattedAddress?.length !== 0 ? ( // show the avatar of the address in the URL
Copy link
Contributor

Choose a reason for hiding this comment

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

simplify

{formattedAddress?.length ? (

...

Copy link
Contributor Author

Choose a reason for hiding this comment

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

how did i not see that, on it..

@fricoben fricoben added the ❌ Change request Change requested from reviewer label Nov 8, 2024
@wheval
Copy link
Contributor Author

wheval commented Nov 8, 2024

@fricoben please review, thanks!

Copy link
Contributor

@fricoben fricoben left a comment

Choose a reason for hiding this comment

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

lgtm

@fricoben fricoben merged commit 0fe9402 into lfglabs-dev:testnet Nov 10, 2024
0 of 2 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Nov 10, 2024
@wheval wheval deleted the fix/profile-pic-is-never-defined branch November 11, 2024 17:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
❌ Change request Change requested from reviewer
Projects
None yet
Development

Successfully merging this pull request may close these issues.

profile pic is never defined
2 participants