Combobox
Required Choice
A required choice inside a form: the error shows up only after a submit, is tied to the field through aria-describedby and clears as soon as a row is picked.
- combobox
- form
- validation
- required
Preview
Use it with AI
- 1. Copy the link.
- 2. Write to your agent in your own words and drop the link into the sentence.
- 3. The agent opens the link and installs the component from the registry.
put this in the header: https://vibeui.ru/c/combobox-010?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-010" (Required Choice) 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-010.json
Registry item: https://vibeui.ru/r/combobox-010.json
Installs to: components/vibeui/combobox-010.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 required choice inside a form: the error shows up only after a submit, is tied to the field through aria-describedby and clears as soon as a row is picked.
A required combobox with form validation: the error message lives in role="alert", the field carries aria-invalid and focus returns after a failed submit. One file, zero dependencies.
## 3. How to use it
import { Combobox010 } from "@/components/vibeui/combobox-010"
<Combobox010
label="Payment method"
options={["Card online", "Cash on delivery"]}
errorText="Pick a payment method from the list"
onSubmitValue={(value) => console.log(value)}
/>
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-010-* palette — do not swap it for your theme tokens
- showing the error only after a submit: highlighting while typing reads as an accusation
- aria-invalid together with aria-describedby — without the pair the message is not read next to the field
- role="alert" on the message: it has to be spoken without stealing focus
- intercepting Enter in the field — otherwise the form submits instead of picking a row
- the block's own light surface: without it the dark text disappears on the dark catalog card
## 6. You may change
- the error copy through errorText and the hint through hintText
- the button caption through submitLabel and the list content through options
- the field caption through label and the placeholder through placeholder
- the accent color through accent and the error color through the danger variable
## 7. Rules
- noValidate turns off native hints for the whole form: other fields need your own checks.
- The error and the hint share one slot — texts of different length make the block jump, set a min-height if that hurts.
- The value does not reach a server by itself: the handler hands it over through onSubmitValue.
- 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-010.jsonhttps://vibeui.ru/r/combobox-010.jsonКомпонент самодостаточен: один файл, без зависимостей, собственная палитра --vibeui-combobox-010-*. Корень — form с noValidate: браузерная валидация не умеет проверять рисованный список, поэтому проверку ведёт обработчик submit. Ошибка ставится только после попытки отправки, а не на каждое нажатие: ругаться на человека, пока он ещё заполняет форму, — худшее, что может сделать поле. Поле получает aria-invalid и aria-describedby, указывающий на сообщение или на подсказку, сообщение живёт в role="alert" и потому проговаривается без перевода фокуса. Enter в поле выбирает строку и не отправляет форму — иначе половина людей отправит её, промахнувшись мимо списка. После неудачной отправки фокус возвращается в поле.
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,
FormEvent,
KeyboardEvent,
} from "react"
export type Combobox010Props = Omit<
ComponentPropsWithoutRef<"form">,
"children" | "onSubmit"
> & {
label?: string
placeholder?: string
options?: string[]
errorText?: string
hintText?: string
submitLabel?: string
onSubmitValue?: (value: string) => void
accent?: string
}
// Идея компонента: обязательный выбор с честной ошибкой. Ошибка появляется
// не на каждое нажатие, а только после отправки: ругаться на человека, пока
// он ещё заполняет форму, — худшее, что может сделать поле. Сообщение
// связано с полем через aria-describedby и живёт в role="alert", поэтому
// скринридер узнаёт о нём без перевода фокуса.
const STYLES = `
:where([data-vibeui-block="combobox-010"]){
--vibeui-combobox-010-bg:oklch(1 0 0);
--vibeui-combobox-010-fg:oklch(0.22 0.014 265);
--vibeui-combobox-010-muted:oklch(0.55 0.014 265);
--vibeui-combobox-010-border:oklch(0.9 0.006 265);
--vibeui-combobox-010-field:oklch(0.985 0.002 265);
--vibeui-combobox-010-active:oklch(0.95 0.02 265);
--vibeui-combobox-010-accent:oklch(0.52 0.15 265);
--vibeui-combobox-010-danger:oklch(0.55 0.2 25);
--vibeui-combobox-010-dangerbg:oklch(0.96 0.03 25);
--vibeui-combobox-010-radius:0.625rem;
--vibeui-combobox-010-font:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
}
[data-vibeui-block="combobox-010"]{
display:flex;flex-direction:column;gap:0.4rem;
width:100%;max-width:21rem;box-sizing:border-box;padding:0.875rem;
background:var(--vibeui-combobox-010-bg);
border:1px solid var(--vibeui-combobox-010-border);
border-radius:calc(var(--vibeui-combobox-010-radius) + 0.25rem);
color:var(--vibeui-combobox-010-fg);
font-family:var(--vibeui-combobox-010-font);
}
[data-vibeui-block="combobox-010"] label{font-size:0.8125rem;font-weight:600}
[data-vibeui-block="combobox-010"] label span{color:var(--vibeui-combobox-010-danger)}
[data-vibeui-block="combobox-010"] input{
box-sizing:border-box;width:100%;height:2.5rem;padding:0 0.75rem;
border:1px solid var(--vibeui-combobox-010-border);
border-radius:var(--vibeui-combobox-010-radius);
background:var(--vibeui-combobox-010-field);
color:inherit;font:inherit;font-size:0.875rem;
}
[data-vibeui-block="combobox-010"] input::placeholder{color:var(--vibeui-combobox-010-muted)}
[data-vibeui-block="combobox-010"] input:focus-visible{outline:2px solid var(--vibeui-combobox-010-accent);outline-offset:1px;border-color:transparent}
[data-vibeui-block="combobox-010"] input[aria-invalid="true"]{
border-color:var(--vibeui-combobox-010-danger);background:var(--vibeui-combobox-010-dangerbg);
}
[data-vibeui-block="combobox-010"] input[aria-invalid="true"]:focus-visible{outline-color:var(--vibeui-combobox-010-danger)}
[data-vibeui-block="combobox-010"] [data-part="list"]{
margin:0;padding:0.25rem;list-style:none;max-height:9rem;overflow-y:auto;
border:1px solid var(--vibeui-combobox-010-border);
border-radius:var(--vibeui-combobox-010-radius);
}
[data-vibeui-block="combobox-010"] [data-part="option"]{
display:flex;align-items:center;min-height:2rem;padding:0 0.5rem;
border-radius:0.375rem;font-size:0.875rem;cursor:pointer;
}
[data-vibeui-block="combobox-010"] [data-part="option"][data-active="true"]{background:var(--vibeui-combobox-010-active)}
[data-vibeui-block="combobox-010"] [data-part="option"][aria-selected="true"]{font-weight:650;color:var(--vibeui-combobox-010-accent)}
[data-vibeui-block="combobox-010"] [data-part="hint"]{margin:0;font-size:0.75rem;color:var(--vibeui-combobox-010-muted)}
[data-vibeui-block="combobox-010"] [data-part="error"]{
display:flex;align-items:center;gap:0.4rem;margin:0;
font-size:0.75rem;font-weight:600;color:var(--vibeui-combobox-010-danger);
}
[data-vibeui-block="combobox-010"] [data-part="error"]::before{
content:"!";display:inline-flex;align-items:center;justify-content:center;flex:none;
width:1rem;height:1rem;border-radius:999px;font-size:0.7rem;
background:var(--vibeui-combobox-010-danger);color:oklch(1 0 0);
}
[data-vibeui-block="combobox-010"] [data-part="submit"]{
appearance:none;border:0;cursor:pointer;align-self:flex-start;
height:2.25rem;padding:0 1rem;border-radius:var(--vibeui-combobox-010-radius);
background:var(--vibeui-combobox-010-accent);color:oklch(1 0 0);
font:inherit;font-size:0.8125rem;font-weight:650;
transition:filter .16s ease;
}
[data-vibeui-block="combobox-010"] [data-part="submit"]:hover{filter:brightness(1.08)}
[data-vibeui-block="combobox-010"] [data-part="submit"]:focus-visible{outline:2px solid var(--vibeui-combobox-010-accent);outline-offset:2px}
@media (prefers-reduced-motion:reduce){[data-vibeui-block="combobox-010"] *{animation:none!important;transition:none!important}}
`
const DEFAULT_OPTIONS = [
"Наличными курьеру",
"Картой онлайн",
"Счёт для компании",
"Рассрочка",
"Криптовалютой",
]
/**
* Combobox с обязательным выбором: ошибка показывается после отправки,
* связана с полем через aria-describedby и снимается выбором значения.
*/
export function Combobox010({
label = "Способ оплаты",
placeholder = "Выберите из списка",
options = DEFAULT_OPTIONS,
errorText = "Выберите способ оплаты из списка",
hintText = "Свой вариант вписать нельзя",
submitLabel = "Оформить",
onSubmitValue,
accent,
className,
style,
...props
}: Combobox010Props) {
const id = useId()
const [query, setQuery] = useState("")
const [value, setValue] = useState("")
const [active, setActive] = useState(0)
const [invalid, setInvalid] = useState(false)
const inputRef = useRef<HTMLInputElement>(null)
const listRef = useRef<HTMLUListElement>(null)
const matches = useMemo(() => {
const needle = query.trim().toLowerCase()
if (!needle) return options
return options.filter((option) => option.toLowerCase().includes(needle))
}, [options, query])
const palette = {
...(accent ? { "--vibeui-combobox-010-accent": accent } : null),
...style,
} as CSSProperties
const commit = (option: string) => {
setValue(option)
setQuery("")
setActive(0)
setInvalid(false)
inputRef.current?.focus()
}
const move = (delta: number) => {
if (!matches.length) return
const next = (active + delta + matches.length) % matches.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") {
// Enter в поле выбирает строку, а не отправляет форму: иначе половина
// людей отправит форму, промахнувшись мимо списка.
event.preventDefault()
if (matches[active]) commit(matches[active])
} else if (event.key === "Escape") {
event.preventDefault()
setQuery("")
setActive(0)
}
}
const onSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault()
if (!value) {
setInvalid(true)
inputRef.current?.focus()
return
}
setInvalid(false)
onSubmitValue?.(value)
}
return (
<>
<style href="vibeui-combobox-010" precedence="medium">
{STYLES}
</style>
<form
{...props}
data-vibeui-block="combobox-010"
className={className}
style={palette}
onSubmit={onSubmit}
noValidate
>
<label htmlFor={`${id}-input`}>
{label} <span aria-hidden="true">*</span>
</label>
<input
ref={inputRef}
id={`${id}-input`}
type="text"
role="combobox"
autoComplete="off"
required
placeholder={value || placeholder}
aria-expanded="true"
aria-controls={`${id}-list`}
aria-autocomplete="list"
aria-required="true"
aria-invalid={invalid}
aria-describedby={invalid ? `${id}-error` : `${id}-hint`}
aria-activedescendant={
matches[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"
>
{matches.map((option, index) => (
<li
key={option}
id={`${id}-option-${index}`}
role="option"
data-part="option"
data-active={index === active}
aria-selected={option === value}
onMouseEnter={() => setActive(index)}
onMouseDown={(event) => {
event.preventDefault()
commit(option)
}}
>
{option}
</li>
))}
</ul>
{invalid ? (
<p data-part="error" id={`${id}-error`} role="alert">
{errorText}
</p>
) : (
<p data-part="hint" id={`${id}-hint`}>
{hintText}
</p>
)}
<button type="submit" data-part="submit">
{submitLabel}
</button>
</form>
</>
)
}