# Search results

An extensions marketplace search: a query `Input` with a live result count, a facet sidebar of category `Checkbox`es with counts and price and rating `RadioGroup`s, removable chips for the active filters, a sort `Select`, results with the matched terms in `<mark>`, and an empty state when the filters leave nothing.

**Example: Extensions search** (`examples/recipes/search-results.tsx`)

```tsx
'use client'

import { Badge, Body, BodySmall, Button, Checkbox, Heading, Input, Label, Radio, RadioGroup, Select, Stack, Text } from '@blocks/design-system'
import { Search, SlidersHorizontal, Star, X } from 'lucide-react'
import { Fragment, useId, useState } from 'react'
import styles from './search-results.module.css'

interface Extension {
  slug: string
  name: string
  category: string
  description: string
  /** Monthly price in dollars; 0 is free. */
  price: number
  rating: number
  installs: number
}

const extensions: Extension[] = [
  { slug: 'invoice-parser', name: 'Invoice Parser', category: 'Finance', description: 'Reads PDF invoices and fills in the vendor, totals and due date.', price: 0, rating: 4.7, installs: 12_400 },
  { slug: 'recurring-invoices', name: 'Recurring Invoices', category: 'Finance', description: 'Schedules monthly or yearly invoices and sends them on time.', price: 8, rating: 4.5, installs: 8_100 },
  { slug: 'expense-snap', name: 'Expense Snap', category: 'Finance', description: 'Photograph receipts and match them to invoices automatically.', price: 5, rating: 4.2, installs: 5_300 },
  { slug: 'ledger-sync', name: 'Ledger Sync', category: 'Finance', description: 'Two-way sync of invoices and payments with your accounting ledger.', price: 12, rating: 4.8, installs: 3_900 },
  { slug: 'tax-rates', name: 'Tax Rates', category: 'Finance', description: 'Current sales tax rates for quotes and invoices in 40 countries.', price: 0, rating: 4.0, installs: 7_600 },
  { slug: 'timesheet-invoice', name: 'Timesheet to Invoice', category: 'Productivity', description: 'Turns approved timesheets into draft invoices for each client.', price: 0, rating: 4.1, installs: 6_700 },
  { slug: 'standup-bot', name: 'Standup Bot', category: 'Productivity', description: 'Collects daily updates from the team and posts a summary.', price: 0, rating: 4.6, installs: 22_000 },
  { slug: 'invoice-reminders', name: 'Invoice Reminders', category: 'Communication', description: 'Polite, scheduled reminders for unpaid invoices by email or text.', price: 0, rating: 3.9, installs: 9_800 },
  { slug: 'client-portal', name: 'Client Portal', category: 'Communication', description: 'A portal where clients view quotes, invoices and shared files.', price: 15, rating: 4.3, installs: 4_400 },
  { slug: 'contract-vault', name: 'Contract Vault', category: 'Legal', description: 'Stores signed contracts and links them to clients and invoices.', price: 9, rating: 4.4, installs: 2_100 },
  { slug: 'signature-pad', name: 'Signature Pad', category: 'Legal', description: 'Collects signatures on quotes before they become invoices.', price: 0, rating: 4.6, installs: 3_200 },
]

const categories = ['Finance', 'Productivity', 'Communication', 'Legal']
const priceOptions = [
  { value: 'any', label: 'Any price' },
  { value: 'free', label: 'Free' },
  { value: 'paid', label: 'Paid' },
]
const ratingOptions = [
  { value: 'any', label: 'Any rating' },
  { value: '4', label: '4 stars and up' },
  { value: '4.5', label: '4.5 stars and up' },
]
const labelOf = (options: { value: string; label: string }[], value: string) => options.find((option) => option.value === value)?.label ?? value
const sorts = [
  { value: 'relevance', label: 'Best match' },
  { value: 'rating', label: 'Highest rated' },
  { value: 'installs', label: 'Most installed' },
  { value: 'name', label: 'Name' },
]

const escapeRegExp = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')

// Wraps each matched term in <mark>; the text itself is unchanged for screen readers.
function Highlight({ text, terms }: { text: string; terms: string[] }) {
  if (terms.length === 0) return text
  const pattern = new RegExp(`(${terms.map(escapeRegExp).join('|')})`, 'gi')
  return text.split(pattern).map((part, index) =>
    // Split with a capture group puts the matches at odd indexes.
    index % 2 === 1 ? (
      // biome-ignore lint/suspicious/noArrayIndexKey: the pieces of one string, always in the same order
      <mark key={index} className={styles.mark}>
        {part}
      </mark>
    ) : (
      // biome-ignore lint/suspicious/noArrayIndexKey: the pieces of one string, always in the same order
      <Fragment key={index}>{part}</Fragment>
    ),
  )
}

export default function SearchResults() {
  const [query, setQuery] = useState('invoice')
  const [selectedCategories, setSelectedCategories] = useState<string[]>([])
  const [price, setPrice] = useState('any')
  const [rating, setRating] = useState('any')
  const [sort, setSort] = useState('relevance')
  const [filtersOpen, setFiltersOpen] = useState(false)
  const id = useId()

  const terms = query.toLowerCase().split(/\s+/).filter(Boolean)
  const matchesQuery = (item: Extension) => terms.every((term) => `${item.name} ${item.description} ${item.category}`.toLowerCase().includes(term))
  const matchesPrice = (item: Extension) => price === 'any' || (price === 'free' ? item.price === 0 : item.price > 0)
  const matchesRating = (item: Extension) => rating === 'any' || item.rating >= Number(rating)
  const relevance = (item: Extension) => terms.filter((term) => item.name.toLowerCase().includes(term)).length

  // Category counts ignore the category filter itself, so each box says what checking it would add.
  const beforeCategory = extensions.filter((item) => matchesQuery(item) && matchesPrice(item) && matchesRating(item))
  const results = beforeCategory
    .filter((item) => selectedCategories.length === 0 || selectedCategories.includes(item.category))
    .sort((a, b) => {
      if (sort === 'rating') return b.rating - a.rating
      if (sort === 'installs') return b.installs - a.installs
      if (sort === 'name') return a.name.localeCompare(b.name)
      return relevance(b) - relevance(a) || b.installs - a.installs
    })

  const chips = [
    ...selectedCategories.map((category) => ({
      key: `category-${category}`,
      label: category,
      remove: () => setSelectedCategories((current) => current.filter((item) => item !== category)),
    })),
    ...(price === 'any' ? [] : [{ key: 'price', label: labelOf(priceOptions, price), remove: () => setPrice('any') }]),
    ...(rating === 'any' ? [] : [{ key: 'rating', label: labelOf(ratingOptions, rating), remove: () => setRating('any') }]),
  ]

  function clearFilters() {
    setSelectedCategories([])
    setPrice('any')
    setRating('any')
  }

  return (
    <Stack as="section" gap="lg" aria-labelledby={`${id}-title`} dangerouslySetClassName={styles.page}>
      <Stack gap="sm">
        <Heading as="h2" id={`${id}-title`} fontSize="xl">
          Extensions
        </Heading>
        <Stack as="search" gap="sm">
          <Label htmlFor={`${id}-query`} dangerouslySetClassName="visually-hidden">
            Search extensions
          </Label>
          <div className={styles.queryField}>
            <Search aria-hidden size={16} className={styles.queryIcon} />
            <Input
              id={`${id}-query`}
              type="search"
              size="lg"
              value={query}
              placeholder="Search extensions"
              onChange={(event) => setQuery(event.target.value)}
              dangerouslySetClassName={styles.queryInput}
            />
          </div>
        </Stack>
      </Stack>

      <Stack direction="row" justify="space-between" align="end" gap="md" wrap="wrap">
        <Text fontSize="sm" color="text-muted" role="status">
          {results.length} {results.length === 1 ? 'result' : 'results'}
          {terms.length > 0 && <> for “{query.trim()}”</>}
        </Text>
        <Stack direction="row" gap="sm" align="center" wrap="wrap">
          <Button
            type="button"
            size="sm"
            aria-expanded={filtersOpen}
            aria-controls={`${id}-filters`}
            onClick={() => setFiltersOpen(!filtersOpen)}
            dangerouslySetClassName={styles.filtersToggle}
          >
            <SlidersHorizontal aria-hidden size={14} />
            Filters{chips.length > 0 && ` (${chips.length})`}
          </Button>
          <Select items={sorts} value={sort} onValueChange={(value) => value && setSort(value)}>
            <Select.Label>Sort</Select.Label>
            <Select.Trigger size="sm" dangerouslySetClassName={styles.sortTrigger} />
            <Select.Content>
              {sorts.map((item) => (
                <Select.Item key={item.value} value={item.value}>
                  {item.label}
                </Select.Item>
              ))}
            </Select.Content>
          </Select>
        </Stack>
      </Stack>

      {chips.length > 0 && (
        <Stack as="ul" direction="row" gap="sm" wrap="wrap" align="center" margin="none" padding="none" aria-label="Active filters" dangerouslySetClassName={styles.chips}>
          {chips.map((chip) => (
            <li key={chip.key} className={styles.chip}>
              {chip.label}
              <button type="button" className={styles.chipRemove} onClick={chip.remove} aria-label={`Remove filter: ${chip.label}`}>
                <X aria-hidden size={12} />
              </button>
            </li>
          ))}
          <li>
            <Button type="button" size="sm" variant="link" onClick={clearFilters}>
              Clear all
            </Button>
          </li>
        </Stack>
      )}

      <div className={styles.layout}>
        {/* Always shown beside the results; on a narrow screen it waits behind the Filters button. */}
        <Stack as="aside" id={`${id}-filters`} gap="lg" aria-label="Filters" data-open={filtersOpen || undefined} dangerouslySetClassName={styles.facets}>
          <fieldset className={styles.fieldset}>
            <legend className={styles.legend}>Category</legend>
            <Stack gap="sm">
              {categories.map((category) => {
                const count = beforeCategory.filter((item) => item.category === category).length
                return (
                  <Checkbox
                    key={category}
                    checked={selectedCategories.includes(category)}
                    onCheckedChange={(checked) =>
                      setSelectedCategories((current) => (checked ? [...current, category] : current.filter((item) => item !== category)))
                    }
                  >
                    <span className={styles.facetLabel}>
                      {category}
                      <Text fontSize="xs" color="text-muted" dangerouslySetClassName={styles.numeric}>
                        {count}
                      </Text>
                    </span>
                  </Checkbox>
                )
              })}
            </Stack>
          </fieldset>
          <Stack gap="sm">
            <Text id={`${id}-price`} fontSize="sm" fontWeight="semibold">
              Price
            </Text>
            <RadioGroup aria-labelledby={`${id}-price`} value={price} onValueChange={(value) => setPrice(String(value))}>
              {priceOptions.map((option) => (
                <Radio key={option.value} value={option.value}>
                  {option.label}
                </Radio>
              ))}
            </RadioGroup>
          </Stack>
          <Stack gap="sm">
            <Text id={`${id}-rating`} fontSize="sm" fontWeight="semibold">
              Rating
            </Text>
            <RadioGroup aria-labelledby={`${id}-rating`} value={rating} onValueChange={(value) => setRating(String(value))}>
              {ratingOptions.map((option) => (
                <Radio key={option.value} value={option.value}>
                  {option.label}
                </Radio>
              ))}
            </RadioGroup>
          </Stack>
        </Stack>

        <Stack gap="md" dangerouslySetClassName={styles.results}>
          {results.length === 0 ? (
            <Stack align="center" gap="sm" paddingY="xl" dangerouslySetClassName={styles.empty}>
              <Search aria-hidden size={24} />
              <Text fontWeight="semibold">No extensions match</Text>
              <BodySmall color="text-muted" margin="none">
                Try fewer filters or a broader search.
              </BodySmall>
              {chips.length > 0 && (
                <Button type="button" size="sm" onClick={clearFilters}>
                  Clear filters
                </Button>
              )}
            </Stack>
          ) : (
            <ol className={styles.list}>
              {results.map((item) => (
                <li key={item.slug} className={styles.result}>
                  <Stack gap="xs">
                    <Stack direction="row" gap="sm" align="center" wrap="wrap">
                      <Heading as="h3" fontSize="md">
                        <a href={`#extension-${item.slug}`} className={styles.resultLink}>
                          <Highlight text={item.name} terms={terms} />
                        </a>
                      </Heading>
                      <Badge>{item.price === 0 ? 'Free' : `$${item.price}/mo`}</Badge>
                    </Stack>
                    <Body margin="none" fontSize="sm">
                      <Highlight text={item.description} terms={terms} />
                    </Body>
                    <Stack direction="row" gap="md" wrap="wrap">
                      <Text fontSize="xs" color="text-muted">
                        {item.category}
                      </Text>
                      <Text fontSize="xs" color="text-muted" dangerouslySetClassName={styles.rating}>
                        <Star aria-hidden size={12} />
                        {item.rating.toFixed(1)}
                        <span className="visually-hidden"> out of 5 stars</span>
                      </Text>
                      <Text fontSize="xs" color="text-muted" dangerouslySetClassName={styles.numeric}>
                        {item.installs.toLocaleString('en-US')} installs
                      </Text>
                    </Stack>
                  </Stack>
                </li>
              ))}
            </ol>
          )}
        </Stack>
      </div>
    </Stack>
  )
}
```

## How it works

- **Facets filter for real.** Every term in the query must match; then price, rating and category narrow the list. Category counts are computed before the category filter itself, so each count says how many results checking that box would add.
- **Chips mirror the facets.** Each active filter becomes a chip whose remove button is labelled “Remove filter: Finance”, plus a Clear all. The empty state offers the same way out.
- **Matches are marked, not rewritten.** Highlighting splits the text around the terms and wraps them in `<mark>`, so the words read the same to a screen reader. The result count is a `role="status"` region, so typing announces how many results remain.
- **Filters wait behind a button on a phone.** A container query places the facets beside the results when there is room. When there isn’t, a Filters button next to Sort (with `aria-expanded` and the number of active filters) opens them in a panel above the results, so the first screen shows results.

## App-owned CSS

The search field’s icon, the two-column layout, chips, the result list and the highlight.

`examples/recipes/search-results.module.css`:

```css
.page {
  container-type: inline-size;
}

