Input · TagInput

TagInput

Taginput is a input component that can add content as a tag.

Demos

How to import

<script lang="ts">
    import { Avatar, Button, TagInput, Toast } from '@fibrae/semi-ui-svelte';
</script>

Basic Usage

After pressing the Enter key, the input will add value as a tag. If the tag content is an empty string or pure space, it will be filtered.

抖音

火山

西瓜视频

Code
<script lang="ts">
    import { TagInput } from '@fibrae/semi-ui-svelte';

    let value = $state(['抖音', '火山', '西瓜视频']);
</script>

<TagInput bind:value placeholder="请输入..." />

Batch Add

You can use separator to set the separator to achieve batch input, and its default value is a comma. Multiple separators are supported in string[] format.



Code
<script lang="ts">
    import { TagInput } from '@fibrae/semi-ui-svelte';

    const separators = ['-', '/', '|', '++'];
</script>

<TagInput placeholder="使用 - 进行批量输入" separator="-" />
<br />
<br />
<TagInput placeholder="支持多个分隔符进行批量输入" separator={separators} />

Batch Remove

You can also use showClear to set whether to support one-click deletion of all tags and input.

抖音

火山

Code
<script lang="ts">
    import { TagInput } from '@fibrae/semi-ui-svelte';

    let value = $state(['抖音', '火山']);
</script>

<TagInput bind:value placeholder="请输入..." showClear />

Disabled

抖音

火山

西瓜视频

Code
<script lang="ts">
    import { TagInput } from '@fibrae/semi-ui-svelte';

    let value = $state(['抖音', '火山', '西瓜视频']);
</script>

<TagInput bind:value disabled placeholder="请输入..." showClear />

Size

Use size to set the size of the TagInput, optional: small, default, large.





Code
<script lang="ts">
    import { TagInput } from '@fibrae/semi-ui-svelte';
</script>

<TagInput placeholder="small" size="small" />
<br />
<br />
<TagInput placeholder="default" />
<br />
<br />
<TagInput placeholder="large" size="large" />

Different validate status

validateStatus: default, warning, error.





Code
<script lang="ts">
    import { TagInput } from '@fibrae/semi-ui-svelte';
</script>

<TagInput placeholder="default" />
<br />
<br />
<TagInput placeholder="warning" validateStatus="warning" />
<br />
<br />
<TagInput placeholder="error" validateStatus="error" />

Prefix / Suffix

You can pass the input box prefix through the prefix snippet and the suffix through the suffix snippet, as text or nodes such as icons.
The left and right padding is added automatically when the snippet content is plain text or an Icon. For custom nodes the padding is 0; set it on the nodes you pass in if needed.



Prefix




Suffix
Code
<script lang="ts">
    import { IconGift, IconVigoLogo } from '@fibrae/semi-icons-svelte';
    import { TagInput } from '@fibrae/semi-ui-svelte';
</script>

