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(components): add Avatar #1519

Merged
merged 6 commits into from
Jan 15, 2025
Merged
Show file tree
Hide file tree
Changes from 4 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
5 changes: 5 additions & 0 deletions .changeset/witty-kangaroos-grin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@launchpad-ui/components": patch
---

Add `Avatar`
60 changes: 60 additions & 0 deletions packages/components/__tests__/Avatar.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { afterAll, beforeAll, describe, expect, it } from 'vitest';

import { render, screen } from '../../../test/utils';
import { Avatar } from '../src';

class MockImage {
onload: () => void = () => {};
src = '';
constructor() {
setTimeout(() => {
this.onload();
}, 300);
// biome-ignore lint/correctness/noConstructorReturn: <explanation>
return this;
}
}

class ErrorImage {
onerror: () => void = () => {};
src = '';
constructor() {
setTimeout(() => {
this.onerror();
}, 300);
// biome-ignore lint/correctness/noConstructorReturn: <explanation>
return this;
}
}

describe('Avatar', () => {
const orignalGlobalImage = window.Image;

beforeAll(() => {
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
(window.Image as any) = MockImage;
});

afterAll(() => {
window.Image = orignalGlobalImage;
});

it('renders', async () => {
render(<Avatar src="https://avatars.githubusercontent.com/u/2147624?v=4" />);
expect(await screen.findByRole('img')).toBeVisible();
});

it('renders icon on error', async () => {
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
(window.Image as any) = ErrorImage;
render(<Avatar src="https://avatars.githubusercontent.com/u/00000" />);
expect(await screen.findByRole('img', { hidden: true })).toBeVisible();
});

it('renders initials on error', async () => {
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
(window.Image as any) = ErrorImage;
render(<Avatar src="https://avatars.githubusercontent.com/u/00000">RN</Avatar>);
expect(await screen.findByRole('img')).toHaveTextContent('RN');
});
});
105 changes: 105 additions & 0 deletions packages/components/src/Avatar.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import type { IconProps } from '@launchpad-ui/icons';
import type { VariantProps } from 'class-variance-authority';
import type { ImgHTMLAttributes, RefObject, SVGAttributes } from 'react';

import { Icon } from '@launchpad-ui/icons';
import { cva, cx } from 'class-variance-authority';

import styles from './styles/Avatar.module.css';
import { useImageLoadingStatus } from './utils';

const avatar = cva(styles.base, {
variants: {
size: {
small: styles.small,
medium: styles.medium,
large: styles.large,
},
},
defaultVariants: {
size: 'medium',
},
});

const colors = cva(null, {
variants: {
color: {
0: styles.yellow,
1: styles.blue,
2: styles.pink,
3: styles.cyan,
4: styles.purple,
},
},
});

interface AvatarVariants extends VariantProps<typeof avatar> {}

interface AvatarProps extends ImgHTMLAttributes<HTMLImageElement>, AvatarVariants {
ref?: RefObject<HTMLImageElement | null>;
}

interface IconAvatarProps extends Omit<IconProps, 'size'>, AvatarVariants {
ref?: RefObject<SVGSVGElement | null>;
}

interface InitialsAvatarProps extends SVGAttributes<SVGElement>, AvatarVariants {}

const Avatar = ({ className, children, size = 'medium', ref, src, ...props }: AvatarProps) => {
const status = useImageLoadingStatus(src);
Niznikr marked this conversation as resolved.
Show resolved Hide resolved

if (status === 'error') {
return children ? (
<InitialsAvatar size={size}>{children}</InitialsAvatar>
) : (
<IconAvatar size={size} />
);
}

// biome-ignore lint/a11y/useAltText: <explanation>
Niznikr marked this conversation as resolved.
Show resolved Hide resolved
return status === 'loaded' ? (
<img ref={ref} src={src} {...props} className={avatar({ size, className })} />
) : null;
};

const IconAvatar = ({ className, size = 'medium', name = 'person', ...props }: IconAvatarProps) => {
return (
<Icon
name={name}
size={size}
className={cx(avatar({ size, className }), styles.icon)}
{...props}
/>
);
};

const InitialsAvatar = ({
className,
size = 'medium',
children,
...props
}: InitialsAvatarProps) => {
const color = children
? (children.toString().charCodeAt(0) + children.toString().charCodeAt(1)) % 5
: 0;
return (
// biome-ignore lint/a11y/noSvgWithoutTitle: <explanation>
<svg
role="img"
className={cx(
avatar({ size, className }),
colors({ color: color as keyof typeof colors }),
styles.initials,
)}
viewBox="0 0 24 24"
{...props}
>
<text x="50%" y="50%" className={styles.text}>
{children}
</text>
</svg>
);
};

export { Avatar, IconAvatar, InitialsAvatar };
export type { AvatarProps, IconAvatarProps, InitialsAvatarProps };
4 changes: 3 additions & 1 deletion packages/components/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import './styles/base.css';
import './styles/themes.css';

