Skip to content
Open
27 changes: 26 additions & 1 deletion example/src/Examples/AvatarExample.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { StyleSheet, View } from 'react-native';
import { Image, StyleSheet, View } from 'react-native';

import { Avatar, List, Palette } from 'react-native-paper';

Expand Down Expand Up @@ -36,6 +36,7 @@ const AvatarExample = () => {
<Avatar.Image
style={styles.avatar}
source={require('../../assets/images/avatar.png')}
alt="Jane Doe"
/>
<Avatar.Image
style={styles.avatar}
Expand All @@ -44,6 +45,30 @@ const AvatarExample = () => {
/>
</View>
</List.Section>
<List.Section title="Image fallback">
<View style={styles.row}>
<Avatar.Image
style={styles.avatar}
source={{ uri: 'file:///missing-avatar.png' }}
alt="Jane Doe"
fallback={({ size }) => <Avatar.Text size={size} label="JD" />}
/>
<Avatar.Image
style={styles.avatar}
source={({ style, onError, ...a11y }) => (
<Image
source={require('../../assets/images/avatar.png')}
style={style}
onError={onError}
accessibilityIgnoresInvertColors
{...a11y}
/>
)}
alt="Jane Doe"
fallback={({ size }) => <Avatar.Text size={size} label="JD" />}
/>
</View>
</List.Section>
</ScreenWrapper>
);
};
Expand Down
4 changes: 3 additions & 1 deletion src/components/Avatar/AvatarIcon.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { StyleSheet, View } from 'react-native';
import type { ColorValue, StyleProp, ViewProps, ViewStyle } from 'react-native';

