# Command search

> A search dialog over the search index, with favorites and recents before the user types.

- Block: [search](https://bettersupabase.com/blocks/search.md)
- Kind: component
- Hook: `useCommandSearch` from `@/hooks/use-search`
- Page: https://bettersupabase.com/recipes/command-search

## Install the block

```bash
npx better-supabase add search
```

## Web (Next.js)

Add the shadcn components:

```bash
npx shadcn add button command dialog kbd
```

Add the glue from the better-supabase registry:

```bash
npx shadcn add @better-supabase/use-search
```

From `apps/examples/nextjs/src/features/search/components/command-center.tsx` (https://github.com/ScaleDockHQ/better-supabase/blob/main/apps/examples/nextjs/src/features/search/components/command-center.tsx):

```tsx
"use client";

import type { LucideIcon } from "lucide-react";

import { useTheme } from "@wrksz/themes/client";
import {
  ArrowRightIcon,
  BotIcon,
  ClockIcon,
  CompassIcon,
  FileTextIcon,
  HandshakeIcon,
  LanguagesIcon,
  LayoutGridIcon,
  MonitorIcon,
  MoonIcon,
  PlusIcon,
  RotateCwIcon,
  SearchIcon,
  StarIcon,
  SunIcon,
  UserPlusIcon,
  ZapIcon,
} from "lucide-react";
import { hasLocale, useExtracted, useLocale } from "next-intl";
import { useState } from "react";

import type { AreaCommand } from "@/features/areas/area-commands";
import type { CommandSearchItem } from "@/hooks/use-search";

import { Alert, AlertDescription, AlertTitle } from "@/components/reui/alert";
import { Button } from "@/components/ui/button";
import {
  CommandDialog,
  Command,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
  CommandSeparator,
} from "@/components/ui/command";
import { Kbd, KbdGroup } from "@/components/ui/kbd";
import { Skeleton } from "@/components/ui/skeleton";
import { CreateOrganizationDialog } from "@/features/organization/components/create-organization-dialog";
import { useCommandSearch } from "@/hooks/use-search";
import { usePathname, useRouter, toAppHref } from "@/i18n/navigation";
import { routing } from "@/i18n/routing";
import { searchConfig } from "@/lib/supabase/blocks/slices";

import { useSubjectTypeLabel } from "../use-subject-type-label";
import { CommandSearchTrigger } from "./command-search-trigger";
import { OrganizationCommands } from "./organization-commands";

/** A page of the side menu the caller may open. */
export interface CommandPage {
  readonly id: string;
  /** Without the locale prefix. */
  readonly href: string;
  readonly label: string;
}

/** The API schema `gen` wrote for the search block. */
const API_SCHEMA = searchConfig.api;

/** Pages listed before the user types; typing searches all of them. */
const PAGES_WHEN_EMPTY = 6;

/** Area entries listed for a query; the hub page lists the rest. */
const AREA_ENTRIES_SHOWN = 8;

const AREA_ICONS = {
  area: LayoutGridIcon,
  step: CompassIcon,
  action: ZapIcon,
} as const satisfies Record<AreaCommand["kind"], LucideIcon>;

const LOCALE_NAMES = { en: "English", nl: "Nederlands" } as const;

/** Every word of `query` appears in one of the texts. */
function matches(query: string, ...texts: readonly string[]): boolean {
  const haystack = texts.join(" ").toLowerCase();

  return query
    .toLowerCase()
    .split(/\s+/)
    .filter((word) => word !== "")
    .every((word) => haystack.includes(word));
}

/**
 * The record types the caller may create; each has a page whose dialog opens on
 * `?new=1`.
 */
export interface CommandCreate {
  readonly customer?: boolean;
  readonly contact?: boolean;
  readonly deal?: boolean;
  readonly quote?: boolean;
}

interface CommandAction {
  readonly id: string;
  readonly label: string;
  readonly keywords: string;
  readonly icon: LucideIcon;
  readonly run: () => void;
}

/**
 * Cmd+K over the app: records from every subject the search block indexes (one
 * call to `search(q)` per typing burst, answered by Postgres under the caller's
 * access), recents and favorites, actions, and the pages of the menu. The code
 * loads on the first intent (ADR 0483), so it stays out of every route's first
 * load.
 */
export function CommandCenter({
  pages,
  areas,
  canCreate,
}: {
  pages: readonly CommandPage[];
  areas: readonly AreaCommand[];
  canCreate: CommandCreate;
}) {
  const t = useExtracted("search");
  const typeLabel = useSubjectTypeLabel();
  const router = useRouter();
  const pathname = usePathname();
  const locale = useLocale();
  const { setTheme } = useTheme();
  const [creatingOrganization, setCreatingOrganization] = useState(false);
  const search = useCommandSearch({ schema: API_SCHEMA, limit: 30 });
  const query = search.query.trim();

  const go = (href: string) => {
    search.setOpen(false);
    router.push(toAppHref(href));
  };

  const open = (item: CommandSearchItem) => {
    if (item.url === null) {
      return;
    }

    const href = item.url;
    void search.select(item);
    router.push(toAppHref(href));
  };

  const actions: readonly CommandAction[] = [
    ...(canCreate.customer
      ? [
          {
            id: "new-customer",
            label: t("New customer"),
            keywords: t("create add customer"),
            icon: UserPlusIcon,
            run: () => {
              go("/customers?new=1");
            },
          },
        ]
      : []),
    ...(canCreate.contact
      ? [
          {
            id: "new-contact",
            label: t("New contact"),
            keywords: t("create add contact company person"),
            icon: UserPlusIcon,
            run: () => {
              go("/crm/contacts?new=1");
            },
          },
        ]
      : []),
    ...(canCreate.deal
      ? [
          {
            id: "new-deal",
            label: t("New deal"),
            keywords: t("create add deal opportunity"),
            icon: HandshakeIcon,
            run: () => {
              go("/crm/deals?new=1");
            },
          },
        ]
      : []),
    ...(canCreate.quote
      ? [
          {
            id: "new-quote",
            label: t("New quote"),
            keywords: t("create add quote proposal"),
            icon: FileTextIcon,
            run: () => {
              go("/crm/quotes?new=1");
            },
          },
        ]
      : []),
    {
      id: "new-organization",
      label: t("Create organization"),
      keywords: t("new organization workspace"),
      icon: PlusIcon,
      run: () => {
        search.setOpen(false);
        setCreatingOrganization(true);
      },
    },
    {
      id: "theme-light",
      label: t("Light theme"),
      keywords: t("theme appearance light"),
      icon: SunIcon,
      run: () => {
        setTheme("light");
        search.setOpen(false);
      },
    },
    {
      id: "theme-dark",
      label: t("Dark theme"),
      keywords: t("theme appearance dark"),
      icon: MoonIcon,
      run: () => {
        setTheme("dark");
        search.setOpen(false);
      },
    },
    {
      id: "theme-system",
      label: t("System theme"),
      keywords: t("theme appearance system"),
      icon: MonitorIcon,
      run: () => {
        setTheme("system");
        search.setOpen(false);
      },
    },
    ...routing.locales
      .filter((option) => option !== locale)
      .map((option) => ({
        id: `locale-${option}`,
        label: t("Switch language to {language}", {
          language: LOCALE_NAMES[option],
        }),
        keywords: t("language locale"),
        icon: LanguagesIcon,
        run: () => {
          search.setOpen(false);

          if (hasLocale(routing.locales, option)) {
            router.replace(pathname, { locale: option });
          }
        },
      })),
  ];

  const shownActions =
    query === ""
      ? actions
      : actions.filter((action) =>
          matches(query, action.label, action.keywords),
        );

  const shownPages =
    query === ""
      ? pages.slice(0, PAGES_WHEN_EMPTY)
      : pages.filter((page) => matches(query, page.label, page.href));

  // Areas answer a query only, so the empty palette stays short.
  const shownAreas =
    query === ""
      ? []
      : areas
          .filter((entry) => matches(query, entry.area, entry.label))
          .slice(0, AREA_ENTRIES_SHOWN);

  const waiting = search.loading && search.results.length === 0;
  const noMatches = query !== "" && !search.loading;

  return (
    <>
      <CommandSearchTrigger
        onClick={() => {
          search.setOpen(true);
        }}
      />
      <CommandDialog
        open={search.open}
        onOpenChange={search.setOpen}
        title={t("Search")}
        description={t(
          "Find records, run an action or open a page. Press Escape to close.",
        )}
        className="sm:max-w-xl"
      >
        <Command shouldFilter={false} loop>
          <CommandInput
            value={search.query}
            onValueChange={search.setQuery}
            placeholder={t("Search records, actions and pages")}
            aria-label={t("Search records, actions and pages")}
          />
          <CommandList aria-live="polite">
            {search.error === undefined ? null : (
              <div className="p-1">
                <Alert variant="destructive">
                  <AlertTitle>{t("Search failed")}</AlertTitle>
                  <AlertDescription className="flex items-center justify-between gap-2">
                    {t("Records could not load. Actions and pages still work.")}
                    <Button
                      size="sm"
                      variant="outline"
                      onClick={() => {
                        // The controller queries again only when the trimmed text changes.
                        const again = search.query;
                        search.setQuery("");
                        search.setQuery(again);
                      }}
                    >
                      <RotateCwIcon />
                      {t("Retry")}
                    </Button>
                  </AlertDescription>
                </Alert>
              </div>
            )}

            {query === "" ? (
              <>
                {search.groups.map((group) => (
                  <CommandGroup
                    key={group.key}
                    heading={
                      group.key === "favorites" ? t("Favorites") : t("Recent")
                    }
                  >
                    {group.items.map((item) => (
                      <CommandItem
                        key={`${group.key}:${item.subjectType}:${item.subjectId}`}
                        value={`${group.key}:${item.subjectType}:${item.subjectId}`}
                        disabled={item.url === null}
                        onSelect={() => {
                          open(item);
                        }}
                      >
                        {group.key === "favorites" ? (
                          <StarIcon />
                        ) : (
                          <ClockIcon />
                        )}
                        <span className="truncate">
                          {item.title ?? item.subjectId}
                        </span>
                        <span className="ml-auto text-xs text-muted-foreground">
                          {typeLabel(item.subjectType)}
                        </span>
                      </CommandItem>
                    ))}
                  </CommandGroup>
                ))}
              </>
            ) : (
              <>
                {search.groups.map((group) => (
                  <CommandGroup key={group.key} heading={typeLabel(group.key)}>
                    {group.items.map((item) => (
                      <CommandItem
                        key={`${item.subjectType}:${item.subjectId}`}
                        value={`${item.subjectType}:${item.subjectId}`}
                        disabled={item.url === null}
                        onSelect={() => {
                          open(item);
                        }}
                      >
                        <span className="truncate">
                          {item.title ?? item.subjectId}
                        </span>
                      </CommandItem>
                    ))}
                  </CommandGroup>
                ))}
                {waiting ? (
                  <CommandGroup heading={t("Records")}>
                    <div className="flex flex-col gap-2 p-2" aria-busy="true">
                      <Skeleton className="h-5 w-3/4" />
                      <Skeleton className="h-5 w-1/2" />
                      <Skeleton className="h-5 w-2/3" />
                    </div>
                  </CommandGroup>
                ) : null}
                <CommandGroup>
                  <CommandItem
                    value={`all:${query}`}
                    onSelect={() => {
                      go(`/search?q=${encodeURIComponent(query)}`);
                    }}
                  >
                    <SearchIcon />
                    {t("See all results for {query}", { query })}
                  </CommandItem>
                </CommandGroup>
              </>
            )}

            {shownActions.length === 0 ? null : (
              <>
                <CommandSeparator />
                <CommandGroup heading={t("Actions")}>
                  {shownActions.map((action) => (
                    <CommandItem
                      key={action.id}
                      value={`action:${action.id}`}
                      onSelect={action.run}
                    >
                      <action.icon />
                      {action.label}
                    </CommandItem>
                  ))}
                </CommandGroup>
              </>
            )}

            <OrganizationCommands
              query={query}
              onSwitched={() => {
                search.setOpen(false);
              }}
            />

            {shownPages.length === 0 ? null : (
              <>
                <CommandSeparator />
                <CommandGroup heading={t("Go to")}>
                  {shownPages.map((page) => (
                    <CommandItem
                      key={page.id}
                      value={`page:${page.id}`}
                      onPointerEnter={() => {
                        router.prefetch(toAppHref(page.href));
                      }}
                      onSelect={() => {
                        go(page.href);
                      }}
                    >
                      <CompassIcon />
                      {page.label}
                      <ArrowRightIcon className="ml-auto opacity-50" />
                    </CommandItem>
                  ))}
                </CommandGroup>
              </>
            )}

            {shownAreas.length === 0 ? null : (
              <>
                <CommandSeparator />
                <CommandGroup heading={t("Areas")}>
                  {shownAreas.map((entry) => {
                    const Icon = AREA_ICONS[entry.kind];

                    return (
                      <CommandItem
                        key={entry.id}
                        value={`area:${entry.id}`}
                        onPointerEnter={() => {
                          router.prefetch(toAppHref(entry.href));
                        }}
                        onSelect={() => {
                          go(entry.href);
                        }}
                      >
                        <Icon />
                        <span className="truncate">
                          {entry.kind === "area"
                            ? entry.area
                            : `${entry.area}: ${entry.label}`}
                        </span>
                        <ArrowRightIcon className="ml-auto opacity-50" />
                      </CommandItem>
                    );
                  })}
                </CommandGroup>
              </>
            )}

            {query === "" ? null : (
              <>
                <CommandSeparator />
                <CommandGroup heading={t("Assistant")}>
                  <CommandItem
                    value="ask-assistant"
                    onSelect={() => {
                      go(`/assistant?ask=${encodeURIComponent(query)}`);
                    }}
                  >
                    <BotIcon />
                    {t("Ask the assistant: {query}", { query })}
                  </CommandItem>
                </CommandGroup>
              </>
            )}

            {noMatches &&
            search.results.length === 0 &&
            shownActions.length === 0 &&
            shownPages.length === 0 &&
            shownAreas.length === 0 ? (
              <p className="px-3 py-4 text-center text-sm text-muted-foreground">
                {t("No records match. Ask the assistant or see all results.")}
              </p>
            ) : null}
          </CommandList>
          <div className="flex items-center justify-between gap-2 border-t px-3 py-2 text-xs text-muted-foreground">
            <span className="flex items-center gap-1">
              <KbdGroup>
                <Kbd>↑</Kbd>
                <Kbd>↓</Kbd>
              </KbdGroup>
              {t("to move")}
            </span>
            <span className="flex items-center gap-1">
              <Kbd>↵</Kbd>
              {t("to open")}
            </span>
            <span className="flex items-center gap-1">
              <Kbd>Esc</Kbd>
              {t("to close")}
            </span>
          </div>
        </Command>
      </CommandDialog>
      <CreateOrganizationDialog
        open={creatingOrganization}
        onOpenChange={setCreatingOrganization}
      />
    </>
  );
}
```

## Native (Expo)

The snippet uses `Modal`, `Pressable`, `SectionList`, `Text`, `TextInput`, `View` from `react-native`, so it needs no styling library.

Add the glue from the better-supabase registry:

```bash
npx shadcn add @better-supabase/use-search
```

From `apps/examples/expo-powersync/src/components/command-search.tsx` (https://github.com/ScaleDockHQ/better-supabase/blob/main/apps/examples/expo-powersync/src/components/command-search.tsx):

```tsx
import {
  Modal,
  Pressable,
  SectionList,
  Text,
  TextInput,
  View,
} from "react-native";

import { useCommandSearch } from "../hooks/use-search";
import { API_SCHEMA } from "../lib/blocks";

function heading(key: string): string {
  if (key === "favorites") {
    return "Favorites";
  }

  if (key === "recents") {
    return "Recent";
  }

  if (key === "customer") {
    return "Customers";
  }

  return key;
}

/** Search over the search index: customers by name, plus recents and favorites. */
export function CommandSearch() {
  // Native has no Cmd+K, so the button opens it.
  const search = useCommandSearch({ schema: API_SCHEMA, shortcut: false });

  return (
    <>
      <Pressable
        accessibilityRole="button"
        onPress={() => {
          search.setOpen(true);
        }}
        style={{ padding: 8 }}
      >
        <Text>Search</Text>
      </Pressable>
      <Modal
        visible={search.open}
        animationType="slide"
        onRequestClose={() => {
          search.setOpen(false);
        }}
      >
        <View style={{ flex: 1, gap: 12, padding: 16 }}>
          <TextInput
            value={search.query}
            onChangeText={search.setQuery}
            placeholder="Search customers"
            accessibilityLabel="Search customers"
            style={{ borderWidth: 1, borderRadius: 8, padding: 8 }}
          />
          {search.error === undefined ? null : (
            <Text>Search failed. Try again.</Text>
          )}
          <SectionList
            sections={search.groups.map((group) => ({
              key: group.key,
              title: heading(group.key),
              data: group.items,
            }))}
            keyExtractor={(item) => `${item.subjectType}:${item.subjectId}`}
            renderSectionHeader={({ section }) => (
              <Text style={{ color: "#737373", marginTop: 12 }}>
                {section.title}
              </Text>
            )}
            renderItem={({ item }) => (
              <Pressable
                accessibilityRole="link"
                onPress={() => void search.select(item)}
                style={{ paddingVertical: 8 }}
              >
                <Text>{item.title ?? item.subjectId}</Text>
              </Pressable>
            )}
            ListEmptyComponent={
              search.loading ? undefined : (
                <Text>
                  {search.query.trim() === ""
                    ? "Type to search."
                    : "No matches."}
                </Text>
              )
            }
          />
          <Pressable
            accessibilityRole="button"
            onPress={() => {
              search.setOpen(false);
            }}
          >
            <Text>Close</Text>
          </Pressable>
        </View>
      </Modal>
    </>
  );
}
```

## Prompt

Paste one of these into a coding agent to build the recipe in your app.

### Web

```text
Build "Command search" in a React web app that uses shadcn/ui components. A search dialog over the search index, with favorites and recents before the user types.

It uses the better-supabase `search` block (Search). It calls the hook `useCommandSearch` from `@/hooks/use-search`.

Steps:

1. If the app doesn't have the block yet, add the SQL with `npx better-supabase add search` and apply the migration.
2. Add the shadcn components the recipe uses: `npx shadcn add button command dialog kbd`.
3. Add the glue from the better-supabase registry: `npx shadcn add @better-supabase/use-search`. The items are copied into the app, so edit them as needed.
4. Write the component. Call `useCommandSearch` from `@/hooks/use-search`, starting from the recipe's snippet (`apps/examples/nextjs/src/features/search/components/command-center.tsx`). Adapt it to the app's existing components, styling and data loading instead of copying it as is.
5. Check the result against the recipe and the block's docs: it typechecks, it calls the same hook, and it handles the loading and empty states the snippet handles.

Read the full code first:

- Recipe: https://bettersupabase.com/recipes/command-search.md
- Block docs: https://bettersupabase.com/docs/blocks/search
```

### Native

```text
Build "Command search" in a React Native app built with Expo. A search dialog over the search index, with favorites and recents before the user types.

It uses the better-supabase `search` block (Search). It calls the hook `useCommandSearch` from `@/hooks/use-search`.

Steps:

1. If the app doesn't have the block yet, add the SQL with `npx better-supabase add search` and apply the migration.
2. The recipe uses `Modal`, `Pressable`, `SectionList`, `Text`, `TextInput`, `View` from `react-native`, so it needs no extra UI library. Use the app's own components if it has them.
3. Add the glue from the better-supabase registry: `npx shadcn add @better-supabase/use-search`. The items are copied into the app, so edit them as needed.
4. Write the component. Call `useCommandSearch` from `@/hooks/use-search`, starting from the recipe's snippet (`apps/examples/expo-powersync/src/components/command-search.tsx`). Adapt it to the app's existing components, styling and data loading instead of copying it as is.
5. Check the result against the recipe and the block's docs: it typechecks, it calls the same hook, and it handles the loading and empty states the snippet handles.

Read the full code first:

- Recipe: https://bettersupabase.com/recipes/command-search.md
- Block docs: https://bettersupabase.com/docs/blocks/search
```