export type { AlertProps } from './Alert';
export type { AvatarProps, IconAvatarProps, InitialsAvatarProps } from './Avatar';
export type { BreadcrumbsProps, BreadcrumbProps } from './Breadcrumbs';
export type { ButtonProps } from './Button';
export type { ButtonGroupProps } from './ButtonGroup';
Expand Down Expand Up @@ -79,6 +80,7 @@ export type { ToolbarProps } from './Toolbar';
export type { TooltipProps, TooltipTriggerProps } from './Tooltip';

export { Alert } from './Alert';
export { Avatar, IconAvatar, InitialsAvatar } from './Avatar';
export { Breadcrumbs, Breadcrumb } from './Breadcrumbs';
export { Button } from './Button';
export { ButtonGroup } from './ButtonGroup';
Expand Down Expand Up @@ -159,4 +161,4 @@ export { ToggleButtonGroup } from './ToggleButtonGroup';
export { ToggleIconButton } from './ToggleIconButton';
export { Toolbar } from './Toolbar';
export { Tooltip, TooltipTrigger } from './Tooltip';
export { useHref, useMedia } from './utils';
export { useHref, useImageLoadingStatus, useMedia } from './utils';
57 changes: 57 additions & 0 deletions packages/components/src/styles/Avatar.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
.base {
background-color: var(--lp-color-bg-ui-primary);
border-radius: 100%;
}

.small {
width: var(--lp-size-16);
height: var(--lp-size-16);
}

.medium {
width: var(--lp-size-24);
height: var(--lp-size-24);
}

.large {
width: var(--lp-size-40);
height: var(--lp-size-40);
}

.icon {
border: 1px solid var(--lp-color-border-ui-primary);
}

.image {
}

.initials {
font: var(--lp-text-label-1-semibold);
font-size: var(--lp-font-size-100);
}

.yellow {
background-color: var(--lp-color-brand-yellow-dark);
}

.blue {
background-color: var(--lp-color-blue-600);
}

.pink {
background-color: var(--lp-color-brand-pink-base);
}

.cyan {
background-color: var(--lp-color-brand-cyan-base);
}

.purple {
background-color: var(--lp-color-purple-600);
}

.text {
fill: var(--lp-color-white-950);
text-anchor: middle;
dominant-baseline: central;
}
36 changes: 34 additions & 2 deletions packages/components/src/utils.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import type { Href } from '@react-types/shared';

import { useEffect, useState } from 'react';
import { useEffect, useLayoutEffect, useState } from 'react';
import { useHref as useRouterHref } from 'react-router';

type ImageLoadingStatus = 'idle' | 'loading' | 'loaded' | 'error';

const useMedia = (media: string) => {
const [isActive, setIsActive] = useState(false);

Expand Down Expand Up @@ -40,4 +42,34 @@ const useHref = (href: Href) => {
return absoluteHref || routerHref;
};

export { useHref, useMedia };
const useImageLoadingStatus = (src?: string) => {
const [loadingStatus, setLoadingStatus] = useState<ImageLoadingStatus>('idle');

useLayoutEffect(() => {
if (!src) {
setLoadingStatus('error');
return;
}

let isMounted = true;
const image = new window.Image();

const updateStatus = (status: ImageLoadingStatus) => () => {
if (!isMounted) return;
setLoadingStatus(status);
};

setLoadingStatus('loading');
image.onload = updateStatus('loaded');
image.onerror = updateStatus('error');
image.src = src;

return () => {
isMounted = false;
};
}, [src]);

return loadingStatus;
};

export { useHref, useImageLoadingStatus, useMedia };
48 changes: 48 additions & 0 deletions packages/components/stories/Avatar.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import type { Meta, StoryObj } from '@storybook/react';
import type { ComponentType } from 'react';

import { Box } from '@launchpad-ui/box';
import { Avatar, IconAvatar, InitialsAvatar } from '../src';

const meta: Meta<typeof Avatar> = {
component: Avatar,
subcomponents: { IconAvatar, InitialsAvatar } as Record<string, ComponentType<unknown>>,
title: 'Components/Content/Avatar',
};

export default meta;

type Story = StoryObj<typeof Avatar>;

export const Example: Story = {
args: {
src: 'https://avatars.githubusercontent.com/u/2147624?v=4',
alt: 'engineer',
},
};

export const Icon: Story = {
render: (args) => <IconAvatar size={args.size} />,
};

export const Initials: Story = {
render: (args) => (
<InitialsAvatar size={args.size} aria-label="LD">
LD
</InitialsAvatar>
),
};

export const Sizes: Story = {
render: (args) => (
<Box display="flex" alignItems="flex-end" gap="$300">
<Avatar size="small" {...args} />
<Avatar size="medium" {...args} />
<Avatar size="large" {...args} />
</Box>
),
args: {
src: 'https://avatars.githubusercontent.com/u/2147624?v=4',
alt: 'engineer',
},
};
Loading