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

[#530]: Profile avatar is now either Github profile picture, or capitalized first letter of username #534

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions frontend/src/components/Avatar/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@ function Avatar({ username }) {
style={{
fontSize: '20px',
fontWeight: 300,
letterSpacing: '-2px',
pointerEvents: 'none',
}}
x="20%"
y="50%"
textAnchor="middle"
x="50%"
y="52%"
>
{username}
</text>
Expand Down
38 changes: 37 additions & 1 deletion frontend/src/components/Navigation/UserMenu.jsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useDispatch, useSelector } from 'react-redux';

Expand Down Expand Up @@ -26,6 +27,28 @@ function UserMenu() {
dispatch(actions.openModal({ type: 'newSnippet' }));
};

// The following code checks if the Github profile picture exists
const imageExists = (url) => {
return new Promise((resolve) => {
const img = new Image();
img.onload = () => resolve(true);
img.onerror = () => resolve(false);
img.src = url;
});
};

const [githubImageExists, setGithubExists] = useState(false);

useEffect(() => {
const url = `https://github.com/${username}.png`;
imageExists(url).then((exists) => setGithubExists(exists));
}, [username]);

// This function takes the first letter of the username and converts it to uppercase
const capitalizeFirstLetter = (string) => {
return string.charAt(0).toUpperCase();
};

return (
<Dropdown align="end" as="li" title="User Menu">
<Dropdown.Toggle
Expand All @@ -34,7 +57,20 @@ function UserMenu() {
variant="link"
>
<div className="logo-height">
<Avatar username={username} />
{githubImageExists ? (
<img
alt="Github Profile"
src={`https://github.com/${username}.png`}
style={{
position: 'relative',
width: '32px',
height: '32px',
borderRadius: '50%',
}}
/>
) : (
<Avatar username={capitalizeFirstLetter(username)} />
)}
</div>
<span className="visually-hidden">{tPA('header')}</span>
</Dropdown.Toggle>
Expand Down
Loading