# Filter Params

A URL-backed filter bar with searchable filter selection.

---

## Default

Use `FilterParamsBar` to let people narrow a list and share the resulting view.
Choose **Add Filter**, then a filter and a value. The bar writes the selection
to the URL so the same filters appear when someone opens the link.

```tsx
'use client';

import {
  decodeDateRangeValue,
  encodeDateRangeValue,
  FilterParamsBar,
  type DateRangePreset,
  type DateRangeValue,
  type FilterParam,
} from '@vercel/geistcn/components/filter-params';
import type { JSX } from 'react';

const createdPresets: DateRangePreset[] = [
  {
    label: 'Last 7 Days',
    range: () => {
      const to = new Date();
      const from = new Date(to);
      from.setDate(to.getDate() - 7);
      return { from, to };
    },
  },
];

const filters: FilterParam<any>[] = [
  {
    key: 'Environment',
    type: 'select',
    label: (value) => value ?? 'All Environments',
    encode: (value) => ({ environment: value }),
    decode: (params) =>
      typeof params.environment === 'string' ? params.environment : undefined,
    options: ['Production', 'Preview', 'Development'],
  },
  {
    key: 'Branch',
    type: 'select',
    label: (value) => value ?? 'All Branches',
    encode: (value) => ({ branch: value }),
    decode: (params) =>
      typeof params.branch === 'string' ? params.branch : undefined,
    options: ['main', 'canary', 'feature/filter-bar'],
  },
  {
    key: 'Created',
    type: 'date-range',
    label: (value: DateRangeValue | undefined) =>
      value?.kind === 'preset' ? value.preset.label : 'Any Time',
    encode: (value: DateRangeValue | undefined) => ({
      created: encodeDateRangeValue(value),
    }),
    decode: (params) => decodeDateRangeValue(params.created, createdPresets),
    presets: createdPresets,
  },
];

export function FilterParamsDefault(): JSX.Element {
  return <FilterParamsBar params={filters} />;
}
```

## Filter a list

Define a `FilterParam` for each filter. Its `key` is the name people see,
`encode` maps the selected value to query parameters, and `decode` reads it
back. Return `undefined` from `decode` when the URL has no valid value.

Pass the definition to `FilterParamsBar` and read it with `useFilterParam` in
the component that displays the results. The bar manages the selection; the
list decides which rows to show.

Try **Add Filter → Branch → canary**. Only “Preview the new search” remains.
Reload to see the same selection, or remove the Branch pill to show all three
deployments again.

```tsx
'use client';

import {
  FilterParamsBar,
  useFilterParam,
  type FilterParam,
} from '@vercel/geistcn/components/filter-params';
import type { JSX } from 'react';

const deployments = [
  { commit: 'Fix the checkout redirect', branch: 'main' },
  { commit: 'Preview the new search', branch: 'canary' },
  { commit: 'Update the pricing page', branch: 'main' },
];

const branch: FilterParam<string> = {
  key: 'Branch',
  type: 'select',
  options: ['main', 'canary'],
  label: (value) => value ?? 'All Branches',
  encode: (value) => ({ deploymentBranch: value }),
  decode: ({ deploymentBranch }) =>
    deploymentBranch === 'main' || deploymentBranch === 'canary'
      ? deploymentBranch
      : undefined,
};

const filters = [branch];

export function FilterParamsDeployments(): JSX.Element {
  const [selectedBranch] = useFilterParam(branch);
  const visible = deployments.filter(
    (deployment) => !selectedBranch || deployment.branch === selectedBranch,
  );

  return (
    <div className="w-full max-w-lg">
      <FilterParamsBar params={filters} openOnPageSearchShortcut={false} />
      <ul aria-label="Deployments" className="mt-4 divide-y divide-gray-400">
        {visible.map((deployment) => (
          <li
            className="flex items-center justify-between gap-4 py-3"
            key={deployment.commit}
          >
            <span className="text-label-14">{deployment.commit}</span>
            <span className="text-label-13-mono text-gray-900">
              {deployment.branch}
            </span>
          </li>
        ))}
      </ul>
    </div>
  );
}
```

## Suggestions

Provide a `suggestion` for filters that have a useful starting value. Suggestions
remain optional until users select them.

