Skip to content
Star

Search input

Search with scoped filters, recent queries and an agent answer. Free and MIT licensed, as HTML, a typed React component or an Astro component, in three styles with light and dark mode.

$npx designme add search-input
$npx shadcn@latest add https://designme.dev/r/shadcn/search-input.json

Need this designed into your product? Book a call

⌘K
01

Install

Add it to your project with the CLI.

HTML, CSS and JS

$npx designme add search-input

React

$npx designme add search-input --react

Astro

$npx designme add search-input --astro

shadcn, React

$npx shadcn@latest add https://designme.dev/r/shadcn/search-input.json

shadcn, Astro

$npx shadcn@latest add https://designme.dev/r/shadcn/astro/search-input.json

The CLI copies the source into your project, so you own it and can change anything. Where each version lands, what it needs and the shadcn theme bridge: Installation.

02

About

What it is for and what it does.

Search input is a search box that opens to show recent searches, matching results, and an answer from the agent above them. Typing @ lists sources such as Figma or Notion, and picking one narrows the search to that source with a removable chip. It lets a person find a file directly or ask a question and get a written answer in the same list.

  • When people search across several connected tools and need to narrow to one
  • When a question typed into search should get an agent answer as well as matching files
  • When the empty box should offer recent searches to pick up where someone left off
  • When nothing matches and Enter should hand the query to the agent
03

Usage

Import it in React and drive it from your own state, or place it in an Astro page.

React

import { SearchInput } from '@/components/designme/search-input/SearchInput';

React example

The demo above as a React component, 48 lines you can copy.

'use client';
// The animated preview from designme.dev, rebuilt from the React component: an example of driving it from your own state.
import { useEffect, useRef, useState } from 'react';
import { SearchInput, type SearchInputItem, type SearchInputSource } from './SearchInput';
import { useStory } from '../lib/useScript';

const ITEMS: SearchInputItem[] = [
  { icon: 'figma', label: 'Pricing v4', source: 'Figma' }, { icon: 'figma', label: 'Pricing mobile', source: 'Figma' },
  { icon: 'file-text', label: 'Pricing research notes', source: 'Notion' }, { icon: 'code', label: 'PricingCard.tsx', source: 'GitHub' },
  { icon: 'figma', label: 'Checkout flow', source: 'Figma' }, { icon: 'file-text', label: 'Brand voice guide', source: 'Notion' },
  { icon: 'code', label: 'tokens.css', source: 'GitHub' }
];
const SOURCES: SearchInputSource[] = [{ key: 'figma', label: 'Figma', icon: 'figma' }, { key: 'notion', label: 'Notion', icon: 'file-text' }, { key: 'github', label: 'GitHub', icon: 'code' }];
const RECENT = ['pricing contrast', 'checkout copy', 'tokens'];
const ANSWER = 'Pricing changed on Sep 18: annual plans first, one CTA per card. Trial to paid is up 8.1 points since.'.split(' ');

/* ---------- Search input: the box lifts, then someone asks a question and the agent answers above the results ---------- */
export default function SearchInputDemo() {
  const [open, setOpen] = useState(false);
  const [value, setValue] = useState('');
  const [answer, setAnswer] = useState('');
  // the preview types a question on its own; clicking, focusing or typing in it takes over, and what it had typed goes
  const ref = useRef<HTMLDivElement>(null);
  useStory(ref, async ({ wait, taken }) => {
    await wait(900); setOpen(true);
    await wait(600);
    let typed = '', typing = true;
    taken(() => { if (typing) setValue(''); });
    for (const ch of 'why did pricing change?') { typed += ch; setValue(typed); await wait(45); }
    typing = false;
  });
  // a question gets an answer, a word every 45ms, which keeps going while the question is still being typed
  const v = value.trim(), asking = v.split(' ').length > 2 || v.endsWith('?');
  useEffect(() => {
    if (!asking) { setAnswer(''); return; }
    let n = 0;
    const id = setInterval(() => { n++; setAnswer(ANSWER.slice(0, n).join(' ')); if (n >= ANSWER.length) clearInterval(id); }, 45);
    return () => clearInterval(id);
  }, [asking]);
  return (
    // the list opens over whatever is under the box, so this preview keeps room for it under the box
    <div ref={ref} style={{ width: '100%', minHeight: 330 }}>
      <SearchInput items={ITEMS} sources={SOURCES} recent={RECENT} value={value} onValueChange={setValue} open={open} onOpenChange={setOpen}
        answer={asking ? answer : undefined} />
    </div>
  );
}

Astro

In a page in src/pages. It plays the demo above; change its search-input.js to show your own data. Attributes like class go on its root element.

---
import SearchInput from '../components/designme/search-input/SearchInput.astro';
---
<SearchInput />
<SearchInput data-style="soft" class="my-class" />
04

Props

Everything SearchInput takes.

PropTypeWhat it does
itemsrequiredSearchInputItem[]
sourcesSearchInputSource[]Typing @ lists these, and picking one adds it as a filter chip
recentstring[]Earlier searches, shown while the box is empty
valuestringWhat is typed. Leave it out to let the box hold its own
defaultValuestring
onValueChange(value: string) => void
scopestring | nullThe source filter, by label, or null. Backspace in an empty box removes it
defaultScopestring | null
onScopeChange(scope: string | null) => void
openbooleanWhether the list of results is open under the box. Focus opens it and leaving closes it when you leave it out
defaultOpenboolean
onOpenChange(open: boolean) => void
answerstringAn answer from the agent, shown above the results once it has a word. Feed it as it grows and each new word fades in
filter(item: SearchInputItem, search: string) => booleanWhich items match the search. By default an item matches the whole search or any word longer than two letters
onSelect(item: SearchInputItem) => voidCalled when a result is picked, by click or Enter
onSubmit(search: string, scope: string | null) => voidCalled by Enter when no row is highlighted, with the search and the source filter
placeholderstring
shortcutstringThe key hint at the end of the empty box
resultsLabelstringThe heading over the results. Defaults to "Results"
emptyLabelstringWhat the list says when nothing matches
classNamestring
05

