Skip to content

Commit

Permalink
Added Avatar image prop
Browse files Browse the repository at this point in the history
  • Loading branch information
Reggionick committed Jul 20, 2022
1 parent 1c9db48 commit 74948aa
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 3 deletions.
4 changes: 4 additions & 0 deletions packages/bento-design-system/src/Avatar/Avatar.css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,7 @@ export const avatarRecipe = strictRecipe({
},
},
});

export const avatarImage = bentoSprinkles({
width: 24,
});
30 changes: 27 additions & 3 deletions packages/bento-design-system/src/Avatar/createAvatar.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { Label } from "..";
import { avatarRecipe } from "./Avatar.css";
import { avatarImage, avatarRecipe } from "./Avatar.css";
import { Box } from "../internal";
import { AvatarConfig } from "./Config";
import { useEffect, useState } from "react";

type Props = {
name?: string;
Expand All @@ -16,14 +17,28 @@ type Props = {
| "indigo"
| "violet"
| "pink";
imageSrc?: string;
};

export type { Props as AvatarProps };

export function createAvatar(config: AvatarConfig) {
return function Avatar({ color, name }: Props) {
return function Avatar({ color, name, imageSrc }: Props) {
const initial = name?.trim()[0];

const [imageAvailable, setImageAvailable] = useState<boolean | undefined>(undefined);

useEffect(() => {
setImageAvailable(undefined);
}, [imageSrc]);

const handleImageLoaded = () => {
setImageAvailable(true);
};
const handleImageErrored = () => {
setImageAvailable(false);
};

return (
<Box display="flex">
<Box
Expand All @@ -35,7 +50,16 @@ export function createAvatar(config: AvatarConfig) {
borderRadius={config.radius}
boxShadow={config.outline}
>
{initial ? (
{imageSrc && imageAvailable !== false ? (
<Box
as="img"
display={imageAvailable ? "block" : "none"}
src={imageSrc}
className={avatarImage}
onLoad={handleImageLoaded}
onError={handleImageErrored}
/>
) : initial ? (
<Label size={config.labelSize}>{initial}</Label>
) : (
config.icon({
Expand Down
10 changes: 10 additions & 0 deletions packages/storybook/stories/Components/Avatar.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,13 @@ export const WithoutName = createStory({
color: "blue",
name: undefined,
});

export const WithImageUrl = createStory({
color: "blue",
imageSrc: "https://bento.buildo.io/img/logo.svg",
});

export const WithImageUrlBroken = createStory({
color: "blue",
imageSrc: "https://bento.buildo.io/broken-url.svg",
});

0 comments on commit 74948aa

Please sign in to comment.