.queryField {
  position: relative;
}

.queryIcon {
  position: absolute;
  top: 50%;
  left: var(--ds-space-md);
  color: var(--ds-color-text-muted);
  transform: translateY(-50%);
  pointer-events: none;
}

.queryInput {
  width: 100%;
  padding-left: calc(var(--ds-space-xl) + var(--ds-space-xs));
}

/* Facets beside the results when there is room; above them on a phone. */
.layout {
  display: grid;
  gap: var(--ds-space-xl);
}

@container (min-width: 36rem) {
  .layout {
    grid-template-columns: 11rem minmax(0, 1fr);
  }
}

/* Controls fill their container by default; the sort menu sizes to its options. */
button.sortTrigger {
  width: auto;
  min-width: 9rem;
}

/* The Filters button only exists where the facets can't sit beside the results. */
button.filtersToggle {
  display: none;
}

@container (max-width: 36rem) {
  button.filtersToggle {
    display: inline-flex;
  }

  .facets:not([data-open]) {
    display: none;
  }

  .facets[data-open] {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(9rem, 1fr));
    padding: var(--ds-space-lg);
    border: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
    border-radius: var(--ds-border-radius-md);
    background-color: var(--ds-color-bg-subtle);
  }
}

.fieldset {
  margin: 0;
  padding: 0;
  border: none;
}

