MeDo

Gerador de Barra de Pesquisa IA.

Descreva o que as pessoas pesquisam e o MeDo gera o widget inteiro — consultas com debounce, dropdown typeahead, navegação por setas, pesquisas recentes, estados de carregamento e sem resultados, e um atalho cmd+K para focar.

Barra de pesquisa
Barra de pesquisa

A barra de pesquisa é o único input em que o foco visual e o foco do DOM discordam

Todo o resto em uma página mantém foco e destaque no mesmo lugar. Um typeahead não pode: o cursor precisa permanecer no campo de texto para que a pessoa continue digitando, enquanto o destaque desce pela lista de sugestões. O padrão correto é aria-activedescendant, em que o input mantém o foco do DOM e aponta para a opção ativa por id. Implementações que em vez disso movem o foco real para a lista quebram a digitação imediatamente, e é por isso que tantas barras de pesquisa feitas à mão funcionam com o mouse e desmoronam com o teclado. Gerar o campo e a lista como um único widget significa que essa relação já vem conectada desde o início, em vez de ser remendada depois de um relato de bug.

6 modelos

Modelos de Barra de pesquisa que você pode gerar

Cada modelo é um prompt real, não uma captura de tela. Copie para qualquer editor de IA, ou rode no MeDo e receba código React + Tailwind.

BasicInput + Clear

Plain Search Field With Submit

No dropdown, no fetch — just a field that submits to a results page. Start here when the corpus is large enough that suggestions would be guesses rather than shortcuts.

Create a search field: a 40px-tall rounded input inside a real form with role="search", type="search" on the input, enterkeyhint="search" for mobile keyboards, and a visible label or aria-label since a magnifier icon is not an accessible name. Put a 16px magnifier on the left with aria-hidden, and a clear button on the right that appears only once there is text, is a real button with an accessible label, and returns focus to the input after clearing. Enter submits the raw query through the form so search still works with JavaScript disabled. Escape clears the field when it has text. Show a focus-visible ring on the wrapper, not the bare input, so the icon and field read as one control.

Teste no MeDo
ComboboxTypeahead

Debounced Suggestions Listbox

The full combobox: debounce, listbox, aria-activedescendant. The critical rule is that DOM focus never leaves the input, or typing stops working the moment someone presses Arrow Down.

Create a typeahead search bar using the ARIA combobox pattern: aria-expanded, aria-controls and aria-activedescendant on the input, role="listbox" on the panel, role="option" with a unique id on each row. DOM focus must stay in the text field at all times — move the visual highlight by updating aria-activedescendant, never by focusing an option, or typing breaks. Debounce queries at 250ms and cancel in-flight requests so a slow earlier response cannot overwrite a newer one. Arrow Down and Up move the active option and wrap at the ends, Home and End jump to the first and last, Enter selects the active option or submits the raw query when none is active, Escape closes the panel and restores the typed text, and Tab closes and moves on rather than walking the options.

Teste no MeDo
cmd+KCommand Palette

Modal Search Overlay

Search as primary navigation, opened from anywhere with cmd+K. It is a modal dialog, which means a focus trap and focus restoration — the part most palette clones skip.

Create a command-palette search overlay opened by cmd+K and ctrl+K: a centered dialog with a backdrop, using the native dialog element or role="dialog" with aria-modal="true". Trap focus inside it, place initial focus in the input, close on Escape and backdrop click, and return focus to the element that was focused before opening. Ignore the shortcut while the user is typing in another input or a contenteditable region. Inside, run the ARIA combobox pattern with aria-activedescendant, group results under headed sections such as Pages, Docs and Actions, and let Arrow Down and Up move across group boundaries while skipping the group headings. Show a visible cmd+K hint in the trigger and keyboard hints in the dialog footer.

Teste no MeDo
StatesRecent + Empty

Search With Recent Queries and No-Results

Three panels, not one: recent searches on an empty query, skeleton rows in flight, a no-results row with a fallback. Leave any out and the dropdown flickers blank between keystrokes.

Create a search bar that renders three distinct dropdown states rather than one panel that empties. On an empty query, show up to five recent searches from localStorage under a Recent heading, each with a small remove button and a Clear all action. While a request is in flight, keep the previous results visible and overlay three skeleton rows, and swap the magnifier for an inline spinner rather than blanking the panel. On zero matches, show a no-results row naming the query plus a "Search everything" fallback action that submits the raw text. Announce the outcome in an aria-live="polite" region — "8 results available" or "No results" — debounced so intermediate counts are not read out. Arrow keys, Enter and Escape behave identically in all three states.