import { DEFAULT_SIZE } from './utils';
import { DEFAULT_SIZE, getLabelledAvatarProps, hasCustomLabel } from './utils';
import { useInternalTheme } from '../../core/theming';
import { cornerFull } from '../../theme/tokens/sys/shape';
import type { ThemeProp } from '../../theme/types';
Expand Down Expand Up @@ -60,6 +60,7 @@ const Avatar = ({
...rest
}: Props) => {
const theme = useInternalTheme(themeOverrides);
const hasLabel = hasCustomLabel(rest);

return (
<View
Expand All @@ -76,6 +77,7 @@ const Avatar = ({
customBackgroundColor ?? theme.colors.primaryContainer,
},
]}
{...(hasLabel && getLabelledAvatarProps(rest.accessibilityRole))}
{...rest}
>
<Icon
Expand Down
165 changes: 150 additions & 15 deletions src/components/Avatar/AvatarImage.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as React from 'react';
import { Image, View } from 'react-native';
import { Image, Platform, StyleSheet, View } from 'react-native';
import type {
ColorValue,
ImageProps,
Expand All @@ -9,22 +9,61 @@ import type {
ViewStyle,
} from 'react-native';

import { DEFAULT_SIZE } from './utils';
import {
DEFAULT_SIZE,
getAvatarImageSourceKey,
getLabelledAvatarProps,
} from './utils';
import { useInternalTheme } from '../../core/theming';
import { cornerFull } from '../../theme/tokens/sys/shape';
import type { ThemeProp } from '../../theme/types';

export type AvatarImageSourceProps = {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

AvatarImageSourceProps is exported here but not from src/index.tsx, which exports only AvatarImageProps. Anyone typing a function source can't import it, and the tests retype the shape inline (Avatar.test.tsx:536, :565, :614). Export it next to AvatarImageProps.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Exported next to AvatarImageProps in c19b81e.

size: number;
style: { width: number; height: number; borderRadius: number };
onError?: ImageProps['onError'];
/**
* Present when the host received a description through `alt`, `aria-label`
* or `accessibilityLabel`, except on Android, where `aria-label` alone is
* announced. Pass it to your image so it is announced by assistive
* technology.
*/
alt?: string;
/**
* Mirrors `alt`. `react-native-web` fills the rendered `<img alt>` from
* `aria-label` only, so pass both to your image.
*/
'aria-label'?: string;
/**
* `false` when the host received no description, marking the image as
* decorative.
*/
accessible?: boolean;
};

export type AvatarImageSource =
| ImageSourcePropType
| ((props: { size: number }) => React.ReactNode);
| ((props: AvatarImageSourceProps) => React.ReactNode);

export type Props = Omit<ViewProps, 'style'> & {
/**
* Image to display for the `Avatar`.
* It accepts a standard React Native Image `source` prop
* Or a function that returns an `Image`.
* or a function that returns an image component.
* Function sources receive `{ size, style, onError, alt, 'aria-label',
* accessible }` matching the host avatar. Apply `style` so the image fills
* the circle, forward the accessibility props for assistive technology, and
* call `onError` to trigger `fallback`.
*/
source: AvatarImageSource;
/**
* Identity of the image that a function `source` renders, for example the
* user id. When it changes, a failed function source loads again instead of
* keeping `fallback`. Without it, `fallback` stays after a function source
* fails. Other sources do not use it, because their `uri` or module id
* identifies them.
*/
sourceKey?: string | number;
/**
* Size of the avatar.
*/
Expand All @@ -39,6 +78,18 @@ export type Props = Omit<ViewProps, 'style'> & {
* Background color should be specified via the `backgroundColor` prop instead.
*/
style?: StyleProp<Omit<ViewStyle, 'backgroundColor'>>;
/**
* Text describing the image for assistive technology. `aria-label` and
* `accessibilityLabel` are treated the same way.
* Leave it out when the name is already shown next to the avatar, such as
* a `List.Item` title, or screen readers read the name twice.
*/
alt?: string;
/**
* Content shown when the image fails to load.
* Receives host `size` so custom content can match the avatar.
*/
fallback?: (props: { size: number }) => React.ReactNode;
/**
* Invoked on load error.
*/
Expand Down Expand Up @@ -78,14 +129,47 @@ export type Props = Omit<ViewProps, 'style'> & {
* import { Avatar } from 'react-native-paper';
*
* const MyComponent = () => (
* <Avatar.Image size={24} source={require('../assets/avatar.png')} />
* <Avatar.Image size={24} source={require('../assets/avatar.png')} alt="Jane Doe" />
* );
* export default MyComponent
* ```
*
* Pass `alt` to describe the image to assistive technology — `aria-label` and
* `accessibilityLabel` work the same way. Avatars without a description are
* treated as decorative and skipped by screen readers, so leave `alt` out when
* the name is already shown next to the avatar.
*
* Show another avatar when the image fails to load:
* ```js
* <Avatar.Image
* size={64}
* source={{ uri: user.avatarUrl }}
* alt="Jane Doe"
* fallback={({ size }) => <Avatar.Text size={size} label="JD" />}
* />
* ```
*
* Custom image components should apply the host `style`, `onError` and the
* accessibility props:
* ```js
* <Avatar.Image
* size={64}
* alt="Jane Doe"
* source={({ size, style, onError, ...a11y }) => (
* <CustomImage source={{ uri }} style={style} onError={onError} {...a11y} />
* )}
* fallback={({ size }) => <Avatar.Text size={size} label="JD" />}
* />
* ```
*/
const AvatarImage = ({
size = DEFAULT_SIZE,
source,
sourceKey: sourceKeyProp,
fallback,
alt,
'aria-label': ariaLabel,
accessibilityLabel,
style,
onError,
onLayout,
Expand All @@ -99,42 +183,93 @@ const AvatarImage = ({
...rest
}: Props) => {
const theme = useInternalTheme(themeOverrides);
const imageStyle = {
width: size,
height: size,
borderRadius: cornerFull,
};
const description = alt ?? ariaLabel ?? accessibilityLabel;
// `Image` makes `alt` an accessibility element, which on Android is a second
// TalkBack stop inside a pressable parent. Android reads `aria-label` alone.
const imageA11y =
description === undefined
? { accessible: false as const }
: Platform.OS === 'android'
? { 'aria-label': description }
: { alt: description, 'aria-label': description };
const sourceKey = getAvatarImageSourceKey(source, sourceKeyProp);
const [failedSource, setFailedSource] = React.useState<{ key: unknown }>();
const hasError =
failedSource !== undefined && Object.is(failedSource.key, sourceKey);

const handleError: ImageProps['onError'] = (event) => {
setFailedSource({ key: sourceKey });
onError?.(event);
};

const showImage = !(hasError && fallback !== undefined);

const hostA11y = showImage
Comment thread
Stoneski93 marked this conversation as resolved.
Resolved
? { accessible: false, importantForAccessibility: 'no' as const }
: description !== undefined
? {
'aria-label': description,
...getLabelledAvatarProps(rest.accessibilityRole),
}
: {};
Comment thread
Stoneski93 marked this conversation as resolved.
Resolved

return (
<View
style={[
{
width: size,
height: size,
borderRadius: cornerFull,
},
imageStyle,
styles.container,
style,
{
backgroundColor:
customBackgroundColor ?? theme.colors.primaryContainer,
},
]}
{...hostA11y}
{...rest}
>
{typeof source === 'function' && source({ size })}
{typeof source !== 'function' && (
{showImage && typeof source === 'function'
? source({
size,
style: imageStyle,
onError: handleError,
...imageA11y,
})
: null}
{showImage && typeof source !== 'function' ? (
<Image
testID={testID}
source={source}
style={{ width: size, height: size, borderRadius: cornerFull }}
onError={onError}
style={imageStyle}
onError={handleError}
onLayout={onLayout}
onLoad={onLoad}
onLoadEnd={onLoadEnd}
onLoadStart={onLoadStart}
onProgress={onProgress}
accessibilityIgnoresInvertColors
{...imageA11y}
/>
)}
) : null}
{!showImage ? (
<View aria-hidden={description !== undefined}>
{fallback({ size })}
</View>
) : null}
</View>
);
};

AvatarImage.displayName = 'Avatar.Image';

const styles = StyleSheet.create({
container: {
overflow: 'hidden',
},
});

export default AvatarImage;
7 changes: 6 additions & 1 deletion src/components/Avatar/AvatarText.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import type {
ViewStyle,
} from 'react-native';

import { DEFAULT_SIZE } from './utils';
import { DEFAULT_SIZE, getLabelledAvatarProps, hasCustomLabel } from './utils';
import { useInternalTheme } from '../../core/theming';
import { cornerFull } from '../../theme/tokens/sys/shape';
import type { ThemeProp } from '../../theme/types';
Expand Down Expand Up @@ -76,6 +76,7 @@ const AvatarText = ({
}: Props) => {
const theme = useInternalTheme(themeOverrides);
const { fontScale } = useWindowDimensions();
const hasLabel = hasCustomLabel(rest);

return (
<View
Expand All @@ -92,6 +93,7 @@ const AvatarText = ({
customBackgroundColor ?? theme.colors.primaryContainer,
},
]}
{...(hasLabel && getLabelledAvatarProps(rest.accessibilityRole))}
{...rest}
>
<Text
Expand All @@ -108,6 +110,9 @@ const AvatarText = ({
]}
numberOfLines={1}
maxFontSizeMultiplier={maxFontSizeMultiplier}
{...(hasLabel
? { 'aria-hidden': true }
: { 'aria-label': label, role: 'img' as const })}
>
{label}
</Text>
Expand Down
Loading
Loading