# or
yarn add @zag-js/tags-input @zag-js/svelte
```

## Anatomy

To set up the tags input correctly, you'll need to understand its anatomy and
how we name its parts.

> Each part includes a `data-part` attribute to help identify them in the DOM.



## Usage

First, import the tags input package into your project

```jsx
import * as tagsInput from "@zag-js/tags-input"
```

The tags input package exports two key functions:

- `machine` â The state machine logic for the tags input widget.
- `connect` â The function that translates the machine's state to JSX attributes
  and event handlers.

> You'll also need to provide a unique `id` to the `useMachine` hook. This is
> used to ensure that every part has a unique identifier.

Next, import the required hooks and functions for your framework and use the
tags input machine in your project ð¥

```svelte
<script lang="ts">
  import * as tagsInput from "@zag-js/tags-input"
  import { useMachine, normalizeProps } from "@zag-js/svelte"

  const id = $props.id()
  const service = useMachine(tagsInput.machine, {
    id,
    defaultValue: ["React", "Vue"],
  })
  const api = $derived(tagsInput.connect(service, normalizeProps))
</script>

<div {...api.getRootProps()}>
  {#each api.value as value, index}
    <span {...api.getItemProps({ index, value })}>
      <div {...api.getItemPreviewProps({ index, value })}>
        <span>{value} </span>
        <button {...api.getItemDeleteTriggerProps({ index, value })}> &#x2715; </button>
      </div>
      <input {...api.getItemInputProps({ index, value })} />
    </span>
  {/each}
  <input placeholder="Add tag..." {...api.getInputProps()} />
</div>
```

### Navigating and Editing tags

When the input has an empty value or the caret is at the start position, the
tags can be selected by using the arrow left and arrow right keys. When "visual"
focus in on any tag:

- Pressing `Enter` or double clicking on the tag will put the it in edit mode,
  allowing the user change its value and press `Enter` to commit the changes.
- Pressing `Delete` or `Backspace` will delete the tag that has "visual" focus.

### Setting the initial tags

To set the initial tag values, pass the `defaultValue` property in the machine's
context.

```jsx {2}
const service = useMachine(tagsInput.machine, {
  defaultValue: ["React", "Redux", "TypeScript"],
})
```

### Controlled tags input

To control the tags input programmatically, pass the `value` and `onValueChange`
properties to the machine function.

```svelte
<script lang="ts">
  let value = $state(["React", "Vue"])

  const service = useMachine(tagsInput.machine, {
    get value() {
      return value
    },
    onValueChange(details) {
      value = details.value
    },
  })
</script>
```

### Removing all tags

The tags input will remove all tags when the clear button is clicked. To remove
all tags, use the provided `clearButtonProps` function from the `api`.

```jsx {4}
//...
<div {...api.getControlProps()}>
  <input {...api.getInputProps()} />
  <button {...api.getClearButtonProps()} />
</div>
//...
```

To programmatically remove all tags, use the `api.clearAll()` method that's
available in the `connect`.

### Usage within forms

The tags input works when placed within a form and the form is submitted. We
achieve this by:

- ensuring we emit the input event as the value changes.
- adding a `name` and `value` attribute to a hidden input so the tags can be
  accessed in the `FormData`.

To get this feature working you need to pass a `name` option to the context and
render the `hiddenInput` element.

```jsx {2}
const service = useMachine(tagsInput.machine, {
  name: "tags",
  defaultValue: ["React", "Redux", "TypeScript"],
})
```

### Limiting the number of tags

To limit the number of tags within the component, you can set the `max` property
to the limit you want. The default value is `Infinity`.

When the tag reaches the limit, new tags cannot be added except the
`allowOverflow` option is passed to the context.

```jsx {2-3}
const service = useMachine(tagsInput.machine, {
  max: 10,
  allowOverflow: true,
})
```

### Validating Tags

Before a tag is added, the machine provides a `validate` function you can use to
determine whether to accept or reject a tag.

> **Note:** Duplicate tags are automatically prevented by design. You don't need
> to handle this in your `validate` function.

Common use-cases for validating tags include enforcing format, length, or
content rules.

```jsx {2-4}
const service = useMachine(tagsInput.machine, {
  validate(details) {
    // Example: only allow lowercase alphabetic tags
    return /^[a-z]+$/.test(details.inputValue)
  },
})
```

### Blur behavior

When the tags input is blurred, you can configure the action the machine should
take by passing the `blurBehavior` option to the context.

- `"add"` â Adds the tag to the list of tags.
- `"clear"` â Clears the tags input value.

```jsx {2}
const service = useMachine(tagsInput.machine, {
  blurBehavior: "add",
})
```

### Paste behavior

To add a tag when a arbitrary value is pasted in the input element, pass the
`addOnPaste` option.

When a value is pasted, the machine will:

- check if the value is a valid tag based on the `validate` option
- split the value by the `delimiter` option passed

```jsx {2}
const service = useMachine(tagsInput.machine, {
  addOnPaste: true,
})
```

### Disable tag editing

by default the tags can be edited by double clicking on the tag or focusing on
them and pressing `Enter`. To disable this behavior, pass the
`allowEditTag: false`

```jsx {2}
const service = useMachine(tagsInput.machine, {
  allowEditTag: false,
})
```

### Listening for events

During the lifetime of the tags input interaction, here's a list of events we
emit:

- `onValueChange` â invoked when the tag value changes.
- `onHighlightChange` â invoked when a tag has visual focus.
- `onValueInvalid` â invoked when the max tag count is reached or the `validate`
  function returns `false`.

```jsx
const service = useMachine(tagsInput.machine, {
  onValueChange(details) {
    // details => { value: string[] }
    console.log("tags changed to:", details.value)
  },
  onHighlightChange(details) {
    // details => { value: string }
    console.log("highlighted tag:", details.value)
  },
  onValueInvalid(details) {
    console.log("Invalid!", details.reason)
  },
})
```

## Styling guide

Earlier, we mentioned that each accordion part has a `data-part` attribute added
to them to select and style them in the DOM.

### Focused state

The combobox input is focused when the user clicks on the input element. In this
focused state, the root, label, input.

```css
[data-part="root"][data-focus] {
  /* styles for root focus state */
}

[data-part="label"][data-focus] {
  /* styles for label focus state */
}

[data-part="input"]:focus {
  /* styles for input focus state */
}
```

### Invalid state

When the tags input is invalid by setting the `invalid: true` in the machine's
context, the `data-invalid` attribute is set on the root, input, control, and
label.

```css
[data-part="root"][data-invalid] {
  /* styles for invalid state for root */
}

[data-part="label"][data-invalid] {
  /*  styles for invalid state for label */
}

[data-part="input"][data-invalid] {
  /*  styles for invalid state for input */
}
```

### Disabled state

When the tags input is disabled by setting the `disabled: true` in the machine's
context, the `data-disabled` attribute is set on the root, input, control and
label.

```css
[data-part="root"][data-disabled] {
  /* styles for disabled state for root */
}

[data-part="label"][data-disabled] {
  /* styles for disabled state for label */
}

[data-part="input"][data-disabled] {
  /* styles for disabled state for input */
}

[data-part="control"][data-disabled] {
  /* styles for disabled state for control */
}
```

When a tag is disabled, the `data-disabled` attribute is set on the tag.

```css
[data-part="item-preview"][data-disabled] {
  /* styles for disabled tag  */
}
```

### Highlighted state

When a tag is highlighted via the keyboard navigation or pointer hover, a
`data-highlighted` attribute is set on the tag.

```css
[data-part="item-preview"][data-highlighted] {
  /* styles for visual focus */
}
```

### Readonly state

When the tags input is in its readonly state, the `data-readonly` attribute is
set on the root, label, input and control.

```css
[data-part="root"][data-readonly] {
  /* styles for readonly for root */
}

[data-part="control"][data-readonly] {
  /* styles for readonly for control */
}

[data-part="input"][data-readonly] {
  /* styles for readonly for input  */
}

[data-part="label"][data-readonly] {
  /* styles for readonly for label */
}
```

## Methods and Properties

### Machine Context

The tags input machine exposes the following context properties:

**`ids`**
Type: `Partial<{ root: string; input: string; hiddenInput: string; clearBtn: string; label: string; control: string; item: (opts: ItemProps) => string; itemDeleteTrigger: (opts: ItemProps) => string; itemInput: (opts: ItemProps) => string; }>`
Description: The ids of the elements in the tags input. Useful for composition.

**`translations`**
Type: `IntlTranslations`
Description: Specifies the localized strings that identifies the accessibility elements and their states

**`maxLength`**
Type: `number`
Description: The max length of the input.

**`delimiter`**
Type: `string | RegExp`
Description: The character that serves has:
- event key to trigger the addition of a new tag
- character used to split tags when pasting into the input

**`autoFocus`**
Type: `boolean`
Description: Whether the input should be auto-focused

**`disabled`**
Type: `boolean`
Description: Whether the tags input should be disabled

**`readOnly`**
Type: `boolean`
Description: Whether the tags input should be read-only

**`invalid`**
Type: `boolean`
Description: Whether the tags input is invalid

**`required`**
Type: `boolean`
Description: Whether the tags input is required

**`editable`**
Type: `boolean`
Description: Whether a tag can be edited after creation, by pressing `Enter` or double clicking.

**`inputValue`**
Type: `string`
Description: The controlled tag input's value

**`defaultInputValue`**
Type: `string`
Description: The initial tag input value when rendered.
Use when you don't need to control the tag input value.

**`value`**
Type: `string[]`
Description: The controlled tag value

**`defaultValue`**
Type: `string[]`
Description: The initial tag value when rendered.
Use when you don't need to control the tag value.

**`onValueChange`**
Type: `(details: ValueChangeDetails) => void`
Description: Callback fired when the tag values is updated

**`onInputValueChange`**
Type: `(details: InputValueChangeDetails) => void`
Description: Callback fired when the input value is updated

**`onHighlightChange`**
Type: `(details: HighlightChangeDetails) => void`
Description: Callback fired when a tag is highlighted by pointer or keyboard navigation

**`onValueInvalid`**
Type: `(details: ValidityChangeDetails) => void`
Description: Callback fired when the max tag count is reached or the `validateTag` function returns `false`

**`validate`**
Type: `(details: ValidateArgs) => boolean`
Description: Returns a boolean that determines whether a tag can be added.
Useful for preventing duplicates or invalid tag values.

**`blurBehavior`**
Type: `"clear" | "add"`
Description: The behavior of the tags input when the input is blurred
- `"add"`: add the input value as a new tag
- `"clear"`: clear the input value

**`addOnPaste`**
Type: `boolean`
Description: Whether to add a tag when you paste values into the tag input

**`max`**
Type: `number`
Description: The max number of tags

**`allowOverflow`**
Type: `boolean`
Description: Whether to allow tags to exceed max. In this case,
we'll attach `data-invalid` to the root

**`name`**
Type: `string`
Description: The name attribute for the input. Useful for form submissions

**`form`**
Type: `string`
Description: The associate form of the underlying input element.

**`dir`**
Type: `"ltr" | "rtl"`
Description: The document's text/writing direction.

**`id`**
Type: `string`
Description: The unique identifier of the machine.

**`getRootNode`**
Type: `() => ShadowRoot | Node | Document`
Description: A root node to correctly resolve document in custom environments. E.x.: Iframes, Electron.

**`onPointerDownOutside`**
Type: `(event: PointerDownOutsideEvent) => void`
Description: Function called when the pointer is pressed down outside the component

**`onFocusOutside`**
Type: `(event: FocusOutsideEvent) => void`
Description: Function called when the focus is moved outside the component

**`onInteractOutside`**
Type: `(event: InteractOutsideEvent) => void`
Description: Function called when an interaction happens outside the component

### Machine API

The tags input `api` exposes the following methods:

**`empty`**
Type: `boolean`
Description: Whether the tags are empty

**`inputValue`**
Type: `string`
Description: The value of the tags entry input.

**`value`**
Type: `string[]`
Description: The value of the tags as an array of strings.

**`valueAsString`**
Type: `string`
Description: The value of the tags as a string.

**`count`**
Type: `number`
Description: The number of the tags.

**`atMax`**
Type: `boolean`
Description: Whether the tags have reached the max limit.

**`setValue`**
Type: `(value: string[]) => void`
Description: Function to set the value of the tags.

**`clearValue`**
Type: `(id?: string) => void`
Description: Function to clear the value of the tags.

**`addValue`**
Type: `(value: string) => void`
Description: Function to add a tag to the tags.

**`setValueAtIndex`**
Type: `(index: number, value: string) => void`
Description: Function to set the value of a tag at the given index.

**`setInputValue`**
Type: `(value: string) => void`
Description: Function to set the value of the tags entry input.

**`clearInputValue`**
Type: `VoidFunction`
Description: Function to clear the value of the tags entry input.

**`focus`**
Type: `VoidFunction`
Description: Function to focus the tags entry input.

**`getItemState`**
Type: `(props: ItemProps) => ItemState`
Description: Returns the state of a tag

### Data Attributes

**`Root`**

**`data-scope`**: tags-input
**`data-part`**: root
**`data-invalid`**: Present when invalid
**`data-readonly`**: Present when read-only
**`data-disabled`**: Present when disabled
**`data-focus`**: Present when focused
**`data-empty`**: Present when the content is empty

**`Label`**

**`data-scope`**: tags-input
**`data-part`**: label
**`data-disabled`**: Present when disabled
**`data-invalid`**: Present when invalid
**`data-readonly`**: Present when read-only
**`data-required`**: Present when required

**`Control`**

**`data-scope`**: tags-input
**`data-part`**: control
**`data-disabled`**: Present when disabled
**`data-readonly`**: Present when read-only
**`data-invalid`**: Present when invalid
**`data-focus`**: Present when focused

**`Input`**

**`data-scope`**: tags-input
**`data-part`**: input
**`data-invalid`**: Present when invalid
**`data-readonly`**: Present when read-only
**`data-empty`**: Present when the content is empty

**`Item`**

**`data-scope`**: tags-input
**`data-part`**: item
**`data-value`**: The value of the item
**`data-disabled`**: Present when disabled

**`ItemPreview`**

**`data-scope`**: tags-input
**`data-part`**: item-preview
**`data-value`**: The value of the item
**`data-disabled`**: Present when disabled
**`data-highlighted`**: Present when highlighted

**`ItemText`**

**`data-scope`**: tags-input
**`data-part`**: item-text
**`data-disabled`**: Present when disabled
**`data-highlighted`**: Present when highlighted

**`ItemDeleteTrigger`**

**`data-scope`**: tags-input
**`data-part`**: item-delete-trigger
**`data-disabled`**: Present when disabled
**`data-highlighted`**: Present when highlighted

**`ClearTrigger`**

**`data-scope`**: tags-input
**`data-part`**: clear-trigger
**`data-readonly`**: Present when read-only

## Accessibility

### Keyboard Interactions

**`ArrowLeft`**
Description: Moves focus to the previous tag item

**`ArrowRight`**
Description: Moves focus to the next tag item

**`Backspace`**
Description: Deletes the tag item that has visual focus or the last tag item

**`Enter`**
Description: <span>When a tag item has visual focus, it puts the tag in edit mode.<br />When the input has focus, it adds the value to the list of tags</span>

**`Delete`**
Description: Deletes the tag item that has visual focus

**`Control + V`**
Description: When `addOnPaste` is set. Adds the pasted value as a tags
The timer machine is used to record the time elapsed from zero or since a
specified target time.

## Resources


[Latest version: v1.33.1](https://www.npmjs.com/package/@zag-js/timer)
[Logic Visualizer](https://zag-visualizer.vercel.app/timer)
[Source Code](https://github.com/chakra-ui/zag/tree/main/packages/machines/timer)



**Features**

- Countdown from a specified time
- Use as stopwatch to record the time elapsed
- Control the timer with start, stop, and resume buttons
- Set the tick interval for the timer

## Installation

To use the Timer machine in your project, run the following command in your
command line:

```bash
npm install @zag-js/timer @zag-js/svelte