Code

The full source, as the CLI installs it.

SearchInput.tsxReact · 206 lines
'use client';
import { useEffect, useId, useRef, useState, type KeyboardEvent, type ReactNode } from 'react';
import { cx } from '../lib/cx';
import { useControllable, useIsoLayoutEffect, useReducedMotion } from '../lib/hooks';
import { Icon, type IconName } from '../lib/icons';
import { useReflow } from '../lib/motion';
import { useHoverGlide } from '../lib/glide';
import '../designme.css';
import './search-input.css';

/** Something the box can find, like a Figma frame or a doc */
export interface SearchInputItem {
  icon: IconName;
  /** Its name. The part that matches the search is marked */
  label: string;
  /** Where it lives, like "Figma". A source filter keeps only the items whose source is its label */
  source: string;
}

/** A source you can narrow the search to by typing @ and its key, like @figma */
export interface SearchInputSource {
  key: string;
  /** Its name, like "Figma". It becomes the filter chip */
  label: string;
  icon: IconName;
}

export interface SearchInputProps {
  items: SearchInputItem[];
  /** Typing @ lists these, and picking one adds it as a filter chip */
  sources?: SearchInputSource[];
  /** Earlier searches, shown while the box is empty */
  recent?: string[];
  /** What is typed. Leave it out to let the box hold its own */
  value?: string;
  defaultValue?: string;
  onValueChange?: (value: string) => void;
  /** The source filter, by label, or null. Backspace in an empty box removes it */
  scope?: string | null;
  defaultScope?: string | null;
  onScopeChange?: (scope: string | null) => void;
  /** Whether the list of results is open under the box. Focus opens it and leaving closes it when you leave it out */
  open?: boolean;
  defaultOpen?: boolean;
  onOpenChange?: (open: boolean) => void;
  /** An answer from the agent, shown above the results once it has a word. Feed it as it grows and each new word fades in */
  answer?: string;
  /** Which items match the search. By default an item matches the whole search or any word longer than two letters */
  filter?: (item: SearchInputItem, search: string) => boolean;
  /** Called when a result is picked, by click or Enter */
  onSelect?: (item: SearchInputItem) => void;
  /** Called by Enter when no row is highlighted, with the search and the source filter */
  onSubmit?: (search: string, scope: string | null) => void;
  placeholder?: string;
  /** The key hint at the end of the empty box */
  shortcut?: string;
  /** The heading over the results. Defaults to "Results" */
  resultsLabel?: string;
  /** What the list says when nothing matches */
  emptyLabel?: string;
  className?: string;
}

// words too common to match on, as on designme.dev
const STOP = ['why', 'did', 'the', 'how', 'what', 'does'];
const wordsOf = (search: string) => search.toLowerCase().split(/[^a-z0-9.]+/).filter(w => w.length > 2 && !STOP.includes(w));
const matchAny = (item: SearchInputItem, search: string) => {
  const l = item.label.toLowerCase();
  return !search || l.includes(search.toLowerCase()) || wordsOf(search).some(w => l.includes(w));
};
// marks the first place the word appears
const marked = (label: string, word: string): ReactNode => {
  const at = word ? label.toLowerCase().indexOf(word.toLowerCase()) : -1;
  return at < 0 ? label : <>{label.slice(0, at)}<mark>{label.slice(at, at + word.length)}</mark>{label.slice(at + word.length)}</>;
};

type Row = { kind: 'recent'; search: string } | { kind: 'source'; source: SearchInputSource } | { kind: 'item'; item: SearchInputItem };

const rowKey = (r: Row) => r.kind === 'item' ? 'i:' + r.item.label + '|' + r.item.source : r.kind === 'recent' ? 'r:' + r.search : 's:' + r.source.key;

