Autocomplete

Recent Searches

An empty search field shows the person's recent queries instead of nothing: most of the time they want yesterday's search again.

  • autocomplete
  • search
  • history
  • empty state

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/autocomplete-007?lang=en

Недавние запросы

  • наушники
  • рюкзак 30 л
  • кофемолка
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 "autocomplete-007" (Recent Searches) 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/autocomplete-007.json

Registry item: https://vibeui.ru/r/autocomplete-007.json
Installs to: components/vibeui/autocomplete-007.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
An empty search field shows the person's recent queries instead of nothing: most of the time they want yesterday's search again.

Search with history: with no query the panel lists recent searches and a clear button; the moment typing starts, suggestions take their place. Zero dependencies, one file, its own palette.

## 3. How to use it
import { Autocomplete007 } from "@/components/vibeui/autocomplete-007"

<Autocomplete007
  suggestions={["camera"]}
  defaultRecent={["headphones"]}
  onSelect={(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-autocomplete-007-* palette — do not swap it for your theme tokens
- the two separate lists: mixing history with suggestions hides where a row came from
- the panel heading changing with the list, aria-label included
- the clear button: stored queries must be erasable by the person who made them
- moving a pick to the top of the history and trimming the list
- the explanatory copy where an empty history would leave a blank box

## 6. You may change
- the suggestions and defaultRecent arrays
- the label, placeholder and clear button copy
- the onSelect handler
- the accent through the accent prop

## 7. Rules
- History lives in component state and dies on reload. For real history store it yourself and pass defaultRecent.
- Search queries are personal data: clearing must wipe your storage too, not just the screen.
- Suggestions here are local; for server-side ones use the approach from autocomplete-005.
- 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/autocomplete-007.json
https://vibeui.ru/r/autocomplete-007.json

Компонент самодостаточен: один файл, без зависимостей, собственная палитра в локальных переменных --vibeui-autocomplete-007-*. Клиентский: "use client". Панель под полем показывает один из двух списков: недавние при пустом запросе, подсказки при непустом. Заголовок панели меняется вместе со списком, aria-label списка — тоже. Выбранное поднимается в начало недавних, история обрезается до пяти. Часы у строки нарисованы кругом и псевдоэлементом.

Component source

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

"use client"

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

export type Autocomplete007Props = Omit<
  ComponentPropsWithoutRef<"div">,
  "children" | "onSelect"
> & {
  label?: string
  placeholder?: string
  suggestions?: string[]
  defaultRecent?: string[]
  clearLabel?: string
  onSelect?: (value: string) => void
  accent?: string
}

// Идея компонента: пустое поле поиска не должно быть пустым экраном. Пока
// запроса нет, показываем недавние запросы самого человека — чаще всего он
// ищет то же, что вчера. Как только он начал печатать, недавние уступают
// место подсказкам: смешивать два разных списка в один — путать источник.
const STYLES = `
:where([data-vibeui-block="autocomplete-007"]){
--vibeui-autocomplete-007-bg:oklch(1 0 0);
--vibeui-autocomplete-007-fg:oklch(0.22 0.014 265);
--vibeui-autocomplete-007-muted:oklch(0.52 0.014 265);
--vibeui-autocomplete-007-border:oklch(0.9 0.006 265);
--vibeui-autocomplete-007-field:oklch(0.985 0.002 265);
--vibeui-autocomplete-007-active:oklch(0.95 0.02 265);
--vibeui-autocomplete-007-accent:oklch(0.55 0.17 265);
--vibeui-autocomplete-007-radius:0.625rem;
--vibeui-autocomplete-007-font:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
}
[data-vibeui-block="autocomplete-007"]{
display:flex;flex-direction:column;gap:0.375rem;
width:100%;max-width:22rem;box-sizing:border-box;padding:0.875rem;
background:var(--vibeui-autocomplete-007-bg);
border:1px solid var(--vibeui-autocomplete-007-border);
border-radius:calc(var(--vibeui-autocomplete-007-radius) + 0.25rem);
color:var(--vibeui-autocomplete-007-fg);
font-family:var(--vibeui-autocomplete-007-font);
}
[data-vibeui-block="autocomplete-007"] label{font-size:0.8125rem;font-weight:600}
[data-vibeui-block="autocomplete-007"] input{
box-sizing:border-box;width:100%;height:2.5rem;padding:0 0.75rem;
border:1px solid var(--vibeui-autocomplete-007-border);
border-radius:var(--vibeui-autocomplete-007-radius);
background:var(--vibeui-autocomplete-007-field);
color:inherit;font:inherit;font-size:0.875rem;
}
[data-vibeui-block="autocomplete-007"] input::placeholder{color:var(--vibeui-autocomplete-007-muted)}
[data-vibeui-block="autocomplete-007"] input:focus-visible{
outline:2px solid var(--vibeui-autocomplete-007-accent);outline-offset:1px;border-color:transparent;
}
[data-vibeui-block="autocomplete-007"] [data-part="panel"]{
border:1px solid var(--vibeui-autocomplete-007-border);
border-radius:var(--vibeui-autocomplete-007-radius);
background:var(--vibeui-autocomplete-007-bg);overflow:hidden;
}
[data-vibeui-block="autocomplete-007"] [data-part="head"]{
display:flex;align-items:center;justify-content:space-between;gap:0.75rem;
padding:0.5rem 0.625rem 0.25rem;
font-size:0.6875rem;font-weight:650;letter-spacing:0.06em;text-transform:uppercase;
color:var(--vibeui-autocomplete-007-muted);
}
[data-vibeui-block="autocomplete-007"] [data-part="clear"]{
appearance:none;border:0;background:transparent;cursor:pointer;padding:0.125rem 0.25rem;
border-radius:0.25rem;color:var(--vibeui-autocomplete-007-accent);
font:inherit;font-size:0.6875rem;font-weight:650;letter-spacing:0.02em;text-transform:none;
}
[data-vibeui-block="autocomplete-007"] [data-part="clear"]:focus-visible{outline:2px solid var(--vibeui-autocomplete-007-accent);outline-offset:1px}
[data-vibeui-block="autocomplete-007"] [data-part="list"]{margin:0;padding:0.25rem;list-style:none;max-height:10rem;overflow-y:auto}
[data-vibeui-block="autocomplete-007"] [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="autocomplete-007"] [data-part="option"]:hover{background:var(--vibeui-autocomplete-007-active)}
/* Часы у недавнего запроса: круг с двумя стрелками, нарисован рамкой. */
[data-vibeui-block="autocomplete-007"] [data-part="clock"]{
position:relative;flex:none;width:0.75rem;height:0.75rem;
border:1.5px solid var(--vibeui-autocomplete-007-muted);border-radius:9999px;
}
[data-vibeui-block="autocomplete-007"] [data-part="clock"]::after{
content:"";position:absolute;left:50%;top:0.125rem;
width:1.5px;height:0.25rem;background:var(--vibeui-autocomplete-007-muted);
margin-left:-0.75px;transform-origin:bottom;
}
[data-vibeui-block="autocomplete-007"] [data-part="empty"]{padding:0.75rem 0.625rem;font-size:0.8125rem;color:var(--vibeui-autocomplete-007-muted)}
@media (prefers-reduced-motion:reduce){[data-vibeui-block="autocomplete-007"] *{animation:none!important;transition:none!important}}
`

const DEFAULT_SUGGESTIONS = [
  "фотоаппарат",
  "фонарь налобный",
  "фильтр для воды",
  "флешка 256 гб",
  "фен дорожный",
]

const DEFAULT_RECENT = ["наушники", "рюкзак 30 л", "кофемолка"]

/**
 * Поиск с недавними запросами: пустое поле показывает вчерашние.
 * Один файл, ноль зависимостей, собственная палитра.
 */
export function Autocomplete007({
  label = "Поиск",
  placeholder = "Что ищете?",
  suggestions = DEFAULT_SUGGESTIONS,
  defaultRecent = DEFAULT_RECENT,
  clearLabel = "Очистить",
  onSelect,
  accent,
  className,
  style,
  ...props
}: Autocomplete007Props) {
  const id = useId()
  const [query, setQuery] = useState("")
  const [recent, setRecent] = useState(defaultRecent)

  const matches = useMemo(() => {
    const needle = query.trim().toLowerCase()
    if (!needle) return []
    return suggestions.filter((item) => item.toLowerCase().includes(needle))
  }, [query, suggestions])

  const palette = {
    ...(accent ? { "--vibeui-autocomplete-007-accent": accent } : null),
    ...style,
  } as CSSProperties

  const showRecent = !query.trim() && recent.length > 0
  const rows = showRecent ? recent : matches

  const pick = (value: string) => {
    setQuery(value)
    setRecent([value, ...recent.filter((item) => item !== value)].slice(0, 5))
    onSelect?.(value)
  }

  return (
    <>
      <style href="vibeui-autocomplete-007" precedence="medium">
        {STYLES}
      </style>
      <div
        {...props}
        data-vibeui-block="autocomplete-007"
        className={className}
        style={palette}
      >
        <label htmlFor={id}>{label}</label>
        <input
          id={id}
          type="search"
          role="combobox"
          autoComplete="off"
          placeholder={placeholder}
          value={query}
          aria-expanded={rows.length > 0}
          aria-controls={`${id}-list`}
          aria-autocomplete="list"
          onChange={(event) => setQuery(event.target.value)}
        />
        <div data-part="panel">
          <p data-part="head">
            {showRecent ? "Недавние запросы" : "Подсказки"}
            {showRecent ? (
              <button
                type="button"
                data-part="clear"
                onClick={() => setRecent([])}
              >
                {clearLabel}
              </button>
            ) : null}
          </p>
          {rows.length ? (
            <ul
              id={`${id}-list`}
              role="listbox"
              aria-label={showRecent ? "Недавние запросы" : "Подсказки"}
              data-part="list"
            >
              {rows.map((row) => (
                <li
                  key={row}
                  role="option"
                  aria-selected="false"
                  data-part="option"
                  onMouseDown={(event) => {
                    event.preventDefault()
                    pick(row)
                  }}
                >
                  {showRecent ? (
                    <span data-part="clock" aria-hidden="true" />
                  ) : null}
                  {row}
                </li>
              ))}
            </ul>
          ) : (
            <p data-part="empty">
              {query.trim()
                ? "Ничего не нашлось — попробуйте короче"
                : "История пуста: здесь появятся ваши запросы"}
            </p>
          )}
        </div>
      </div>
    </>
  )
}