The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
refactor: move docs search logic into own hook (#22914)
Charis19b64ef9b282
diff --git a/packages/common/hooks/index.ts b/packages/common/hooks/index.tsindex 74e8477312a..c1b77bca5ab 100644--- a/packages/common/hooks/index.ts+++ b/packages/common/hooks/index.ts@@ -2,6 +2,7 @@ export * from './useBreakpoint'export * from './useConstant'export * from './useCopy'export * from './useDebounce'+export * from './useDocsSearch'export * from './useParams'export * from './useTelemetryProps'export * from './useThemeSandbox'diff --git a/packages/common/hooks/useDocsSearch.ts b/packages/common/hooks/useDocsSearch.tsnew file mode 100644index 00000000000..f16dd122fb8--- /dev/null+++ b/packages/common/hooks/useDocsSearch.ts@@ -0,0 +1,270 @@+import { useSupabaseClient } from '@supabase/auth-helpers-react'+import { compact, debounce, uniqBy } from 'lodash'+import { useCallback, useMemo, useReducer, useRef } from 'react'++const NUMBER_SOURCES = 2++const FUNCTIONS_URL = '/functions/v1/'++enum PageType {+ Markdown = 'markdown',+ Reference = 'reference',+ Integration = 'partner-integration',+ GithubDiscussion = 'github-discussions',+}++interface PageSection {+ heading: string+ slug: string+}++interface Page {+ id: number+ path: string+ type: PageType+ title: string+ subtitle: string | null+ description: string | null+ sections: PageSection[]+}++type SearchState =+ | {+ status: 'initial'+ key: number+ }+ | {+ status: 'loading'+ key: number+ staleResults: Page[]+ }+ | {+ status: 'partialResults'+ key: number+ results: Page[]+ }+ | {+ status: 'fullResults'+ key: number+ results: Page[]+ }+ | {+ status: 'noResults'+ key: number+ }+ | {+ status: 'error'+ key: number+ message: string+ }++type Action =+ | {+ type: 'resultsReturned'+ key: number+ sourcesLoaded: number+ results: unknown[]+ }+ | {+ type: 'newSearchDispatched'+ key: number+ }+ | {+ type: 'reset'+ key: number+ }+ | {+ type: 'errored'+ key: number+ sourcesLoaded: number+ message: string+ }++function reshapeResults(result: unknown): Page | null {+ if (typeof result !== 'object' || result === null) {+ return null+ }+ if (!('id' in result && 'path' in result && 'type' in result && 'title' in result)) {+ return null+ }++ const sections: PageSection[] = []+ if (+ 'headings' in result &&+ Array.isArray(result.headings) &&+ 'slugs' in result &&+ Array.isArray(result.slugs) &&+ result.headings.length === result.slugs.length+ ) {+ result.headings.forEach((heading, idx) => {+ const slug = (result.slugs as Array<string>)[idx]+ if (heading && slug) {+ sections.push({ heading, slug })+ }+ })+ }++ return {+ id: result.id as number,+ path: result.path as string,+ type: result.type as PageType,+ title: result.title as string,+ subtitle: 'subtitle' in result ? (result.subtitle as string) : null,+ description: 'description' in result ? (result.description as string) : null,+ sections,+ }+}++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':+ const allSourcesLoaded = action.sourcesLoaded === NUMBER_SOURCES+ const newResults = compact(action.results.map(reshapeResults))+ // If the new responses are from the same request as the current responses,+ // combine the responses.+ // If the new responses are from a fresher request, replace the current responses.+ const allResults =+ state.status === 'partialResults' && state.key === action.key+ ? uniqBy(state.results.concat(newResults), (res) => res.id)+ : newResults+ if (!allResults.length) {+ return allSourcesLoaded+ ? {+ status: 'noResults',+ key: action.key,+ }+ : {+ status: 'loading',+ key: action.key,+ staleResults:+ 'results' in state+ ? state.results+ : 'staleResults' in state+ ? state.staleResults+ : [],+ }+ }+ return allSourcesLoaded+ ? {+ status: 'fullResults',+ key: action.key,+ results: allResults,+ }+ : {+ status: 'partialResults',+ key: action.key,+ results: allResults,+ }+ case 'newSearchDispatched':+ return {+ status: 'loading',+ key: action.key,+ staleResults:+ 'results' in state ? state.results : 'staleResults' in state ? state.staleResults : [],+ }+ case 'reset':+ return {+ status: 'initial',+ key: action.key,+ }+ case 'errored':+ // At least one search has failed and all non-failing searches have come back empty+ if (action.sourcesLoaded === NUMBER_SOURCES && !('results' in state)) {+ return {+ status: 'error',+ key: action.key,+ message: action.message,+ }+ }+ return state+ default:+ return state+ }+}++const useDocsSearch = () => {+ const [state, dispatch] = useReducer(reducer, { status: 'initial', key: 0 })+ const supabaseClient = useSupabaseClient()+ const key = useRef(0)++ const handleSearch = useCallback(+ async (query: string) => {+ key.current += 1+ const localKey = key.current+ dispatch({ type: 'newSearchDispatched', key: localKey })++ let sourcesLoaded = 0++ supabaseClient.rpc('docs_search_fts', { query: query.trim() }).then(({ data, error }) => {+ sourcesLoaded += 1+ if (error || !Array.isArray(data)) {+ dispatch({+ type: 'errored',+ key: localKey,+ sourcesLoaded,+ message: error?.message ?? '',+ })+ } else {+ dispatch({+ type: 'resultsReturned',+ key: localKey,+ sourcesLoaded,+ results: data,+ })+ }+ })++ fetch(`${process.env.NEXT_PUBLIC_SUPABASE_URL}${FUNCTIONS_URL}search-embeddings`, {+ method: 'POST',+ body: JSON.stringify({ query }),+ })+ .then((response) => response.json())+ .then((results) => {+ if (!Array.isArray(results)) {+ throw Error("didn't get expected results array")+ }+ sourcesLoaded += 1+ dispatch({+ type: 'resultsReturned',+ key: localKey,+ sourcesLoaded,+ results,+ })+ })+ .catch((error) => {+ sourcesLoaded += 1+ dispatch({+ type: 'errored',+ key: localKey,+ sourcesLoaded,+ message: error.message ?? '',+ })+ })+ },+ [supabaseClient]+ )++ const debouncedSearch = useMemo(() => debounce(handleSearch, 150), [handleSearch])++ const resetSearch = useCallback(() => {+ key.current += 1+ dispatch({+ type: 'reset',+ key: key.current,+ })+ }, [])++ return {+ searchState: state,+ handleDocsSearch: handleSearch,+ handleDocsSearchDebounced: debouncedSearch,+ resetSearch,+ }+}++export { useDocsSearch, PageType as DocsSearchResultType }+export type { Page as DocsSearchResult, PageSection as DocsSearchResultSection }diff --git a/packages/ui-patterns/Cmdk/DocsSearch.tsx b/packages/ui-patterns/Cmdk/DocsSearch.tsxindex 0efc2a5ae6b..4c1f87ac39d 100644--- a/packages/ui-patterns/Cmdk/DocsSearch.tsx+++ b/packages/ui-patterns/Cmdk/DocsSearch.tsx@@ -1,26 +1,24 @@-import { compact, debounce, uniqBy } from 'lodash'-import * as React from 'react'-import { useCallback, useEffect, useMemo, useReducer, useRef } from 'react'--import { useSupabaseClient } from '@supabase/auth-helpers-react'-import { useRouter } from 'next/router'import {- Button,- IconAlertTriangle,- IconBook,- IconChevronRight,- IconGitHub,- IconHash,- IconMessageSquare,- IconSearch,-} from 'ui'+ type DocsSearchResult as Page,+ type DocsSearchResultSection as PageSection,+ DocsSearchResultType as PageType,+ useDocsSearch,+} from 'common'+import {+ AlertTriangle,+ Book,+ ChevronRight,+ Github,+ Hash,+ MessageSquare,+ Search,+} from 'lucide-react'+import { useRouter } from 'next/router'+import { useEffect, useRef } from 'react'+import { Button } from 'ui'import { CommandGroup, CommandItem, CommandLabel, TextHighlighter } from './Command.utils'import { useCommandMenu } from './CommandMenuProvider'-const NUMBER_SOURCES = 2--const FUNCTIONS_URL = '/functions/v1/'-const questions = ['How do I get started with Supabase?','How do I run Supabase locally?',@@ -30,191 +28,14 @@ const questions = ['How do I set up authentication?',]-export enum PageType {- Markdown = 'markdown',- Reference = 'reference',- Integration = 'partner-integration',- GithubDiscussion = 'github-discussions',-}--interface PageSection {- heading: string- slug: string-}--export interface Page {- id: number- path: string- type: PageType- title: string- subtitle: string | null- description: string | null- sections: PageSection[]-}--type SearchState =- | {- status: 'initial'- key: number- }- | {- status: 'loading'- key: number- staleResults: Page[]- }- | {- status: 'partialResults'- key: number- results: Page[]- }- | {- status: 'fullResults'- key: number- results: Page[]- }- | {- status: 'noResults'- key: number- }- | {- status: 'error'- key: number- message: string- }--type Action =- | {- type: 'resultsReturned'- key: number- sourcesLoaded: number- results: unknown[]- }- | {- type: 'newSearchDispatched'- key: number- }- | {- type: 'reset'- key: number- }- | {- type: 'errored'- key: number- sourcesLoaded: number- message: string- }--function reshapeResults(result: unknown): Page | null {- if (typeof result !== 'object' || result === null) {- return null- }- if (!('id' in result && 'path' in result && 'type' in result && 'title' in result)) {- return null- }-- const sections: PageSection[] = []- if (- 'headings' in result &&- Array.isArray(result.headings) &&- 'slugs' in result &&- Array.isArray(result.slugs) &&- result.headings.length === result.slugs.length- ) {- result.headings.forEach((heading, idx) => {- const slug = (result.slugs as Array<string>)[idx]- if (heading && slug) {- sections.push({ heading, slug })- }- })- }-- return {- id: result.id as number,- path: result.path as string,- type: result.type as PageType,- title: result.title as string,- subtitle: 'subtitle' in result ? (result.subtitle as string) : null,- description: 'description' in result ? (result.description as string) : null,- sections,- }-}--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':- const allSourcesLoaded = action.sourcesLoaded === NUMBER_SOURCES- const newResults = compact(action.results.map(reshapeResults))- // If the new responses are from the same request as the current responses,- // combine the responses.- // If the new responses are from a fresher request, replace the current responses.- const allResults =- state.status === 'partialResults' && state.key === action.key- ? uniqBy(state.results.concat(newResults), (res) => res.id)- : newResults- if (!allResults.length) {- return allSourcesLoaded- ? {- status: 'noResults',- key: action.key,- }- : {- status: 'loading',- key: action.key,- staleResults:- 'results' in state- ? state.results- : 'staleResults' in state- ? state.staleResults- : [],- }- }- return allSourcesLoaded- ? {- status: 'fullResults',- key: action.key,- results: allResults,- }- : {- status: 'partialResults',- key: action.key,- results: allResults,- }- case 'newSearchDispatched':- return {- status: 'loading',- key: action.key,- staleResults:- 'results' in state ? state.results : 'staleResults' in state ? state.staleResults : [],- }- case 'reset':- return {- status: 'initial',- key: action.key,- }- case 'errored':- // At least one search has failed and all non-failing searches have come back empty- if (action.sourcesLoaded === NUMBER_SOURCES && !('results' in state)) {- return {- status: 'error',- key: action.key,- message: action.message,- }- }- return state- default:- return state- }-}-const DocsSearch = () => {- const [state, dispatch] = useReducer(reducer, { status: 'initial', key: 0 })- const supabaseClient = useSupabaseClient()+ const {+ searchState: state,+ handleDocsSearch: handleSearch,+ handleDocsSearchDebounced: debouncedSearch,+ resetSearch,+ } = useDocsSearch()const { search, setSearch, inputRef, site, setIsOpen } = useCommandMenu()- const key = useRef(0)const initialLoad = useRef(true)const router = useRouter()@@ -256,75 +77,11 @@ const DocsSearch = () => {state.status === 'partialResults' ||(state.status === 'loading' && state.staleResults.length > 0)- const handleSearch = useCallback(- async (query: string) => {- key.current += 1- const localKey = key.current- dispatch({ type: 'newSearchDispatched', key: localKey })-- let sourcesLoaded = 0-- supabaseClient.rpc('docs_search_fts', { query: query.trim() }).then(({ data, error }) => {- sourcesLoaded += 1- if (error || !Array.isArray(data)) {- dispatch({- type: 'errored',- key: localKey,- sourcesLoaded,- message: error?.message ?? '',- })- } else {- dispatch({- type: 'resultsReturned',- key: localKey,- sourcesLoaded,- results: data,- })- }- })-- fetch(`${process.env.NEXT_PUBLIC_SUPABASE_URL}${FUNCTIONS_URL}search-embeddings`, {- method: 'POST',- body: JSON.stringify({ query }),- })- .then((response) => response.json())- .then((results) => {- if (!Array.isArray(results)) {- throw Error("didn't get expected results array")- }- sourcesLoaded += 1- dispatch({- type: 'resultsReturned',- key: localKey,- sourcesLoaded,- results,- })- })- .catch((error) => {- sourcesLoaded += 1- dispatch({- type: 'errored',- key: localKey,- sourcesLoaded,- message: error.message ?? '',- })- })- },- [supabaseClient]- )-function handleResetPrompt() {setSearch('')-- key.current += 1- dispatch({- type: 'reset',- key: key.current,- })+ resetSearch()}- const debouncedSearch = useMemo(() => debounce(handleSearch, 150), [handleSearch])-useEffect(() => {if (initialLoad.current) {// On first navigation into 'docs search' page, search immediately@@ -338,10 +95,9 @@ const DocsSearch = () => {} else {// If user clears search, reset resultsdebouncedSearch.cancel()- key.current += 1- dispatch({ type: 'reset', key: key.current })+ resetSearch()}- }, [search, handleSearch, debouncedSearch])+ }, [search, handleSearch, debouncedSearch, resetSearch])// Immediately run search if user presses enter// and abort any debounced searches that are waiting@@ -367,7 +123,7 @@ const DocsSearch = () => {}, [search, hasResults])const ChevronArrow = () => (- <IconChevronRight+ <ChevronRightstrokeWidth={1.5}className="text-foreground-muted@@ -497,7 +253,7 @@ const DocsSearch = () => {type="command"key={key}>- <IconSearch />+ <Search />{question}</CommandItem>)@@ -511,7 +267,7 @@ const DocsSearch = () => {)}{state.status === 'noResults' && (<div className="p-6 flex flex-col items-center gap-6 mt-4 text-foreground-light">- <IconAlertTriangle strokeWidth={1.5} size={40} />+ <AlertTriangle strokeWidth={1.5} size={40} /><p className="text-lg text-center">No results found.</p><Button size="tiny" type="secondary" onClick={handleResetPrompt}>Try again?@@ -520,7 +276,7 @@ const DocsSearch = () => {)}{state.status === 'error' && (<div className="p-6 flex flex-col items-center gap-6 mt-4">- <IconAlertTriangle strokeWidth={1.5} size={40} />+ <AlertTriangle strokeWidth={1.5} size={40} /><p className="text-lg text-center">Sorry, looks like we're having some issues with search!</p>@@ -568,9 +324,9 @@ export function getPageIcon(page: Page) {case PageType.Markdown:case PageType.Reference:case PageType.Integration:- return <IconBook strokeWidth={1.5} className="!mr-0 !w-4 !h-4" />+ return <Book strokeWidth={1.5} className="!mr-0 !w-4 !h-4" />case PageType.GithubDiscussion:- return <IconGitHub strokeWidth={1.5} className="!mr-0 !w-4 !h-4" />+ return <Github strokeWidth={1.5} className="!mr-0 !w-4 !h-4" />default:throw new Error(`Unknown page type '${page.type}'`)}@@ -581,9 +337,9 @@ export function getPageSectionIcon(page: Page) {case PageType.Markdown:case PageType.Reference:case PageType.Integration:- return <IconHash strokeWidth={1.5} className="!mr-0 !w-4 !h-4" />+ return <Hash strokeWidth={1.5} className="!mr-0 !w-4 !h-4" />case PageType.GithubDiscussion:- return <IconMessageSquare strokeWidth={1.5} className="!mr-0 !w-4 !h-4" />+ return <MessageSquare strokeWidth={1.5} className="!mr-0 !w-4 !h-4" />default:throw new Error(`Unknown page type '${page.type}'`)}