> ## Documentation Index
> Fetch the complete documentation index at: https://docs.twenty.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Аватар

> Представляйте человека или запись с помощью изображения, инициала или значка.

## Обзор

`Avatar` отображает изображение с резервной первой буквой. Используйте его рядом с названием записи или внутри [Chip](https://docs.twenty.com/ru/ui/primitives/data-display/chip.md). Его корневым элементом по умолчанию является презентационный `span`.

**Light**

[Пример Avatar (light)](https://storybook.twenty.com/iframe.html?id=ui-data-display-avatar--display\&viewMode=story\&globals=colorScheme:light)

**Dark**

[Пример Avatar (dark)](https://storybook.twenty.com/iframe.html?id=ui-data-display-avatar--display\&viewMode=story\&globals=colorScheme:dark)

[Open in Storybook](https://storybook.twenty.com/?path=/story/ui-data-display-avatar--display)

## Использование

```tsx theme={null}
import { Avatar } from 'twenty-ui/primitives/data-display';

export const WorkspaceAvatar = () => (
  <Avatar
    name="Acme"
    colorSeed="acme-app"
    shape="square"
    variant="outline"
    size="md"
  />
);
```

Если изображение отсутствует или не загружается, резервный вариант отображает первую букву имени после удаления пробелов в верхнем регистре. Для пустого имени отображается `-`. `colorSeed` выбирает стабильные цвета резервного варианта и по умолчанию использует `name`; используйте идентификатор записи, чтобы цвет оставался стабильным при изменении имени.

Изображение и резервный вариант по умолчанию являются декоративными. `name` задаёт видимый инициал и цвета резервного варианта, не добавляя доступную метку. Если аватар является единственным представлением человека или записи, задайте `imageProps={{ alt: name }}`, чтобы добавить метку и для изображения, и для резервного варианта по умолчанию. Оставляйте аватар декоративным, если видимое имя или помеченный владелец уже предоставляют эту информацию.

`imageProps` принимает полный набор свойств изображения, включая `srcSet`, `sizes`, `crossOrigin`, `referrerPolicy`, нативные события, refs и `render`. Его `src` переопределяет сокращённое свойство `src`. `fallbackProps` принимает полный набор свойств резервного варианта, включая `delay`, дочерние элементы, маркировку, refs и `render`. Пользовательский `render` резервного варианта определяет его семантику доступности; если он декоративный, явно задайте `aria-hidden`.

```tsx theme={null}
import { Avatar } from 'twenty-ui/primitives/data-display';

type RecordAvatarProps = {
  name: string;
  imageUrl?: string;
  initials: string;
};

export const RecordAvatar = ({
  name,
  imageUrl,
  initials,
}: RecordAvatarProps) => (
  <Avatar
    name={name}
    src={imageUrl}
    size="lg"
    imageProps={{ alt: name, decoding: 'async', referrerPolicy: 'no-referrer' }}
    fallbackProps={{ children: initials, delay: 150 }}
  />
);
```

## Скомпонуйте части

Используйте `Avatar.Root`, `Avatar.Image` и `Avatar.Fallback`, когда вы управляете структурой компонента. Root задаёт размер, форму и внешний вид резервного варианта; он не создаёт дочерние элементы или доступные метки.

```tsx theme={null}
import { Avatar } from 'twenty-ui/primitives/data-display';

type ContactAvatarProps = {
  name: string;
  imageUrl?: string;
  initials: string;
};

export const ContactAvatar = ({
  name,
  imageUrl,
  initials,
}: ContactAvatarProps) => (
  <Avatar.Root name={name} shape="circle" size="xxl">
    <Avatar.Image src={imageUrl} alt={name} decoding="async" />
    <Avatar.Fallback role="img" aria-label={name} delay={150}>
      {initials}
    </Avatar.Fallback>
  </Avatar.Root>
);
```

**Light**

[Части аватара (light)](https://storybook.twenty.com/iframe.html?id=ui-data-display-avatar--parts\&viewMode=story\&globals=colorScheme:light)

**Dark**

[Части аватара (dark)](https://storybook.twenty.com/iframe.html?id=ui-data-display-avatar--parts\&viewMode=story\&globals=colorScheme:dark)

[Open in Storybook](https://storybook.twenty.com/?path=/story/ui-data-display-avatar--parts)

Части используют общее состояние загрузки изображения Base UI. По умолчанию Image отображает `img` после успешной загрузки, а Fallback отображает `span`, пока изображение отсутствует, загружается или не удалось загрузить. `delay` откладывает первоначальное отображение резервного варианта на миллисекунды; значение по умолчанию — `0`. Изменённый источник загружается повторно и может заменить текущее изображение или резервный вариант.

`Avatar.Image` предоставляет `onLoadingStatusChange` со значениями статуса `idle`, `loading`, `loaded` и `error`. Колбэк запускается, когда Base UI сообщает об изменении статуса, отличного от `idle`; размонтирование части Image сбрасывает общее состояние корня на `idle`. Root, Image и Fallback принимают зависящие от состояния функции `className`, `style` и `render` с `imageLoadingStatus`; Image также предоставляет `transitionStatus`.

Используйте `keepMounted` для Image, если отображаемое изображение должно загружаться на месте, в том числе с `loading="lazy"` или оптимизированным компонентом изображения. Перенаправляйте нативные атрибуты, события и ref из пользовательских рендереров изображений. Смонтированное изображение всё ещё может загружаться или завершиться ошибкой; проверяйте состояние загрузки, а не считайте его наличие признаком успеха.

Рендерер front-компонента сейчас поддерживает путь предварительной загрузки по умолчанию с `src`. Его изображение-хост не получает `srcSet`, `sizes`, `loading`, `decoding` или `referrerPolicy`. Изменяющаяся пользовательская функция `render` с `keepMounted` может оставить декодированное изображение скрытым, поскольку worker не может прочитать состояние его завершения или размеры. Используйте там предварительную загрузку по умолчанию, пока эти возможности рендерера не станут доступны.

Публичные типы `AvatarRootProps`, `AvatarImageProps`, `AvatarFallbackProps`, `AvatarRootState`, `AvatarImageState`, `AvatarFallbackState` и `AvatarImageLoadingStatus` экспортируются из `twenty-ui/primitives/data-display`. Refs указывают на отображаемый DOM-элемент: по умолчанию это `span`, `img` и `span` либо элемент, переданный через `render`.

## Форма и внешний вид

**Light**

[Размеры и формы аватара (light)](https://storybook.twenty.com/iframe.html?id=ui-data-display-avatar--catalog\&viewMode=story\&globals=colorScheme:light)

**Dark**

[Размеры и формы аватара (dark)](https://storybook.twenty.com/iframe.html?id=ui-data-display-avatar--catalog\&viewMode=story\&globals=colorScheme:dark)

[Open in Storybook](https://storybook.twenty.com/?path=/story/ui-data-display-avatar--catalog)

`shape` принимает значения `square`, `rounded-square` или `circle`. Размеры: `xs` (12px), `sm` (14px), `md` (16px), `lg` (24px), `xl` (32px) и `xxl` (40px). И `xl`, и `xxl` используют резервный текст размером 16px.

Прежний размер `xl` в 40px теперь называется `xxl`. Замените существующие использования `size="xl"` на `size="xxl"`, если они должны оставаться размером 40px.

`variant="outline"` добавляет границу к резервному варианту. Переопределения `color`, `backgroundColor` и `borderColor` настраивают резервный вариант, тогда как загруженное изображение сохраняет исходный вид.

```tsx theme={null}
import { IconUser } from 'twenty-ui/icon';
import { Avatar } from 'twenty-ui/primitives/data-display';

export const ContactIcon = () => (
  <Avatar
    icon={<IconUser />}
    shape="rounded-square"
    size="xxl"
    role="img"
    aria-label="Contact"
  />
);
```

`icon` имеет приоритет как над изображением, так и над резервной первой буквой. Сам значок декоративный, поэтому добавьте метку корневому элементу, если он передаёт информацию. `pulsing` анимирует непрозрачность и учитывает предпочтения уменьшенного движения.

## Открыть профиль

```tsx theme={null}
import { Avatar } from 'twenty-ui/primitives/data-display';

type ProfileAvatarProps = {
  onOpenProfile: () => void;
  disabled?: boolean;
};

export const ProfileAvatar = ({
  onOpenProfile,
  disabled = false,
}: ProfileAvatarProps) => (
  <Avatar
    name="Jane"
    shape="circle"
    size="lg"
    render={
      <button
        type="button"
        disabled={disabled}
        aria-label="Open Jane's profile"
        onClick={onOpenProfile}
      />
    }
  />
);
```

**Light**

[Аватар, скомпонованный как кнопка (light)](https://storybook.twenty.com/iframe.html?id=ui-data-display-avatar--button-composition\&viewMode=story\&globals=colorScheme:light)

**Dark**

[Аватар, скомпонованный как кнопка (dark)](https://storybook.twenty.com/iframe.html?id=ui-data-display-avatar--button-composition\&viewMode=story\&globals=colorScheme:dark)

[Open in Storybook](https://storybook.twenty.com/?path=/story/ui-data-display-avatar--button-composition)

Для действий скомпонуйте нативную кнопку. Она управляет фокусом, активацией клавишами Enter и Space и отключённым состоянием. Задайте доступное имя, соответствующее действию. Разместите `onClick` и `disabled` на отображаемой кнопке; сокращённый Avatar не имеет свойств `onClick`, `disabled` или `nativeButton`.

Для навигации скомпонуйте якорь с `href` или ссылку маршрутизатора, сохраняющую семантику якоря. Нативные ссылки активируются клавишей Enter. Сохраняйте навигационное и отключённое поведение в ссылке или интерактивном компоненте, который вы компонуете.

```tsx theme={null}
import { Avatar } from 'twenty-ui/primitives/data-display';

export const ProfileLink = () => (
  <Avatar
    name="Jane"
    shape="circle"
    size="lg"
    render={<a href="/people/jane" aria-label="Open Jane's profile" />}
  />
);
```

## Перенос кликабельных аватаров

Для действий скомпонуйте нативную кнопку через `render`, а для навигации — якорь или ссылку маршрутизатора. Перенесите `onClick` и `disabled` на этот элемент и удалите `nativeButton`. Задайте элементу полезное доступное имя и избегайте вложенных интерактивных элементов. `Avatar.Root` и другие явные части сохраняют полный контракт событий Base UI.

Сокращённые аватары по умолчанию декоративны. `name` не задаёт имя изображению, резервному варианту или интерактивному элементу-владельцу. Используйте непустой `imageProps.alt` только в том случае, если аватар передаёт идентичность, которая ещё не указана видимым текстом или меткой элемента-владельца. При использовании явных частей самостоятельно задавайте альтернативный текст изображения и метки резервного варианта или декоративные атрибуты, а переведённый контент храните в приложении.

## Свойства

Типы и значения по умолчанию генерируются из общедоступных типов компонента. Явные части принимают нативные атрибуты и обработчики событий. Сокращённый Avatar не включает `onClick`; задайте его элементу-владельцу, переданному через `render`.

**backgroundColor** `string`

Background color override for a first-letter fallback.

**borderColor** `string`

Border color override for the outline fallback.

**className** `string | ((state: AvatarRootState) =\> string | undefined)`

CSS class applied to the element, or a function that
returns a class based on the component's state.

**color** `string`

Text color override for a first-letter fallback.

**colorSeed** `string`

Stable value used to choose fallback colors. Defaults to `name`.

**fallbackProps** `AvatarFallbackProps`

Complete `Avatar.Fallback` props, including caller-owned children, labeling, refs, `render`, and fallback `delay` in milliseconds.

**icon** `ReactNode`

Decorative icon rendered instead of the image and first-letter fallback. Give the root an accessible label when the icon conveys information.

**imageProps** `AvatarImageProps`

Complete `Avatar.Image` props, including native image attributes, refs, `render`, `keepMounted`, and `onLoadingStatusChange`. Alternative text defaults to an empty string. Supply a nonempty `alt` to label the image and default fallback.

**name** `string`

Name used for the first-letter fallback and fallback colors. Does not add an accessible label.

**pulsing** `boolean` (default: false)

Animates the avatar opacity. Respects reduced-motion preferences.

**render** `ReactElement\<unknown, string | JSXElementConstructor\<any\>\> | ComponentRenderFn\<HTMLProps, AvatarRootState\>`

Caller-supplied root element or renderer. Defaults to a presentational span. Compose a native button or link explicitly for interaction, and put its click handler and disabled state on that owner.

**ring** `boolean` (default: false)

Surrounds the avatar with a background-colored ring so overlapping avatars stay distinct.

**shape** `"circle" | "rounded-square" | "square"` (default: square)

Shape of the avatar and its fallback.

**size** `"lg" | "md" | "sm" | "xl" | "xs" | "xxl"` (default: md)

Avatar size: `xs` (12px), `sm` (14px), `md` (16px), `lg` (24px), `xl` (32px), or `xxl` (40px).

**src** `string | null`

Image URL. A missing or failed image shows the fallback. `imageProps.src` overrides this value.

**style** `CSSProperties | ((state: AvatarRootState) =\> CSSProperties | undefined)`

Style applied to the element, or a function that
returns a style object based on the component's state.

**variant** `"outline" | "soft"` (default: soft)

Visual treatment of the fallback.

### Avatar.Root

**Root.backgroundColor** `string`

Background color override for a first-letter fallback.

**Root.borderColor** `string`

Border color override for the outline fallback.

**Root.children** `ReactNode`

Caller-owned Image, Fallback, and other content.

**Root.className** `string | ((state: AvatarRootState) =\> string | undefined)`

CSS class applied to the element, or a function that
returns a class based on the component's state.

**Root.color** `string`

Text color override for a first-letter fallback.

**Root.colorSeed** `string`

Stable value used to choose fallback colors. Defaults to `name`.

**Root.name** `string`

Name used to choose fallback colors. Does not add children or accessible labels.

**Root.pulsing** `boolean` (default: false)

Animates the avatar opacity. Respects reduced-motion preferences.

**Root.render** `ReactElement\<unknown, string | JSXElementConstructor\<any\>\> | ComponentRenderFn\<HTMLProps, AvatarRootState\>`

Caller-supplied root element or renderer. Defaults to a presentational span. Compose a native button or link explicitly for interaction, and put its click handler and disabled state on that owner.

**Root.ring** `boolean` (default: false)

Surrounds the avatar with a background-colored ring so overlapping avatars stay distinct.

**Root.shape** `"circle" | "rounded-square" | "square"` (default: square)

Shape of the avatar and its fallback.

**Root.size** `"lg" | "md" | "sm" | "xl" | "xs" | "xxl"` (default: md)

Avatar size: `xs` (12px), `sm` (14px), `md` (16px), `lg` (24px), `xl` (32px), or `xxl` (40px).

**Root.style** `CSSProperties | ((state: AvatarRootState) =\> CSSProperties | undefined)`

Style applied to the element, or a function that
returns a style object based on the component's state.

**Root.variant** `"outline" | "soft"` (default: soft)

Visual treatment of the fallback.

### Avatar.Image

**Image.alt** `string`

Caller-owned alternative text. Use an empty string for decorative images.

**Image.className** `string | ((state: AvatarImageState) =\> string | undefined)`

CSS class applied to the element, or a function that
returns a class based on the component's state.

**Image.crossOrigin** `"" | "anonymous" | "use-credentials"`

Native image cross-origin policy, also used during preloading.

**Image.keepMounted** `boolean` (default: false)

Keeps the image mounted and loads it in place. Loading and failed images stay hidden while Fallback is shown.

**Image.loading** `"eager" | "lazy"`

Native eager or lazy loading. Use keepMounted for lazy loading.

**Image.onLoadingStatusChange** `((status: ImageLoadingStatus) =\> void)`

Called when Base UI reports a loading, loaded, or error status. Shares that state with Root and Fallback.

**Image.referrerPolicy** `"" | "no-referrer-when-downgrade" | "no-referrer" | "origin-when-cross-origin" | "origin" | "same-origin" | "strict-origin-when-cross-origin" | "strict-origin" | "unsafe-url"`

Native image referrer policy, also used during preloading.

**Image.render** `ReactElement\<unknown, string | JSXElementConstructor\<any\>\> | ComponentRenderFn\<DetailedHTMLProps\<ImgHTMLAttributes\<HTMLImageElement\>, HTMLImageElement\>, AvatarImageState\>`

Replaces the image. Preserve a native image and forward the supplied attributes, events, and ref.

**Image.sizes** `string`

Native responsive image sizes used with srcSet.

**Image.src** `string`

Image URL. Image renders after a successful load unless keepMounted is enabled.

**Image.srcSet** `string`

Native responsive image source candidates.

**Image.style** `CSSProperties | ((state: AvatarImageState) =\> CSSProperties | undefined)`

Style applied to the element, or a function that
returns a style object based on the component's state.

### Avatar.Fallback

**Fallback.children** `ReactNode`

Caller-owned fallback content, such as initials or an icon.

**Fallback.className** `string | ((state: AvatarFallbackState) =\> string | undefined)`

CSS class applied to the element, or a function that
returns a class based on the component's state.

**Fallback.delay** `number` (default: 0)

Milliseconds before the initial fallback is shown. Defaults to 0.

**Fallback.render** `ReactElement\<unknown, string | JSXElementConstructor\<any\>\> | ComponentRenderFn\<HTMLProps, AvatarFallbackState\>`

Replaces the fallback span. Forward the supplied props and ref, and provide its accessible label or decorative attributes.

**Fallback.style** `CSSProperties | ((state: AvatarFallbackState) =\> CSSProperties | undefined)`

Style applied to the element, or a function that
returns a style object based on the component's state.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.