/** Search with source filters, recent searches and an answer from the agent. Type @ to filter by source. */
export function SearchInput({ items, sources = [], recent = [], value, defaultValue = '', onValueChange, scope, defaultScope = null, onScopeChange,
  open, defaultOpen = false, onOpenChange, answer, filter = matchAny, onSelect, onSubmit, placeholder = 'Search frames, files and docs',
  shortcut = '⌘K', resultsLabel = 'Results', emptyLabel = 'No matches. Press Enter to ask the agent', className }: SearchInputProps) {
  const [text, setText] = useControllable(value, defaultValue, onValueChange);
  const [sc, setScope] = useControllable(scope, defaultScope, onScopeChange);
  const [isOpen, setOpen] = useControllable(open, defaultOpen, onOpenChange);
  const v = text.trim();
  const root = useRef<HTMLDivElement>(null), input = useRef<HTMLInputElement>(null);
  const id = useId();

  // while the box is open, rows that were showing a moment ago glide to their new places as the answer comes and goes or the
  // results narrow, new rows and the answer fade in, and rows that no longer match fade where they were, so typing never
  // restarts the list; the list eases to its new height
  const [opens, setOpens] = useState(0), [wasOpen, setWasOpen] = useState(isOpen);
  if (wasOpen !== isOpen) { setWasOpen(isOpen); if (isOpen) setOpens(opens + 1); }

  const at = /@\w*$/.test(v) && sources.length ? v.split('@').pop()!.toLowerCase() : null;
  const found = items.filter(it => (!sc || it.source === sc) && filter(it, v));
  const word = wordsOf(v).find(w => found.some(it => it.label.toLowerCase().includes(w))) || v;
  const mode = at !== null ? 'sources' : !v && !sc ? 'recent' : 'results';
  const rows: Row[] = mode === 'sources' ? sources.filter(s => s.key.startsWith(at!)).map(source => ({ kind: 'source', source }))
    : mode === 'recent' ? recent.map(search => ({ kind: 'recent', search }))
    : found.map(item => ({ kind: 'item', item }));
  const paint = `${opens}|${text}|${sc}`;
  // places are read against the list, which opens from the box
  const list = useRef<HTMLDivElement>(null), field = useRef<HTMLDivElement>(null), pop = useRef<HTMLDivElement>(null);
  // Studio's one hover: a highlight that glides from row to row
  useHoverGlide(pop, '.dm-six-it');
  useReflow(pop, '.dm-six-res > [data-key]', { host: list });
  // the list opens under the box, or over it when the room under it in the window is too short, and keeps that side while it
  // is open, growing away from the box as the answer and the results come in
  const [up, setUp] = useState(false);
  useIsoLayoutEffect(() => {
    const f = field.current, p = pop.current; if (!isOpen || !f || !p) return;
    const b = f.getBoundingClientRect();
    setUp(b.bottom + p.offsetHeight + 12 > innerHeight && b.top - p.offsetHeight - 12 > innerHeight - b.bottom);
  }, [isOpen]);
  const lastH = useRef(0), grow = useRef<Animation | null>(null), reduce = useReducedMotion();
  useIsoLayoutEffect(() => {
    const el = list.current; if (!el) { lastH.current = 0; return; }
    const from = grow.current?.playState === 'running' ? el.getBoundingClientRect().height : lastH.current;
    grow.current?.cancel(); grow.current = null;
    const to = el.getBoundingClientRect().height; lastH.current = to;
    if (!isOpen || !from || Math.abs(from - to) < 1 || reduce || !el.animate) return;
    grow.current = el.animate([{ height: from + 'px', boxSizing: 'border-box', overflow: 'hidden' }, { height: to + 'px', boxSizing: 'border-box', overflow: 'hidden' }], { duration: 280, easing: 'cubic-bezier(.22,1,.36,1)' });
  });

  // the highlight only moves with the arrow keys, and starts afresh with each new list
  const [hi, setHi] = useState({ at: -1, for: paint });
  const cur = hi.for === paint && hi.at < rows.length ? hi.at : -1;

  // a click outside lowers the box, unless the cursor is still in it
  useEffect(() => {
    if (!isOpen) return;
    const down = (e: PointerEvent) => { if (!root.current?.contains(e.target as Node) && document.activeElement !== input.current) setOpen(false); };
    document.addEventListener('pointerdown', down);
    return () => document.removeEventListener('pointerdown', down);
  }, [isOpen, setOpen]);

  const pick = (row: Row) => {
    if (row.kind === 'recent') setText(row.search);
    else if (row.kind === 'source') { setScope(row.source.label); setText(text.replace(/@\w*$/, '')); }
    else onSelect?.(row.item);
  };
  const key = (e: KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
      e.preventDefault(); if (!isOpen) setOpen(true);
      if (rows.length) setHi({ at: cur < 0 ? (e.key === 'ArrowDown' ? 0 : rows.length - 1) : (cur + (e.key === 'ArrowDown' ? 1 : -1) + rows.length) % rows.length, for: paint });
    } else if (e.key === 'Enter') { if (cur >= 0) pick(rows[cur]); else onSubmit?.(v, sc); }
    // Escape closes the list and keeps the focus in the box; a second Escape clears it
    else if (e.key === 'Escape') { e.preventDefault(); if (isOpen) setOpen(false); else if (text || sc) { setText(''); setScope(null); } }
    else if (e.key === 'Backspace' && !text && sc) setScope(null);
  };
  // rows are picked on mousedown, so the cursor stays in the box
  const row = (r: Row, i: number, body: ReactNode) => {
    const k = rowKey(r);
    return (
      <button key={k} data-key={k} type="button" tabIndex={-1} id={`${id}-${i}`} role="option" aria-selected={i === cur} className={cx('dm-six-it', i === cur && 'dm-hl')}
        onMouseDown={ev => { ev.preventDefault(); pick(r); }}>{body}</button>
    );
  };

  const words = answer?.split(' ').filter(Boolean) ?? [];
  // the list shows while the box is open and has something to show
  const shown = isOpen && (mode !== 'recent' || rows.length > 0);
  return (
    <div data-dm="" ref={root} className={cx('dm-six', className)}>
      {/* the box: its edge steps up while it is in use */}
      <div ref={field} className={cx('dm-six-box', isOpen && 'dm-f')}>
        <div className="dm-six-in">
          <Icon name="search" size="xs" />
          <span className="dm-six-chips">
            {sc && <span key={sc} className="dm-six-ch dm-enter">{sc}<button type="button" aria-label="Remove filter" onMouseDown={e => { e.preventDefault(); setScope(null); }}><Icon name="x" size="xs" /></button></span>}
          </span>
          <input ref={input} placeholder={placeholder} aria-label="Search" spellCheck={false} value={text} role="combobox" aria-expanded={isOpen}
            aria-controls={`${id}-list`} aria-autocomplete="list" aria-activedescendant={isOpen && cur >= 0 ? `${id}-${cur}` : undefined}
            onChange={e => setText(e.target.value)} onFocus={() => setOpen(true)} onBlur={() => setOpen(false)} onKeyDown={key} />
          <span className="dm-kbd dm-six-k" hidden={!!v || !!sc}>{shortcut}</span>
          <button type="button" className="dm-ib dm-six-x" aria-label="Clear" hidden={!v && !sc} onMouseDown={e => { e.preventDefault(); setText(''); setScope(null); }}><Icon name="x" size="xs" /></button>
        </div>
      </div>
      <div ref={pop} className={cx('dm-pop dm-six-pop', shown && 'dm-open')} inert={!shown}
        style={up ? { top: 'auto', bottom: 'calc(100% + 6px)', ['--dm-origin' as string]: 'bottom left' } : { top: 'calc(100% + 6px)', ['--dm-origin' as string]: 'top left' }}>
        <div key={opens} ref={list} className="dm-six-res" id={`${id}-list`} role="listbox" aria-label="Results">
          {mode === 'sources' && <>
            <div className="dm-six-g" data-key="g">Filter by source</div>
            {rows.map((r, i) => r.kind === 'source' && row(r, i, <><span className="dm-ic"><Icon name={r.source.icon} size="xs" /></span>{r.source.label}<span className="dm-d">@{r.source.key}</span></>))}
          </>}
          {mode === 'recent' && !!rows.length && <>
            <div className="dm-six-g" data-key="g">Recent</div>
            {rows.map((r, i) => r.kind === 'recent' && row(r, i, <><span className="dm-ic"><Icon name="history" size="xs" /></span>{r.search}</>))}
          </>}
          {mode === 'results' && <>
            {words.length > 0 && <div className="dm-six-ans" data-key="ans"><Icon name="spark" size="xs" /><span>{words.map((w, i) => <span key={i} className="dm-w">{w} </span>)}</span></div>}
            {rows.length ? <>
              <div className="dm-six-g" data-key="g">{resultsLabel}</div>
              {rows.map((r, i) => r.kind === 'item' && row(r, i, <><span className="dm-ic"><Icon name={r.item.icon} size="xs" /></span><span>{marked(r.item.label, word)}</span><span className="dm-d">{r.item.source}</span></>))}
            </> : <div className="dm-six-g" data-key="g">{emptyLabel}</div>}
          </>}
        </div>
      </div>
    </div>
  );
}
search-input.cssReact · 63 lines
/* Generated from designme.dev by scripts/sync.mjs. Edit the site, then sync. */
/* ---------- Search input ---------- */
/* one field, as wide as the other single fields (the full width on a phone), with its suggestions in a list that opens from
   it: under it, or over it when the room under it is too short (placePop). Its script keeps the field and the open list
   centred in the stage together, the field gliding up as the list opens (centre()); no room is kept for the list. The
   field's glass, the rows' icons, the answer's spark and the group names share one column 12px in, and the words another */