```tsx
'use client';

import {
  FilterParamsBar,
  type FilterParam,
} from '@vercel/geistcn/components/filter-params';
import type { JSX } from 'react';

const filters: FilterParam<any>[] = [
  {
    key: 'Environment',
    type: 'select',
    label: (value: string | undefined) => value ?? 'All Environments',
    encode: (value: string | undefined) => ({
      suggestedEnvironment: value,
    }),
    decode: (params) =>
      typeof params.suggestedEnvironment === 'string'
        ? params.suggestedEnvironment
        : undefined,
    options: ['Production', 'Preview', 'Development'],
    suggestion: () => 'Production',
  },
  {
    key: 'Status',
    type: 'multi-select',
    label: (value: string[] | undefined) =>
      value === undefined
        ? 'All Statuses'
        : value.length
          ? `${value.length} Statuses`
          : 'None',
    optionLabel: (value) => value,
    encode: (value: string[] | undefined) => ({
      suggestedStatus: value?.join(','),
    }),
    decode: (params) => {
      const value = params.suggestedStatus;
      // An empty value is the explicit "none selected" state, not `['']`.
      if (typeof value !== 'string') return undefined;
      return value === '' ? [] : value.split(',');
    },
    options: ['Ready', 'Building', 'Error'],
    suggestion: () => ['Error'],
  },
];

export function FilterParamsSuggestions(): JSX.Element {
  return <FilterParamsBar params={filters} />;
}
```

## AI

Pass an `ai` callback to offer natural-language filter suggestions. This example
simulates a request and always applies the Production environment filter.

```tsx
'use client';

import {
  FilterParamsBar,
  useSearchParamState,
  type FilterParam,
} from '@vercel/geistcn/components/filter-params';
import { useCallback, useRef, useState, type JSX } from 'react';

const filters: FilterParam<string>[] = [
  {
    key: 'Environment',
    type: 'select',
    label: (value) => value ?? 'All Environments',
    encode: (value) => ({ aiEnvironment: value }),
    decode: (params) =>
      typeof params.aiEnvironment === 'string'
        ? params.aiEnvironment
        : undefined,
    options: ['Production', 'Preview', 'Development'],
  },
];

export function FilterParamsAi(): JSX.Element {
  const [searchParams, setSearchParams] = useSearchParamState();
  const [isThinking, setIsThinking] = useState(false);
  const requestId = useRef(0);

  const onAbort = useCallback(() => {
    requestId.current += 1;
    setIsThinking(false);
  }, []);

  const onQuery = useCallback(async (): Promise<number | void> => {
    const id = ++requestId.current;
    setIsThinking(true);
    await new Promise((resolve) => setTimeout(resolve, 3000));

    if (id !== requestId.current) return;

    const nextSearchParams = new URLSearchParams(searchParams);
    nextSearchParams.set('aiEnvironment', 'Production');
    setSearchParams(nextSearchParams);
    setIsThinking(false);
    return 1;
  }, [searchParams, setSearchParams]);

  return (
    <FilterParamsBar ai={{ isThinking, onAbort, onQuery }} params={filters} />
  );
}
```

## Readonly filters

Use a readonly filter for page context that should be visible but cannot be
changed or removed. The page passes its value through `readonlyValues`, keyed by
the filter's `key`; it is never read from or written to the URL. A value can be
a promise, such as one passed down from a server component, and only that
filter's pill waits for it. Add a `note` to explain the context in a hover card.

```tsx
'use client';

import {
  FilterParamsBar,
  type FilterParam,
} from '@vercel/geistcn/components/filter-params';
import type { JSX } from 'react';

const filters: FilterParam<any>[] = [
  {
    key: 'Team',
    type: 'readonly',
    label: (value: string | undefined) => value ?? '',
    encode: (value: string | undefined) => ({ team: value }),
    decode: (params) =>
      typeof params.team === 'string' ? params.team : undefined,
    note: 'The current team is set by the page context and cannot be changed.',
  },
  {
    key: 'Environment',
    type: 'select',
    label: (value: string | undefined) => value ?? 'All Environments',
    encode: (value: string | undefined) => ({ environment: value }),
    decode: (params) =>
      typeof params.environment === 'string' ? params.environment : undefined,
    options: ['Production', 'Preview', 'Development'],
  },
];

export function FilterParamsReadonly(): JSX.Element {
  return <FilterParamsBar params={filters} readonlyValues={{ Team: 'Acme' }} />;
}
```