Teste no MeDo
FiltersScoped Search

Search With Scope Chips and Filters

A scope chip inside the field narrows the query before it runs. Make Backspace on an empty query remove the chip — anything else and people are hunting for a tiny × with the mouse.

Create a scoped search bar: removable scope chips render inside the input wrapper to the left of the text caret, each a button with an accessible label such as "Remove filter: Invoices". Pressing Backspace with an empty query removes the last chip rather than doing nothing, and typing a known prefix followed by a colon converts it into a chip. Keep the chips out of the input value itself and send them as separate query parameters. Below the field, render filter pills that are toggle buttons with aria-pressed, and re-run the debounced query on every change. Preserve the caret position when a chip is added, keep the ARIA combobox wiring for the suggestion listbox, and reflect the active scope in the aria-live result-count announcement.

Teste no MeDo
Media rowsRich Results

Suggestions With Thumbnails and Prices

Product and media rows where each suggestion carries an image, title and price. Reserve the thumbnail box explicitly, or every keystroke reflows the panel as images resolve.

Create a search bar with rich suggestion rows: each row is a role="option" containing a 40px thumbnail with explicit width and height attributes so the panel does not reflow as images load, a title with the matched substring bolded, and a secondary line with price or category. Because the row holds several elements, give each option an aria-label describing the whole row so a screen reader hears one coherent option rather than fragments. Cap the panel at 320px with internal scroll, and scroll the active option into view with block nearest as aria-activedescendant moves. Keep the last row a "See all results for <query>" action that submits the raw text. Highlight matches by wrapping the substring, never by injecting HTML from the response.

Teste no MeDo

Como personalizar seu Barra de pesquisa

Nomeie o intervalo de debounce

Diga "debounce em 250ms" em vez de "aplique debounce no input". Abaixo de cerca de 150ms você dispara uma requisição por tecla; passando de uns 400ms o dropdown parece quebrado. Combine com cancelamento para que uma resposta anterior lenta não sobrescreva uma mais nova.

Descreva os três estados vazios separadamente

Consulta vazia, consulta em andamento e zero resultados são três telas diferentes. Peça pesquisas recentes na primeira, um spinner ou linhas skeleton na segunda, e uma linha de sem resultados com ação alternativa na terceira. Deixe alguma de fora e você terá um painel piscando em branco.

Diga se Enter envia ou seleciona

Com uma sugestão destacada, Enter deve selecioná-la; sem nada destacado, Enter deve enviar a consulta bruta para uma página de resultados. Detalhe as duas ramificações e peça um form real com role="search" para que o caminho de envio funcione sem JavaScript.

Peça que a contagem de resultados seja anunciada

Usuários com visão veem a lista crescer. Usuários de leitor de tela precisam de uma região aria-live="polite" dizendo algo como "8 resultados disponíveis". Solicite a região live explicitamente e peça que ela também tenha debounce, para não ler cada contagem intermediária.

Quem usa o componente Barra de pesquisa

Site de documentação

Uma barra de pesquisa com cmd+K que abre sobre a página, agrupa os resultados por seção, mostra a linha correspondente sob cada título e guarda as últimas cinco consultas para voltar a uma página lembrada pela metade.

Loja de e-commerce

Sugestões de produto com miniatura, nome e preço por linha, atalhos de categoria acima delas e uma linha final "Ver todos os resultados para..." que envia a consulta bruta à página completa de resultados.

Dashboard ou ferramenta administrativa

Um único campo pesquisando entre clientes, faturas e configurações, com resultados agrupados por tipo e um chip de escopo no input para restringir a uma única entidade antes de digitar.

Biblioteca de conteúdo ou mídia

Uma barra de pesquisa larga com pílulas de filtro ao lado, linhas skeleton enquanto a consulta roda e um estado de sem resultados que sugere correções ortográficas em vez de exibir um painel vazio.

Padrões de Barra de pesquisa para diferentes sites

O mesmo componente barra de pesquisa, ajustado ao tipo de site em que ele entra.

01 / 06

Documentation Search

A cmd+K palette that groups hits by section and shows the matching line under each title, since a page title alone rarely tells a reader whether the answer is on it. Keep the last five queries — docs search is mostly people returning to a page they half remember.

Estilos e variações de Barra de pesquisa

Escolha a variação que combina com o resto da página e gere-a.

01 / 06

Inline Field Search