.dm-six{position:relative;width:100%;max-width:var(--dm-field-w);margin:0 auto}
.dm-six-box{background:var(--dm-surface);border-radius:var(--dm-r-field);box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--dm-field-line) 50%,transparent);transition:box-shadow var(--dm-t-fast)}
@supports (corner-shape:squircle){.dm-six-box{corner-shape:squircle;border-radius:var(--dm-r-field-sq)}}
/* the edge steps up while the field is in use (it has the focus, or the preview types in it); nothing else changes */
.dm-six-box.dm-f{box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--dm-field-line-strong) 50%,transparent)}
/* 12px in at both ends: the magnifier on the left, and on the right the ⌘K key or the clear button's box (check-rules R2, 27 Nov) */
.dm-six-in{display:flex;align-items:center;gap:var(--dm-s-2);height:var(--dm-field-h);padding:0 var(--dm-s-3);color:var(--dm-muted)}
.dm-six-in input{flex:1;min-width:0;height:100%;border:0;outline:0;background:transparent;font:inherit;font-size:13.5px;color:var(--dm-fg)}
/* (its words start right after the glass, as the rows' words do) */
.dm-six .dm-six-in input{padding:0}
.dm-six-in input::placeholder{color:var(--dm-muted)}
.dm-six-chips{display:flex;gap:var(--dm-s-1)}
.dm-six-chips:empty{display:none}
.dm-six-ch{display:inline-flex;align-items:center;gap:2px;height:24px;padding:0 2px 0 var(--dm-s-2);border-radius:var(--dm-r-tag);background:var(--dm-accent-bg);color:var(--dm-accent-fg,var(--dm-accent));font-size:12px;font-weight:500;white-space:nowrap}
.dm-six-ch button{width:20px;height:20px;border-radius:50%;display:grid;place-items:center;opacity:.7;transition:opacity var(--dm-t-fast),background var(--dm-t-fast)}
@media (hover:hover) and (pointer:fine){.dm-six-ch button:hover{opacity:1;background:color-mix(in srgb,currentColor 12%,transparent)}}
@supports (corner-shape:squircle){.dm-six-ch{corner-shape:squircle;border-radius:var(--dm-r-tag-sq)}}
/* the key hint and the clear button's cross end 14px in, where the rows' sources end */
.dm-six-x{width:24px;height:24px}
/* nothing in it grows or shrinks when pressed */
.dm-six :is(.dm-ib,.dm-pill):active,:root[data-style="studio"] .dm-six .dm-ib:active,:root [data-style="studio"] .dm-six .dm-ib:active,:root [data-style="studio"].dm-six .dm-ib:active{transform:none}
/* the list: one family with the field (owner, 21 Nov: "the input is different shape than the dropdown"): as wide as it, 6px
   under it, with the field's corners. Its rows sit 6px in, their corners the list's less those 6px, so their icons and words
   fall on the field's columns and their sources end where the field's cross does. (The 6px are the results' own padding, so
   the answer above them can run to the list's edges) */
.dm-six-pop{left:0;right:0;min-width:0;padding:0;border-radius:var(--dm-r-field)}
@supports (corner-shape:squircle){.dm-six-pop{border-radius:var(--dm-r-field-sq)}}
.dm-six-res{position:relative;padding:6px}
.dm-six-g{font-size:11.5px;color:var(--dm-muted);padding:var(--dm-s-2) var(--dm-s-2) var(--dm-s-1) 6px}
.dm-six-it{display:flex;align-items:center;gap:var(--dm-s-2);width:100%;padding:7px var(--dm-s-2) 7px 6px;border-radius:calc(var(--dm-r-field) - 4px);font-size:13px;text-align:left;transition:background .15s}
@supports (corner-shape:squircle){.dm-six-it{border-radius:calc(var(--dm-r-field-sq) - 6px)}}
.dm-six-it.dm-hl{background:var(--dm-row)}
@media (hover:hover) and (pointer:fine){.dm-six-it:hover{background:var(--dm-row)}}
.dm-six-it .dm-ic{color:var(--dm-muted);display:grid;flex:none}
.dm-six-it .dm-d{margin-left:auto;padding-left:var(--dm-s-2);font-size:12px;color:var(--dm-muted);transition:color .15s}
/* on a highlighted row's grey the source steps up, so it keeps 4.5:1 and APCA Lc 60 in dark mode */
@media (hover:hover) and (pointer:fine){.dm-six-it:is(:hover,.dm-hl) .dm-d{color:var(--dm-fg2)}}
.dm-six-it mark{background:transparent;color:var(--dm-accent-fg,var(--dm-accent));font-weight:500}
/* the agent's answer is the list's head section (owner, 21 Nov: "too stark"): no box and no tint, running to the list's edges
   with a hairline under it. Its spark is on the icons' column, in the accent's mark colour, the only colour in it; its words
   are on the words' column, in the text colour at the rows' size. It grows with the list as its words come in. Studio makes
   it the list's off-white head strip, with the spark muted */
