Skip to content

@ogygia/content · Docs sites

Search

The site indexes every page section by section, so a hit lands on the right heading. Ship the index as a static file and search on the visitor's device, or query it on the server, with a page that still searches when JavaScript is off.

On this page

A docs site’s search has to find the paragraph you half remember and take you to it. The site layer indexes each page’s prose split at its headings, so every section is its own document and a hit links straight to the heading it matched.

Where the query runs is up to you. The usual choice for a prerendered site is to ship the index as a static search.json and search it on the visitor’s device, in a web worker: it costs nothing to serve, no server sees what anyone types, and a query needs no network. Query on the server instead when the corpus is private, too big to ship, or changes per request. Both use the same documents and the same ranking. This site works the first way: press ⌘K. With DocsShell, one route is all it takes:

import { docs } from '$lib/docs.server';

export const prerender = true;
export const GET = docs.emit.search();

Static index

docs.emit.search() is a GET handler that answers with the index. Mount it at search.json under the site’s mount prefix and prerender it, as in the route above.

That’s all DocsShell needs: its search box loads {base}/search.json the first time someone shows intent to search. The engine is Orama, which comes with @ogygia/content, so there’s nothing else to install.

Search palette

<Search> is the search box DocsShell and BlogShell show, and you can place it anywhere as an island: import { Search } from '@ogygia/content' with { wake: 'idle' }. It comes in two halves so a visitor who never searches pays almost nothing:

  • The trigger is rendered on the server: a real link to the search page, labeled with placeholder, with a ⌘K hint. ⌘K or Ctrl+K opens the palette and closes it again. / opens it too, unless you’re typing in a field or an editor.
  • The palette loads on the first sign of intent: the pointer over the trigger, focus on it, a click or a key. It’s a dialog with a search field and a result list, and it starts a worker that fetches the index and builds it off the main thread. Typing searches once you pause. When the palette’s code can’t load, a click follows the link to the search page instead.
