Combobox

Create Option

A combobox that can create: the last row turns the query into a new label, selects it right away and marks it as new.

  • combobox
  • create
  • tags
  • keyboard

Preview

1440pxHost theme

Use it with AI

  1. 1. Copy the link.
  2. 2. Write to your agent in your own words and drop the link into the sentence.
  3. 3. The agent opens the link and installs the component from the registry.

put this in the header: https://vibeui.ru/c/combobox-005?lang=en

  • Баг
  • Улучшение
  • Документация
  • Регресс
  • Техдолг

Ничего не выбрано

Show the full instructions

What the link says, spelled out. Use it when your agent cannot open links — paste this text instead.

# Install and place "combobox-005" (Create Option) from VibeUI

## 1. Install first — do not skip, do not recreate
Run this exact command before writing any code:
npx shadcn@latest add https://vibeui.ru/r/combobox-005.json

Registry item: https://vibeui.ru/r/combobox-005.json
Installs to: components/vibeui/combobox-005.tsx (the exact path follows this project's components.json aliases).
npm dependencies: none.
Registry dependencies: none.

Install it from the registry. Do not recreate it from the description,
do not substitute a similar component from another library, and do not
rewrite it to match the project's existing style.

## 2. What it is
A combobox that can create: the last row turns the query into a new label, selects it right away and marks it as new.

A combobox that can add what is missing: a "Create …" row appears when there is no exact match, works from the keyboard and puts the value into the list. One file, zero dependencies.

## 3. How to use it
import { Combobox005 } from "@/components/vibeui/combobox-005"

<Combobox005
  label="Issue label"
  options={["Bug", "Enhancement"]}
  createLabel="Create"
  onSelect={(value, created) => console.log(value, created)}
/>

Read the installed file for the full prop list.

## 4. Where to place it
This is a small inline component. Put it exactly where the user asked,
inside the existing markup. Do not create a new page, section or
wrapper for it. If a similar control already sits in that spot,
replace it instead of adding a second one.

Placement: ___
(The user fills this line in. If it is still blank, ask where to put it
instead of guessing.)

## 5. Keep exactly as installed
- the local --vibeui-combobox-005-* palette — do not swap it for your theme tokens
- the create row as role="option" — a side button falls out of the list's keyboard walk
- the exact-match check: without it the list offers to create something that already exists
- the row's position at the very end: at the top it gets hit by accident instead of the first match
- the dashed rule and color that set it apart — creating is not selecting and must not look the same
- the block's own light surface: without it the dark text disappears on the dark catalog card

## 6. You may change
- the starting list through options and the action caption through createLabel
- the new-value marker through newBadge
- the field caption through label, the placeholder through placeholder and the initial value through defaultValue
- the accent color through accent

## 7. Rules
- Created values live only in component state: persist them from onSelect using its second argument.
- The query is only trimmed, not normalized: "Bug" and "bug " become different labels if you drop the case check.
- A long query stretches the create row — add an ellipsis if that matters.
- Do not lift the CSS variables into globals.css: the component has to stay a single file.

## 8. Verify
- it renders with no console errors;
- it looks like the preview on the VibeUI page you copied this from;
- if it does not, you changed something listed in section 5 — put it back.

For developers

npx shadcn@latest add https://vibeui.ru/r/combobox-005.json
https://vibeui.ru/r/combobox-005.json

Компонент самодостаточен: один файл, без зависимостей, собственная палитра --vibeui-combobox-005-*. Клиентский: useState держит известный список, список созданного, запрос, значение и курсор. Строка создания добавляется в конец массива строк, только если запрос непустой и точного совпадения нет; она полноценный role="option", поэтому берётся стрелками и Enter, а не отдельной кнопкой мимо клавиатуры. Созданное попадает в known и получает бейдж — человек видит, что список изменился по его вине. aria-selected на строке создания всегда false: выбранным считается только существующее значение. Строка отделена пунктиром и цветом, чтобы её не нажимали вслепую вместо совпадения.

Component source

The same file your agent installs. Here in case you would rather copy it by hand.

"use client"

import { useId, useMemo, useRef, useState } from "react"
import type {
  ComponentPropsWithoutRef,
  CSSProperties,
  KeyboardEvent,
} from "react"

export type Combobox005Props = Omit<
  ComponentPropsWithoutRef<"div">,
  "children" | "onSelect"
> & {
  label?: string
  placeholder?: string
  options?: string[]
  createLabel?: string
  newBadge?: string
  defaultValue?: string
  onSelect?: (value: string, created: boolean) => void
  accent?: string
}

// Идея компонента: список закрытый ровно до тех пор, пока в нём есть нужное.
// Строка «Создать» живёт последней и появляется только при непустом запросе
// без точного совпадения — она полноценный option, поэтому берётся стрелками
// и Enter, а не отдельной кнопкой мимо клавиатуры.
const STYLES = `
:where([data-vibeui-block="combobox-005"]){
--vibeui-combobox-005-bg:oklch(1 0 0);
--vibeui-combobox-005-fg:oklch(0.22 0.02 150);
--vibeui-combobox-005-muted:oklch(0.52 0.02 150);
--vibeui-combobox-005-border:oklch(0.9 0.01 150);
--vibeui-combobox-005-field:oklch(0.985 0.005 150);
--vibeui-combobox-005-active:oklch(0.95 0.04 150);
--vibeui-combobox-005-accent:oklch(0.5 0.13 150);
--vibeui-combobox-005-radius:0.625rem;
--vibeui-combobox-005-font:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
}
[data-vibeui-block="combobox-005"]{
display:flex;flex-direction:column;gap:0.375rem;
width:100%;max-width:21rem;box-sizing:border-box;padding:0.875rem;
background:var(--vibeui-combobox-005-bg);
border:1px solid var(--vibeui-combobox-005-border);
border-radius:calc(var(--vibeui-combobox-005-radius) + 0.25rem);
color:var(--vibeui-combobox-005-fg);
font-family:var(--vibeui-combobox-005-font);
}
[data-vibeui-block="combobox-005"] label{font-size:0.8125rem;font-weight:600}
[data-vibeui-block="combobox-005"] input{
box-sizing:border-box;width:100%;height:2.5rem;padding:0 0.75rem;
border:1px solid var(--vibeui-combobox-005-border);
border-radius:var(--vibeui-combobox-005-radius);
background:var(--vibeui-combobox-005-field);
color:inherit;font:inherit;font-size:0.875rem;
}
[data-vibeui-block="combobox-005"] input::placeholder{color:var(--vibeui-combobox-005-muted)}
[data-vibeui-block="combobox-005"] input:focus-visible{outline:2px solid var(--vibeui-combobox-005-accent);outline-offset:1px;border-color:transparent}
[data-vibeui-block="combobox-005"] [data-part="list"]{
margin:0;padding:0.25rem;list-style:none;max-height:11rem;overflow-y:auto;
border:1px solid var(--vibeui-combobox-005-border);
border-radius:var(--vibeui-combobox-005-radius);
}
[data-vibeui-block="combobox-005"] [data-part="option"]{
display:flex;align-items:center;gap:0.5rem;min-height:2rem;padding:0 0.5rem;
border-radius:0.375rem;font-size:0.875rem;cursor:pointer;
}
[data-vibeui-block="combobox-005"] [data-part="option"][data-active="true"]{background:var(--vibeui-combobox-005-active)}
[data-vibeui-block="combobox-005"] [data-part="option"][data-create="true"]{
margin-top:0.25rem;border-top:1px dashed var(--vibeui-combobox-005-border);
padding-top:0.35rem;color:var(--vibeui-combobox-005-accent);font-weight:600;
}
[data-vibeui-block="combobox-005"] [data-part="plus"]{
display:inline-flex;align-items:center;justify-content:center;flex:none;
width:1.15rem;height:1.15rem;border-radius:0.35rem;line-height:1;font-size:0.8rem;
background:var(--vibeui-combobox-005-active);
}
[data-vibeui-block="combobox-005"] [data-part="badge"]{
margin-left:auto;padding:0.05rem 0.35rem;border-radius:999px;
font-size:0.65rem;font-weight:700;text-transform:uppercase;letter-spacing:0.04em;
background:var(--vibeui-combobox-005-active);color:var(--vibeui-combobox-005-accent);
}
[data-vibeui-block="combobox-005"] [data-part="hint"]{font-size:0.75rem;color:var(--vibeui-combobox-005-muted)}
@media (prefers-reduced-motion:reduce){[data-vibeui-block="combobox-005"] *{animation:none!important;transition:none!important}}
`

const DEFAULT_OPTIONS = [
  "Баг",
  "Улучшение",
  "Документация",
  "Регресс",
  "Техдолг",
]

/**
 * Combobox с созданием значения: последняя строка списка заводит новую
 * метку прямо из запроса и сразу её выбирает.
 */
export function Combobox005({
  label = "Метка задачи",
  placeholder = "Найти или создать",
  options = DEFAULT_OPTIONS,
  createLabel = "Создать",
  newBadge = "новая",
  defaultValue = "",
  onSelect,
  accent,
  className,
  style,
  ...props
}: Combobox005Props) {
  const id = useId()
  const [known, setKnown] = useState(options)
  const [created, setCreated] = useState<string[]>([])
  const [query, setQuery] = useState("")
  const [value, setValue] = useState(defaultValue)
  const [active, setActive] = useState(0)
  const listRef = useRef<HTMLUListElement>(null)

  const needle = query.trim()

  const matches = useMemo(() => {
    const lower = needle.toLowerCase()
    if (!lower) return known
    return known.filter((option) => option.toLowerCase().includes(lower))
  }, [known, needle])

  const canCreate =
    needle.length > 0 &&
    !known.some((option) => option.toLowerCase() === needle.toLowerCase())

  const rows = canCreate ? [...matches, needle] : matches
  const palette = {
    ...(accent ? { "--vibeui-combobox-005-accent": accent } : null),
    ...style,
  } as CSSProperties

  const commit = (index: number) => {
    const option = rows[index]
    if (!option) return
    const isNew = canCreate && index === rows.length - 1

    if (isNew) {
      setKnown((previous) => [...previous, option])
      setCreated((previous) => [...previous, option])
    }

    setValue(option)
    setQuery("")
    setActive(0)
    onSelect?.(option, isNew)
  }

  const move = (delta: number) => {
    if (!rows.length) return
    const next = (active + delta + rows.length) % rows.length
    setActive(next)
    listRef.current?.children[next]?.scrollIntoView({ block: "nearest" })
  }

  const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
    if (event.key === "ArrowDown") {
      event.preventDefault()
      move(1)
    } else if (event.key === "ArrowUp") {
      event.preventDefault()
      move(-1)
    } else if (event.key === "Enter") {
      event.preventDefault()
      commit(active)
    } else if (event.key === "Escape") {
      event.preventDefault()
      setQuery("")
      setActive(0)
    }
  }

  return (
    <>
      <style href="vibeui-combobox-005" precedence="medium">
        {STYLES}
      </style>
      <div
        {...props}
        data-vibeui-block="combobox-005"
        className={className}
        style={palette}
      >
        <label htmlFor={`${id}-input`}>{label}</label>
        <input
          id={`${id}-input`}
          type="text"
          role="combobox"
          autoComplete="off"
          placeholder={value || placeholder}
          aria-expanded="true"
          aria-controls={`${id}-list`}
          aria-autocomplete="list"
          aria-activedescendant={
            rows[active] ? `${id}-option-${active}` : undefined
          }
          value={query}
          onChange={(event) => {
            setQuery(event.target.value)
            setActive(0)
          }}
          onKeyDown={onKeyDown}
        />
        <ul
          ref={listRef}
          id={`${id}-list`}
          role="listbox"
          aria-label={label}
          data-part="list"
        >
          {rows.map((option, index) => {
            const isCreateRow = canCreate && index === rows.length - 1

            return (
              <li
                key={isCreateRow ? `${id}-create` : option}
                id={`${id}-option-${index}`}
                role="option"
                data-part="option"
                data-create={isCreateRow}
                data-active={index === active}
                aria-selected={!isCreateRow && option === value}
                onMouseEnter={() => setActive(index)}
                onMouseDown={(event) => {
                  event.preventDefault()
                  commit(index)
                }}
              >
                {isCreateRow ? (
                  <>
                    <span data-part="plus" aria-hidden="true">
                      +
                    </span>
                    {createLabel} «{option}»
                  </>
                ) : (
                  <>
                    {option}
                    {created.includes(option) ? (
                      <span data-part="badge">{newBadge}</span>
                    ) : null}
                  </>
                )}
              </li>
            )
          })}
        </ul>
        <p data-part="hint" aria-live="polite">
          {value ? `Выбрано: ${value}` : "Ничего не выбрано"}
        </p>
      </div>
    </>
  )
}