.dm-six-ans{display:flex;gap:var(--dm-s-2);margin:-6px -6px 6px;padding:10px 14px 10px 12px;border-bottom:1px solid color-mix(in srgb,var(--dm-line) 50%,transparent);font-size:13px;line-height:1.5;color:var(--dm-fg)}
.dm-six-ans>svg{color:var(--dm-accent-mark);flex:none;margin-top:3px}
.dm-six-ans .dm-w{animation:dm-sxw .4s var(--dm-ease) both}
.dm-six-ans .dm-w.dm-done{animation:none}
@keyframes dm-sxw{from{opacity:0;filter:blur(3px)}}
@keyframes dm-sxwc{from{opacity:0}}
/* Studio: the list has the field's 10px corners and its rows follow them, 6px in (4px corners); the answer is the off-white
   head strip under the list's top corners, with a full hairline under it; the rows' hover is Studio's quiet fill at its own
   ease; the filter is a tag with rounded corners, not a pill; new words fade in without a blur */
:root[data-style="studio"] .dm-six-it,:root [data-style="studio"] .dm-six-it,:root [data-style="studio"].dm-six-it{border-radius:calc(var(--dm-r-field) - 6px);transition:background-color var(--dm-t-fast) var(--dm-ease)}
:root[data-style="studio"] .dm-six-ans,:root [data-style="studio"] .dm-six-ans,:root [data-style="studio"].dm-six-ans{background:var(--dm-strip);border-bottom-color:var(--dm-line);border-radius:var(--dm-r-field) var(--dm-r-field) 0 0}
:root[data-style="studio"] .dm-six-ans>svg,:root [data-style="studio"] .dm-six-ans>svg,:root [data-style="studio"].dm-six-ans>svg{color:var(--dm-muted)}
:root[data-style="studio"] .dm-six-ch,:root [data-style="studio"] .dm-six-ch,:root [data-style="studio"].dm-six-ch{border-radius:var(--dm-r-sm)}
:root[data-style="studio"] .dm-six-ans .dm-w:not(.dm-done),:root [data-style="studio"] .dm-six-ans .dm-w:not(.dm-done),:root [data-style="studio"].dm-six-ans .dm-w:not(.dm-done){animation-name:dm-sxwc;animation-duration:var(--dm-t)}
SearchInput.astroAstro · 29 lines
---
// Generated from designme.dev by scripts/sync.mjs. Edit the site, then sync.
// Search input: Search with scoped filters, recent queries and an agent answer.
// The markup, CSS and script are designme.dev's own, run by the shared core in ../core, which mounts the component when it scrolls
// into view and plays its demo. To show your own data, change search-input.js. The markup is kept exactly as it is (is:raw).
import type { HTMLAttributes } from 'astro/types';
import '../core/designme.css';
import './search-input.css';

export interface Props extends HTMLAttributes<'div'> {
  /** "soft" or "studio" draws it in that style. Leave it out for Blueprint, or for the style set on <html> (data-style="soft" or "studio") */
  'data-style'?: 'soft' | 'studio';
}
const { class: className, ...rest } = Astro.props;
---
<div class:list={['card', className]} data-c="search-input" {...rest}>
  <div class="stage-in"><Fragment is:raw>
<div class="six">
  <div class="six-box">
    <div class="six-in"><svg class="i xs"><use href="#i-search"/></svg><span class="six-chips"></span><input placeholder="Search frames, files and docs" aria-label="Search" spellcheck="false"><span class="kbd six-k">⌘K</span><button class="ib six-x" aria-label="Clear" hidden><svg class="i xs"><use href="#i-x"/></svg></button></div>
  </div>
  <div class="pop six-pop"><div class="six-res"></div></div>
</div>
  </Fragment></div>
</div>
<script>
  import './search-input.js';
</script>
search-input.htmlHTML · 11 lines
<div class="card" data-c="search-input">
  <div class="stage-in">
    <div class="six">
      <div class="six-box">
        <div class="six-in"><svg class="i xs"><use href="#i-search"/></svg><span class="six-chips"></span><input placeholder="Search frames, files and docs" aria-label="Search" spellcheck="false"><span class="kbd six-k">⌘K</span><button class="ib six-x" aria-label="Clear" hidden><svg class="i xs"><use href="#i-x"/></svg></button></div>
      </div>
      <div class="pop six-pop"><div class="six-res"></div></div>
    </div>
  </div>
</div>
search-input.cssHTML · 62 lines
/* ---------- Search input ---------- */
/* one field, as wide as the other single fields (the full width on a phone), with its suggestions in a list that opens from
   it: under it, or over it when the room under it is too short (placePop). Its script keeps the field and the open list
   centred in the stage together, the field gliding up as the list opens (centre()); no room is kept for the list. The
   field's glass, the rows' icons, the answer's spark and the group names share one column 12px in, and the words another */