A permanent bordered input in the header or page body. The most discoverable option and the only one that works without JavaScript, since a real form with role="search" submits on Enter regardless. Give the wrapper the focus ring so the icon and field read as one control.

Barra de pesquisa em React, Next.js, Vue e Svelte

React, Next.js, Vue 3, SvelteKit, Astro ou HTML puro — o mesmo barra de pesquisa, seis formas de integrar.

01 / 06

React Search Bar

Track the active index as a number and derive aria-activedescendant from it — that is the entire highlight mechanism, with no focus moves. Abort the previous fetch in the effect cleanup so a slow response cannot land after a newer one.

src/components/SearchBar.tsx

const [active, setActive] = useState(-1)
const debounced = useDebounce(query, 250)

<input
  type="search"
  role="combobox"
  aria-expanded={open}
  aria-controls="search-listbox"
  aria-activedescendant={active >= 0 ? `opt-${active}` : undefined}
  onKeyDown={onArrowKeys}
/>

Como adicionar o seu Barra de pesquisa a um projeto

Quatro passos, de escolher um modelo de barra de pesquisa até subir para produção.

01~30s

Pick a Search Pattern

Decide whether you need suggestions at all. A plain field posting to a results page is often the honest answer; reach for the typeahead or the cmd+K palette only when search is a primary navigation path.

02~10s

Copy the Prompt

Take the prompt into MeDo, Lovable, Bolt, v0 or Cursor, then set two numbers: the debounce interval and how many suggestions the panel shows. Name what is being searched too, since that decides how a result row is shaped.

03~1min

Generate and Refine

You get React + Tailwind back with a live preview. Follow up in plain English — "add recent searches", "group results by type", "announce the result count politely" — rather than rewriting the keydown handler.

04~2min

Connect Your Index and Ship

Point the query at your real endpoint, then test with the keyboard only: type, Arrow Down, Enter, Escape. If typing stops working after Arrow Down, focus was moved into the list and the highlight needs to go back to aria-activedescendant.

Perguntas comuns sobre Barra de pesquisa

Como gerar uma barra de pesquisa com IA?

Descreva o que está sendo pesquisado, de onde vêm as sugestões e quais estados você precisa — pesquisas recentes, carregamento, sem resultados. O MeDo gera o input, o dropdown de sugestões, o tratamento de consultas com debounce e os atalhos de teclado como um só componente, não um campo de texto cru que você tenha que conectar depois.

Qual é a diferença entre uma barra de pesquisa e um autocomplete?

Uma barra de pesquisa envia uma consulta de texto livre e trata as sugestões como atalhos, então digitar algo sem correspondências continua válido. Um autocomplete restringe o valor a uma lista, então o input só é confirmado quando uma opção é escolhida. A distinção muda a marcação: uma barra de pesquisa pertence a um form com role="search", enquanto um autocomplete restrito é um combobox vinculado a um valor de formulário.

A IA pode gerar uma barra de pesquisa acessível?

Sim, se você pedir o padrão pelo nome. O MeDo implementa o padrão ARIA combobox com aria-expanded, aria-controls e aria-activedescendant no input, role="listbox" e role="option" no painel, e uma região live polite para a contagem de resultados. O foco permanece no campo de texto todo o tempo, e é isso que mantém a digitação e as setas funcionando juntas.

Como a navegação por teclado deve funcionar em um dropdown de pesquisa?

Seta para baixo vai à primeira sugestão e continua descendo a lista, seta para cima volta e pode devolver o foco à consulta bruta, Enter seleciona o item destacado e Escape fecha o painel restaurando o que a pessoa digitou. Home e End são uma adição útil para listas longas. Tab deve fechar o painel e seguir adiante, em vez de percorrer as opções.

Devo usar type="search" no input?

Sim. Ele fornece o botão de limpar do navegador em algumas plataformas, sinaliza a intenção às tecnologias assistivas e combina com um enterkeyhint de "search" em teclados móveis. Envolva-o em um form real com role="search" para que a consulta ainda seja enviada se o script falhar, e dê ao input um label ou aria-label, já que um ícone de lupa sozinho não é um nome acessível.

Uma barra de pesquisa precisa de um atalho cmd+K?

Ajuda onde a busca é um caminho de navegação primário, como documentação, dashboards e ferramentas de desenvolvimento. Vincule tanto cmd+K quanto ctrl+K, ignore o atalho enquanto o usuário digita em outro input e mostre a dica dentro do campo para que seja descobrível. Mencione isso no seu prompt para o MeDo e o listener junto com a dica visível são gerados de uma vez.