> ## 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.

# ImageInput

> Выбор изображения, предварительный просмотр и действия загрузки, управляемые вызывающей стороной.

## Обзор

`ImageInput` объединяет предварительный просмотр изображения, нативный выбор файла и действия загрузки, удаления или отмены. `onFileSelect` срабатывает при выборе файла. Ваше приложение проверяет и загружает файл, управляет ходом загрузки и отменой, а также передаёт URL предварительного просмотра через `src`.

**Light**

[Выберите, просмотрите и удалите изображение (light)](https://storybook.twenty.com/iframe.html?id=ui-input-imageinput--display\&viewMode=story\&globals=colorScheme:light)

**Dark**

[Выберите, просмотрите и удалите изображение (dark)](https://storybook.twenty.com/iframe.html?id=ui-input-imageinput--display\&viewMode=story\&globals=colorScheme:dark)

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

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

```tsx theme={null}
import { useState } from 'react';
import { ImageInput } from 'twenty-ui/components/input';

export const WorkspaceImage = () => {
  const [preview, setPreview] = useState<{
    src?: string;
    reader?: FileReader;
  }>({});

  return (
    <ImageInput
      helperText="Choose a square image for your workspace."
      src={preview.src}
      onFileSelect={(file) => {
        const reader = new FileReader();
        setPreview((current) => ({ src: current.src, reader }));
        reader.onload = () => {
          setPreview((current) => {
            if (current.reader !== reader) {
              return current;
            }

            return { src: reader.result?.toString() };
          });
        };
        reader.readAsDataURL(file);
      }}
      onRemove={() => setPreview({})}
    />
  );
};
```

В примере сохраняется текущее предпросмотренное изображение во время чтения замены и игнорируется чтение из удаленных или замененных выборок.

## Выбор и предварительный просмотр

Предварительный просмотр и кнопка «Загрузить» открывают один и тот же нативный выбор файла. `onFileSelect` получает выбранный `File`; сам он не запускает загрузку. Отмена или возврат пустого выбора оставляет текущее изображение без изменений. После выбора поле ввода файла очищается, поэтому тот же файл можно выбрать снова, а `File` в обратном вызове остаётся пригодным для использования.

Компоненты Front поддерживают нативный выбор и читаемое содержимое `File`. Потоки React и Preact, созданные SDK, проверены в Chromium с активацией указателем, клавишами Enter и Space. Средство выбора открывается только после доверенного щелчка внутри компонента. URL-адреса объектов, созданные Worker и назначенные `src` изображения, поддерживают предпросмотр.

По умолчанию `accept` имеет значение `image/*` и фильтрует средство выбора файлов. Проверяйте допустимые форматы, размеры и размер файла в вашем приложении. Этот селектор, управляемый обратными вызовами, не сохраняет файл для нативной отправки формы. Его кнопки действий используют `type="button"`, поэтому не отправляют окружающую форму.

Для пустого изображения или изображения с ошибкой отображается заполнитель. Изменение `src` повторяет попытку предварительного просмотра, в том числе после сбоя загрузки предыдущего изображения. Удаление вызывает `onRemove`; обновите `src` после того, как ваше приложение удалит изображение. Приложение управляет локальными URL предварительного просмотра и отзывает URL объектов, созданные воркером, когда они больше не нужны. Рендерер отвечает за очистку URL предварительного просмотра своего хоста.

## Свойства корневого элемента и поля ввода файла

`className`, `style` и `ref` применяются к корневому div. Корневой ref по умолчанию получает `HTMLDivElement`; для скрытого поля ввода файла используйте `inputRef`. Используйте `render={<div ... />}` для передачи нативных атрибутов корневого элемента или обработчиков событий. Не делайте этот корневой элемент интерактивным, поскольку модуль уже содержит кнопки. `dir` применяется как к корневому элементу, так и к полю ввода файла; для макета справа налево используйте `dir="rtl"`.

Атрибуты нативного поля ввода файла являются свойствами верхнего уровня, включая `accept`, `capture`, `name`, `id`, `title`, `form`, `required`, доступные атрибуты, атрибуты данных и обработчики событий. Они применяются к скрытому полю ввода. `inputRef` получает свой `HTMLInputElement`. Элемент управления всегда использует `type="file"`, принимает один файл и сбрасывает своё значение после каждого выбора. `children`, `dangerouslySetInnerHTML`, `type`, `multiple`, `value`, `defaultValue` и `hidden` нельзя настраивать.

Нативная проверка `required` по-прежнему видит пустое поле ввода после выбора, поскольку поле сбрасывается. Проверяйте завершённые загрузки в своём приложении.

`onChange` получает нативное событие изменения, пока поле ввода всё ещё содержит выбранный файл. Затем поле ввода сбрасывается до срабатывания `onFileSelect`. Свойства нативных событий соответствуют контракту поля ввода React. `onAbort` — это действие отмены загрузки.

## Состояния загрузки и отключения

`isUploading` помечает корневой элемент как занятый и делает выбор и удаление недоступными. Доступные элементы управления остаются доступными для фокуса, поэтому при начале загрузки фокус клавиатуры не теряется. Передайте `onAbort`, чтобы во время загрузки заменить «Загрузить» на «Отменить». Отмена работает до появления первого URL изображения. Приложение управляет отменой и устанавливает `isUploading` обратно в `false` после завершения загрузки.

`disabled` отключает все действия. Для выбора требуется `onFileSelect`. Для удаления необходимы и `onRemove`, и непустой `src`.

**Light**

[Загрузка изображения с действием отмены (light)](https://storybook.twenty.com/iframe.html?id=ui-input-imageinput--uploading\&viewMode=story\&globals=colorScheme:light)

**Dark**

[Загрузка изображения с действием отмены (dark)](https://storybook.twenty.com/iframe.html?id=ui-input-imageinput--uploading\&viewMode=story\&globals=colorScheme:dark)

[Open in Storybook](https://storybook.twenty.com/?path=/story/ui-input-imageinput--uploading)

## Метки, инструкции и ошибки

Предоставьте локализованные строки `uploadLabel`, `removeLabel` и `abortLabel`. По умолчанию они имеют значения `Upload`, `Remove` и `Abort`. Метка загрузки также задаёт имя кнопки предварительного просмотра и скрытого поля ввода файла. Нативные доступные атрибуты могут задавать другое имя поля ввода файла. `aria-describedby` также описывает кнопки выбора и объединяется со вспомогательным текстом приложения и текстом ошибки.

`helperText` и `errorMessage` принадлежат приложению. Оба описывают элементы управления выбором, а ошибки объявляются как предупреждения. Встроенные ограничения файлов или инструкции по продукту отсутствуют.

**Light**

[Поле ввода изображения с инструкциями и ошибкой (light)](https://storybook.twenty.com/iframe.html?id=ui-input-imageinput--with-error\&viewMode=story\&globals=colorScheme:light)

**Dark**

[Поле ввода изображения с инструкциями и ошибкой (dark)](https://storybook.twenty.com/iframe.html?id=ui-input-imageinput--with-error\&viewMode=story\&globals=colorScheme:dark)

[Open in Storybook](https://storybook.twenty.com/?path=/story/ui-input-imageinput--with-error)

## Миграция

Замените `onUpload` на `onFileSelect`. Сохраните `accept` как свойство верхнего уровня. Обратный вызов по-прежнему получает `File`; сохраните существующий код проверки и загрузки в своём приложении.

```tsx theme={null}
import { ImageInput } from 'twenty-ui/components/input';

export const WorkspaceImageSelector = ({
  uploadImage,
}: {
  uploadImage: (file: File) => void;
}) => <ImageInput onFileSelect={uploadImage} accept="image/png, image/jpeg" />;
```

## Свойства

**abortLabel** `string` (default: Abort)

Label for the Abort action.

**accept** `string` (default: image/\*)

Native file picker filter. Defaults to image/\*. The caller validates allowed formats.

**aria-describedby** `string`

Accessible description references for the hidden file input and selection buttons, combined with helperText and errorMessage.

**aria-label** `string`

Accessible name of the hidden file input. Defaults to uploadLabel.

**aria-labelledby** `string`

Accessible name reference for the hidden file input.

**capture** `boolean | "user" | "environment"`

Native device capture hint for the file picker.

**className** `string`

Class applied to the root element.

**dir** `string`

Text direction applied to both the root and hidden file input.

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

Disables file selection, removal, and abort actions.

**errorMessage** `string | null`

Application error, displayed as an alert and associated with the selection controls.

**form** `string`

Native form identifier associated with the hidden file input.

**helperText** `string`

Application instructions, associated with the selection controls.

**id** `string`

Native identifier of the hidden file input.

**inputRef** `Ref\<HTMLInputElement\>`

Ref to the hidden single-file HTMLInputElement.

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

Marks the module busy. Selection and removal controls that would otherwise be enabled stay focusable but unavailable. Shows Abort when onAbort is supplied.

**name** `string`

Native name of the hidden file input.

**onAbort** `(() =\> void)`

Shows an abort action while uploading. It can cancel the first upload before a src exists.

**onChange** `ChangeEventHandler\<HTMLInputElement, HTMLInputElement\>`

Native file input change event, fired while the selected file is present and before the input resets. The input does not retain a file for form submission.

**onFileSelect** `((file: File) =\> void)`

Fires when a file is selected and receives its usable File after the input resets. Empty and canceled selections do not call it. Selection is disabled when omitted. The caller owns validation and uploading.

**onRemove** `(() =\> void)`

Requests removal of the current image. Removal is disabled without this callback or a nonempty src.

**ref** `Ref\<HTMLDivElement\>`

Ref to the root div element.

**removeLabel** `string` (default: Remove)

Label for the Remove action.

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

Custom root element or render function. Supply root native attributes here and keep a non-interactive root.

**required** `boolean`

Native file input requirement. The input resets after selection, so the caller validates completed uploads.

**src** `string | null`

Resolved image URL. Empty or failed images show the image placeholder.

**style** `CSSProperties`

Inline style applied to the root element.

**title** `string`

Native title of the hidden file input.

**uploadLabel** `string` (default: Upload)

Label for the preview, Upload action, and hidden file input.


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