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

Use only text for Avatar #9951

Merged
merged 4 commits into from
Jan 14, 2025
Merged

Use only text for Avatar #9951

merged 4 commits into from
Jan 14, 2025

Conversation

gigincg
Copy link
Member

@gigincg gigincg commented Jan 14, 2025

Proposed Changes

Merge Checklist

  • Add specs that demonstrate bug / test a new feature.
  • Update product documentation.
  • Ensure that UI text is kept in I18n files.
  • Prep screenshot or demo video for changelog entry, and attach it to issue.
  • Request for Peer Reviews
  • Completion of QA

Summary by CodeRabbit

  • New Features

    • Updated avatar component to require a name prop for better input validation.
    • Simplified avatar rendering logic by using a static name for logged-in users.
    • Enhanced loading state handling in the facility home view to improve user experience.
    • Added fallback name for avatars when patient context is not available.
  • Improvements

    • Enhanced avatar generation logic to use only alphabetic characters from names.
    • Improved background color and initials derivation for more consistent avatar rendering.
    • Removed underline style from the ghost button variant for a cleaner appearance.

@gigincg gigincg requested a review from a team as a code owner January 14, 2025 09:34
Copy link
Contributor

coderabbitai bot commented Jan 14, 2025

Walkthrough

The pull request modifies the Avatar.tsx component to improve how the name prop is handled, making it a required field. It introduces a new variable, avatarText, which extracts alphabetic characters from the name, enhancing the logic for background color and initials generation. The LoginHeader.tsx component has been updated to use a static name for the avatar, while the FacilityHome.tsx component adjusts the loading state logic. Additionally, the PatientSwitcher component ensures robust handling of the selected patient context.

Changes

File Change Summary
src/components/Common/Avatar.tsx - Changed name prop from optional to required
- Introduced avatarText to extract alphabetic characters from name prop
- Modified background color generation and initials rendering to use avatarText
src/components/Common/LoginHeader.tsx - Removed dynamic initials logic; replaced with static name "User" for Avatar
- Adjusted styling for Avatar component
src/components/Facility/FacilityHome.tsx - Updated loading state logic to show loading indicator if facilityData is not available
- Changed name prop access to assume facilityData is defined
src/components/ui/avatar.tsx - Deleted file containing Avatar, AvatarImage, and AvatarFallback components
src/components/ui/sidebar/patient-switcher.tsx - Enhanced checks for patientUserContext and defaulted name to "User" if undefined

Assessment against linked issues

Objective Addressed Explanation
Replace SVG text with regular text element The PR does not address the accessibility improvement of using a div/span instead of SVG text.
Ensure proper text styling and centering No clear evidence of text styling changes.

Possibly related PRs

Suggested labels

needs review, tested

Suggested reviewers

  • rithviknishad
  • Jacobjeevan

Poem

🐰 In the meadow where avatars play,
A name now required, come what may,
Colors and initials, all in a line,
With every change, our code will shine!
Hopping through updates, we dance with glee,
For a cleaner code, just wait and see! 🎨


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. (Beta)
  • @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

netlify bot commented Jan 14, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit d16bdaa
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/67867e25ad03c20008a2bdfd
😎 Deploy Preview https://deploy-preview-9951--care-ohc.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link

cloudflare-workers-and-pages bot commented Jan 14, 2025

Deploying care-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: d16bdaa
Status: ✅  Deploy successful!
Preview URL: https://066c10fa.care-fe.pages.dev
Branch Preview URL: https://fix-9950-avatar-text-refacto.care-fe.pages.dev

View logs

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/components/Common/Avatar.tsx (2)

61-61: LGTM! Consider handling edge cases more explicitly.

The regex pattern effectively sanitizes the name to alphabetic characters. However, consider adding a fallback for cases where name is empty or contains no letters.

-  const avatarText = name?.match(/[a-zA-Z]/g)?.join("");
+  const avatarText = name?.match(/[a-zA-Z]/g)?.join("") || "";

Line range hint 61-105: Consider extracting text sanitization logic.

The current implementation effectively sanitizes the avatar text, but the logic could be more maintainable if extracted into a separate utility function. This would:

  1. Make the sanitization rules more visible and maintainable
  2. Allow for easier testing of the sanitization logic
  3. Enable reuse if needed elsewhere

Consider creating a utility function:

const sanitizeAvatarText = (name?: string): string => {
  return name?.match(/[a-zA-Z]/g)?.join("") || "";
};
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4f10987 and fc48288.