## Persistent filters

Set `persistent` on a filter that belongs to the page rather than to something
users opt into. Its pill is always in the bar and has no remove button.
Persistent filters render ahead of every other pill and suggestion, in the order
they are passed to `params`.

A persistent filter is still editable — open its pill to change the value. If
it also has a `default`, it cannot be turned off, so its options leave out the
empty value: there is no `All Environments` entry to clear it with. Without a
`default`, the empty value stays, so the pill can be set back to `All
Environments`.

```tsx
'use client';

import {
  FilterParamsBar,
  type FilterParam,
} from '@vercel/geistcn/components/filter-params';
import type { JSX } from 'react';

const filters: FilterParam<any>[] = [
  {
    key: 'Environment',
    type: 'select',
    persistent: true,
    default: 'Production',
    label: (value: string | undefined) => value ?? 'All Environments',
    encode: (value: string | undefined) => ({ environment: value }),
    decode: (params) =>
      typeof params.environment === 'string'
        ? params.environment
        : 'Production',
    options: ['Production', 'Preview', 'Development'],
  },
  {
    key: 'Status',
    type: 'select',
    persistent: true,
    default: 'Ready',
    label: (value: string | undefined) => value ?? 'All Statuses',
    encode: (value: string | undefined) => ({ status: value }),
    decode: (params) =>
      typeof params.status === 'string' ? params.status : 'Ready',
    options: ['Ready', 'Building', 'Error'],
  },
  {
    key: 'Branch',
    type: 'select',
    label: (value: string | undefined) => value ?? 'All Branches',
    encode: (value: string | undefined) => ({ branch: value }),
    decode: (params) =>
      typeof params.branch === 'string' ? params.branch : undefined,
    options: ['main', 'canary', 'staging'],
  },
];

export function FilterParamsPersistent(): JSX.Element {
  return <FilterParamsBar params={filters} />;
}
```

## Boolean filters

Use a `boolean` filter for an on/off constraint that has no values to choose
from. Choosing it in **Add Filter** turns it on right away instead of opening a
nested list, and choosing it again turns it off. Clicking an active boolean
pill removes it, the same as its remove button. Its value is `true` while on
and `undefined` while off. Add a `description` to explain it beside its entry in
**Add Filter**.

```tsx
'use client';

import {
  FilterParamsBar,
  type BooleanFilterParam,
  type FilterParam,
} from '@vercel/geistcn/components/filter-params';
import type { JSX } from 'react';

const flag = (
  key: string,
  searchParam: string,
  description?: string,
): BooleanFilterParam => ({
  key,
  type: 'boolean',
  description,
  label: () => key,
  encode: (value) => ({ [searchParam]: value ? 'true' : undefined }),
  decode: (params) => (params[searchParam] === 'true' ? true : undefined),
});

const filters: FilterParam<any>[] = [
  {
    key: 'Environment',
    type: 'select',
    label: (value: string | undefined) => value ?? 'All Environments',
    encode: (value: string | undefined) => ({ environment: value }),
    decode: (params) =>
      typeof params.environment === 'string' ? params.environment : undefined,
    options: ['Production', 'Preview', 'Development'],
  },
  flag(
    'Pinned',
    'pinned',
    'Only show deployments pinned to the top of the list.',
  ),
  flag('Has Errors', 'errors'),
];

export function FilterParamsBoolean(): JSX.Element {
  return <FilterParamsBar params={filters} />;
}
```

## Best Practices

### When to use

* Use `FilterParamsBar` for list and search pages where the active constraints
  should be visible, linkable, and preserved on refresh.
* Keep filter names short and use option labels that explain the selected value
  without requiring users to reopen the menu.

### Behavior

* Encode only the URL parameters owned by each filter so removing a pill does
  not clear unrelated page state.
* Provide suggestions only when they are useful defaults, not as replacements
  for filters users have explicitly selected.

### Accessibility

* Make filter labels and option labels specific enough to identify the
  constraint and selected value when announced by a screen reader.