.six{position:relative;width:100%;max-width:var(--dm-field-w);margin:0 auto}
.six-box{background:var(--dm-surface);border-radius:var(--dm-r-field);box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--dm-field-line) 50%,transparent);transition:box-shadow var(--dm-t-fast)}
@supports (corner-shape:squircle){.six-box{corner-shape:squircle;border-radius:var(--dm-r-field-sq)}}
/* the edge steps up while the field is in use (it has the focus, or the preview types in it); nothing else changes */
.six-box.f{box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--dm-field-line-strong) 50%,transparent)}
/* 12px in at both ends: the magnifier on the left, and on the right the ⌘K key or the clear button's box (check-rules R2, 27 Nov) */
.six-in{display:flex;align-items:center;gap:var(--dm-s-2);height:var(--dm-field-h);padding:0 var(--dm-s-3);color:var(--dm-muted)}
.six-in input{flex:1;min-width:0;height:100%;border:0;outline:0;background:transparent;font:inherit;font-size:13.5px;color:var(--dm-fg)}
/* (its words start right after the glass, as the rows' words do) */
.six .six-in input{padding:0}
.six-in input::placeholder{color:var(--dm-muted)}
.six-chips{display:flex;gap:var(--dm-s-1)}
.six-chips:empty{display:none}
.six-ch{display:inline-flex;align-items:center;gap:2px;height:24px;padding:0 2px 0 var(--dm-s-2);border-radius:var(--dm-r-tag);background:var(--dm-accent-bg);color:var(--dm-accent-fg,var(--dm-accent));font-size:12px;font-weight:500;white-space:nowrap}
.six-ch button{width:20px;height:20px;border-radius:50%;display:grid;place-items:center;opacity:.7;transition:opacity var(--dm-t-fast),background var(--dm-t-fast)}
@media (hover:hover) and (pointer:fine){.six-ch button:hover{opacity:1;background:color-mix(in srgb,currentColor 12%,transparent)}}
@supports (corner-shape:squircle){.six-ch{corner-shape:squircle;border-radius:var(--dm-r-tag-sq)}}
/* the key hint and the clear button's cross end 14px in, where the rows' sources end */
.six-x{width:24px;height:24px}
/* nothing in it grows or shrinks when pressed */
.six :is(.ib,.pill):active,:root[data-style="studio"] .six .ib:active,:root [data-style="studio"] .six .ib:active,:root [data-style="studio"].six .ib:active{transform:none}
/* the list: one family with the field (owner, 21 Nov: "the input is different shape than the dropdown"): as wide as it, 6px
   under it, with the field's corners. Its rows sit 6px in, their corners the list's less those 6px, so their icons and words
   fall on the field's columns and their sources end where the field's cross does. (The 6px are the results' own padding, so
   the answer above them can run to the list's edges) */
.six-pop{left:0;right:0;min-width:0;padding:0;border-radius:var(--dm-r-field)}
@supports (corner-shape:squircle){.six-pop{border-radius:var(--dm-r-field-sq)}}
.six-res{position:relative;padding:6px}
.six-g{font-size:11.5px;color:var(--dm-muted);padding:var(--dm-s-2) var(--dm-s-2) var(--dm-s-1) 6px}
.six-it{display:flex;align-items:center;gap:var(--dm-s-2);width:100%;padding:7px var(--dm-s-2) 7px 6px;border-radius:calc(var(--dm-r-field) - 4px);font-size:13px;text-align:left;transition:background .15s}
@supports (corner-shape:squircle){.six-it{border-radius:calc(var(--dm-r-field-sq) - 6px)}}
.six-it.hl{background:var(--dm-row)}
@media (hover:hover) and (pointer:fine){.six-it:hover{background:var(--dm-row)}}
.six-it .ic{color:var(--dm-muted);display:grid;flex:none}
.six-it .d{margin-left:auto;padding-left:var(--dm-s-2);font-size:12px;color:var(--dm-muted);transition:color .15s}
/* on a highlighted row's grey the source steps up, so it keeps 4.5:1 and APCA Lc 60 in dark mode */
@media (hover:hover) and (pointer:fine){.six-it:is(:hover,.hl) .d{color:var(--dm-fg2)}}
.six-it mark{background:transparent;color:var(--dm-accent-fg,var(--dm-accent));font-weight:500}
/* the agent's answer is the list's head section (owner, 21 Nov: "too stark"): no box and no tint, running to the list's edges
   with a hairline under it. Its spark is on the icons' column, in the accent's mark colour, the only colour in it; its words
   are on the words' column, in the text colour at the rows' size. It grows with the list as its words come in. Studio makes
   it the list's off-white head strip, with the spark muted */
.six-ans{display:flex;gap:var(--dm-s-2);margin:-6px -6px 6px;padding:10px 14px 10px 12px;border-bottom:1px solid color-mix(in srgb,var(--dm-line) 50%,transparent);font-size:13px;line-height:1.5;color:var(--dm-fg)}
.six-ans>svg{color:var(--dm-accent-mark);flex:none;margin-top:3px}
.six-ans .w{animation:sxw .4s var(--dm-ease) both}
.six-ans .w.done{animation:none}
@keyframes sxw{from{opacity:0;filter:blur(3px)}}
@keyframes sxwc{from{opacity:0}}
/* Studio: the list has the field's 10px corners and its rows follow them, 6px in (4px corners); the answer is the off-white
   head strip under the list's top corners, with a full hairline under it; the rows' hover is Studio's quiet fill at its own
   ease; the filter is a tag with rounded corners, not a pill; new words fade in without a blur */