📒 Files selected for processing (1)
  • src/components/Common/Avatar.tsx (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: cypress-run (1)
  • GitHub Check: Cloudflare Pages: care-fe
🔇 Additional comments (2)
src/components/Common/Avatar.tsx (2)

62-63: LGTM! Clean implementation of background color calculation.

The background color calculation properly uses the sanitized text while maintaining support for custom colors through propColors.


105-105: Review initials generation logic with sanitized text.

While using sanitized text is good, the current initials() function might not work as expected with avatarText since it:

  1. Splits on spaces which might have been removed during sanitization
  2. Could generate unexpected initials from concatenated words

Let's verify the current behavior:

Consider adjusting the initials logic to handle sanitized text properly:

const initials = (name: string): string => {
+  // If name is too short, use the entire text
+  if (name.length <= 2) return name.toUpperCase();
+  // Otherwise use first and last character
+  return (name[0] + name[name.length - 1]).toUpperCase();
};
✅ Verification successful

The initials implementation works correctly with sanitized text

The current implementation is robust because:

  • The regex /[a-zA-Z]/g preserves word boundaries when joining letters
  • The initials() function correctly handles the resulting text format
  • All component usages pass raw names which are properly sanitized
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for test cases or usage of the Avatar component
rg -l "Avatar.*name=" --type ts --type tsx

Length of output: 72


Script:

#!/bin/bash
# Find initials function implementation
ast-grep --pattern 'const initials = ($params) => { $$$ }'

# Search for Avatar component usage with proper extension patterns
rg -l "Avatar.*name=" --type-add 'tsx:*.tsx' --type-add 'ts:*.ts' --type ts --type tsx

# Look for Avatar-related test files
fd -e test.tsx -e test.ts -e spec.tsx -e spec.ts | grep -i avatar

Length of output: 414


Script:

#!/bin/bash
# Try different pattern for initials function
ast-grep --pattern 'function initials($params) { $$$ }'

# Show Avatar.tsx implementation
cat src/components/Common/Avatar.tsx

# Show context of Avatar usage in found files
rg -A 2 -B 2 "Avatar.*name=" src/pages/Organization/OrganizationFacilities.tsx src/components/Patient/PatientInfoCard.tsx src/components/Common/Charts/ObservationHistoryTable.tsx src/components/ui/sidebar/patient-switcher.tsx

Length of output: 5115

Copy link

cypress bot commented Jan 14, 2025

CARE    Run #4307

Run Properties:  status check passed Passed #4307  •  git commit d16bdaa42c: Use only text for Avatar
Project CARE
Branch Review fix/9950-avatar-text-refactor
Run status status check passed Passed #4307
Run duration 01m 45s
Commit git commit d16bdaa42c: Use only text for Avatar
Committer Gigin George
View all properties for this run ↗︎

Test results
Tests that failed  Failures 0
Tests that were flaky  Flaky 0
Tests that did not run due to a developer annotating a test with .skip  Pending 0
Tests that did not run due to a failure in a mocha hook  Skipped 0
Tests that passed  Passing 4
View all changes introduced in this branch ↗︎

@@ -58,7 +58,9 @@ const Avatar: React.FC<AvatarProps> = ({
className,
icon,
}) => {
const [bgColor] = propColors || (name ? toColor(name) : toColor(""));
const avatarText = name?.match(/[a-zA-Z]/g)?.join("");
Copy link
Member

Choose a reason for hiding this comment

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

Why is name optional for Avatar component 🤔, also this will break the patient login page.
image

Maybe set a defult if name is not avilable like User?

Copy link

Reminder: To add the "needs testing" label, comment "ready for testing" on this PR.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/components/Common/Avatar.tsx (2)

61-63: Consider handling empty avatarText case more gracefully.

The current implementation falls back to an empty string for background color when avatarText is empty, which might not be the best user experience.

Consider this alternative:

-  const [bgColor] =
-    propColors || (avatarText ? toColor(avatarText) : toColor(""));
+  const [bgColor] =
+    propColors || toColor(avatarText || "User");

105-105: Consider showing a fallback for empty avatarText.

When avatarText is empty (no alphabetic characters), the avatar shows no initials.

Consider showing "U" (for "User") as a fallback:

-            {avatarText ? initials(avatarText) : null}
+            {avatarText ? initials(avatarText) : "U"}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fc48288 and f56ead6.

📒 Files selected for processing (5)
  • src/components/Common/Avatar.tsx (3 hunks)
  • src/components/Common/LoginHeader.tsx (2 hunks)
  • src/components/Facility/FacilityHome.tsx (2 hunks)
  • src/components/ui/avatar.tsx (0 hunks)
  • src/components/ui/sidebar/patient-switcher.tsx (3 hunks)
💤 Files with no reviewable changes (1)
  • src/components/ui/avatar.tsx
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cloudflare Pages: care-fe
🔇 Additional comments (6)
src/components/Common/Avatar.tsx (1)

48-48: LGTM! Making the name prop required.

This change aligns with the past review feedback and ensures consistent avatar rendering.

src/components/Common/LoginHeader.tsx (1)

49-53: LGTM! Consistent Avatar usage with fallback name.

The implementation correctly uses a static "User" name and appropriate styling.

src/components/ui/sidebar/patient-switcher.tsx (2)

29-29: LGTM! Improved null safety check.

The additional check for selectedPatient prevents potential runtime errors.


70-70: LGTM! Consistent fallback to "User".

Both Avatar instances correctly handle undefined names by falling back to "User".

Also applies to: 86-86

src/components/Facility/FacilityHome.tsx (2)

162-162: LGTM! Improved loading state check.

The additional check for facilityData prevents rendering with incomplete data.


213-213: LGTM! Direct access to facility name.

Since the loading state ensures facilityData exists, direct access to name is safe.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
src/components/Common/LoginHeader.tsx (1)

42-42: Consider accessibility improvements for the avatar button.

While the implementation is functional, consider adding an aria-label to improve accessibility for screen readers.

-              <Button variant="ghost" size="icon">
-                <Avatar name={"User"} className="w-7 h-7 rounded-full" />
+              <Button variant="ghost" size="icon" aria-label="User menu">
+                <Avatar name="User" className="w-7 h-7 rounded-full" />

Also applies to: 49-50

src/components/Common/Avatar.tsx (2)

22-28: Consider memoizing color calculation for performance.

The color calculation functions could benefit from memoization to avoid recalculating colors for the same name.

+import { useMemo } from "react";

 const stringToIndex = (name: string): number => {
   return name.split("").reduce((acc, char) => acc + char.charCodeAt(0), 0);
 };

 const getColorPair = (name: string): [string, string] => {
   const index = stringToIndex(name) % colorPairs.length;
   return colorPairs[index];
 };

Then in the component:

-  const [bgColor, textColor] =
-    propColors ||
-    (avatarText ? getColorPair(avatarText) : getColorPair("user"));
+  const [bgColor, textColor] = useMemo(
+    () => propColors || (avatarText ? getColorPair(avatarText) : getColorPair("user")),
+    [propColors, avatarText]
+  );

51-51: Consider handling special characters in name processing.

The current regex might drop certain valid characters (e.g., accented characters). Consider using Unicode-aware regex for better international name support.

-  const avatarText = name.match(/[a-zA-Z]+/g)?.join(" ");
+  const avatarText = name.match(/\p{L}+/gu)?.join(" ");
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f56ead6 and d16bdaa.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (3)
  • src/components/Common/Avatar.tsx (2 hunks)
  • src/components/Common/LoginHeader.tsx (2 hunks)
  • src/components/ui/button.tsx (1 hunks)
🔇 Additional comments (5)
src/components/ui/button.tsx (1)

23-23: Verify the removal of underline from ghost variant.

The removal of underline from the ghost variant buttons could affect UI consistency across the application. Please ensure this change aligns with the design system guidelines.

✅ Verification successful

Ghost button hover style change appears safe to proceed

The removal of underline from ghost variant buttons affects 31 files across the application, but the change maintains other hover effects (background and text color changes) that ensure good visual feedback. No design system guidelines were found that would contradict this change.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for ghost variant button usage to assess impact
rg -l 'variant="ghost"' 'src/'

Length of output: 1717


Script:

#!/bin/bash
# Search for design system or style guide documentation
fd -e md -e mdx . src/

Length of output: 52

src/components/Common/LoginHeader.tsx (1)

15-16: LGTM! Clean import organization.

The Avatar import is correctly moved to a dedicated line.

src/components/Common/Avatar.tsx (3)

7-19: LGTM! Well-designed color system.

The color pairs provide good contrast ratios and maintain a professional appearance. The combinations are WCAG compliant and ensure text readability.


72-93: LGTM! Accessible SVG implementation.

The SVG implementation with proper text attributes (textAnchor, dominantBaseline) ensures consistent text centering across browsers.


42-42: LGTM! Required name prop.

Making the name prop required addresses the previous review feedback and prevents potential rendering issues.

@gigincg gigincg merged commit 27fef8d into develop Jan 14, 2025
24 checks passed
@gigincg gigincg deleted the fix/9950-avatar-text-refactor branch January 14, 2025 15:24
Copy link

@gigincg Your efforts have helped advance digital healthcare and TeleICU systems. 🚀 Thank you for taking the time out to make CARE better. We hope you continue to innovate and contribute; your impact is immense! 🙌

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.

Refactor Avatar component to avoid non-text items
2 participants