.legend {
  margin-bottom: var(--ds-space-sm);
  padding: 0;
  font-size: var(--ds-font-size-sm);
  font-weight: var(--ds-font-weight-semibold);
}

.facetLabel {
  display: inline-flex;
  align-items: baseline;
  gap: var(--ds-space-sm);
}

.numeric {
  font-variant-numeric: tabular-nums;
}

.results {
  min-width: 0;
}

.chips {
  list-style: none;
}

.chip {
  display: inline-flex;
  align-items: center;
  gap: var(--ds-space-xs);
  padding: var(--ds-space-xxs) var(--ds-space-xs) var(--ds-space-xxs) var(--ds-space-md);
  border: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
  border-radius: var(--ds-border-radius-pill);
  background-color: var(--ds-color-bg-subtle);
  font-size: var(--ds-font-size-xs);
  font-weight: var(--ds-font-weight-medium);
}

.chipRemove {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: calc(var(--ds-space-lg) + var(--ds-space-sm));
  height: calc(var(--ds-space-lg) + var(--ds-space-sm));
  padding: 0;
  border: none;
  border-radius: var(--ds-border-radius-circle);
  background: none;
  color: var(--ds-color-text-muted);
  cursor: pointer;

  &:hover {
    background-color: var(--ds-color-surface-hover);
    color: var(--ds-color-text);
  }

  &:focus-visible {
    outline: var(--ds-border-width-md) solid var(--ds-color-focus-ring);
  }
}

.list {
  margin: 0;
  padding: 0;
  list-style: none;
}

.result {
  padding-block: var(--ds-space-lg);

  & + & {
    border-top: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
  }

  &:first-child {
    padding-top: var(--ds-space-sm);
  }
}

.resultLink {
  color: var(--ds-color-accent-text);
  text-decoration: none;

  &:hover {
    text-decoration: underline;
  }

  &:focus-visible {
    border-radius: var(--ds-border-radius-sm);
    outline: var(--ds-border-width-md) solid var(--ds-color-focus-ring);
    outline-offset: var(--ds-space-xs);
  }
}

.mark {
  padding-inline: var(--ds-space-xxs);
  border-radius: var(--ds-border-radius-sm);
  background-color: var(--ds-color-warning-subtle);
  color: inherit;
}

.rating {
  display: inline-flex;
  align-items: center;
  gap: var(--ds-space-xs);
}

.empty {
  border: var(--ds-border-width-sm) dashed var(--ds-color-border);
  border-radius: var(--ds-border-radius-md);
  color: var(--ds-color-text-muted);
  text-align: center;
}
```