:root[data-style="studio"] .six-it,:root [data-style="studio"] .six-it,:root [data-style="studio"].six-it{border-radius:calc(var(--dm-r-field) - 6px);transition:background-color var(--dm-t-fast) var(--dm-ease)}
:root[data-style="studio"] .six-ans,:root [data-style="studio"] .six-ans,:root [data-style="studio"].six-ans{background:var(--dm-strip);border-bottom-color:var(--dm-line);border-radius:var(--dm-r-field) var(--dm-r-field) 0 0}
:root[data-style="studio"] .six-ans>svg,:root [data-style="studio"] .six-ans>svg,:root [data-style="studio"].six-ans>svg{color:var(--dm-muted)}
:root[data-style="studio"] .six-ch,:root [data-style="studio"] .six-ch,:root [data-style="studio"].six-ch{border-radius:var(--dm-r-sm)}
:root[data-style="studio"] .six-ans .w:not(.done),:root [data-style="studio"] .six-ans .w:not(.done),:root [data-style="studio"].six-ans .w:not(.done){animation-name:sxwc;animation-duration:var(--dm-t)}
search-input.jsHTML · 86 lines
DM.def('search-input', (r, c) => {
  r.innerHTML = r.innerHTML.replace('{search}', I('search','xs')).replace('{x}', I('x','xs'));
  // Studio's one hover: a highlight that glides from row to row (hoverGlide)
  c.offs.push(hoverGlide($('.six-pop', r), '.six-it'));
  const root = $('.six', r), box = $('.six-box', r), inp = $('.six-in input', r), pop = $('.six-pop', r), res = $('.six-res', r), chips = $('.six-chips', r), xB = $('.six-x', r), k = $('.six-k', r);
  const isOpen = () => pop.classList.contains('open');
  const ITEMS = [['figma','Pricing v4','Figma'],['figma','Pricing mobile','Figma'],['file-text','Pricing research notes','Notion'],['code','PricingCard.tsx','GitHub'],['figma','Checkout flow','Figma'],['file-text','Brand voice guide','Notion'],['code','tokens.css','GitHub']];
  const SC = { figma:'Figma', notion:'Notion', github:'GitHub' };
  let scope = null, at = null, ans = 0, grow = null, growTo = 0, hi = -1, lastPaint = 0;
  res.id = 'six-r-' + Math.random().toString(36).slice(2, 7); res.setAttribute('role', 'listbox'); res.setAttribute('aria-label', 'Suggestions');
  inp.setAttribute('role', 'combobox'); inp.setAttribute('aria-autocomplete', 'list'); inp.setAttribute('aria-expanded', 'false'); inp.setAttribute('aria-controls', res.id);
  // the agent's answer streams in word by word and keeps going while the question is still being typed
  const WS = 'Pricing changed on Sep 18: annual plans first, one CTA per card. Trial to paid is up 8.1 points since.'.split(' ');
  function paint(){
    // the list eases to its new height instead of jumping as the results change
    const h0 = isOpen() ? res.offsetHeight : 0; if (grow) grow.cancel();
    const v = inp.value.trim(); xB.hidden = !v && !scope; k.hidden = !!v || !!scope;
    let h = '', asking = false;
    if (/@\w*$/.test(v)){ const q = v.split('@').pop().toLowerCase(); h = '<div class="six-g">Filter by source</div>' + Object.entries(SC).filter(([key]) => key.startsWith(q)).map(([key, n]) => `<button class="six-it" data-sc="${n}"><span class="ic">${I(key === 'figma' ? 'figma' : key === 'github' ? 'code' : 'file-text','xs')}</span>${n}<span class="d">@${key}</span></button>`).join(''); }
    else if (!v && !scope){ h = '<div class="six-g">Recent</div>' + ['pricing contrast','checkout copy','tokens'].map(q => `<button class="six-it" data-q="${q}"><span class="ic">${I('history','xs')}</span>${q}</button>`).join(''); }
    else {
      const words = v.toLowerCase().split(/[^a-z0-9.]+/).filter(w => w.length > 2 && !['why','did','the','how','what','does'].includes(w)); const hit = i => !v || i[1].toLowerCase().includes(v.toLowerCase()) || words.some(w => i[1].toLowerCase().includes(w));
      const m = ITEMS.filter(i => (!scope || i[2] === scope) && hit(i)); const hw = words.find(w => m.some(i => i[1].toLowerCase().includes(w))) || v;
      // the answer shows once the agent has its first word, drawn with the words it already has, so the rows under it are
      // measured where they will stay
      asking = v.split(' ').length > 2 || v.endsWith('?');
      if (asking && ans) h += `<div class="six-ans">${I('spark','xs')}<span class="six-at">${WS.slice(0, ans).map(w => `<span class="w done">${w} </span>`).join('')}</span></div>`;
      h += m.length ? '<div class="six-g">Results</div>' + m.map(i => `<button class="six-it"><span class="ic">${I(i[0],'xs')}</span><span>${hw ? i[1].replace(new RegExp(hw.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i'), s => `<mark>${s}</mark>`) : i[1]}</span><span class="d">${i[2]}</span></button>`).join('') : '<div class="six-g">No matches. Press Enter to ask the agent</div>';
    }
    // rows that were showing a moment ago glide to their new places as the answer line comes and goes or the results narrow,
    // new rows and the answer fade in, and rows that no longer match fade where they were, so typing never restarts the list.
    // Keys pressed faster than the rows could move (the preview types a letter every 45ms) redraw the list in place instead,
    // so no row is left behind its place, over another, while the next letter comes
    const draw = () => { res.innerHTML = h; [...res.children].forEach(x => x.dataset.key = x.matches('.six-ans') ? 'ans' : x.matches('.six-g') ? 'g' : x.textContent); };
    const t = performance.now(), quick = t - lastPaint < 150; lastPaint = t;
    if (quick){ const had = new Set([...res.children].map(x => x.dataset.key)); [...res.children].forEach(x => (x._rf || []).forEach(a => a.cancel())); draw(); [...res.children].forEach(x => { if (!had.has(x.dataset.key)) enter(x); }); }
    else reflow(() => [...res.children], draw, { root:pop });
    hi = -1; inp.removeAttribute('aria-activedescendant');
    $$('.six-it:not([data-ghost])', res).forEach((b, j) => { b.id = res.id + '-' + j; b.setAttribute('role', 'option'); b.setAttribute('aria-selected', 'false'); b.tabIndex = -1; });
    // a question gets an answer a word every 45ms; its first word brings the answer into the list
    if (asking){
      if (!at && ans < WS.length) at = c.every(45, () => { if (ans >= WS.length){ clearInterval(at); at = null; return; } const el = $('.six-ans:not([data-ghost]) .six-at', res); ans++; if (el) el.insertAdjacentHTML('beforeend', `<span class="w">${WS[ans - 1]} </span>`); else paint(); }); }
    else { if (at){ clearInterval(at); at = null; } ans = 0; }
    const h1 = res.offsetHeight;
    growTo = h1; if (h0 && h1 !== h0 && !REDUCE) grow = res.animate([{ height:h0 + 'px', boxSizing:'border-box', overflow:'hidden' }, { height:h1 + 'px', boxSizing:'border-box', overflow:'hidden' }], { duration:280, easing:'cubic-bezier(.22,1,.36,1)' });
    $$('.six-it[data-q]', res).forEach(b => b.onmousedown = e => { e.preventDefault(); inp.value = b.dataset.q; paint(); });
    $$('.six-it[data-sc]', res).forEach(b => b.onmousedown = e => { e.preventDefault(); scope = b.dataset.sc; inp.value = inp.value.replace(/@\w*$/, ''); chips.innerHTML = `<span class="six-ch">${scope}<button aria-label="Remove filter">${I('x','xs')}</button></span>`; enter(chips.firstChild); $('button', chips).onmousedown = ev => { ev.preventDefault(); scope = null; chips.innerHTML = ''; paint(); }; paint(); });
  }
  // the field sits centred on its own, and glides up as the list opens under it, so the two sit centred together. On a page of
  // your own the list opens over the field when the window has no room for it under the field (placePop), and keeps that side
  // while it is open, growing away from the field as the answer and the results come in
  let up = false;
  // (while the list eases to a new height, the field goes straight to where that height puts it, rather than chasing it)
  const listH = () => grow && grow.playState === 'running' ? pop.offsetHeight - res.offsetHeight + growTo : pop.offsetHeight;
  const centred = centre(c, root, () => isOpen() && !up ? box.offsetHeight + 6 + listH() : root.offsetHeight, [pop]);
  function place(){
    up = false; centred();
    const gy = parseFloat(root.style.getPropertyValue('--dm-gy')) || 0, now = new DOMMatrixReadOnly(getComputedStyle(root).transform).m42, dy = gy - now;
    const room = popRoom(box), b = box.getBoundingClientRect(), below = room.bottom - b.bottom - dy, above = b.top + dy - room.top;
    // (in a demo's stage the list always opens under the field, which glides up to make room for it)
    up = !r.closest('.stage-in') && below < pop.offsetHeight + 12 && above > below; if (up) centred();
    box.dataset.popPos = up ? 'up' : 'down'; placePop(box, pop);
    if (up){ pop.style.top = 'auto'; pop.style.bottom = 'calc(100% + 6px)'; } else pop.style.bottom = '';
  }
  // on closing, the field waits for the list to fade before it glides back to the middle
  function close(){ if (!isOpen()) return; pop.classList.remove('open'); inp.setAttribute('aria-expanded', 'false'); inp.removeAttribute('aria-activedescendant'); c.later(REDUCE ? 0 : 180, centred); }
  function shut(){ box.classList.remove('f'); close(); }
  const list = () => { if (isOpen()) return; pop.classList.add('open'); inp.setAttribute('aria-expanded', 'true'); place(); };
  inp.onfocus = () => { box.classList.add('f'); paint(); list(); };
  inp.onblur = shut;
  inp.oninput = () => { paint(); list(); };
  // the box is a combobox for the list under it: up and down move through the rows and wrap, Enter picks the highlighted
  // one, and Escape closes the list, keeping the focus in the box (a second Escape clears it)
  const light = k => { const all = $$('.six-it:not([data-ghost])', res); if (!all.length) return; hi = (k + all.length) % all.length;
    all.forEach((b, j) => { b.classList.toggle('hl', j === hi); b.setAttribute('aria-selected', j === hi); }); inp.setAttribute('aria-activedescendant', all[hi].id); all[hi].scrollIntoView({ block:'nearest' }); };
  inp.onkeydown = e => {
    if (e.key === 'Backspace' && !inp.value && scope){ scope = null; chips.innerHTML = ''; paint(); }
    if (e.key === 'ArrowDown' || e.key === 'ArrowUp'){ e.preventDefault(); if (!isOpen()){ paint(); list(); } light(hi < 0 ? (e.key === 'ArrowDown' ? 0 : -1) : hi + (e.key === 'ArrowDown' ? 1 : -1)); }
    if (e.key === 'Enter' && hi >= 0 && isOpen()){ const b = $$('.six-it:not([data-ghost])', res)[hi]; if (b && b.onmousedown){ e.preventDefault(); b.onmousedown(e); } }
    if (e.key === 'Escape'){ e.preventDefault(); if (isOpen()) close(); else if (inp.value || scope){ inp.value = ''; scope = null; chips.innerHTML = ''; paint(); } } };
  xB.onmousedown = e => { e.preventDefault(); inp.value = ''; scope = null; chips.innerHTML = ''; paint(); };
  c.on(document, 'pointerdown', e => { if (!r.contains(e.target) && document.activeElement !== inp) shut(); });
  // the preview types a question on its own; clicking, focusing or typing in it takes over, and what it had typed goes
  c.auto(900, () => c.run(async () => { box.classList.add('f'); c.taken(() => { if (document.activeElement !== inp) shut(); }); paint(); list(); await c.step(600); await c.type(inp, 'why did pricing change?', { ms:45, each:paint }); }));
});
06

Questions

What people ask about it.

How do I stream the agent's answer into the results?
Pass the text so far as answer and update it as tokens arrive. Each word is its own span, so new words fade in while earlier ones stay put.
What happens when the person presses Enter without picking a result?
onSubmit is called with the trimmed search and the current source filter, or null. That is the place to send the question to your agent.
Can I use my own matching, like fuzzy search?
Yes. Pass filter(item, search) and return true for the items to keep. The source filter is still applied first.
07

More in Forms and inputs

Buttons, fields, pickers and sign-in flows for any product.

TooltipQuiet labels on hover, with shortcuts and a richer preview card.
FormA project brief with inline checks and an agent that drafts the rest.