# Custom Search

Write a custom search plugin.

A custom search [plugin](/plugin-api) connects another search engine or service to the search dialog. It's built on `vuesho/search` and `vuesho/theme`, like the built-in search and the [search services](/search/services), and takes the same options, like `filter`, `buildIndex` and `tags`. It has two parts:

- On the server, it builds or uploads an index per language.
- In the browser, its theme fills the `search-dialog`
  [slot](/theme#slots).

A site turns off the built-in search with `search: false` in the [recommended preset](/plugins#replacing-a-plugin), then adds the plugin.

## Search Engine [#search-engine]

An engine searches an index in the browser on a static site, or on the server with [server-side search](/search#searching-on-the-server). Its module exports a function that takes the index and returns a `SearchFunction`:

```ts title="acme-search/engine.ts"
import type { SearchFunction } from "vuesho/search";

export type AcmeIndex = { url: string; title: string; text: string }[];

export default function searchIndex(index: AcmeIndex): SearchFunction {
  return (query) => {
    const words = query.toLowerCase();
    return index
      .filter((page) => `${page.title} ${page.text}`.toLowerCase().includes(words))
      .map((page) => ({ id: page.url, url: page.url, type: "page" as const, content: page.title }));
  };
}
```

### SearchQueryOptions

| Prop     | Type                    | Description                                                                                               |
| -------- | ----------------------- | --------------------------------------------------------------------------------------------------------- |
| `tag?`   | `string[] \| undefined` | Only pages with every one of these tags.                                                                  |
| `limit?` | `number \| undefined`   | The maximum number of results.                                                                            |
| `mode?`  | `"vector" \| undefined` | A search by meaning, which engines with vectors run, like ZBSearch with a plugin that fills `embeddings`. |

The plugin creates the index routes with `createIndexRoutes()`, and passes the dialog options with `createSearchRootProps()`:

```ts title="acme-search/index.ts"
import type { AppShape, Plugin } from "vuesho/config";
import {
  createIndexRoutes,
  getIndexValues,
  createSearchRootProps,
  type SearchOptions,
} from "vuesho/search";
import searchIndex, { type AcmeIndex } from "./engine";

export function acmeSearchPlugin<C extends AppShape>(options: SearchOptions<C> = {}): Plugin<C> {
  return {
    name: "acme-search",
    theme: "acme-search/theme",
    rootProps: createSearchRootProps(options, function () {
      return getIndexValues(this, options);
    }),
    routes(fns) {
      createIndexRoutes(this, fns, options, async (indexes) => {
        const index: AcmeIndex = (await indexes()).map((page) => ({
          url: page.url,
          title: page.title,
          text: page.structuredData.contents.map((item) => item.content).join(" "),
        }));
        // `export` returns the index that the browser loads, and `search` answers queries on the server.
        return { export: () => index, search: searchIndex(index) }; // [!code highlight]
      });
    },
  };
}
```

Each entry in `indexes()` is a page's search index:

### SearchIndex

| Prop             | Type                              | Description                                                                  |
| ---------------- | --------------------------------- | ---------------------------------------------------------------------------- |
| `id`             | `string`                          | Unique in the index. Defaults to the page's URL.                             |
| `url`            | `string`                          | The page's URL: a site path or, for another site's index, its full URL.      |
| `title`          | `string`                          | The title the results show.                                                  |
| `description?`   | `string \| undefined`             | The page's summary, left out when its text repeats it.                       |
| `breadcrumbs?`   | `string[] \| undefined`           | The page tree folders above the page, which the results show.                |
| `tag?`           | `string \| string[] \| undefined` | The tags the dialog filters results by.                                      |
| `structuredData` | `StructuredData`                  | The page's headings and the text under each, from `getPageStructuredData()`. |

The theme fills the slot with the default dialog. `useIndexSearch()` loads the engine on the first search, or calls the search API on the server:

```ts title="acme-search/theme.ts"
import type { PluginTheme } from "vuesho/client";
import { defineDefaultSearchDialog, useIndexSearch } from "vuesho/theme";

export default {
  slots: {
    "search-dialog": defineDefaultSearchDialog((props, tag) =>
      useIndexSearch(props, tag, { client: () => import("./engine") }),
    ),
  },
} satisfies PluginTheme;
```

## Search Service [#search-service]

The `build` hook uploads the indexes to a hosted service, and the dialog queries the service. `syncIndexes()` returns that hook, which skips the upload when `writeApiKey` is missing:

```ts tab="acme-cloud/index.ts"
import type { AppShape, Plugin } from "vuesho/config";
import { createSearchRootProps, syncIndexes, type SearchOptions } from "vuesho/search";
import { upload } from "./service";

export interface AcmeCloudOptions<C extends AppShape> extends Omit<SearchOptions<C>, "render"> {
  writeApiKey?: string;
}

export function acmeCloudPlugin<C extends AppShape>(
  options: AcmeCloudOptions<NoInfer<C>>,
): Plugin<C> {
  return {
    name: "acme-cloud",
    theme: "acme-cloud/theme",
    rootProps: createSearchRootProps(options, (lang) => ({ index: `docs_${lang}` })),
    build: syncIndexes("acmeCloudPlugin", options, async function (key, indexesOf) {
      for (const lang of this.languages) await upload(key, `docs_${lang}`, await indexesOf(lang));
    }),
  };
}
```

```ts tab="acme-cloud/service.ts"
import type { SortedResult } from "vuesho/search";

const api = "https://search.acme.dev";

export async function upload(key: string, index: string, pages: unknown[]) {
  await fetch(`${api}/indexes/${index}`, {
    method: "PUT",
    headers: { Authorization: `Bearer ${key}` },
    body: JSON.stringify(pages),
  });
}

export async function query(index: string, text: string, tag?: string): Promise<SortedResult[]> {
  const url = new URL(`${api}/indexes/${index}/search`);
  url.searchParams.set("q", text);
  if (tag) url.searchParams.set("tag", tag);
  return (await fetch(url)).json();
}
```

The `search-footer` slot of the plugin theme renders the service's label in the dialog's footer. A site can build a [custom dialog](/search#custom-dialog) with the exported composable:

```ts title="acme-cloud/theme.ts"
import { computed, h, type Ref } from "vue";
import type { PluginTheme } from "vuesho/client";
import { defineDefaultSearchDialog, type SearchPluginDialogProps } from "vuesho/theme";
import { useSearchFunction } from "vuesho/ui/search";
import { query } from "./service";

export function useAcmeSearch(
  props: SearchPluginDialogProps & { index: string },
  tag: Ref<string | undefined>,
) {
  const run = computed(() => {
    const { index } = props;
    const selected = tag.value;
    return (text: string) => query(index, text, selected);
  });
  return useSearchFunction(run, { delayMs: props.delayMs });
}

export default {
  slots: {
    "search-dialog": defineDefaultSearchDialog(useAcmeSearch),
    "search-footer": () => h("span", "Acme Search"), // [!code highlight]
  },
} satisfies PluginTheme;
```

When a service's search key is secret, query the service through a route on your site instead. `createIndexRoutes()` with `render: "dynamic"` creates that route, and the theme passes `useIndexSearch` to `defineDefaultSearchDialog()`, so `service.ts` stays on the server:

```ts title="acme-cloud/index.ts"
const routes = { path: "/_acme-cloud", render: "dynamic" } as const;

// In the plugin:
rootProps: createSearchRootProps(options, function () {
  return getIndexValues(this, options);
}),
routes(fns) {
  // Never calls `indexes()`, so a request reads no page.
  createIndexRoutes(this, fns, routes, (_indexes, { lang }) => ({
    search: (text, { tag }) => query(`docs_${lang}`, text, tag?.[0]),
    export: () => [],
  }));
},
```

## Search Outside the Dialog [#search-outside-the-dialog]

To search from another component, call `createIndexSearch()` from `vuesho/theme` with the values that `getIndexValues()` returns. The plugin serves the values from a data route:

```ts tab="Plugin"
routes(fns) {
  const options = { path: "/_acme/search" };
  createIndexRoutes(this, fns, options, async (indexes) => {
    const index = (await indexes()).map(({ url, title }) => ({ url, title, text: "" }));
    return { export: () => index, search: searchIndex(index) };
  });
  fns.createDataRoute({
    path: "/_acme/search.json",
    shared: true,
    load: () => getIndexValues(this, options),
  });
},
```

```ts tab="search.ts"
import type { IndexValues } from "vuesho/search";
import { createIndexSearch } from "vuesho/theme";

const searchOf = createIndexSearch({ path: "/_acme/search", client: () => import("./engine") });

export async function search(values: IndexValues, lang: string, query: string) {
  return (await searchOf(values, lang))(query, {});
}
```

The component reads the values with `useDataRoute<IndexValues>("/_acme/search.json")`, and the language with `useSite()`.

## Search Helpers [#search-helpers]

`vuesho/search` exports these helpers for search plugins:

### SearchHelpers

| Prop                    | Type                                                                                                                                                                                                                                                                                                                                                                                                                             | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `buildIndexDefault`     | `<C extends AppShape>(this: Context<C>, page: C["page"]) => Promise<SearchIndex>`                                                                                                                                                                                                                                                                                                                                                | A page's search index, the default for a search plugin's `buildIndex`: its title and description, and the headings and text of its content.                                                                                                                                                                                                                                                                                                                                                               |
| `createIndexRoutes`     | `<C extends AppShape>(ctx: Context<C>, { createDataRoute, createApi }: RouteFns<C>, options: IndexRouteOptions<C> & IndexOptions<C>, server: (indexes: () => Promise<SearchIndex[]>, env: { lang: string; render: "static" \| "dynamic"; }) => Awaitable<SearchServer>) => void`                                                                                                                                                 | Creates an engine's index routes in each language: the index as a data route, which the browser searches, or a search API on request, `?query=` with `tag`, `limit` and `mode`. `server` creates a language's engine on its first request, and again for new content or after a failure, from a function that reads the language's search indexes; an engine that searches elsewhere never calls it. The browser searches with the routes' values, from `getIndexValues()`. Call it in the `routes` hook. |
| `createSearchRootProps` | `<C extends AppShape>({ links, hotKey, tags, defaultTag, allowClear, delayMs }: SearchOptions<C>, values?: (this: Context<C>, lang: C["lang"]) => Awaitable<object>) => (this: Context<C>, env: LangEnv<C>) => Promise<RootProps>`                                                                                                                                                                                               | A search plugin's `rootProps` hook: the search options the root component reads, like `hotKey`, and in `options` the dialog's props from the plugin's options, like `tags`, with what `values` returns for the language, like the index route values from `getIndexValues()`.                                                                                                                                                                                                                             |
| `getIndexValues`        | `<C extends AppShape>(ctx: Context<C>, { render }: Pick<SearchOptions<C>, "render">) => IndexValues`                                                                                                                                                                                                                                                                                                                             | The values of the index routes that `createIndexRoutes()` creates with the same options.                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `syncIndexes`           | `<C extends AppShape>(plugin: string, input: { writeApiKey?: string; } & IndexOptions<C>, upload: (this: Context<C>, key: string, indexesOf: (lang: C["lang"]) => Promise<SearchIndex[]>) => Promise<void>) => (this: Context<C>) => Promise<void>`                                                                                                                                                                              | The `build` hook of a search service that fills its index from the build. `upload` receives the write key and reads a language's search indexes with `indexesOf`, one language at a time where the service syncs them separately. Without `writeApiKey`, the build leaves the index as it is. When the option is set but empty, like from a variable the build doesn't have, it warns and names the plugin's function, `plugin`, as other plugins name theirs.                                            |
| `toServiceDocument`     | `({ id, title, description, breadcrumbs, url, structuredData, tag, ...extra }: SearchIndex) => { id: string; extra: {}; document: { title: string; description: string \| undefined; breadcrumbs: string[] \| undefined; url: string; structured: { headings: { id: string; content: string; }[]; contents: { heading: string \| undefined; content: string; table?: string; }[]; }; tag: string \| string[] \| undefined; }; }` | A search index as a document for Fumadocs' search services, which their `sync()` uploads, except for what each service names its own way: the ID, and the other fields that `buildIndex` returns.                                                                                                                                                                                                                                                                                                         |