PropDefaultWhat it does
basethe shell’s baseThe mount prefix: hits link under it, and the index is fetched from {base}/search.json.
endpoint{base}/search.jsonWhere the index is, if you mounted emit.search() somewhere else.
action{base}/searchThe trigger’s link, the page that works without JavaScript.
placeholder'Search'The trigger’s label and the field’s placeholder.
limit10The most hits shown. Ignored with query: the server decides how many (10 for the search remote) (#2287).
querynoneA function (q) => Promise<SearchHit[]> that answers instead of the worker. See Query on the server.
mode'dialog''inline' drops the trigger and the keys and shows the field and list in place, as the phone sheet does.
<script lang="ts">
  import { Search } from '@ogygia/content' with {
    wake: 'idle'
  };
</script>

<header>
  <a href="/docs">Docs</a>
  <Search base="/docs" placeholder="Search the docs" />
</header>

Server search

The search remote from remotes() runs docs.search on the server for each query. Hand it to the search box as query, and the palette asks the server instead of starting a worker; the index never ships.

query is a function, and a function can’t be passed to an island from the server (#2272). So put the search box inside a small island of your own, which imports the remote itself, and place that island where the search box goes. With DocsShell, that’s its tools region.

The phone bottom bar’s search still uses the worker, so it needs search.json too: keep the index mounted, or pass your own bar.

import { remotes } from '@ogygia/content/server';
import { docs } from './docs.server';

export const { meta, page, search } = remotes(docs, {
  base: '/docs'
});
<script lang="ts">
  import { Search } from '@ogygia/content';
  import { search } from '$lib/docs.remote';
</script>

<Search base="/docs" query={search} />
<script lang="ts">
  import DocsShell from '@ogygia/content/docs-shell';
  import { ThemeToggle } from '@ogygia/content' with {
    wake: 'load'
  };
  import ServerSearch from '$lib/ServerSearch.svelte' with {
    wake: 'idle'
  };
  import '@ogygia/content/theme.css';
  import '@ogygia/content/shell.css';
  import { meta } from '$lib/docs.remote';

  let { children } = $props();
  const shell = await meta();
</script>

<DocsShell meta={shell} base="/docs" title="Example">
  {#snippet tools()}
    <div class="og-cheader-tools">
      <ServerSearch /><ThemeToggle />
    </div>
  {/snippet}
  {@render children()}
</DocsShell>

No-JS search

The trigger is a real link to {base}/search, so a page without JavaScript (or before the palette loads) can still search. <SearchPage> is that page: a GET form that sends the term as q, and the hits rendered on the server with a count, or a “no results” line. Its props are q, hits, title (default 'Search'), placeholder and action (default: the current URL).

The results need a server, so the route can’t be prerendered: its load reads q from the URL and calls docs.search with the mount prefix.

On a site with no server at all, prerender the page without a load (<SearchPage /> on its own). It’s then only a form: it gives the trigger somewhere to go, and with JavaScript the palette takes over. The Playground ↗ does this.

import { docs } from '$lib/docs.server';

export const prerender = false;

export const load = async ({ url }) => {
  const q = (url.searchParams.get('q') ?? '').trim();
  return {
    q,
    hits: q ? await docs.search(q, { base: '/docs' }) : []
  };
};
<script lang="ts">
  import { SearchPage } from '@ogygia/content';

  let { data } = $props();
</script>

<SearchPage
  q={data.q}
  hits={data.hits}
  title="Search the docs"
/>

Indexing

docs.emit.search() and docs.search build the same documents:

  • A markdown page is split at its ##, ### and #### headings. Each section is one document that links to its heading; the text before the first heading is one more that links to the page. The text is the page’s prose with the frontmatter, code blocks, HTML tags and markdown syntax taken out; inline code stays as words. A ## line inside a code block is read as a heading today, which shifts the sections after it (#2281).
  • A page with no markdown source (a JSON entry, say) is one document made of its summary and every other text field in its data.
  • Each document also carries the page title and the top-level section label.

The index covers what the public sees: pages hidden by the collection’s filter are left out even in a preview. On a site with dimensions, only the default version and language are indexed.

docs.search(q, options) takes limit (default 10), base (default ''; it doesn’t read the site’s base, #2282) and in, a list of collections to search. in narrows a site that holds, say, docs and a blog to one of them; each distinct list gets its own index on the server. The static index always holds every collection.

The server builds its index on the first query and keeps it. When the content changes (a live source, an edit in dev), the next query builds it again; a build that fails isn’t kept.

Ranking

The default engine matches with a typo tolerance of one letter and weighs a match in the page title three times and in a heading twice as much as one in the text. It then reorders the hits. A hit moves up when its page title holds the whole query (more) or every word of it (less), and when its heading holds every word. The page’s opening text gets one more lift when the title holds the query, so it usually comes before its own sections, and searching for a page’s name usually finds that page first.

Each hit is plain data:

FieldWhat it holds
hrefThe link, with base in front and #heading for a section.
slugThe page’s address.
titleThe page title.
sectionThe page’s top-level section label.
headingThe heading of the matched section; empty for the page’s opening text.
excerptAbout 150 characters around the first match, HTML-escaped, with <mark> around each matched word. Render it with {@html}.
scoreThe rank, highest first.

Custom UI

SearchClient is the worker the palette uses, for a search UI of your own. It’s browser-only, so create it in an island. new SearchClient({ base?, endpoint?, limit? }) starts the worker and fetches the index. client.query(q) answers with hits (an empty term answers []), client.ready resolves once the index is built and rejects with the reason when it can’t be, and client.destroy() stops the worker.

Every query settles. A failed download, a crashed worker or destroy() rejects every query that waits and every later one, with the reason; create a new client to try again. Queries answer in the order the worker finishes them, so keep the latest term and drop an answer for an older one, as below.

<script lang="ts">
  import { onMount } from 'svelte';
  import {
    SearchClient,
    type SearchHit
  } from '@ogygia/content';

  let client: SearchClient | undefined;
  let hits = $state<SearchHit[]>([]);

  onMount(() => {
    client = new SearchClient({ base: '/docs', limit: 5 });
    return () => client?.destroy();
  });

  let latest = '';

  async function run(q: string) {
    latest = q;
    let found: SearchHit[] = [];
    try {
      found = (await client?.query(q)) ?? [];
    } catch {
      // the index didn't load or the worker stopped: show no hits
    }
    if (q === latest) hits = found;
  }
</script>

<input
  type="search"
  oninput={(e) => run(e.currentTarget.value)}
/>
{#each hits as hit (hit.href)}
  <a href={hit.href}>{hit.title}: {@html hit.excerpt}</a>
{/each}

Other engines

site({ search: { engine } }) replaces Orama for docs.search, the search remote and the search page: a hosted service, another library, a test double. An engine is two functions. init(), optional, runs before each index build (once per in scope, and again after content changes), so make it cheap to call twice: load once and keep it. build(sections) takes the section documents (id, slug, anchor, title, section, heading, text) and returns an index whose query(q, { limit, base }) answers with hits.

The worker behind the search box always uses Orama over search.json. With another engine, search on the server.

createSearch(outline, engine), buildDocs(outline), splitSections, stripProse and oramaEngine() are exported too, for building an index outside a site.

import {
  content,
  site,
  type SearchEngine,
  type SearchHit
} from '@ogygia/content';

const guides = content({
  loader: import.meta.og.loader.folder('../content/docs')
});

const naive: SearchEngine = {
  async build(sections) {
    return {
      async query(q, { limit, base }) {
        const term = q.toLowerCase();
        return sections
          .filter((d) => d.text.toLowerCase().includes(term))
          .slice(0, limit)
          .map((d, i): SearchHit => ({
            href: `${base}/${d.slug}${d.anchor ? `#${d.anchor}` : ''}`,
            slug: d.slug,
            title: d.title,
            section: d.section,
            heading: d.heading,
            excerpt: '',
            score: limit - i
          }));
      }
    };
  }
};

export const docs = site({
  outline: guides,
  search: { engine: naive }
});

Error handling

  • The index can’t be fetched: the worker reports content_search_index_fetch_failed with the URL and status. Mount emit.search() at {base}/search.json, or point endpoint at it.
  • The palette can’t load its index: it logs content_search_unavailable and shows the reason in place of results. It doesn’t try again until the page is reloaded, even after a brief network failure (#2287).
  • One query fails: the palette logs content_search_query_failed and shows the error for that term. With a server query that failed once (a server that was down), the next term asks again.
  • The worker crashes: every later term fails the same way until the page is reloaded. The palette keeps one worker per page and doesn’t start another (#2283).

Do and don’t

  • Do ship the static index for a prerendered site. It’s free to serve and keeps every keystroke on the visitor’s device.
  • Do mount the index at {base}/search.json, where the search box looks for it.
  • Do pass base to docs.search, or hit links miss the mount prefix.
  • Don’t build an index from raw bodies yourself. The section split is what lets a hit land on the right heading.