<TagInput>
    {#snippet prefix()}
        <IconVigoLogo />
    {/snippet}
</TagInput>
<br />
<br />
<TagInput>
    {#snippet prefix()}Prefix{/snippet}
</TagInput>
<br />
<br />
<TagInput>
    {#snippet suffix()}
        <IconGift />
    {/snippet}
</TagInput>
<br />
<br />
<TagInput>
    {#snippet suffix()}Suffix{/snippet}
</TagInput>

Autocomplete

You can use addOnBlur to set whether the current input value is automatically created as a tag when the blur event is triggered.

抖音

火山

西瓜视频

Code
<script lang="ts">
    import { TagInput } from '@fibrae/semi-ui-svelte';

    let value = $state(['抖音', '火山', '西瓜视频']);
</script>

<TagInput addOnBlur bind:value placeholder="请输入..." />

Allow Duplicates

You can use allowDuplicates to set whether to allow the creation of the same tag.

抖音

火山

西瓜视频

Code
<script lang="ts">
    import { TagInput } from '@fibrae/semi-ui-svelte';

    let value = $state(['抖音', '火山', '西瓜视频']);
</script>

<TagInput allowDuplicates={false} bind:value placeholder="请输入..." />

Limits

You can use max to limit the number of tags. Tags added past the limit are dropped, and the onExceed() callback is invoked.

You can use maxLength to limit the maximum length of a single tag, and the onInputExceed() callback will be invoked when this value is exceeded.

Code
<script lang="ts">
    import { TagInput, Toast } from '@fibrae/semi-ui-svelte';
</script>

<TagInput max={3} onExceed={() => Toast.warning('超过 max')} placeholder="最多输入3条标签.." />
<TagInput maxLength={5} onInputExceed={() => Toast.warning('超过 maxLength')} placeholder="单个标签长度不超过5..." style="margin-top: 12px" />

Limit the number of tags displayed

You can use maxTagCount to limit the number of tags displayed, and the excess will be displayed as +N. You can use showRestTagsPopover to set whether hover +N displays Popover after maxTagCount is exceeded, and you can configure Popover in the restTagsPopoverProps property.

抖音

火山

+1
Code
<script lang="ts">
    import { TagInput } from '@fibrae/semi-ui-svelte';

    let value = $state(['抖音', '火山', '西瓜视频']);
    const restTagsPopoverProps = { position: 'top' } as const;
</script>

<TagInput bind:value maxTagCount={2} {restTagsPopoverProps} showRestTagsPopover />

Controlled Tag

Bind the tags with bind:value to control them. There is no defaultValue: a one-way value={x} only seeds the tags, and bind:value={get, set} makes the input fully controlled. Binding value to undefined clears the tags.

抖音

Code
<script lang="ts">
    import { TagInput } from '@fibrae/semi-ui-svelte';

    let value = $state(['抖音']);
</script>

<TagInput bind:value />

Controlled Input

Bind the input text with bind:inputValue to control it; bind:inputValue={get, set} makes it fully controlled.

Code
<script lang="ts">
    import { TagInput } from '@fibrae/semi-ui-svelte';

    let inputValue = $state('abc');
</script>

<TagInput bind:inputValue />

Callback

抖音

Code
<script lang="ts">
    import { TagInput } from '@fibrae/semi-ui-svelte';

    let value = $state(['抖音']);
    let logs = $state<string[]>([]);

    const log = (message: string) => {
        logs = [message, ...logs].slice(0, 5);
    };
</script>

<TagInput
    bind:value
    onAdd={(tag) => log(`onAdd,新增:${tag}`)}
    onBlur={() => log('onBlur')}
    onChange={(tags) => log(`onChange,当前标签数组:${tags}`)}
    onFocus={() => log('onFocus')}
    onInputChange={(input) => log(`onInputChange,当前输入内容:${input}`)}
    onRemove={(removed, index) => log(`onRemove,移除:${removed},序号:${index}`)}
    placeholder="请输入..."
    showClear
/>
<ul>
    {#each logs as message, index (index)}
        <li>{message}</li>
    {/each}
</ul>

Focus Management

Bind the component with bind:this and call its focus() and blur() methods to manage the focus. focus() focuses the input and activates the component; blur() removes the focus from whichever element inside the component holds it.

抖音

火山

Code
<script lang="ts">
    import { Button, TagInput } from '@fibrae/semi-ui-svelte';

    let value = $state(['抖音', '火山']);
    let tagInput = $state<ReturnType<typeof TagInput>>();
</script>

<TagInput bind:this={tagInput} bind:value />
<Button style="margin-top: 10px" onclick={() => tagInput?.focus()}>点击按钮聚焦</Button>

Custom TagInput rendering

You can use the tag snippet to replace each tag as a whole; it receives { value, index, onClose }. Empty content renders no tag and does not fall back to the default tag. onClose calls preventDefault on the event it receives, so you can pass it straight to a button's onclick.

avatar 夏可漫@semi.com
Code
<script lang="ts">
    import { IconClose } from '@fibrae/semi-icons-svelte';
    import { Avatar, Button, TagInput } from '@fibrae/semi-ui-svelte';

    let value = $state(['夏可漫']);
    const fallbackAvatar = '/assets/placeholder/avatar-a.svg';
    const avatars = new Map([
        ['夏可漫', '/assets/root-web-sites/avatarDemo.jpeg'],
        ['申悦', '/assets/root-web-sites/bf8647bffab13c38772c9ff94bf91a9d.jpg'],
        ['曲晨一', '/assets/root-web-sites/bf8647bffab13c38772c9ff94bf91a9d.jpg'],
        ['文嘉茂', '/assets/root-web-sites/avatarDemo.jpeg'],
    ]);
    const itemStyle = 'background-color: var(--semi-color-info-light-default); padding: 4px 8px; border-radius: 12px; display: flex; align-items: center; font-size: 14px; margin-right: 10px';
</script>

<TagInput bind:value>
    {#snippet tag({ value: tag, onClose })}
        <div style={itemStyle}>
            <Avatar alt="avatar" size="extra-small" src={avatars.get(tag) ?? fallbackAvatar} />
            <span style="margin-left: 8px">{`${tag}@semi.com`}</span>
            <Button aria-label={`移除 ${tag}`} size="small" theme="borderless" type="tertiary" onclick={onClose}>
                {#snippet icon()}
                    <IconClose size="small" />
                {/snippet}
            </Button>
        </div>
    {/snippet}
</TagInput>

Drag to sort

Set draggable to true to enable drag and drop sorting. After the drag function is enabled, once TagInput is focused (by click or Tab) the tags can be dragged; after the focus leaves TagInput they cannot. The drag handle sits beside its tag and works from the keyboard, see "Keyboard and focus" below. Tags with the same value can be sorted separately.

抖音

火山

西瓜视频

Code
<script lang="ts">
    import { TagInput } from '@fibrae/semi-ui-svelte';

    let value = $state(['抖音', '火山', '西瓜视频']);
</script>

<TagInput allowDuplicates={false} bind:value draggable placeholder="请输入..." />

API Reference

Props

PropertyDescriptionTypeDefault
addOnBlurWhether the input text becomes a tag when the focus leaves the component.booleanfalse
allowDuplicatesWhether the same tag can be added more than once.booleantrue
autofocusWhether the input is focused and the component activated on mount; ignored when disabled.booleanfalse
clearIconSnippet that replaces the icon in the clear button; empty content keeps the default icon.Snippet-
disabledWhether the component is disabled.boolean-
draggableWhether tags can be reordered by dragging.booleanfalse
expandRestTagsOnClickWhen not draggable, whether the collapsed tags expand once focus enters the component (click, Tab or the focus method).booleantrue
inputValueCurrent input text, supports bind:inputValue. Left out, the component manages it; for a fully controlled text use the function binding bind:inputValue={get, set}. Binding it to undefined clears the text.string-
insetLabelSnippet for the inset label shown before the input; when prefix is also given, only prefix is shown. When shown, it names an input that has no aria-label or aria-labelledby.Snippet-
insetLabelIdid of the inset label container, for aria-labelledby.string-
maxMaximum number of tags.number-
maxLengthMaximum length of one tag.number-
maxTagCountMaximum number of tags shown; the rest are shown as +N.number-
onAddCalled when tags are added, with the added tags.Type(addedValue: string[]) => void-
onBlurCalled once when the focus leaves the whole component; moving inside it does not call it.Type(event: FocusEvent) => void-
onChangeCalled when the tags change.Type(value: string[]) => void-
onclickCalled on a click on the root element, after the component's own activation handling.TypeMouseEventHandler<T> | null-
onExceedCalled when adding would exceed max, with the whole list before it is cut.Type(value: string[]) => void-
onFocusCalled once when the focus enters from outside; moving between the input, tags and clear button does not call it.Type(event: FocusEvent) => void-
onInputChangeCalled when the input text changes. The event may be an input, keydown, focusout, click or composition event; narrow it by event.type before reading its own fields.Type(value: string, event: Event) => void-
onInputExceedCalled when the input text exceeds maxLength, with the rejected input text.Type(value: string) => void-
onKeyDownCalled on keydown in the input after the component handled it; calling preventDefault there does not stop Enter from adding a tag.Type(event: KeyboardEvent) => void-
onRemoveCalled when a tag is removed, with the removed tag and its index.Type(removedValue: string, index: number) => void-
placeholderPlaceholder of the input while there are no tags.string-
prefixSnippet for the prefix of the input; text or an icon gets side spacing automatically.Snippet-
preventScrollWhether the focus calls inside the component stop the browser from scrolling the focused element into view.boolean-
restTagsPopoverPropsPopover props of the +N popover, without content, child and children.RestTagsPopoverProps-
separatorSeparator(s) for adding several tags at once; null disables splitting.string | string[] | null","
showClearWhether to show the button that clears all tags and the input text.booleanfalse
showContentTooltipWhether hovering a truncated tag shows its full text in an overlay; an object picks the overlay type and the props passed to it.boolean | ShowTooltiptrue
showRestTagsPopoverWhether hovering +N shows the remaining tags in a Popover once maxTagCount is exceeded.booleantrue
sizeSize: small, default or large.TagInputSize-
splitCustom split function that returns the split strings.Type(originString: string, separators: string | string[] | null) => string[]-
suffixSnippet for the suffix of the input; text or an icon gets side spacing automatically.Snippet-
tagSnippet that replaces each tag as a whole, receiving { value, index, onClose }; empty content renders no tag and does not fall back to the default tag.TypeSnippet<[TagInputTagSnippetProps]>-
validateStatusValidation status, which only affects styling; error also sets aria-invalid on the input.TagInputValidateStatus"default"
valueCurrent tags, supports bind:value. Left out, the component manages them; null means controlled with no tags; a one-way value={x} only seeds them, and for a fully controlled input use the function binding bind:value={get, set}. Binding it to undefined clears the tags. There is no defaultValue.string[] | null-

Methods

MethodDescriptionType
blurRemoves focus from whichever element inside the component holds it (input, tag or clear button).Type() => void
focusFocuses the input and activates the component.Type() => void

class (a string, array or object), style (a string) and native attributes and event handlers land on the root element, except id, name, role, tabindex and the aria-* attributes that describe the input (aria-label, aria-labelledby, aria-describedby, aria-invalid, aria-required, aria-controls, aria-expanded, aria-haspopup, aria-autocomplete, aria-activedescendant, aria-errormessage), which land on the inner input. The lowercase listeners onchange, onfocus, onblur and onkeydown are not native passthroughs; use the callbacks onChange, onFocus, onBlur and onKeyDown above. onclick and onmousedown run in addition to the component's own handling.

Accessibility

ARIA

  • TagInput supports the input of aria-label to indicate the function of the TagInput; it lands on the input box, not on the root node;
  • The root node has the group role, which holds the input, the tags and the clear button as one control; when disabled it carries aria-disabled="true", otherwise it has no aria-disabled;
  • When disabled, the input is natively disabled and the tags are static text without an aria-label; with validateStatus set to error the input carries aria-invalid, and an explicit aria-invalid wins;
  • With showClear, tags or input text, and no disabled, a clear button is rendered. It is a native button named "Clear TagInput value" from the locale, shown on hover or while focus is inside the TagInput. From the input, Tab moves to the clear button; Enter or Space clears, as a mouse click does, and the focus goes back to the input. Backspace in the empty input also removes the last tag.

Keyboard and focus

  • Enter in the input adds the input text as a tag; with empty input it does nothing. Enter always has its default action prevented, so a TagInput inside a form never submits it.
  • Backspace in the empty input removes the last tag.
  • A closable tag is a role="button" Tab stop placed before the input; with a tag focused, Backspace or Delete closes it and the focus goes back to the input. When disabled, tags are static text and not focusable.
  • With showClear and some content, the clear button follows the input: Tab reaches it, Enter or Space clears, and the focus goes back to the input.
  • The active state follows the focus: it starts when the focus comes in from outside (click, Tab or focus()) and ends when it leaves the whole component. Moving the focus between the input, the tags and the clear button is not leaving, so it does not fire focus or blur and does not trigger addOnBlur. While active, tags folded by maxTagCount expand (unless expandRestTagsOnClick is false).
  • With draggable and the component active, each tag gets a drag handle that is its own Tab stop, placed before the tag it belongs to. Focus a handle, press Space to pick up, the arrow keys to move and Space to drop; screen readers announce the pick up, moves and drop.

Design Tokens

These are the component's internal Sass variables and cannot be overridden. To customize styles, override the --semi-* CSS variables (see the Design Token page) or write unlayered CSS rules.
Sass variableValueUsage
$transition_duration-tagInput-bgvar(--semi-transition_duration-none)标签输入框-背景色-动画持续时间
$transition_function-tagInput-bgvar(--semi-transition_function-easeIn)标签输入框-背景色-过渡曲线
$transition_delay-tagInput-bgvar(--semi-transition_delay-none)标签输入框-背景色-延迟时间
$transition_duration-tagInput-bordervar(--semi-transition_duration-none)标签输入框-边框-动画持续时间
$transition_function-tagInput-bordervar(--semi-transition_function-easeIn)标签输入框-边框-过渡曲线
$transition_delay-tagInput-bordervar(--semi-transition_delay-none)标签输入框-边框-延迟时间
$color-tagInput-icon-defaultvar(--semi-color-text-2)标签输入框图标颜色 - 默认
$color-tagInput-icon-hovervar(--semi-color-primary-hover)标签输入框图标颜色 - 悬浮
$color-tagInput_disabled-text-defaultvar(--semi-color-disabled-text)标签输入框禁用文字颜色
$color-tagInput_disabled-bgvar(--semi-color-disabled-fill)标签输入框禁用背景色
$color-tagInput_default-bg-focusvar(--semi-color-fill-0)标签输入框背景颜色 - 选中态
$color-tagInput-border-defaulttransparent标签输入框描边颜色 - 默认
$color-tagInput-border-hovertransparent标签输入框描边颜色 - 悬浮
$color-tagInput-border-focusvar(--semi-color-focus-border)标签输入框描边颜色 - 选中态
$color-tagInput_prefix-defaultvar(--semi-color-text-2)标签输入框 prefix 颜色
$color-tagInput_suffix-defaultvar(--semi-color-text-2)标签输入框 suffix 颜色
$color-tagInput_default-bg-defaultvar(--semi-color-fill-0)标签输入框背景颜色 - 默认
$color-tagInput_default-bg-hovervar(--semi-color-fill-1)标签输入框背景颜色 - 悬浮
$color-tagInput_warning-bg-defaultvar(--semi-color-warning-light-default)警告标签输入框背景颜色 - 默认
$color-tagInput_warning-border-defaultvar(--semi-color-warning-light-default)警告标签输入框描边颜色 - 默认
$color-tagInput_warning-bg-hovervar(--semi-color-warning-light-hover)警告标签输入框背景颜色 - 悬浮
$color-tagInput_warning-border-hovervar(--semi-color-warning-light-hover)警告标签输入框描边颜色 - 悬浮
$color-tagInput_warning-bg-focusvar(--semi-color-warning-light-default)警告标签输入框背景颜色 - 选中
$color-tagInput_warning-border-focusvar(--semi-color-warning)警告标签输入框描边颜色 - 选中
$color-tagInput_danger-bg-defaultvar(--semi-color-danger-light-default)危险标签输入框背景颜色 - 默认
$color-tagInput_danger-border-defaultvar(--semi-color-danger-light-default)危险标签输入框描边颜色 - 默认
$color-tagInput_danger-bg-hovervar(--semi-color-danger-light-hover)危险标签输入框背景颜色 - 悬浮
$color-tagInput_danger-border-hovervar(--semi-color-danger-light-hover)危险标签输入框描边颜色 - 悬浮
$color-tagInput_danger-bg-focusvar(--semi-color-danger-light-default)危险标签输入框背景颜色 - 选中
$color-tagInput_danger-border-focusvar(--semi-color-danger)危险标签输入框描边颜色 - 选中
$color-tagInput_sortable_item_over-bgvar(--semi-color-primary)拖拽经过的元素前竖线背景色
$color-tagInput_handler-icon-defaultvar(--semi-color-text-2)可拖拽的标签拖拽按钮颜色
$spacing-tagInput_small-Y1px小尺寸标签输入框标签顶部外边距
$spacing-tagInput_default-Y$spacing-super-tight默认尺寸标签输入框标签顶部外边距
$spacing-tagInput_large-Y3px大尺寸标签输入框标签顶部外边距
$spacing-tagInput_wrapper_n_paddingX$spacing-tight标签输入框标签容器水平内边距
$spacing-tagInput_drag_handler-marginRight4px拖拽handler icon的右外边距
$spacing-tagInput_tag_icon_paddingLeft4pxtag中有handler icon时tag的左内边距
$spacing-tagInput_prefix_suffix-marginX$spacing-base-tight标签输入框 prefix/suffix 水平外边距
$height-tagInput-large$height-control-large大尺寸标签输入框高度
$height-tagInput-default$height-control-default默认尺寸标签输入框高度
$height-tagInput-small$height-control-small小尺寸标签输入框高度
$height-tagInput_input_small20px小尺寸标签输入框Input框高度
$height-tagInput_input_default24px默认尺寸标签输入框Input框高度
$height-tagInput_input_large24px大尺寸标签输入框Input框高度
$width-tagInput-clear-medium$width-icon-medium * 2标签输入框清空按钮宽度
$width-tagInput-border-default$border-thickness-control标签输入框描边描边宽度 - 默认
$width-tagInput-border-hover$width-tagInput-border-default标签输入框描边描边宽度 - 悬浮
$width-tagInput-border-focus$border-thickness-control-focus标签输入框描边宽度 - 选中态
$width-tagInput_sortable_item_over2px拖拽经过的元素前竖线宽度
$radius-tagInputvar(--semi-border-radius-small)标签输入框圆角
$font-tagInput_prefix_suffix-fontWeight$font-weight-bold标签输入框 prefix/suffix 文字字重