Files
supabase/packages/common/hooks/useDocsSearchV2.ts
Jeremias Menichelli 8b4be6cdfd feat: Add search to kb (#52089)
## Problem

There's currently no search on kb.

## Solution

- Move components used in Docs' Search V2 project to a common package
for re-usage.
 - Use these components on the Search V2 on docs
 - Refactor useDocsSearchV2 to accept endpoint for other solutions
 - Connect the search with the new `kb_search` table

<!--
## Preview links

If relevant, include links to changed pages for easy review access.

Copy the preview base URL from the Vercel bot comment on this PR. Use
the following table as an example template.

| Site | Live | Preview | Search for |
| -------------- |
-------------------------------------------------------------------------
|
------------------------------------------------------------------------------------------------------------
| ----------------------------- |
| WWW | [/blog/your-post](https://supabase.com/blog/your-post) |
[/blog/your-post](https://zone-www-dot-com-git-branch-name-supabase.vercel.app/blog/your-post)
| unique phrase from the change |
| Docs |
[/docs/guides/your-page](https://supabase.com/docs/guides/your-page) |
[/docs/guides/your-page](https://docs-git-branch-name-supabase.vercel.app/docs/guides/your-page)
| unique phrase from the change |
| Studio | [/dashboard](https://supabase.com/dashboard) |
[/dashboard](https://studio-git-branch-name-supabase.vercel.app/dashboard)
| unique phrase from the change |
| Design system | [/design-system](https://supabase.com/design-system) |
[/design-system](https://design-system-git-branch-name-supabase.vercel.app/design-system)
| unique phrase from the change |
| UI library | [/library](https://supabase.com/library) |
[/library](https://ui-library-git-branch-name-supabase.vercel.app/library)
| unique phrase from the change |
| Knowledge base |
[/kb/guides/your-page](https://supabase.com/kb/guides/your-page) |
[/kb/guides/your-page](https://kb-git-branch-name-supabase.vercel.app/kb/guides/your-page)
| unique phrase from the change |
-->

<!-- ## Additional context

Optionally add any other context or screenshots.

-->

## Review instructions

For both, the kb preview and the docs preview with the search v2
experiment active using the `?docs-search-v2=search-v2-active`:

 - Open the preview link of the project
 - On the homepage, press cmd/ctrl + k or click the search trigger
- A search panel should open, type something, for example "edge
functions" and wait for results to appear
 - Clicking a result should lead to the desired page

<img width="1173" height="832" alt="Screenshot 2026-10-22 at 13 34 43"
src="https://github.com/user-attachments/assets/1c3a3d7f-2fe3-452a-91dd-20ba7be3ef1b"
/>

_Search modal working on kb preview_

## Checklist

Check all before review:

- [x] I have read
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
- [x] If I wrote a new docs topic or edited an existing topic, I used
the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs
[style
guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide)
2026-10-22 17:30:49 +02:00

154 lines
4.8 KiB
TypeScript

'use client'
import { compact, debounce } from 'lodash'
import { useCallback, useMemo, useReducer, useRef } from 'react'
import { useMountEffect } from './useMountEffect'
interface DocsSearchV2Result {
path: string
title: string
heading: string
excerpt: string
headingPath: string[]
score: number
}
type SearchState =
| { status: 'initial'; key: number }
| { status: 'loading'; key: number; staleResults: DocsSearchV2Result[]; staleQuery: string }
| { status: 'results'; key: number; results: DocsSearchV2Result[]; query: string }
| { status: 'noResults'; key: number; query: string }
| { status: 'error'; key: number; message: string }
type Action =
| { type: 'resultsReturned'; key: number; results: DocsSearchV2Result[]; query: string }
| { type: 'newSearchDispatched'; key: number }
| { type: 'reset'; key: number }
| { type: 'errored'; key: number; message: string }
function reshapeResult(row: unknown): DocsSearchV2Result | null {
if (typeof row !== 'object' || row === null) return null
if (
!(
'slug' in row &&
'page_title' in row &&
'heading' in row &&
'excerpt' in row &&
'heading_path' in row &&
'score' in row
)
)
return null
const slug = row.slug as string
return {
// Next's router already prepends the app's basePath ('/docs'), so don't add it here.
path: slug ? `/${slug}` : '/',
title: row.page_title as string,
heading: row.heading as string,
excerpt: row.excerpt as string,
headingPath: row.heading_path as string[],
score: row.score as number,
}
}
function reducer(state: SearchState, action: Action): SearchState {
// Ignore responses from outdated async functions
if (state.key > action.key) {
return state
}
switch (action.type) {
case 'resultsReturned':
return action.results.length
? { status: 'results', key: action.key, results: action.results, query: action.query }
: { status: 'noResults', key: action.key, query: action.query }
case 'newSearchDispatched':
return {
status: 'loading',
key: action.key,
staleResults:
'results' in state ? state.results : 'staleResults' in state ? state.staleResults : [],
// keep highlighted query while loading
staleQuery: 'query' in state ? state.query : 'staleQuery' in state ? state.staleQuery : '',
}
case 'reset':
return { status: 'initial', key: action.key }
case 'errored':
return { status: 'error', key: action.key, message: action.message }
default:
return state
}
}
interface UseDocsSearchV2Options {
/** URL of a search endpoint that takes `?q=` and returns a JSON array. Relative or absolute. */
endpoint: string
/**
* Turns one row of the endpoint's response into a result, or null to drop it. Defaults to the
* docs' row shape. Pass a stable reference (module scope), or every render restarts the debounce.
*/
reshape?: (row: unknown) => DocsSearchV2Result | null
}
const useDocsSearchV2 = ({ endpoint, reshape = reshapeResult }: UseDocsSearchV2Options) => {
const [state, dispatch] = useReducer(reducer, { status: 'initial', key: 0 })
const key = useRef(0)
const handleSearch = useCallback(
async (query: string) => {
key.current += 1
const localKey = key.current
dispatch({ type: 'newSearchDispatched', key: localKey })
try {
const params = new URLSearchParams({ q: query.trim() })
const response = await fetch(`${endpoint}?${params}`)
const data = await response.json()
if (!Array.isArray(data)) {
throw new Error(data?.error ?? "didn't get expected results array")
}
dispatch({
type: 'resultsReturned',
key: localKey,
results: compact(data.map(reshape)),
query: query.trim(),
})
} catch (error) {
console.error(`[ERROR] Error fetching docs search v2 results: ${error}`)
dispatch({
type: 'errored',
key: localKey,
message: error instanceof Error ? error.message : '',
})
}
},
[endpoint, reshape]
)
const debouncedSearch = useMemo(() => debounce(handleSearch, 250), [handleSearch])
const debounceCancel = useCallback(() => {
debouncedSearch.cancel()
}, [debouncedSearch])
// the dialog unmounts on close, so cancel any pending search instead of fetching after it's gone
useMountEffect(() => debounceCancel)
const resetSearch = useCallback(() => {
debounceCancel()
key.current += 1
dispatch({ type: 'reset', key: key.current })
}, [debounceCancel])
return {
searchState: state,
handleDocsSearch: handleSearch,
handleDocsSearchDebounced: debouncedSearch,
resetSearch,
}
}
export { useDocsSearchV2 }
export type { DocsSearchV2Result, UseDocsSearchV2Options, SearchState as DocsSearchV2State }