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

[Avatar] Adding support for Framework image #3154

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
3 changes: 3 additions & 0 deletions .yarn/versions/5ffaf749.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
releases:
"@radix-ui/react-avatar": patch
primitives: patch
36 changes: 36 additions & 0 deletions packages/react/avatar/src/Avatar.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,17 @@ export default { title: 'Components/Avatar' };

const src = 'https://picsum.photos/id/1005/400/400';
const srcBroken = 'https://broken.link.com/broken-pic.jpg';
const otherSrc = 'https://picsum.photos/id/1006/400/400';

const FakeFrameworkImage = (props: any) => {
console.log(props);

return (
<div>
<img {...props} alt="framework test" data-testid="framework-image-component" />
</div>
);
};

export const Styled = () => (
<>
Expand Down Expand Up @@ -33,6 +44,31 @@ export const Styled = () => (
<AvatarIcon />
</Avatar.Fallback>
</Avatar.Root>

<h1>With image framework component & with fallback</h1>
<Avatar.Root className={rootClass()}>
<Avatar.Image className={imageClass()} alt="John Smith" asChild>
<FakeFrameworkImage src={otherSrc} />
</Avatar.Image>
<Avatar.Fallback delayMs={300} className={fallbackClass()}>
JS
</Avatar.Fallback>
</Avatar.Root>

<h1>With image framework component & with fallback (but broken src)</h1>
<Avatar.Root className={rootClass()}>
<Avatar.Image
className={imageClass()}
alt="John Smith"
onLoadingStatusChange={console.log}
asChild
>
<FakeFrameworkImage src={srcBroken} />
</Avatar.Image>
<Avatar.Fallback delayMs={300} className={fallbackClass()}>
<AvatarIcon />
</Avatar.Fallback>
</Avatar.Root>
</>
);

Expand Down
90 changes: 47 additions & 43 deletions packages/react/avatar/src/Avatar.test.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { axe } from 'jest-axe';
import type { RenderResult } from '@testing-library/react';
import { render, waitFor } from '@testing-library/react';
import { fireEvent, render, waitFor } from '@testing-library/react';
import * as Avatar from '@radix-ui/react-avatar';

const ROOT_TEST_ID = 'avatar-root';
const FALLBACK_TEXT = 'AB';
const IMAGE_ALT_TEXT = 'Fake Avatar';
const DELAY = 300;
const FRAMEWORK_IMAGE_TEST_ID = 'framework-image-component';
const FRAMEWORK_IMAGE_ALT_TEXT = 'framework test';

describe('given an Avatar with fallback and no image', () => {
let rendered: RenderResult;
Expand All @@ -27,24 +29,6 @@ describe('given an Avatar with fallback and no image', () => {
describe('given an Avatar with fallback and a working image', () => {
let rendered: RenderResult;
let image: HTMLElement | null = null;
const orignalGlobalImage = window.Image;

beforeAll(() => {
(window.Image as any) = class MockImage {
onload: () => void = () => {};
src: string = '';
constructor() {
setTimeout(() => {
this.onload();
}, DELAY);
return this;
}
};
});

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

beforeEach(() => {
rendered = render(
Expand All @@ -66,6 +50,7 @@ describe('given an Avatar with fallback and a working image', () => {
});

it('should render the image after it has loaded', async () => {
fireEvent.load(rendered.getByRole('img', { hidden: true }));
image = await rendered.findByRole('img');
expect(image).toBeInTheDocument();
});
Expand Down Expand Up @@ -103,30 +88,6 @@ describe('given an Avatar with fallback and delayed render', () => {

describe('given an Avatar with an image that only works when referrerPolicy=no-referrer', () => {
let rendered: RenderResult;
const orignalGlobalImage = window.Image;

beforeAll(() => {
(window.Image as any) = class MockImage {
onload: () => void = () => {};
onerror: () => void = () => {};
src: string = '';
referrerPolicy: string | undefined;
constructor() {
setTimeout(() => {
if (this.referrerPolicy === 'no-referrer') {
this.onload();
} else {
this.onerror();
}
}, DELAY);
return this;
}
};
});

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

describe('referrerPolicy=no-referrer', () => {
beforeEach(() => {
Expand All @@ -149,6 +110,7 @@ describe('given an Avatar with an image that only works when referrerPolicy=no-r
});

it('should render the image after it has loaded', async () => {
fireEvent.load(rendered.getByRole('img', { hidden: true }));
const image = await rendered.findByRole('img');
expect(image).toBeInTheDocument();
});
Expand Down Expand Up @@ -187,3 +149,45 @@ describe('given an Avatar with an image that only works when referrerPolicy=no-r
});
});
});

describe('given an Avatar with fallback and child image', () => {
let rendered: RenderResult;
let image: HTMLElement | null = null;

beforeEach(() => {
rendered = render(
<Avatar.Root data-testid={ROOT_TEST_ID}>
<Avatar.Image asChild>
<img
src="/test.jpg"
data-testid={FRAMEWORK_IMAGE_TEST_ID}
alt={FRAMEWORK_IMAGE_ALT_TEXT}
/>
</Avatar.Image>
<Avatar.Fallback>{FALLBACK_TEXT}</Avatar.Fallback>
</Avatar.Root>
);
console.log(rendered);
});

it('should render the image after it has loaded', async () => {
fireEvent.load(rendered.getByRole('img', { hidden: true }));
image = await rendered.findByRole('img');
expect(image).toBeInTheDocument();
});

it('should have alt text on the image', async () => {
image = await rendered.findByAltText(FRAMEWORK_IMAGE_ALT_TEXT);
expect(image).toBeInTheDocument();
});

it('should render the fallback initially', () => {
const fallback = rendered.queryByText(FALLBACK_TEXT);
expect(fallback).toBeInTheDocument();
});

it('should render the image framework component', () => {
const frameworkImage = rendered.queryByTestId(FRAMEWORK_IMAGE_TEST_ID);
expect(frameworkImage).toBeInTheDocument();
});
});
76 changes: 28 additions & 48 deletions packages/react/avatar/src/Avatar.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import * as React from 'react';
import { createContextScope } from '@radix-ui/react-context';
import { useCallbackRef } from '@radix-ui/react-use-callback-ref';
import { useLayoutEffect } from '@radix-ui/react-use-layout-effect';
import { Primitive } from '@radix-ui/react-primitive';

import type { Scope } from '@radix-ui/react-context';
Expand Down Expand Up @@ -62,21 +60,35 @@ const AvatarImage = React.forwardRef<AvatarImageElement, AvatarImageProps>(
(props: ScopedProps<AvatarImageProps>, forwardedRef) => {
const { __scopeAvatar, src, onLoadingStatusChange = () => {}, ...imageProps } = props;
const context = useAvatarContext(IMAGE_NAME, __scopeAvatar);
const imageLoadingStatus = useImageLoadingStatus(src, imageProps.referrerPolicy);
const handleLoadingStatusChange = useCallbackRef((status: ImageLoadingStatus) => {
onLoadingStatusChange(status);
context.onImageLoadingStatusChange(status);
});

useLayoutEffect(() => {
if (imageLoadingStatus !== 'idle') {
handleLoadingStatusChange(imageLoadingStatus);
}
}, [imageLoadingStatus, handleLoadingStatusChange]);
const [imageLoadingStatus, setLoadingStatus] = React.useState<ImageLoadingStatus>('loading');

const handleImageEvent = React.useCallback(
(status: ImageLoadingStatus) => (event: React.SyntheticEvent<HTMLImageElement, Event>) => {
status === 'error' ? props.onError?.(event) : props.onLoad?.(event);
setLoadingStatus(status);
onLoadingStatusChange(status);
context.onImageLoadingStatusChange(status);
},
[context, onLoadingStatusChange, props]
);

return imageLoadingStatus === 'loaded' ? (
<Primitive.img {...imageProps} ref={forwardedRef} src={src} />
) : null;
if (imageLoadingStatus === 'error') {
return null;
}

return (
<Primitive.img
{...imageProps}
ref={forwardedRef}
src={src}
style={{
display: imageLoadingStatus === 'loading' ? 'none' : props.style?.display,
...props.style,
}}
onError={handleImageEvent('error')}
onLoad={handleImageEvent('loaded')}
/>
);
}
);

Expand Down Expand Up @@ -116,38 +128,6 @@ AvatarFallback.displayName = FALLBACK_NAME;

/* -----------------------------------------------------------------------------------------------*/

function useImageLoadingStatus(src?: string, referrerPolicy?: React.HTMLAttributeReferrerPolicy) {
const [loadingStatus, setLoadingStatus] = React.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;
if (referrerPolicy) {
image.referrerPolicy = referrerPolicy;
}

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

return loadingStatus;
}
const Root = Avatar;
const Image = AvatarImage;
const Fallback = AvatarFallback;
Expand Down