InputПоле ввода
Поле ввода — это текстовое поле. Input — одна строка, InputTextArea — несколько, а InputPassword, InputSearch и InputOTP — пароль, поиск и одноразовый код. Каждое рендерит нативный <input> или <textarea>.
Когда использовать
- Используйте поле ввода, когда пользователю нужно набрать короткий текст: имя, email, запрос.
InputTextArea— для длинного текста,InputPassword— для секрета,InputSearch— для запроса с действием,InputOTP— для кода.- Чтобы выбрать один или несколько элементов списка, лучше подойдёт флажок.
Примеры
The name is "" no change yet
<script lang="ts">
import { Input } from 'svelte-ant-design';
let name = $state('');
let last = $state('no change yet');
</script>
<!-- bind:value keeps a variable in sync with the field; onchange receives the new text and the native input event. -->
<Input
bind:value={name}
aria-label="Name"
placeholder="Your name"
onchange={(value, event) => (last = `onchange("${value}", ${event.type})`)}
/>
<span>The name is "{name}"</span>
<span role="status">{last}</span>
<script lang="ts">
import { Input } from 'svelte-ant-design';
</script>
<!-- large is 40px high, medium 32px, small 24px. middle and default are aliases of medium. -->
<Input size="large" aria-label="Large" placeholder="large" />
<Input size="medium" aria-label="Medium" placeholder="medium" />
<Input size="small" aria-label="Small" placeholder="small" />
<Input size="middle" aria-label="Middle" placeholder="middle (alias of medium)" />
<Input size="default" aria-label="Default" placeholder="default (alias of medium)" />
<script lang="ts">
import { Input } from 'svelte-ant-design';
</script>
<Input variant="outlined" aria-label="Outlined" placeholder="outlined" />
<Input variant="filled" aria-label="Filled" placeholder="filled" />
<Input variant="borderless" aria-label="Borderless" placeholder="borderless" />
<Input variant="underlined" aria-label="Underlined" placeholder="underlined" />
<script lang="ts">
import { Input } from 'svelte-ant-design';
</script>
<!-- error also sets aria-invalid="true"; warning is a look only. -->
<Input status="error" aria-label="Error" placeholder="Error" value="not an email" />
<Input status="warning" aria-label="Warning" placeholder="Warning" value="maybe a typo" />
<Input status="error" variant="filled" aria-label="Filled error" placeholder="Filled, error" />
<Input status="warning" variant="underlined" aria-label="Underlined warning" placeholder="Underlined, warning" />
<script lang="ts">
import { Input } from 'svelte-ant-design';
</script>
<!-- A disabled field is not focusable and is not submitted; a read-only one is focusable and can be copied. -->
<Input disabled aria-label="Disabled" value="Disabled" />
<Input disabled variant="filled" aria-label="Disabled, filled" value="Disabled, filled" />
<Input readonly aria-label="Read only" value="Read only" />
$ USD kg
<script lang="ts">
import { Input } from 'svelte-ant-design';
</script>
{#snippet at()}
<span aria-hidden="true">@</span>
{/snippet}
{#snippet unit()}
<em>kg</em>
{/snippet}
<!-- prefix and suffix take plain text or a snippet, and sit inside the border. -->
<Input prefix="$" suffix="USD" aria-label="Amount" placeholder="0.00" />
<Input prefix={at} aria-label="User name" placeholder="username" />
<Input suffix={unit} aria-label="Weight" placeholder="Weight" />
https:// .com https:// .org
<script lang="ts">
import { Input } from 'svelte-ant-design';
</script>
{#snippet domain()}
<strong>.com</strong>
{/snippet}
<!-- addonBefore and addonAfter are cells outside the border; they take plain text or a snippet. -->
<Input addonBefore="https://" aria-label="Site" placeholder="example" />
<Input addonAfter={domain} aria-label="Domain" placeholder="example" />
<Input addonBefore="https://" addonAfter=".org" aria-label="Both" placeholder="example" size="small" />
onclear called 0 times
<script lang="ts">
import { Input } from 'svelte-ant-design';
let cleared = $state(0);
</script>
{#snippet bin()}
<span aria-hidden="true">×</span>
{/snippet}
<!-- The clear button shows while there is text. It does not take focus from the field; focus stays in it. -->
<Input allowClear value="Clear me" aria-label="Clearable" onclear={() => cleared++} />
<!-- The object form names the button, takes it out of the Tab order and replaces the icon (text or a snippet). -->
<Input
allowClear={{ label: 'Erase the text', tabIndex: -1, clearIcon: bin }}
value="Custom button"
aria-label="Custom clear button"
/>
<Input allowClear={{ clearIcon: 'x' }} value="Text icon" aria-label="Text icon" />
<span role="status">onclear called {cleared} times</span>
0 0 / 20 0 of 10 used
<script lang="ts">
import { Input } from 'svelte-ant-design';
</script>
<!-- showCount shows the length; with maxlength it shows "n / max" and the browser stops the input at the limit. -->
<Input showCount aria-label="Counted" placeholder="Type something" />
<Input showCount maxlength={20} aria-label="Limited to 20" placeholder="At most 20 characters" />
<Input
showCount={{ formatter: ({ count, maxLength }) => `${count} of ${maxLength} used` }}
maxlength={10}
aria-label="Formatted count"
placeholder="Formatted count"
/>
24 / 10 6 words 0 / 8
<script lang="ts">
import { Input } from 'svelte-ant-design';
// An emoji is one code point, so it is one character here (and a combined emoji is several).
const words = (value: string) => value.trim().split(/\s+/).filter(Boolean).length;
</script>
<!-- max is a soft limit: past it the count turns red and the field is invalid, the text is kept. -->
<Input count={{ max: 10, show: true }} value="more than ten characters" aria-label="Soft limit" />
<!-- strategy replaces the count; show can be a function that formats it. -->
<Input
count={{ strategy: words, show: ({ count }) => `${count} words` }}
value="count the words, not the letters"
aria-label="Words"
/>
<!-- exceedFormatter cuts the text when it passes max (after an IME composition ends, not in the middle of it). -->
<Input
count={{
max: 8,
show: true,
exceedFormatter: (value, { max }) => [...value].slice(0, max).join('')
}}
aria-label="Cut at 8"
placeholder="Cut at 8 characters"
/>
Entered:
<script lang="ts">
import { Input } from 'svelte-ant-design';
let digits = $state('');
let searched = $state('');
</script>
<!-- A function binding can refuse an edit: the field goes back to the last accepted text. Digits only here. -->
<Input
bind:value={() => digits, (next) => (/^\d*$/.test(next) ? (digits = next) : undefined)}
aria-label="Digits only"
placeholder="Digits only"
/>
<!-- onpressenter runs on Enter, but not on the Enter that confirms an IME candidate. -->
<Input
aria-label="Press Enter"
placeholder="Type and press Enter"
onpressenter={(event) => (searched = (event.currentTarget as HTMLInputElement).value)}
/>
<span role="status">Entered: {searched}</span>
0 / 120 nothing yet; Enter pressed 0 times 44 / 20
<script lang="ts">
import { InputTextArea } from 'svelte-ant-design';
let notes = $state('');
let log = $state('nothing yet');
let presses = $state(0);
</script>
<!-- A native textarea with the props of the input: value, allowClear, showCount, maxlength and the callbacks. -->
<InputTextArea
bind:value={notes}
rows={3}
allowClear
showCount
maxlength={120}
aria-label="Notes"
placeholder="Notes"
onchange={(value) => (log = `onchange: ${[...value].length} characters`)}
onpressenter={() => presses++}
onclear={() => (log = 'onclear')}
/>
<span role="status">{log}; Enter pressed {presses} times</span>
<InputTextArea count={{ max: 20, show: true }} value="a note that is longer than twenty characters" aria-label="Soft limit" />
<InputTextArea status="error" variant="filled" aria-label="Filled error" value="Filled, error" />
<InputTextArea size="small" variant="underlined" aria-label="Small underlined" placeholder="Small, underlined" />
<InputTextArea disabled aria-label="Disabled" value="Disabled" />
<InputTextArea readonly aria-label="Read only" value="Read only" />
<script lang="ts">
import { InputTextArea } from 'svelte-ant-design';
let story = $state('Type here and the field grows.\nPress Enter for a new line.');
</script>
<!-- autoSize follows the content, within minRows and maxRows lines; past maxRows the field scrolls. -->
<InputTextArea bind:value={story} autoSize aria-label="Grows with the text" />
<InputTextArea
autoSize={{ minRows: 2, maxRows: 4 }}
aria-label="Two to four rows"
placeholder="Two to four rows"
/>
The password is hidden; the first field toggled 0 times
<script lang="ts">
import { InputPassword } from 'svelte-ant-design';
let shown = $state(false);
let changes = $state(0);
</script>
{#snippet word(visible: boolean)}
<small>{visible ? 'hide' : 'show'}</small>
{/snippet}
<!-- The toggle is a native button named "Show password"; aria-pressed follows the state. -->
<InputPassword aria-label="Password" placeholder="Password" onvisiblechange={() => changes++} />
<!-- bind:visible controls the state from outside. -->
<InputPassword bind:visible={shown} aria-label="Controlled password" value="secret" />
<span role="status">The password is {shown ? 'shown' : 'hidden'}; the first field toggled {changes} times</span>
<!-- visibilityToggle: false hides the button; the object form names it and sets its tab index. -->
<InputPassword visibilityToggle={false} aria-label="No toggle" value="secret" />
<InputPassword
visibilityToggle={{ label: 'Reveal the password', tabIndex: -1 }}
aria-label="Named toggle"
value="secret"
/>
<!-- iconRender replaces the icon and receives the visibility. -->
<InputPassword iconRender={word} aria-label="Text toggle" value="secret" />
nothing searched yet
<script lang="ts">
import { InputSearch } from 'svelte-ant-design';
let log = $state('nothing searched yet');
let busy = $state(false);
function search(value: string, _event: Event, info: { source: 'input' | 'clear' }) {
log = `onsearch("${value}", source: ${info.source})`;
busy = true;
setTimeout(() => (busy = false), 1500);
}
</script>
{#snippet find()}
Find
{/snippet}
{#snippet lens()}
<span aria-hidden="true">?</span>
{/snippet}
<!-- The icon inside the field is a button. A click, Enter and the clear button call onsearch. -->
<InputSearch aria-label="Search" placeholder="Search" allowClear onsearch={search} loading={busy} />
<span role="status">{log}</span>
<!-- enterButton: true is a primary button with the icon; a string or a snippet is its content. -->
<InputSearch aria-label="Search with a button" placeholder="Search" enterButton />
<InputSearch aria-label="Search with text" placeholder="Search" enterButton="Search" size="large" />
<InputSearch aria-label="Search with a snippet" placeholder="Search" enterButton={find} size="small" />
<!-- loading shows a spinner and ignores the search action. -->
<InputSearch aria-label="Loading" value="slow query" enterButton loading />
<InputSearch aria-label="Custom icon" searchIcon={lens} placeholder="Custom icon" />
Six cells, the default The code is "" onchange (all filled): ""; oninput:
Four cells
<script lang="ts">
import { InputOTP } from 'svelte-ant-design';
let code = $state('');
let done = $state('');
let last = $state('');
</script>
<div class="stack">
<div class="field">
<span class="caption">Six cells, the default</span>
<!-- Cells take one character each; focus moves on, Backspace goes back, a pasted code is spread over the cells. -->
<InputOTP
bind:value={code}
aria-label="Verification code"
onchange={(value) => (done = value)}
oninput={(values) => (last = JSON.stringify(values))}
/>
<span>The code is "{code}"</span>
<span role="status">onchange (all filled): "{done}"; oninput: {last}</span>
</div>
<div class="field">
<span class="caption">Four cells</span>
<InputOTP length={4} aria-label="Four digits" />
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 20px;
}
.field {
display: grid;
justify-items: start;
gap: 8px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
mask
mask with a string
formatter
separator as text
- - - - -
separator as a snippet
size, variant, status
size, variant
disabled
<script lang="ts">
import { InputOTP } from 'svelte-ant-design';
</script>
{#snippet dash(index: number)}
<span aria-hidden="true">{index === 1 ? '·' : '-'}</span>
{/snippet}
<div class="stack">
<!-- mask hides the characters (true is a bullet, a string is the character shown); the value is not changed. -->
<div class="field">
<span class="caption">mask</span>
<InputOTP mask aria-label="Masked" length={4} value="1234" />
</div>
<div class="field">
<span class="caption">mask with a string</span>
<InputOTP mask="*" aria-label="Masked with a star" length={4} value="1234" />
</div>
<!-- formatter maps the whole text to the displayed text. -->
<div class="field">
<span class="caption">formatter</span>
<InputOTP formatter={(value) => value.toUpperCase()} aria-label="Uppercase" length={4} value="ab" />
</div>
<!-- separator is text, or a snippet that receives the index of the cell before it. -->
<div class="field">
<span class="caption">separator as text</span>
<InputOTP separator="-" aria-label="Separated" length={6} />
</div>
<div class="field">
<span class="caption">separator as a snippet</span>
<InputOTP separator={dash} aria-label="Separated by a snippet" length={4} />
</div>
<!-- size, variant and status apply to every cell; autocomplete helps the browser fill a code. -->
<div class="field">
<span class="caption">size, variant, status</span>
<InputOTP size="large" variant="filled" status="error" autocomplete="one-time-code" aria-label="Large, filled, error" length={4} />
</div>
<div class="field">
<span class="caption">size, variant</span>
<InputOTP size="small" variant="underlined" aria-label="Small, underlined" length={4} />
</div>
<div class="field">
<span class="caption">disabled</span>
<InputOTP disabled aria-label="Disabled" length={4} value="12" />
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 20px;
}
.field {
display: grid;
justify-items: start;
gap: 8px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
$ 6 USD 15
/ / /
<script lang="ts">
import { Input, InputOTP, InputSearch, InputTextArea } from 'svelte-ant-design';
</script>
<!-- Each component names its parts: classNames adds a class to a part, styles adds inline styles to it. -->
<Input
prefix="$"
suffix="USD"
allowClear
showCount
value="Styled"
aria-label="Styled input"
class="own-root"
style="max-width: 320px"
classNames={{ root: 'own-root-part', prefix: 'own-prefix', suffix: 'own-suffix', clear: 'own-clear', count: 'own-count' }}
styles={{
input: { 'font-weight': 600 },
prefix: { color: '#1677ff' },
suffix: { 'font-style': 'italic' },
count: { 'letter-spacing': '1px' }
}}
/>
<!-- numbers are written as they are (no automatic px); custom properties work too. -->
<InputTextArea
value="Styled textarea"
showCount
aria-label="Styled textarea"
class="own-area"
style="max-width: 360px"
classNames={{ textarea: 'own-textarea' }}
styles={{ textarea: { 'font-family': 'monospace', '--own': 1 }, count: { color: 'crimson' } }}
/>
<!-- InputSearch has one more part, the button. -->
<InputSearch
enterButton="Go"
aria-label="Styled search"
class="own-search"
style="max-width: 360px"
classNames={{ button: 'own-button' }}
styles={{ button: { 'letter-spacing': '1px' } }}
/>
<InputOTP
length={4}
separator="/"
aria-label="Styled code"
class="own-otp"
style="gap: 4px"
classNames={{ input: 'own-cell', separator: 'own-separator' }}
styles={{ input: { 'font-weight': 700 }, separator: { opacity: 0.5 } }}
/>
City The city you live in 0 / 80 A short line about you
<script lang="ts">
import { Input, InputTextArea } from 'svelte-ant-design';
</script>
<!-- A field has no label of its own: name it with an external label, aria-label or aria-labelledby. -->
<label for="input-labels-email">Email</label>
<Input id="input-labels-email" type="email" placeholder="you@example.com" />
<Input aria-label="Search the catalogue" title="Search the catalogue" placeholder="aria-label and title" />
<span id="input-labels-city">City</span>
<Input aria-labelledby="input-labels-city" aria-describedby="input-labels-city-hint" placeholder="aria-labelledby" />
<small id="input-labels-city-hint">The city you live in</small>
<!-- With a count, the count is joined to the field by aria-describedby, after your own ids. -->
<label for="input-labels-bio">Bio</label>
<InputTextArea id="input-labels-bio" showCount maxlength={80} aria-describedby="input-labels-bio-hint" />
<small id="input-labels-bio-hint">A short line about you</small>
<script lang="ts">
import { Button, Input, InputPassword, InputTextArea } from 'svelte-ant-design';
let email = $state('');
let password = $state('');
let about = $state('');
let result = $state('');
function submit(event: SubmitEvent) {
event.preventDefault();
const data = new FormData(event.currentTarget as HTMLFormElement);
result = `Submitted: ${JSON.stringify([...data.entries()])}`;
}
// A native reset does not change the state of the components: reset it here.
function reset() {
email = '';
password = '';
about = '';
result = '';
}
</script>
<!-- name, required and type are native: the form submits the text of each field. -->
<form onsubmit={submit} onreset={reset}>
<Input bind:value={email} type="email" name="email" required aria-label="Email" placeholder="Email" />
<InputPassword bind:value={password} name="password" required autocomplete="new-password" aria-label="New password" />
<InputTextArea bind:value={about} name="about" aria-label="About you" placeholder="About you" />
<Input type="number" name="age" aria-label="Age" placeholder="Age" />
<span>
<Button htmlType="submit" type="primary">Save</Button>
<Button htmlType="reset">Reset</Button>
</span>
</form>
<span role="status">{result}</span>
API
| Свойство | Описание | Тип | По умолчанию |
|---|---|---|---|
| value | Текст. bind:value — двусторонняя привязка; обычное значение — начальный текст. Функциональная привязка может отклонить правку; null считается пустым. | string | '' |
| type | Нативный type. Поддерживаются текстовые типы (text, search, email, tel, url, number). Для пароля используйте InputPassword. | string | 'text' |
| disabled | Нативный disabled: нет фокуса, правки и отправки. | boolean | false |
| readonly | Нативный readonly: получает фокус и копируется, но не редактируется. Кнопка очистки не показывается. | boolean | false |
| size | Размер поля: высота 40px, 32px или 24px. middle и default — совместимые алиасы medium. В SpaceCompact элемент без своего size берёт размер блока. | 'large' | 'medium' | 'middle' | 'small' | 'default' | 'medium' |
| variant | Визуальный вариант. У поля без границы при фокусе рисуется контур. | 'outlined' | 'filled' | 'borderless' | 'underlined' | 'outlined' |
| status | Вид проверки. error ещё ставит aria-invalid="true"; warning меняет только вид. | 'error' | 'warning' | — |
| prefix | Содержимое перед текстом, внутри границы: текст или snippet. | string | Snippet | — |
| suffix | Содержимое после текста, внутри границы, после кнопки очистки и счётчика: текст или snippet. | string | Snippet | — |
| addonBefore | Ячейка перед полем, снаружи границы: текст или snippet. Пока задан addon, поле лежит в элементе-группе; добавление первого addon или удаление последнего пересоздаёт input (он теряет фокус). | string | Snippet | — |
| addonAfter | Ячейка после поля, снаружи границы: текст или snippet. | string | Snippet | — |
| allowClear | Показывает нативную кнопку очистки, пока есть текст (но не при disabled и readonly). Нажатие оставляет фокус в поле и вызывает onchange(""), затем onclear. Объектная форма задаёт иконку, доступное имя (по умолчанию Clear) и tabindex. | boolean | { clearIcon?: string | Snippet; label?: string; tabIndex?: number } | false |
| showCount | Показывает длину текста. С maxlength — n / max. Объектная форма форматирует текст; результат — строка. | boolean | { formatter: (info: CountInfo) => string } | false |
| count | Подсчёт символов: мягкий лимит max (сверх него счётчик красный, поле невалидно, текст сохраняется), strategy заменяет подсчёт (по умолчанию считаются code points), show (как showCount, и он главнее) и exceedFormatter, обрезающий текст. | { max?: number; strategy?: (value: string) => number; show?: boolean | ((info: CountInfo) => string); exceedFormatter?: (value: string, config: { max: number }) => string } | — |
| maxlength | Нативный maxlength: браузер не даёт ввести больше. Для лимита, который лишь предупреждает, используйте count.max. | number | — |
| onchange | Вызывается один раз на каждую правку с новым текстом и событием правки: нативным input или compositionend, если браузер (например, Firefox) завершает IME-композицию раньше последнего input. Как onChange в React. Не вызывается при изменении value родителем и при disabled. Нативный oninput тоже пробрасывается и срабатывает первым. | (value: string, event: Event) => void | — |
| onpressenter | Вызывается по Enter, но не по Enter, подтверждающему кандидат IME. | (event: KeyboardEvent) => void | — |
| onclear | Вызывается после того, как кнопка очистки опустошила текст. | (event: MouseEvent) => void | — |
| classNames | Дополнительные классы частей, добавляются к собственным. | Partial<Record<'root' | 'prefix' | 'input' | 'suffix' | 'clear' | 'count', string>> | — |
| styles | Инлайн-стили частей. Имена свойств — kebab-case или custom properties, числа записываются как есть (без автоматического px). Они сильнее стилей компонента. | Partial<Record<'root' | 'prefix' | 'input' | 'suffix' | 'clear' | 'count', Record<string, string | number>>> | — |
| class | Дополнительный CSS-класс корня. | string | — |
| style | Инлайн-стиль корня; styles.root записывается после него. | string | — |
| native attributes | Нативные атрибуты input (id, name, placeholder, required, autocomplete, inputmode, title, aria-*, data-*, onfocus, onblur, onkeydown, oncompositionstart и другие) передаются в <input>. Компонент управляет value, disabled, readonly, maxlength и onchange. | HTMLInputAttributes | — |
Отличия от Ant Design:
onchange получает (value, event) при каждой правке (React передаёт событие); нет defaultValue: его заменяет bind:value; части — отдельные компоненты (в Svelte нет Input.TextArea); форматтеры showCount и count.show возвращают строку (в React — узел); visible и onvisiblechange у пароля — отдельные свойства (в React они вложены в visibilityToggle); bordered не берём, используйте variant="borderless"; Input.Group и compact не берём.API компонента InputTextArea
| Свойство | Описание | Тип | По умолчанию |
|---|---|---|---|
| value | Как у Input. | string | '' |
| disabled | Как у Input. | boolean | false |
| readonly | Как у Input. | boolean | false |
| size | Как у Input. | 'large' | 'medium' | 'middle' | 'small' | 'default' | 'medium' |
| variant | Как у Input. | 'outlined' | 'filled' | 'borderless' | 'underlined' | 'outlined' |
| status | Как у Input. | 'error' | 'warning' | — |
| allowClear | Как у Input; кнопка стоит в верхнем углу поля. | boolean | { clearIcon?: string | Snippet; label?: string; tabIndex?: number } | false |
| showCount | Как у Input; у счётчика своя строка внизу поля. | boolean | { formatter: (info: CountInfo) => string } | false |
| count | Как у Input. | { max?: number; strategy?: (value: string) => number; show?: boolean | ((info: CountInfo) => string); exceedFormatter?: (value: string, config: { max: number }) => string } | — |
| maxlength | Как у Input. | number | — |
| autoSize | Высота следует за содержимым в пределах minRows и maxRows строк (минимум одна строка); сверх maxRows поле прокручивается. Пересчитывается при изменении текста, ширины или шрифта. Ручное изменение размера при этом скрыто. | boolean | { minRows?: number; maxRows?: number } | false |
| onchange | Как у Input. | (value: string, event: Event) => void | — |
| onpressenter | Как у Input. | (event: KeyboardEvent) => void | — |
| onclear | Как у Input. | (event: MouseEvent) => void | — |
| classNames | Дополнительные классы частей, добавляются к собственным. | Partial<Record<'root' | 'textarea' | 'clear' | 'count', string>> | — |
| styles | Инлайн-стили частей; они сильнее стилей компонента. | Partial<Record<'root' | 'textarea' | 'clear' | 'count', Record<string, string | number>>> | — |
| class | Как у Input. | string | — |
| style | Как у Input. | string | — |
| native attributes | Нативные атрибуты textarea (rows, cols, placeholder, name, id, required, aria-*, data-*, onfocus и другие) передаются в <textarea>. | HTMLTextareaAttributes | — |
API компонента InputPassword
InputPassword принимает все свойства Input, кроме type (его задаёт компонент), и добавляет эти.
| Свойство | Описание | Тип | По умолчанию |
|---|---|---|---|
| visible | Показан ли текст. bind:visible — двусторонняя привязка; обычное значение — начальное состояние. | boolean | false |
| visibilityToggle | Показывает кнопку переключения. false скрывает её, и управлять можно только через visible. Объектная форма задаёт доступное имя (по умолчанию Show password; у кнопки есть aria-pressed, поэтому имя не меняется) и tabindex. | boolean | { tabIndex?: number; label?: string } | true |
| onvisiblechange | Вызывается один раз на каждое переключение пользователем с новым состоянием; не вызывается, когда родитель меняет visible. | (visible: boolean) => void | — |
| iconRender | Своё содержимое кнопки переключения; получает текущую видимость. | Snippet<[visible: boolean]> | — |
API компонента InputSearch
InputSearch принимает все свойства Input и добавляет эти. У его classNames и styles есть ещё одна часть — button.
| Свойство | Описание | Тип | По умолчанию |
|---|---|---|---|
| enterButton | Кнопка после поля: true — основная кнопка с иконкой поиска, строка или snippet — её содержимое. false оставляет только кнопку-иконку внутри поля. Конфликтует с addonAfter: вне production их совместное использование бросает ошибку, в production побеждает кнопка. | boolean | string | Snippet | false |
| loading | Показывает спиннер вместо иконки поиска; действие поиска (клик и Enter) игнорируется. | boolean | false |
| onsearch | Вызывается по клику на иконку или кнопку, по Enter (не во время композиции) и по кнопке очистки. source равен "clear" для кнопки очистки и "input" иначе; для очистки текст пустой. | (value: string, event: Event, info: { source: 'input' | 'clear' }) => void | — |
| searchIcon | Своя иконка поиска: текст или snippet. | string | Snippet | — |
| classNames | Части Input и кнопка поиска button. | Partial<Record<'root' | 'prefix' | 'input' | 'suffix' | 'clear' | 'count' | 'button', string>> | — |
| styles | Инлайн-стили тех же частей. | Partial<Record<'root' | 'prefix' | 'input' | 'suffix' | 'clear' | 'count' | 'button', Record<string, string | number>>> | — |
| class / style | Корень, в который входят поле и кнопка. type равен search, если не задан другой. | string | — |
API компонента InputOTP
| Свойство | Описание | Тип | По умолчанию |
|---|---|---|---|
| value | Введённые символы, без пропусков. bind:value — двусторонняя привязка; обычное значение — начальный текст. Ячейка i показывает i-й символ. | string | '' |
| length | Число ячеек. Значение, не являющееся положительным целым, вне production бросает ошибку, а в production означает 6. | number | 6 |
| mask | Скрывает символы: true показывает точку, строка — единственный символ, показываемый вместо. Значение не меняется. | boolean | string | false |
| formatter | Преобразует весь текст в отображаемый; ячейка с индексом i показывает i-й символ результата. Маска главнее. | (value: string) => string | — |
| separator | Выводится после ячейки с данным индексом (после последней — нет): текст или snippet, получающий индекс. | string | Snippet<[index: number]> | — |
| disabled | Отключает каждую ячейку. | boolean | false |
| size | Размер ячеек; ячейка так же широка, как поле высоко. middle и default — алиасы medium. | 'large' | 'medium' | 'middle' | 'small' | 'default' | 'medium' |
| variant | Визуальный вариант ячеек. | 'outlined' | 'filled' | 'borderless' | 'underlined' | 'outlined' |
| status | Вид проверки ячеек; error ставит aria-invalid каждой. | 'error' | 'warning' | — |
| autocomplete | Нативный autocomplete каждой ячейки; one-time-code включает автозаполнение кода. | HTMLInputAttributes['autocomplete'] | — |
| onchange | Вызывается, когда заполнены все ячейки, с полным текстом; не вызывается при изменении value родителем. | (value: string) => void | — |
| oninput | Вызывается при каждом изменении, по одной записи на ячейку ("" для пустой). | (values: string[]) => void | — |
| classNames | Дополнительные классы корня, ячеек (input) и разделителя. | Partial<Record<'root' | 'input' | 'separator', string>> | — |
| styles | Инлайн-стили тех же частей. | Partial<Record<'root' | 'input' | 'separator', Record<string, string | number>>> | — |
| class | Дополнительный CSS-класс корня. | string | — |
| style | Инлайн-стиль корня; styles.root записывается после него. | string | — |
| native attributes | Нативные атрибуты группы (id, aria-label, aria-labelledby, aria-describedby, data-*, обработчики) передаются в <div>, у которого остаётся role="group". Каждая ячейка названа Character i of n (по-английски; механизм локализации запланирован). | HTMLAttributes<HTMLDivElement> | — |
Методы
Эти методы есть у всех пяти компонентов, через bind:this.
| Метод | Описание | Тип |
|---|---|---|
| focus | Переводит фокус на поле (в InputOTP — на первую пустую ячейку). cursor ставит курсор в начало или конец либо выделяет весь текст; тип без выделения (email, number) его игнорирует. | (options?: { preventScroll?: boolean; cursor?: 'start' | 'end' | 'all' }) => void |
| blur | Снимает фокус с поля. | () => void |
Дизайн-токены
| Токен | Описание | По умолчанию |
|---|---|---|
| --ads-input-font-size | Размер шрифта поля medium. | 14px |
| --ads-input-font-size-lg | Размер шрифта поля large. | 16px |
| --ads-input-font-size-sm | Размер шрифта поля small. | 14px |
| --ads-input-padding-block | Вертикальный отступ поля medium; вместе со строкой и границей даёт высоту 32px. | 4px |
| --ads-input-padding-block-lg | Вертикальный отступ поля large (высота 40px). | 7px |
| --ads-input-padding-block-sm | Вертикальный отступ поля small (высота 24px). | 0px |
| --ads-input-padding-inline | Горизонтальный отступ поля medium. | 11px |
| --ads-input-padding-inline-lg | Горизонтальный отступ поля large. | 11px |
| --ads-input-padding-inline-sm | Горизонтальный отступ поля small. | 7px |
| --ads-input-radius | Радиус скругления поля medium. | 6px |
| --ads-input-radius-lg | Радиус скругления поля large. | 8px |
| --ads-input-radius-sm | Радиус скругления поля small. | 4px |
| --ads-input-border-width | Толщина границы. | 1px |
| --ads-input-line-height | Высота строки полей medium и small. | 1.5714285714285714 |
| --ads-input-line-height-lg | Высота строки поля large. | 1.5 |
| --ads-input-gap | Отступ между текстом и префиксом, кнопкой очистки, счётчиком и суффиксом. | 4px |
| --ads-input-icon-size | Размер иконок очистки, переключения и поиска. | 14px |
| --ads-input-addon-padding-inline | Горизонтальный отступ ячейки addon. | 11px |
| --ads-input-otp-gap | Отступ между ячейками InputOTP. | 8px |
| --ads-input-bg | Фон поля. | #ffffff |
| --ads-input-bg-hover | Фон при наведении. | #ffffff |
| --ads-input-bg-active | Фон в фокусе. | #ffffff |
| --ads-input-border | Граница (контур поля). tokens-accessible.css затемняет её до #737373, чтобы сохранить 3:1 к фону страницы. | #d9d9d9 |
| --ads-input-border-hover | Граница при наведении. tokens-accessible.css затемняет её до #0958d9 (#4096ff даёт 2.99:1). | #4096ff |
| --ads-input-border-active | Граница в фокусе. tokens-accessible.css затемняет её до #1668dc. | #1677ff |
| --ads-input-shadow-active | Кольцо-тень в фокусе. | 0 0 0 2px rgba(5, 145, 255, 0.1) |
| --ads-input-placeholder | Цвет плейсхолдера (наш: в документации его нет). tokens-accessible.css берёт #6b6b6b ради 4.5:1. | rgba(0, 0, 0, 0.25) |
| --ads-input-icon-color | Цвет иконок очистки, переключения и поиска. tokens-accessible.css берёт #737373. | rgba(0, 0, 0, 0.45) |
| --ads-input-icon-color-hover | Цвет этих иконок при наведении. | rgba(0, 0, 0, 0.65) |
| --ads-input-count-color | Цвет счётчика. tokens-accessible.css берёт #666666 ради 4.5:1. Сверх мягкого лимита — --ads-color-danger-text. | rgba(0, 0, 0, 0.45) |
| --ads-input-addon-bg | Фон ячейки addon. | rgba(0, 0, 0, 0.02) |
| --ads-input-filled-bg | Фон варианта filled. | rgba(0, 0, 0, 0.04) |
| --ads-input-filled-bg-hover | Фон варианта filled при наведении (наш). | rgba(0, 0, 0, 0.06) |
| --ads-input-disabled-bg | Фон отключённого поля. | rgba(0, 0, 0, 0.04) |
| --ads-input-disabled-border | Граница отключённого поля. | #d9d9d9 |
| --ads-input-error | Граница статуса error. | #ff4d4f |
| --ads-input-error-hover | Граница статуса error при наведении. tokens-accessible.css затемняет её до #d9363e. | #ff7875 |
| --ads-input-error-shadow | Кольцо-тень статуса error в фокусе. | 0 0 0 2px rgba(255, 38, 5, 0.06) |
| --ads-input-error-bg | Фон варианта filled со статусом error. | #fff2f0 |
| --ads-input-warning | Граница статуса warning. tokens-accessible.css затемняет её до #ad6800 (иначе 1.9:1). | #faad14 |
| --ads-input-warning-hover | Граница статуса warning при наведении (наш). tokens-accessible.css берёт #d46b08. | #ffc53d |
| --ads-input-warning-shadow | Кольцо-тень статуса warning в фокусе. | 0 0 0 2px rgba(255, 215, 5, 0.1) |
| --ads-input-warning-bg | Фон варианта filled со статусом warning. | #fffbe6 |
Доступность
- Поля — нативные элементы
<input>и<textarea>: Tab, выделение, автозаполнение, проверка орфографии и формы берутся из браузера. У поля нет собственной подписи: назовите его через<label for>,aria-labelилиaria-labelledby. status="error"и счётчик сверхcount.maxставятaria-invalid="true". Счётчик связан с полем черезaria-describedbyи не является live-областью, поэтому не озвучивается при каждом нажатии.- Кнопки очистки, показа пароля и поиска — нативные кнопки с доступным именем (
Clear,Show passwordиSearch, по-английски; меняются опциямиlabel). Они остаются в порядке Tab, а нажатие не забирает фокус у поля. - IME:
onpressenterиonsearchне срабатывают на Enter, подтверждающий кандидат, аcount.exceedFormatterобрезает текст только после завершения композиции. InputOTP— этоrole="group"из ячеек с именамиCharacter i of n: Backspace возвращается назад, стрелки перемещают между ячейками (зеркально в правосторонних раскладках), а вставка заполняет ячейки. Ячейка после первой пустой не получает фокус.- Светлые цвета по умолчанию — цвета Ant Design, и они не дотягивают до WCAG: граница даёт 1.41:1, плейсхолдер — 1.83:1. Подключите
tokens-accessible.css, чтобы получить 3:1 для границы и 4.5:1 для плейсхолдера и счётчика; тёмной теме файл не нужен. У вариантовfilledиborderlessграницы нет по замыслу: где граница должна давать 3:1, беритеoutlinedилиunderlined.