The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat: Add search to kb (#52089)
Jeremias Menichelli8b4be6cdfd4d
diff --git a/apps/docs/features/SearchV2/SearchV2.telemetry.test.tsx b/apps/docs/features/SearchV2/SearchV2.telemetry.test.tsxnew file mode 100644index 00000000000..b2d919c5ef8--- /dev/null+++ b/apps/docs/features/SearchV2/SearchV2.telemetry.test.tsx@@ -0,0 +1,246 @@+// @vitest-environment jsdom+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'+import type { DocsSearchV2State } from 'common'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { SearchV2Trigger } from './SearchV2Trigger'++const sendTelemetryEvent = vi.fn()+const push = vi.fn()+const handleDocsSearchDebounced = vi.fn()+const resetSearch = vi.fn()+let searchState: DocsSearchV2State++vi.mock('@/lib/telemetry', () => ({ useSendTelemetryEvent: () => sendTelemetryEvent }))+vi.mock('next/navigation', () => ({ useRouter: () => ({ push }) }))+vi.mock('next/link', () => ({+ default: ({+ prefetch: _prefetch,+ ...props+ }: React.ComponentProps<'a'> & { prefetch?: boolean }) => <a {...props} />,+}))+const useDocsSearchV2 = vi.fn((_options: { endpoint: string }) => ({+ searchState,+ handleDocsSearchDebounced,+ resetSearch,+}))+vi.mock('common', () => ({+ useDocsSearchV2: (options: { endpoint: string }) => useDocsSearchV2(options),+}))++const result = {+ path: '/guides/auth',+ title: 'Auth',+ heading: 'Auth',+ excerpt: 'Learn about auth',+ headingPath: ['Auth'],+ score: 1,+}+const resultsState: DocsSearchV2State = {+ status: 'results',+ key: 1,+ results: [result],+ query: 'auth',+}++// cmdk and Radix lean on browser APIs jsdom doesn't ship+beforeEach(() => {+ globalThis.ResizeObserver ??= class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ Element.prototype.scrollIntoView ??= () => {}+ searchState = { status: 'initial', key: 0 }+})++afterEach(() => {+ cleanup()+ vi.clearAllMocks()+})++const eventActions = () => sendTelemetryEvent.mock.calls.map(([event]) => event.action)++function openDialog() {+ const view = render(<SearchV2Trigger />)+ fireEvent.click(screen.getByRole('button', { name: /search/i }))+ return view+}++function setSearchState(view: ReturnType<typeof render>, next: DocsSearchV2State) {+ searchState = next+ act(() => view.rerender(<SearchV2Trigger />))+}++describe('SearchV2 telemetry', () => {+ it("searches through the docs app's own route, under its base path", () => {+ openDialog()++ expect(useDocsSearchV2).toHaveBeenCalledWith({ endpoint: '/docs/api/search_v2' })+ })++ it('sends docs_search_v2_opened with search_input when the trigger is clicked', () => {+ openDialog()++ expect(screen.getByRole('combobox')).toBeTruthy()+ expect(sendTelemetryEvent).toHaveBeenCalledTimes(1)+ expect(sendTelemetryEvent).toHaveBeenCalledWith({+ action: 'docs_search_v2_opened',+ properties: { triggerType: 'search_input' },+ })+ })++ it('sends docs_search_v2_opened with keyboard_shortcut on Cmd+K', () => {+ render(<SearchV2Trigger />)++ fireEvent.keyDown(window, { key: 'k', metaKey: true })++ expect(screen.getByRole('combobox')).toBeTruthy()+ expect(sendTelemetryEvent).toHaveBeenCalledTimes(1)+ expect(sendTelemetryEvent).toHaveBeenCalledWith({+ action: 'docs_search_v2_opened',+ properties: { triggerType: 'keyboard_shortcut' },+ })+ })++ it('ignores k without Cmd', () => {+ render(<SearchV2Trigger />)++ fireEvent.keyDown(window, { key: 'k' })++ expect(screen.queryByRole('combobox')).toBeNull()+ expect(sendTelemetryEvent).not.toHaveBeenCalled()+ })++ it('sends docs_search_v2_closed when the dialog closes', () => {+ openDialog()+ sendTelemetryEvent.mockClear()++ fireEvent.keyDown(screen.getByRole('combobox'), { key: 'Escape' })++ expect(screen.queryByRole('combobox')).toBeNull()+ expect(sendTelemetryEvent).toHaveBeenCalledTimes(1)+ expect(sendTelemetryEvent).toHaveBeenCalledWith({ action: 'docs_search_v2_closed' })+ })++ it('runs the debounced search while typing and resets when the input is cleared', () => {+ openDialog()+ const input = screen.getByRole('combobox')++ fireEvent.change(input, { target: { value: 'auth' } })+ expect(handleDocsSearchDebounced).toHaveBeenCalledWith('auth')+ expect(resetSearch).not.toHaveBeenCalled()++ fireEvent.change(input, { target: { value: '' } })+ expect(resetSearch).toHaveBeenCalledTimes(1)+ })++ it('resets the search from the Clear button', () => {+ openDialog()+ fireEvent.change(screen.getByRole('combobox'), { target: { value: 'auth' } })++ fireEvent.click(screen.getByRole('button', { name: 'Clear' }))++ expect(resetSearch).toHaveBeenCalledTimes(1)+ })++ describe('docs_search_v2_search_submitted', () => {+ it('is sent with hasResults true once results settle', () => {+ const view = openDialog()+ sendTelemetryEvent.mockClear()++ setSearchState(view, resultsState)++ expect(sendTelemetryEvent).toHaveBeenCalledTimes(1)+ expect(sendTelemetryEvent).toHaveBeenCalledWith({+ action: 'docs_search_v2_search_submitted',+ properties: { query: 'auth', hasResults: true },+ })+ })++ it('is sent with hasResults false when nothing matches', () => {+ const view = openDialog()+ sendTelemetryEvent.mockClear()++ setSearchState(view, { status: 'noResults', key: 1, query: 'zzz' })++ expect(sendTelemetryEvent).toHaveBeenCalledWith({+ action: 'docs_search_v2_search_submitted',+ properties: { query: 'zzz', hasResults: false },+ })+ })++ it('is not sent while loading or on error', () => {+ const view = openDialog()+ sendTelemetryEvent.mockClear()++ setSearchState(view, { status: 'loading', key: 1, staleResults: [], staleQuery: '' })+ setSearchState(view, { status: 'error', key: 2, message: 'nope' })++ expect(eventActions()).not.toContain('docs_search_v2_search_submitted')+ })+ })++ describe('docs_search_v2_result_clicked', () => {+ it('is sent when a result link is clicked, which closes the dialog without a router push', () => {+ const view = openDialog()+ setSearchState(view, resultsState)+ sendTelemetryEvent.mockClear()++ fireEvent.click(screen.getByRole('option', { name: /Learn about auth/ }))++ expect(sendTelemetryEvent).toHaveBeenCalledWith({+ action: 'docs_search_v2_result_clicked',+ properties: { resultPath: '/guides/auth', query: 'auth' },+ })+ // the link's own click handler closes the dialog before cmdk's onSelect reports the click+ expect(eventActions()).toEqual(['docs_search_v2_closed', 'docs_search_v2_result_clicked'])+ expect(push).not.toHaveBeenCalled()+ })++ it('is sent once and does not close the dialog for a new-tab click', () => {+ const view = openDialog()+ setSearchState(view, resultsState)+ sendTelemetryEvent.mockClear()++ fireEvent.click(screen.getByRole('option', { name: /Learn about auth/ }), { metaKey: true })++ expect(eventActions()).toEqual(['docs_search_v2_result_clicked'])+ expect(screen.getByRole('combobox')).toBeTruthy()+ })++ it('is sent on Enter, which navigates with the router and closes the dialog', () => {+ const view = openDialog()+ setSearchState(view, resultsState)+ sendTelemetryEvent.mockClear()++ fireEvent.keyDown(screen.getByRole('combobox'), { key: 'Enter' })++ expect(sendTelemetryEvent).toHaveBeenCalledWith({+ action: 'docs_search_v2_result_clicked',+ properties: { resultPath: '/guides/auth', query: 'auth' },+ })+ expect(push).toHaveBeenCalledWith('/guides/auth')+ expect(eventActions()).toEqual(['docs_search_v2_result_clicked', 'docs_search_v2_closed'])+ })++ it('reports the query the visible results belong to while a new search is loading', () => {+ const view = openDialog()+ setSearchState(view, {+ status: 'loading',+ key: 2,+ staleResults: [result],+ staleQuery: 'auth',+ })+ fireEvent.change(screen.getByRole('combobox'), { target: { value: 'authent' } })+ sendTelemetryEvent.mockClear()++ fireEvent.keyDown(screen.getByRole('combobox'), { key: 'Enter' })++ expect(sendTelemetryEvent).toHaveBeenCalledWith({+ action: 'docs_search_v2_result_clicked',+ properties: { resultPath: '/guides/auth', query: 'auth' },+ })+ })+ })+})diff --git a/apps/docs/features/SearchV2/SearchV2Dialog.tsx b/apps/docs/features/SearchV2/SearchV2Dialog.tsxindex 67cfde97255..b079569e482 100644--- a/apps/docs/features/SearchV2/SearchV2Dialog.tsx+++ b/apps/docs/features/SearchV2/SearchV2Dialog.tsx@@ -1,82 +1,44 @@'use client'-import { LoadingBeam } from '~/features/ui/LoadingBeam'-import { useDocsSearchV2, type DocsSearchV2Result } from 'common'-import { useRouter } from 'next/navigation'-import { VisuallyHidden } from 'radix-ui'-import { useEffect, useRef, useState, type KeyboardEvent } from 'react'+import { useDocsSearchV2 } from 'common'import {- Command,- CommandEmpty,- CommandGroup,- CommandInput,- CommandItem,- CommandList,- Dialog,- DialogContent,- DialogDescription,- DialogTitle,- KeyboardShortcut,-} from 'ui'+ SearchDialog,+ SearchPanel,+ type SearchDialogProps,+ type SearchPanelProps,+} from 'docs-search/components'+import Link from 'next/link'+import { useRouter } from 'next/navigation'+import { useEffect } from 'react'-import { getIsSearching } from './SearchV2.utils'-import { SearchV2Result } from './SearchV2Result'+import { SEARCH_V2_ENDPOINT } from './constants'import { useSendTelemetryEvent } from '@/lib/telemetry'-interface SearchV2DialogProps {- open: boolean- onOpenChange: (open: boolean) => void-}+type SearchV2DialogProps = Pick<SearchDialogProps, 'open' | 'onOpenChange'>-interface SearchV2PanelProps {- onResultSelect: (path: string) => void- onResultOpen: () => void-}+type SearchV2PanelProps = Pick<SearchPanelProps, 'onResultNavigate' | 'onResultLinkNavigate'>export function SearchV2Dialog({ open, onOpenChange }: SearchV2DialogProps) {const router = useRouter()- function handleSelect(path: string) {- router.push(path)- onOpenChange(false)- }-- function handleResultOpen() {- onOpenChange(false)- }-return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent- hideClose- centered={false}- dialogOverlayProps={{- className:- 'data-closed:animate-out! data-closed:fade-out-0 data-closed:fill-mode-forwards data-closed:duration-150 data-closed:ease-enter pt-20 sm:pt-20',+ <SearchDialog open={open} onOpenChange={onOpenChange}>+ <SearchV2Panel+ onResultNavigate={(path) => {+ router.push(path)+ onOpenChange(false)}}- size="large"- className="overflow-hidden rounded-lg border-0 p-0 inset-ring inset-ring-border shadow-(--shadow-codeblock)!"- >- <SearchV2Panel onResultSelect={handleSelect} onResultOpen={handleResultOpen} />- </DialogContent>- </Dialog>+ onResultLinkNavigate={() => onOpenChange(false)}+ />+ </SearchDialog>)}-function SearchV2Panel({ onResultSelect, onResultOpen }: SearchV2PanelProps) {+function SearchV2Panel({ onResultNavigate, onResultLinkNavigate }: SearchV2PanelProps) {const sendTelemetryEvent = useSendTelemetryEvent()- const { searchState, handleDocsSearchDebounced, resetSearch } = useDocsSearchV2()- const [query, setQuery] = useState('')- const [isDeleting, setIsDeleting] = useState(false)- const inputRef = useRef<HTMLInputElement>(null)-- // highlight with the query the visible results belong to, not the one being typed- const highlightQuery =- 'query' in searchState- ? searchState.query- : 'staleQuery' in searchState- ? searchState.staleQuery- : ''+ const { searchState, handleDocsSearchDebounced, resetSearch } = useDocsSearchV2({+ endpoint: SEARCH_V2_ENDPOINT,+ })useEffect(() => {if (searchState.status === 'results' || searchState.status === 'noResults') {@@ -87,136 +49,25 @@ function SearchV2Panel({ onResultSelect, onResultOpen }: SearchV2PanelProps) {}}, [searchState, sendTelemetryEvent])- const results: DocsSearchV2Result[] =- 'results' in searchState- ? searchState.results- : 'staleResults' in searchState- ? searchState.staleResults- : []-- const isListVisible =- results.length > 0 || searchState.status === 'noResults' || searchState.status === 'error'- const isSearching = getIsSearching({ searchState, query })-- function handleClear() {- setQuery('')- resetSearch()- inputRef.current?.focus()- }-- // cmdk's root turns enter into "open highlighted result", so keep it on the button.- // other keys must bubble, or tab never reaches the dialog's focus trap- function handleClearKeyDown(event: KeyboardEvent<HTMLButtonElement>) {- if (event.key === 'Enter') event.stopPropagation()- }-- function handleValueChange(value: string) {- setIsDeleting(value.length < query.length)- setQuery(value)- if (value) {- handleDocsSearchDebounced(value)- } else {- resetSearch()- }- }-- // Announced via the aria-live region below — a sighted user sees the spinner/list update,- // but a screen reader user gets no equivalent signal unless we say so explicitly. Also covers- // the result count, which isn't reliably announced by the listbox/option roles alone.- function getStatusMessage(): string {- if (searchState.status === 'loading') return 'Searching the docs…'- if (searchState.status === 'noResults') return 'No results found.'- if (searchState.status === 'error') return 'Something went wrong. Please try again.'- if (results.length > 0) {- return `${results.length} result${results.length === 1 ? '' : 's'} found.`- }- return ''- }-- return (- <Command shouldFilter={false} className="bg-transparent">- <VisuallyHidden.VisuallyHidden>- <DialogTitle>Search docs</DialogTitle>- <DialogDescription>Search the Supabase documentation</DialogDescription>- </VisuallyHidden.VisuallyHidden>- <div className="relative flex items-center gap-3 pr-4">- <CommandInput- ref={inputRef}- value={query}- placeholder="Search docs..."- aria-label="Search the Supabase documentation"- onValueChange={handleValueChange}- wrapperClassName="flex-1 border-0 pl-3 pr-0 text-foreground-lighter [&_svg]:size-4.5 [&_svg]:stroke-2 [&_svg]:opacity-100"- className="h-12 pl-2.5 text-base text-foreground placeholder:text-foreground-lighter"- />- {query ? (- <button- type="button"- tabIndex={0}- onClick={handleClear}- onKeyDown={handleClearKeyDown}- className="relative -mx-2 shrink-0 cursor-pointer rounded-md px-2 py-1 text-xs text-foreground-lighter transition-colors duration-150 after:absolute after:inset-x-0 after:-inset-y-2 after:content-[''] hover:bg-overlay-hover hover:text-foreground focus-ring"- >- Clear- </button>- ) : null}- <LoadingBeam- isActive={isSearching}- direction={isDeleting ? 'backward' : 'forward'}- className={isListVisible ? '-bottom-px' : undefined}- />- </div>- {/*- Screen-reader-only status announcement. Focus stays in the input as results come in- (that's what lets people keep typing), so nothing else here gets read aloud on its- own — this is what tells a screen reader user a search ran and how many results it found.- */}- <div role="status" aria-live="polite" className="sr-only">- {getStatusMessage()}- </div>- <CommandList- label="Search results"- className="h-(--cmdk-list-height) max-h-[min(477px,70dvh)] inset-shadow-2xs inset-shadow-border mx-px transition-all duration-150 ease-enter motion-reduce:transition-none scroll-fade-bottom"- >- {searchState.status === 'noResults' && <CommandEmpty>No results found.</CommandEmpty>}- {searchState.status === 'error' && (- <CommandEmpty>Something went wrong. Please try again.</CommandEmpty>- )}- {results.length > 0 && (- <CommandGroup className="pt-1.25">- {results.map((result) => (- <SearchV2Result- key={result.path}- result={result}- highlightQuery={highlightQuery}- onResultSelect={onResultSelect}- onResultOpen={onResultOpen}- />- ))}- </CommandGroup>- )}- </CommandList>- {results.length > 0 ? <SearchV2Footer /> : null}- </Command>- )-}--function SearchV2Footer() {return (- <footer- aria-hidden- className="flex items-center justify-end gap-3 border-t px-4 py-2.5 text-xs text-foreground-lighter mx-px max-lg:hidden"- >- <span className="flex items-center gap-1.5">- Navigate- <KeyboardShortcut keys={['ArrowUp']} />- <KeyboardShortcut keys={['ArrowDown']} />- </span>- <span className="h-3 w-px bg-border" />- <span className="flex items-center gap-1.5">- Open- <KeyboardShortcut keys={['Enter']} />- </span>- </footer>+ <SearchPanel+ searchState={searchState}+ renderLink={(props) => <Link prefetch={false} {...props} />}+ onQueryChange={(query) => {+ if (query) {+ handleDocsSearchDebounced(query)+ } else {+ resetSearch()+ }+ }}+ onResultActivate={(result, { query }) =>+ sendTelemetryEvent({+ action: 'docs_search_v2_result_clicked',+ properties: { resultPath: result.path, query },+ })+ }+ onResultNavigate={(path) => onResultNavigate(path)}+ onResultLinkNavigate={() => onResultLinkNavigate?.()}+ />)}diff --git a/apps/docs/features/SearchV2/SearchV2Result.tsx b/apps/docs/features/SearchV2/SearchV2Result.tsxdeleted file mode 100644index 38ff3603105..00000000000--- a/apps/docs/features/SearchV2/SearchV2Result.tsx+++ /dev/null@@ -1,67 +0,0 @@-'use client'--import type { DocsSearchV2Result } from 'common'-import Link from 'next/link'-import { useRef, type MouseEvent } from 'react'-import { CommandItem } from 'ui'--import { formatHeadingPath, highlightMatches } from './SearchV2.utils'-import { useSendTelemetryEvent } from '@/lib/telemetry'--interface SearchV2ResultProps {- result: DocsSearchV2Result- highlightQuery: string- onResultSelect: (path: string) => void- onResultOpen: () => void-}--export function SearchV2Result({- result,- highlightQuery,- onResultSelect,- onResultOpen,-}: SearchV2ResultProps) {- const sendTelemetryEvent = useSendTelemetryEvent()- // clicks navigate via the link and also fire onSelect, so onSelect only navigates for Enter- const isPointerSelectRef = useRef(false)-- function handleLinkClick(event: MouseEvent<HTMLAnchorElement>) {- isPointerSelectRef.current = true- const isNewTab = event.metaKey || event.ctrlKey || event.shiftKey || event.altKey- if (!isNewTab) onResultOpen()- }-- function handleSelect() {- sendTelemetryEvent({- action: 'docs_search_v2_result_clicked',- properties: { resultPath: result.path, query: highlightQuery },- })- if (isPointerSelectRef.current) {- isPointerSelectRef.current = false- return- }- onResultSelect(result.path)- }-- return (- <CommandItem- asChild- value={result.path}- onSelect={handleSelect}- className="cursor-pointer rounded-md px-2 py-2"- >- <Link href={result.path} prefetch={false} tabIndex={-1} onClick={handleLinkClick}>- <div className="flex min-w-0 flex-1 flex-col gap-0.5">- <p className="text-sm leading-5 text-foreground">- {highlightMatches(formatHeadingPath(result.headingPath), highlightQuery)}- </p>- {result.excerpt ? (- <p className="line-clamp-2 text-pretty text-sm leading-5 text-foreground-lighter">- {highlightMatches(result.excerpt, highlightQuery)}- </p>- ) : null}- </div>- </Link>- </CommandItem>- )-}diff --git a/apps/docs/features/SearchV2/SearchV2Trigger.tsx b/apps/docs/features/SearchV2/SearchV2Trigger.tsxindex fadb6e383cb..7f9516ff658 100644--- a/apps/docs/features/SearchV2/SearchV2Trigger.tsx+++ b/apps/docs/features/SearchV2/SearchV2Trigger.tsx@@ -1,18 +1,14 @@'use client'-import { Search } from 'lucide-react'-import { useCallback, useEffect, useState, type ReactNode } from 'react'-import { cn, KeyboardShortcut } from 'ui'+import { SearchTrigger, useSearchShortcut, type SearchTriggerProps } from 'docs-search/components'+import { useCallback, useState } from 'react'import { SearchV2Dialog } from './SearchV2Dialog'import { useSendTelemetryEvent } from '@/lib/telemetry'-interface SearchV2TriggerProps {- className?: string- placeholder?: ReactNode-}+type SearchV2TriggerProps = Pick<SearchTriggerProps, 'className' | 'placeholder'>-export function SearchV2Trigger({ className, placeholder = 'Search...' }: SearchV2TriggerProps) {+export function SearchV2Trigger({ className, placeholder }: SearchV2TriggerProps) {const [open, setOpen] = useState(false)const sendTelemetryEvent = useSendTelemetryEvent()@@ -26,38 +22,22 @@ export function SearchV2Trigger({ className, placeholder = 'Search...' }: Search[sendTelemetryEvent])- useEffect(() => {- function openOnKeyDown(event: globalThis.KeyboardEvent) {- if (event.key === 'k' && event.metaKey) {- /**- * This two methods prevent, first search V1 dialog to open and second- * browser propietary search commands to be fired, repectively.- */- event.stopImmediatePropagation()- event.preventDefault()-- setOpen(true)- sendTelemetryEvent({- action: 'docs_search_v2_opened',- properties: { triggerType: 'keyboard_shortcut' },- })- }- }-- window.addEventListener('keydown', openOnKeyDown, { capture: true })-- return () => {- window.removeEventListener('keydown', openOnKeyDown, { capture: true })- }+ const handleShortcut = useCallback(() => {+ setOpen(true)+ sendTelemetryEvent({+ action: 'docs_search_v2_opened',+ properties: { triggerType: 'keyboard_shortcut' },+ })}, [sendTelemetryEvent])+ useSearchShortcut(handleShortcut)+return (<>- <button- type="button"- tabIndex={0}- aria-haspopup="dialog"- aria-expanded={open}+ <SearchTrigger+ className={className}+ placeholder={placeholder}+ expanded={open}onClick={() => {setOpen(true)sendTelemetryEvent({@@ -65,24 +45,7 @@ export function SearchV2Trigger({ className, placeholder = 'Search...' }: Searchproperties: { triggerType: 'search_input' },})}}- className={cn(- 'cursor-pointer',- 'grow md:min-w-44 xl:min-w-56 h-[30px] rounded-md',- 'pl-2 pr-1',- 'flex items-center justify-between',- 'border border-default bg-surface-75 text-foreground-lighter shadow-(--shadow-codeblock)',- 'hover:border-strong hover:text-foreground-light',- 'focus-ring',- 'transition-colors',- className- )}- >- <div className="flex items-center gap-2">- <Search aria-hidden className="size-4 shrink-0" strokeWidth={2.25} />- <p className="flex pr-2 text-sm">{placeholder}</p>- </div>- <KeyboardShortcut keys={['Meta', 'k']} aria-hidden className="hidden md:inline-flex" />- </button>+ /><SearchV2Dialog open={open} onOpenChange={handleOpenChange} /></>)diff --git a/apps/docs/features/SearchV2/constants.ts b/apps/docs/features/SearchV2/constants.tsindex e934ed44244..1b03f68a844 100644--- a/apps/docs/features/SearchV2/constants.ts+++ b/apps/docs/features/SearchV2/constants.ts@@ -1,4 +1,9 @@+import { BASE_PATH } from '@/lib/constants'+// PostHog multivariate flag, already configured on staging.export const SEARCH_V2_FLAG = 'docs-search-v2'export type SearchV2Variant = 'control' | 'search-v2-active'++// fetch doesn't add Next's basePath, so the route is called with it+export const SEARCH_V2_ENDPOINT = `${BASE_PATH}/api/search_v2`diff --git a/apps/docs/next.config.mjs b/apps/docs/next.config.mjsindex 41470a1a4a8..7618501e7e7 100644--- a/apps/docs/next.config.mjs+++ b/apps/docs/next.config.mjs@@ -56,6 +56,7 @@ const nextConfig = {'ui','ui-patterns','common',+ 'docs-search','dayjs','shared-data','api-types',diff --git a/apps/docs/styles/globals.css b/apps/docs/styles/globals.cssindex d933c406ab6..6386fd016a6 100644--- a/apps/docs/styles/globals.css+++ b/apps/docs/styles/globals.css@@ -3,8 +3,7 @@@import 'ui-patterns/CodeBlock/code-block.css';@import './code-block.css';@import './reference.css';-@import './loading-beam.css';-@import './scroll-fade.css';+@import 'docs-search/styles.css';@source '../app/**/*.{ts,tsx,mdx}';@source '../components/**/*.tsx';@@ -15,6 +14,7 @@@source '../pages/**/*.{tsx,mdx}';@source './../../../packages/ui/src/**/*.{tsx,ts,js}';@source './../../../packages/ui-patterns/src/**/*.{tsx,ts,js}';+@source './../../../packages/docs-search/src/**/*.{tsx,ts}';@theme inline {--font-sans:diff --git a/apps/kb/.env.example b/apps/kb/.env.exampleindex b1f225fb6b5..7b82f3c5543 100644--- a/apps/kb/.env.example+++ b/apps/kb/.env.example@@ -19,3 +19,8 @@ GH_TOKEN=# expose it to client code.SUPABASE_URL=SUPABASE_SERVICE_ROLE_KEY=++# Dev only: where the search dialog calls api/search. It's a Vercel function, which `astro dev`+# doesn't serve, so point this at a deployed instance, e.g. https://supabase.com/kb/api/search.+# Ignored in production and preview builds, which use the site's own /kb/api/search.+PUBLIC_KB_SEARCH_URL=diff --git a/apps/kb/api/search/_types.ts b/apps/kb/api/search/_types.tsindex 07c11e69d34..784b616a13a 100644--- a/apps/kb/api/search/_types.ts+++ b/apps/kb/api/search/_types.ts@@ -12,6 +12,7 @@ export interface KbSearchResult {title: stringhref: stringheading: string+ headingPath: string[]excerpt: stringscore: numbercontent?: string | nulldiff --git a/apps/kb/api/search/index.ts b/apps/kb/api/search/index.tsindex ed69f13551c..82941566b71 100644--- a/apps/kb/api/search/index.ts+++ b/apps/kb/api/search/index.ts@@ -54,8 +54,10 @@ export async function GET(request: Request) {let results: KbSearchResult[] = data.map((row) => ({title: row.page_title,- href: `https://supabase.com/${row.slug.toLowerCase()}`,+ // slugs keep the case of the content file, same as the pages and their markdown exports+ href: `https://supabase.com/${row.slug}`,heading: row.heading,+ headingPath: row.heading_path,excerpt: row.excerpt,score: row.score,}))diff --git a/apps/kb/scripts/search/ingest.ts b/apps/kb/scripts/search/ingest.tsindex 79bb958d2e8..5f4cda5247c 100644--- a/apps/kb/scripts/search/ingest.ts+++ b/apps/kb/scripts/search/ingest.ts@@ -19,6 +19,8 @@ ingestMarkdown({table: TABLE_NAME,contentRoot: path.resolve(process.cwd(), 'public/markdown'),include: ['**/*.md'],+ // listing pages (the sitemap and one per topic) only link to the content that's already indexed+ ignore: ['sitemap.md', 'topics/**'],slugPrefix: 'kb/',}).catch((err) => {console.error(err instanceof Error ? err.message : err)diff --git a/apps/kb/src/components/GuideSearchDialog.tsx b/apps/kb/src/components/GuideSearchDialog.tsxdeleted file mode 100644index 86b68d9b3f3..00000000000--- a/apps/kb/src/components/GuideSearchDialog.tsx+++ /dev/null@@ -1,75 +0,0 @@-import {- cn,- Command,- CommandEmpty,- CommandInput,- CommandItem,- CommandList,- Dialog,- DialogContent,- DialogTitle,-} from 'ui'--import type { GuideSummary } from '../lib/guides'--export interface GuideSearchDialogProps {- guides: GuideSummary[]- isOpen: boolean- onOpenChange: (isOpen: boolean) => void-}--interface GuideResultProps {- guide: GuideSummary- onGuideSelect: (href: string) => void-}--export const GuideSearchDialog = ({ guides, isOpen, onOpenChange }: GuideSearchDialogProps) => {- const handleGuideSelect = (href: string) => window.location.assign(href)-- return (- <Dialog open={isOpen} onOpenChange={onOpenChange}>- <DialogContent- hideClose- centered={false}- aria-describedby={undefined}- className="mx-auto overflow-hidden p-0 shadow-raised"- >- <DialogTitle className="sr-only">Search guides</DialogTitle>- <Command- className={cn(- '**:[[cmdk-input]]:h-12 **:[[cmdk-item]]:px-3 **:[[cmdk-item]]:py-2.5',- '**:[[cmdk-list]]:max-h-[min(420px,60vh)] **:[[cmdk-list]]:overflow-y-auto **:[[cmdk-list]]:p-1.5',- '**:[[cmdk-list]]:box-content **:[[cmdk-list]]:h-(--cmdk-list-height) **:[[cmdk-list]]:transition-[height]',- '**:[[cmdk-list]]:duration-200 **:[[cmdk-list]]:ease-out-strong',- 'motion-reduce:**:[[cmdk-list]]:transition-none'- )}- >- <CommandInput placeholder="Search guides" />- <CommandList>- <CommandEmpty className="px-3 py-6 text-center text-sm text-foreground-lighter">- No guide titles match your search. Try a shorter or different term.- </CommandEmpty>- {guides.map((guide) => (- <GuideResult key={guide.id} guide={guide} onGuideSelect={handleGuideSelect} />- ))}- </CommandList>- </Command>- </DialogContent>- </Dialog>- )-}--const GuideResult = ({ guide, onGuideSelect }: GuideResultProps) => {- const handleSelect = () => onGuideSelect(guide.href)-- return (- <CommandItem- value={guide.title}- onSelect={handleSelect}- className="flex items-center justify-between gap-4 rounded-md text-sm text-foreground"- >- <span className="truncate">{guide.title}</span>- <span className="shrink-0 text-xs text-foreground-lighter">{guide.topics.join(', ')}</span>- </CommandItem>- )-}diff --git a/apps/kb/src/components/Hero.tsx b/apps/kb/src/components/Hero.tsxindex 3bcaecbba1d..7b1d276ab9e 100644--- a/apps/kb/src/components/Hero.tsx+++ b/apps/kb/src/components/Hero.tsx@@ -15,9 +15,9 @@ import type { Topic } from '../lib/topics'import { useQueryVariant } from '../lib/use-query-variant'import { AsciiCanvas, type CanvasSize } from './AsciiCanvas'import { AsciiHoverText } from './AsciiHoverText'-import { GuideSearchDialog } from './GuideSearchDialog'import { HeroGrid } from './HeroGrid'import { InfallText } from './InfallText'+import { KbSearchDialog } from './KbSearchDialog'import { TopicShape } from './TopicShape'import { WarpCanvas } from './WarpCanvas'@@ -53,13 +53,6 @@ export interface HomeHeroProps {className?: string}-interface HeroSearchProps {- guides: GuideSummary[]-}--// hidden for launch. preview with ?search=on, flip the fallback to ship it-const SEARCH_FLAG = ['off', 'on'] as const-const DRAW_OUT = 'motion-safe:animate-draw-out'const FLANK_BOX = cn(@@ -186,9 +179,6 @@ export const Hero = ({}export const HomeHero = ({ guides, className }: HomeHeroProps) => {- const isSearchEnabled =- useQueryVariant({ key: 'search', options: SEARCH_FLAG, fallback: 'off' }) === 'on'-return (<Herotitle="Knowledge base"@@ -196,7 +186,7 @@ export const HomeHero = ({ guides, className }: HomeHeroProps) => {guides={guides}className={className}>- {isSearchEnabled ? <HeroSearch guides={guides} /> : null}+ <HeroSearch /></Hero>)}@@ -272,7 +262,7 @@ const CopyFrame = ({ lines }: CopyFrameProps) =>/>))-const HeroSearch = ({ guides }: HeroSearchProps) => {+const HeroSearch = () => {const [isSearchOpen, setIsSearchOpen] = useState(false)const isMac = useSyncExternalStore(subscribeToNothing, getIsMac, getIsMacOnServer)@@ -308,7 +298,7 @@ const HeroSearch = ({ guides }: HeroSearchProps) => {<span className="flex-1 truncate">Search guides</span><KeyboardShortcut keys={[isMac ? '⌘' : 'Ctrl', 'K']} /></button>- <GuideSearchDialog guides={guides} isOpen={isSearchOpen} onOpenChange={setIsSearchOpen} />+ <KbSearchDialog isOpen={isSearchOpen} onOpenChange={setIsSearchOpen} /></>)}diff --git a/apps/kb/src/components/KbSearchDialog.tsx b/apps/kb/src/components/KbSearchDialog.tsxnew file mode 100644index 00000000000..ba3fd9943b1--- /dev/null+++ b/apps/kb/src/components/KbSearchDialog.tsx@@ -0,0 +1,43 @@+import { useDocsSearchV2 } from 'common/hooks/useDocsSearchV2'+import { SearchDialog, SearchPanel, type SearchLabels } from 'docs-search/components'++import { KB_SEARCH_URL, reshapeKbResult } from '../lib/search'++export interface KbSearchDialogProps {+ isOpen: boolean+ onOpenChange: (isOpen: boolean) => void+}++const LABELS: Partial<SearchLabels> = {+ dialogTitle: 'Search the knowledge base',+ dialogDescription: 'Search guides and troubleshooting articles',+ inputPlaceholder: 'Search guides...',+ inputLabel: 'Search the knowledge base',+ searching: 'Searching the knowledge base…',+ noResults: 'No results found. Try a shorter or different term.',+ error: 'Search failed. Check your connection and try again.',+}++export const KbSearchDialog = ({ isOpen, onOpenChange }: KbSearchDialogProps) => (+ <SearchDialog open={isOpen} onOpenChange={onOpenChange} labels={LABELS}>+ <KbSearchPanel onOpenChange={onOpenChange} />+ </SearchDialog>+)++// mounted only while the dialog is open, so closing it drops the search state+const KbSearchPanel = ({ onOpenChange }: Pick<KbSearchDialogProps, 'onOpenChange'>) => {+ const { searchState, handleDocsSearchDebounced, resetSearch } = useDocsSearchV2({+ endpoint: KB_SEARCH_URL,+ reshape: reshapeKbResult,+ })++ return (+ <SearchPanel+ searchState={searchState}+ labels={LABELS}+ onQueryChange={(query) => (query ? handleDocsSearchDebounced(query) : resetSearch())}+ onResultNavigate={(path) => window.location.assign(path)}+ onResultLinkNavigate={() => onOpenChange(false)}+ />+ )+}diff --git a/apps/kb/src/lib/search.test.ts b/apps/kb/src/lib/search.test.tsnew file mode 100644index 00000000000..dea2e8077d0--- /dev/null+++ b/apps/kb/src/lib/search.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from 'vitest'++import { reshapeKbResult } from './search'++const row = {+ title: 'Migrate from Neon to Supabase',+ href: 'https://supabase.com/kb/guides/migrate-from-neon',+ heading: 'Export your data',+ headingPath: ['Migrate from Neon to Supabase', 'Export your data'],+ excerpt: 'Dump your Neon database',+ score: 0.8,+}++describe('reshapeKbResult', () => {+ it('maps an api/search row to a search result with a site-relative path', () => {+ expect(reshapeKbResult(row)).toEqual({+ path: '/kb/guides/migrate-from-neon',+ title: row.title,+ heading: row.heading,+ excerpt: row.excerpt,+ headingPath: row.headingPath,+ score: 0.8,+ })+ })++ it('keeps the case of the href, so mixed-case articles stay reachable', () => {+ const result = reshapeKbResult({+ ...row,+ href: 'https://supabase.com/kb/troubleshooting/42501--permission-denied-KnozmQ',+ })+ expect(result?.path).toBe('/kb/troubleshooting/42501--permission-denied-KnozmQ')+ })++ it('falls back to the page title when there is no heading path', () => {+ expect(reshapeKbResult({ ...row, headingPath: [] })?.headingPath).toEqual([row.title])+ expect(reshapeKbResult({ ...row, headingPath: undefined })?.headingPath).toEqual([row.title])+ })++ it('drops rows that are not search results', () => {+ expect(reshapeKbResult(null)).toBeNull()+ expect(reshapeKbResult('nope')).toBeNull()+ expect(reshapeKbResult({ title: 'No href' })).toBeNull()+ })+})diff --git a/apps/kb/src/lib/search.ts b/apps/kb/src/lib/search.tsnew file mode 100644index 00000000000..10ef87f2522--- /dev/null+++ b/apps/kb/src/lib/search.ts@@ -0,0 +1,45 @@+import type { DocsSearchV2Result } from 'common/hooks/useDocsSearchV2'++import { BASE_PATH } from './constants'++// api/search is a Vercel function on the same site, so a path works in production and previews.+// `astro dev` doesn't serve it: when developing, point PUBLIC_KB_SEARCH_URL at a deployed+// instance (CORS is open). The override is compiled out of production builds.+export const KB_SEARCH_URL =+ (import.meta.env.DEV && import.meta.env.PUBLIC_KB_SEARCH_URL) || `${BASE_PATH}/api/search`++/**+ * Reshapes one row of `api/search`'s response (`KbSearchResult`) into what the search+ * components render. `path` keeps the base path, since links are plain anchors with no router+ * to add it. Module scope on purpose: the hook restarts its debounce if this changes identity.+ */+export function reshapeKbResult(row: unknown): DocsSearchV2Result | null {+ if (typeof row !== 'object' || row === null) return null+ if (+ !(+ 'href' in row &&+ typeof row.href === 'string' &&+ 'title' in row &&+ 'heading' in row &&+ 'excerpt' in row &&+ 'score' in row+ )+ )+ return null++ const title = row.title as string+ const headingPath =+ 'headingPath' in row && Array.isArray(row.headingPath) && row.headingPath.length > 0+ ? (row.headingPath as string[])+ : [title]++ return {+ // origin is dropped so previews and local runs link to themselves, not to production+ path: new URL(row.href, 'https://supabase.com').pathname,+ title,+ heading: row.heading as string,+ excerpt: row.excerpt as string,+ headingPath,+ score: row.score as number,+ }+}diff --git a/apps/kb/src/styles/globals.css b/apps/kb/src/styles/globals.cssindex d02f024b102..b2f5c9fdcf3 100644--- a/apps/kb/src/styles/globals.css+++ b/apps/kb/src/styles/globals.css@@ -3,12 +3,14 @@@import 'ui-patterns/CodeBlock/code-block.css';@import './utilities.css';@import './keyframes.css';+@import 'docs-search/styles.css';@source '../pages/**/*.astro';@source '../components/**/*.{astro,tsx}';@source '../layouts/**/*.astro';@source './../../../../packages/ui/src/**/*.{tsx,ts,js}';@source './../../../../packages/ui-patterns/src/**/*.{tsx,ts,js}';+@source './../../../../packages/docs-search/src/**/*.{tsx,ts}';/* apps/docs loads Inter/Manrope via next/font, which injects these two* variables as inline styles on <html>. kb loads the same fonts via thediff --git a/packages/common/hooks/useDocsSearchV2.ts b/packages/common/hooks/useDocsSearchV2.tsindex 26af620d52d..89c3b53e7de 100644--- a/packages/common/hooks/useDocsSearchV2.ts+++ b/packages/common/hooks/useDocsSearchV2.ts@@ -5,13 +5,6 @@ import { useCallback, useMemo, useReducer, useRef } from 'react'import { useMountEffect } from './useMountEffect'-// This app's own base path, set only for apps deployed under a path prefix (docs' is '/docs').-const BASE_PATH = process.env.NEXT_PUBLIC_BASE_PATH ?? ''-// Public URL of the docs deployment, which hosts the search API routes.-const DOCS_URL = process.env.NEXT_PUBLIC_DOCS_URL || 'https://supabase.com/docs'-// From inside the docs app itself, call our own routes relatively; from studio/www, call docs directly.-const SEARCH_API_BASE = BASE_PATH === '/docs' ? BASE_PATH : DOCS_URL-interface DocsSearchV2Result {path: stringtitle: string@@ -88,37 +81,50 @@ function reducer(state: SearchState, action: Action): SearchState {}}-const useDocsSearchV2 = () => {+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(`${SEARCH_API_BASE}/api/search_v2?${params}`)- const data = await response.json()- if (!Array.isArray(data)) {- throw new Error(data?.error ?? "didn't get expected results array")+ 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 : '',+ })}- dispatch({- type: 'resultsReturned',- key: localKey,- results: compact(data.map(reshapeResult)),- 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])@@ -144,4 +150,4 @@ const useDocsSearchV2 = () => {}export { useDocsSearchV2 }-export type { DocsSearchV2Result }+export type { DocsSearchV2Result, UseDocsSearchV2Options, SearchState as DocsSearchV2State }diff --git a/packages/docs-search/package.json b/packages/docs-search/package.jsonindex fcd7fe66368..45e16e44e96 100644--- a/packages/docs-search/package.json+++ b/packages/docs-search/package.json@@ -9,23 +9,37 @@"test": "vitest --run"},"dependencies": {+ "common": "workspace:*","fast-glob": "^3.3.3",+ "lucide-react": "catalog:","mdast-util-to-string": "^3.1.1",+ "radix-ui": "catalog:","remark-frontmatter": "^5.0.0","remark-gfm": "^4.0.0","remark-parse": "^11.0.0",+ "ui": "workspace:*","unified": "^11.0.5"},"devDependencies": {+ "@supabase/supabase-js": "catalog:","@types/mdast": "^3.0.0","@types/node": "catalog:",+ "@types/react": "catalog:",+ "@types/react-dom": "catalog:","@typescript/native": "catalog:",+ "cheerio": "^1.0.0-rc.12",+ "react": "catalog:",+ "react-dom": "catalog:","tsconfig": "workspace:*","typescript": "catalog:",- "vitest": "catalog:",- "@supabase/supabase-js": "catalog:"+ "vitest": "catalog:"},"exports": {- "./ingest": "./src/ingest.ts"+ "./ingest": "./src/ingest.ts",+ "./components": "./src/components/index.ts",+ "./styles.css": "./src/styles.css"+ },+ "peerDependencies": {+ "react": "catalog:"}}diff --git a/apps/docs/features/ui/LoadingBeam.tsx b/packages/docs-search/src/components/LoadingBeam.tsxsimilarity index 100%rename from apps/docs/features/ui/LoadingBeam.tsxrename to packages/docs-search/src/components/LoadingBeam.tsxdiff --git a/packages/docs-search/src/components/SearchDialog.tsx b/packages/docs-search/src/components/SearchDialog.tsxnew file mode 100644index 00000000000..71f0d129529--- /dev/null+++ b/packages/docs-search/src/components/SearchDialog.tsx@@ -0,0 +1,41 @@+'use client'++import { VisuallyHidden } from 'radix-ui'+import type { ReactNode } from 'react'+import { Dialog, DialogContent, DialogDescription, DialogTitle } from 'ui'++import { resolveSearchLabels } from './labels'+import type { SearchLabels } from './types'++export interface SearchDialogProps {+ open: boolean+ onOpenChange: (open: boolean) => void+ /** Rendered inside the dialog, which unmounts it on close. Usually a `SearchPanel`. */+ children: ReactNode+ labels?: Partial<Pick<SearchLabels, 'dialogTitle' | 'dialogDescription'>>+}++export function SearchDialog({ open, onOpenChange, children, labels }: SearchDialogProps) {+ const { dialogTitle, dialogDescription } = resolveSearchLabels(labels)++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent+ hideClose+ centered={false}+ dialogOverlayProps={{+ className:+ 'data-closed:animate-out! data-closed:fade-out-0 data-closed:fill-mode-forwards data-closed:duration-150 data-closed:ease-enter pt-20 sm:pt-20',+ }}+ size="large"+ className="overflow-hidden rounded-lg border-0 p-0 inset-ring inset-ring-border shadow-(--shadow-codeblock)!"+ >+ <VisuallyHidden.VisuallyHidden>+ <DialogTitle>{dialogTitle}</DialogTitle>+ <DialogDescription>{dialogDescription}</DialogDescription>+ </VisuallyHidden.VisuallyHidden>+ {children}+ </DialogContent>+ </Dialog>+ )+}diff --git a/packages/docs-search/src/components/SearchFooter.tsx b/packages/docs-search/src/components/SearchFooter.tsxnew file mode 100644index 00000000000..0b0996cd60b--- /dev/null+++ b/packages/docs-search/src/components/SearchFooter.tsx@@ -0,0 +1,30 @@+import { KeyboardShortcut } from 'ui'++import { resolveSearchLabels } from './labels'+import type { SearchLabels } from './types'++export interface SearchFooterProps {+ labels?: Partial<Pick<SearchLabels, 'navigate' | 'open'>>+}++export function SearchFooter({ labels }: SearchFooterProps) {+ const { navigate, open } = resolveSearchLabels(labels)++ return (+ <footer+ aria-hidden+ className="flex items-center justify-end gap-3 border-t px-4 py-2.5 text-xs text-foreground-lighter mx-px max-lg:hidden"+ >+ <span className="flex items-center gap-1.5">+ {navigate}+ <KeyboardShortcut keys={['ArrowUp']} />+ <KeyboardShortcut keys={['ArrowDown']} />+ </span>+ <span className="h-3 w-px bg-border" />+ <span className="flex items-center gap-1.5">+ {open}+ <KeyboardShortcut keys={['Enter']} />+ </span>+ </footer>+ )+}diff --git a/packages/docs-search/src/components/SearchPanel.tsx b/packages/docs-search/src/components/SearchPanel.tsxnew file mode 100644index 00000000000..9a1aae0db82--- /dev/null+++ b/packages/docs-search/src/components/SearchPanel.tsx@@ -0,0 +1,143 @@+'use client'++import { useRef, useState, type KeyboardEvent } from 'react'+import { Command, CommandEmpty, CommandGroup, CommandInput, CommandList } from 'ui'++import { resolveSearchLabels } from './labels'+import { LoadingBeam } from './LoadingBeam'+import { SearchFooter } from './SearchFooter'+import { SearchResultItem } from './SearchResultItem'+import type { SearchLabels, SearchRenderLink, SearchResult, SearchState } from './types'+import { getHighlightQuery, getIsSearching, getVisibleResults } from './utils'++export interface SearchPanelProps {+ searchState: SearchState+ /**+ * Fires on every change of the input. An empty string means the input was cleared+ * (typed away or via the Clear button), so the consumer should reset its search.+ */+ onQueryChange: (query: string) => void+ /** Fires when a result is activated by click or Enter. `query` is the one its results belong to. */+ onResultActivate?: (result: SearchResult, context: { query: string }) => void+ /** Fires when a result is activated from the keyboard, so the consumer has to navigate. */+ onResultNavigate: (path: string) => void+ /** Fires when a result link is about to navigate in this tab (not a new-tab click). */+ onResultLinkNavigate?: () => void+ renderLink?: SearchRenderLink+ labels?: Partial<SearchLabels>+}++export function SearchPanel({+ searchState,+ onQueryChange,+ onResultActivate,+ onResultNavigate,+ onResultLinkNavigate,+ renderLink,+ labels,+}: SearchPanelProps) {+ const copy = resolveSearchLabels(labels)+ const [query, setQuery] = useState('')+ const [isDeleting, setIsDeleting] = useState(false)+ const inputRef = useRef<HTMLInputElement>(null)++ // highlight with the query the visible results belong to, not the one being typed+ const highlightQuery = getHighlightQuery(searchState)+ const results = getVisibleResults(searchState)++ const isListVisible =+ results.length > 0 || searchState.status === 'noResults' || searchState.status === 'error'+ const isSearching = getIsSearching({ searchState, query })++ function handleClear() {+ setQuery('')+ onQueryChange('')+ inputRef.current?.focus()+ }++ // cmdk's root turns enter into "open highlighted result", so keep it on the button.+ // other keys must bubble, or tab never reaches the dialog's focus trap+ function handleClearKeyDown(event: KeyboardEvent<HTMLButtonElement>) {+ if (event.key === 'Enter') event.stopPropagation()+ }++ function handleValueChange(value: string) {+ setIsDeleting(value.length < query.length)+ setQuery(value)+ onQueryChange(value)+ }++ // Announced via the aria-live region below — a sighted user sees the spinner/list update,+ // but a screen reader user gets no equivalent signal unless we say so explicitly. Also covers+ // the result count, which isn't reliably announced by the listbox/option roles alone.+ function getStatusMessage(): string {+ if (searchState.status === 'loading') return copy.searching+ if (searchState.status === 'noResults') return copy.noResults+ if (searchState.status === 'error') return copy.error+ if (results.length > 0) return copy.resultCount(results.length)+ return ''+ }++ return (+ <Command shouldFilter={false} className="bg-transparent">+ <div className="relative flex items-center gap-3 pr-4">+ <CommandInput+ ref={inputRef}+ value={query}+ placeholder={copy.inputPlaceholder}+ aria-label={copy.inputLabel}+ onValueChange={handleValueChange}+ wrapperClassName="flex-1 border-0 pl-3 pr-0 text-foreground-lighter [&_svg]:size-4.5 [&_svg]:stroke-2 [&_svg]:opacity-100"+ className="h-12 pl-2.5 text-base text-foreground placeholder:text-foreground-lighter"+ />+ {query ? (+ <button+ type="button"+ tabIndex={0}+ onClick={handleClear}+ onKeyDown={handleClearKeyDown}+ className="relative -mx-2 shrink-0 cursor-pointer rounded-md px-2 py-1 text-xs text-foreground-lighter transition-colors duration-150 after:absolute after:inset-x-0 after:-inset-y-2 after:content-[''] hover:bg-overlay-hover hover:text-foreground focus-ring"+ >+ {copy.clear}+ </button>+ ) : null}+ <LoadingBeam+ isActive={isSearching}+ direction={isDeleting ? 'backward' : 'forward'}+ className={isListVisible ? '-bottom-px' : undefined}+ />+ </div>+ {/*+ Screen-reader-only status announcement. Focus stays in the input as results come in+ (that's what lets people keep typing), so nothing else here gets read aloud on its+ own — this is what tells a screen reader user a search ran and how many results it found.+ */}+ <div role="status" aria-live="polite" className="sr-only">+ {getStatusMessage()}+ </div>+ <CommandList+ label={copy.resultsLabel}+ className="h-(--cmdk-list-height) max-h-[min(477px,70dvh)] inset-shadow-2xs inset-shadow-border mx-px transition-all duration-150 ease-enter motion-reduce:transition-none scroll-fade-bottom"+ >+ {searchState.status === 'noResults' && <CommandEmpty>{copy.noResults}</CommandEmpty>}+ {searchState.status === 'error' && <CommandEmpty>{copy.error}</CommandEmpty>}+ {results.length > 0 && (+ <CommandGroup className="pt-1.25">+ {results.map((result) => (+ <SearchResultItem+ key={result.path}+ result={result}+ highlightQuery={highlightQuery}+ renderLink={renderLink}+ onActivate={(activated) => onResultActivate?.(activated, { query: highlightQuery })}+ onNavigate={(path) => onResultNavigate(path)}+ onLinkNavigate={() => onResultLinkNavigate?.()}+ />+ ))}+ </CommandGroup>+ )}+ </CommandList>+ {results.length > 0 ? <SearchFooter labels={copy} /> : null}+ </Command>+ )+}diff --git a/packages/docs-search/src/components/SearchResultItem.tsx b/packages/docs-search/src/components/SearchResultItem.tsxnew file mode 100644index 00000000000..a7f50ad0248--- /dev/null+++ b/packages/docs-search/src/components/SearchResultItem.tsx@@ -0,0 +1,75 @@+'use client'++import { useRef, type MouseEvent } from 'react'+import { CommandItem } from 'ui'++import type { SearchRenderLink, SearchResult } from './types'+import { formatHeadingPath, highlightMatches } from './utils'++const renderDefaultLink: SearchRenderLink = (props) => <a {...props} />++export interface SearchResultItemProps {+ result: SearchResult+ highlightQuery: string+ renderLink?: SearchRenderLink+ /** Fires whenever the result is activated, by click or Enter, before anything navigates. */+ onActivate?: (result: SearchResult) => void+ /** Fires when the result was activated from the keyboard, so the consumer has to navigate. */+ onNavigate: (path: string) => void+ /** Fires when the link itself is about to navigate in this tab (not a new-tab click). */+ onLinkNavigate?: () => void+}++export function SearchResultItem({+ result,+ highlightQuery,+ renderLink = renderDefaultLink,+ onActivate,+ onNavigate,+ onLinkNavigate,+}: SearchResultItemProps) {+ // clicks navigate via the link and also fire onSelect, so onSelect only navigates for Enter+ const isPointerSelectRef = useRef(false)++ function handleLinkClick(event: MouseEvent<HTMLAnchorElement>) {+ isPointerSelectRef.current = true+ const isNewTab = event.metaKey || event.ctrlKey || event.shiftKey || event.altKey+ if (!isNewTab) onLinkNavigate?.()+ }++ function handleSelect() {+ onActivate?.(result)+ if (isPointerSelectRef.current) {+ isPointerSelectRef.current = false+ return+ }+ onNavigate(result.path)+ }++ return (+ <CommandItem+ asChild+ value={result.path}+ onSelect={handleSelect}+ className="cursor-pointer rounded-md px-2 py-2"+ >+ {renderLink({+ href: result.path,+ tabIndex: -1,+ onClick: handleLinkClick,+ children: (+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">+ <p className="text-sm leading-5 text-foreground">+ {highlightMatches(formatHeadingPath(result.headingPath), highlightQuery)}+ </p>+ {result.excerpt ? (+ <p className="line-clamp-2 text-pretty text-sm leading-5 text-foreground-lighter">+ {highlightMatches(result.excerpt, highlightQuery)}+ </p>+ ) : null}+ </div>+ ),+ })}+ </CommandItem>+ )+}diff --git a/packages/docs-search/src/components/SearchTrigger.tsx b/packages/docs-search/src/components/SearchTrigger.tsxnew file mode 100644index 00000000000..1be66160d26--- /dev/null+++ b/packages/docs-search/src/components/SearchTrigger.tsx@@ -0,0 +1,47 @@+'use client'++import { Search } from 'lucide-react'+import type { ReactNode } from 'react'+import { cn, KeyboardShortcut } from 'ui'++export interface SearchTriggerProps {+ className?: string+ placeholder?: ReactNode+ /** Whether the dialog this button opens is currently open. */+ expanded?: boolean+ onClick: () => void+}++export function SearchTrigger({+ className,+ placeholder = 'Search...',+ expanded = false,+ onClick,+}: SearchTriggerProps) {+ return (+ <button+ type="button"+ tabIndex={0}+ aria-haspopup="dialog"+ aria-expanded={expanded}+ onClick={onClick}+ className={cn(+ 'cursor-pointer',+ 'grow md:min-w-44 xl:min-w-56 h-[30px] rounded-md',+ 'pl-2 pr-1',+ 'flex items-center justify-between',+ 'border border-default bg-surface-75 text-foreground-lighter shadow-(--shadow-codeblock)',+ 'hover:border-strong hover:text-foreground-light',+ 'focus-ring',+ 'transition-colors',+ className+ )}+ >+ <div className="flex items-center gap-2">+ <Search aria-hidden className="size-4 shrink-0" strokeWidth={2.25} />+ <p className="flex pr-2 text-sm">{placeholder}</p>+ </div>+ <KeyboardShortcut keys={['Meta', 'k']} aria-hidden className="hidden md:inline-flex" />+ </button>+ )+}diff --git a/packages/docs-search/src/components/index.ts b/packages/docs-search/src/components/index.tsnew file mode 100644index 00000000000..a4880743de2--- /dev/null+++ b/packages/docs-search/src/components/index.ts@@ -0,0 +1,22 @@+export { LoadingBeam, type LoadingBeamProps } from './LoadingBeam'+export { DEFAULT_SEARCH_LABELS } from './labels'+export { SearchDialog, type SearchDialogProps } from './SearchDialog'+export { SearchFooter, type SearchFooterProps } from './SearchFooter'+export { SearchPanel, type SearchPanelProps } from './SearchPanel'+export { SearchResultItem, type SearchResultItemProps } from './SearchResultItem'+export { SearchTrigger, type SearchTriggerProps } from './SearchTrigger'+export type {+ SearchLabels,+ SearchLinkProps,+ SearchRenderLink,+ SearchResult,+ SearchState,+} from './types'+export { useSearchShortcut } from './useSearchShortcut'+export {+ formatHeadingPath,+ getHighlightQuery,+ getIsSearching,+ getVisibleResults,+ highlightMatches,+} from './utils'diff --git a/packages/docs-search/src/components/labels.ts b/packages/docs-search/src/components/labels.tsnew file mode 100644index 00000000000..e83c7c957b7--- /dev/null+++ b/packages/docs-search/src/components/labels.ts@@ -0,0 +1,20 @@+import type { SearchLabels } from './types'++export const DEFAULT_SEARCH_LABELS: SearchLabels = {+ dialogTitle: 'Search docs',+ dialogDescription: 'Search the Supabase documentation',+ inputPlaceholder: 'Search docs...',+ inputLabel: 'Search the Supabase documentation',+ resultsLabel: 'Search results',+ clear: 'Clear',+ searching: 'Searching the docs…',+ noResults: 'No results found.',+ error: 'Something went wrong. Please try again.',+ resultCount: (count) => `${count} result${count === 1 ? '' : 's'} found.`,+ navigate: 'Navigate',+ open: 'Open',+}++export function resolveSearchLabels(labels?: Partial<SearchLabels>): SearchLabels {+ return { ...DEFAULT_SEARCH_LABELS, ...labels }+}diff --git a/packages/docs-search/src/components/types.ts b/packages/docs-search/src/components/types.tsnew file mode 100644index 00000000000..9927c00ac8d--- /dev/null+++ b/packages/docs-search/src/components/types.ts@@ -0,0 +1,35 @@+import type { AnchorHTMLAttributes, ReactElement } from 'react'++// The search data shapes belong to the hook that produces them, so they're re-exported+// from there instead of redefined. Type-only: this package never imports `common` at runtime.+export type {+ DocsSearchV2Result as SearchResult,+ DocsSearchV2State as SearchState,+} from 'common/hooks/useDocsSearchV2'++export interface SearchLinkProps extends AnchorHTMLAttributes<HTMLAnchorElement> {+ href: string+}++/**+ * Renders the anchor of a result. Defaults to a plain `<a>`; return a framework link+ * (e.g. `next/link`) to get client-side navigation. Must return a single element, which+ * receives the result's props, handlers and ref.+ */+export type SearchRenderLink = (props: SearchLinkProps) => ReactElement++/** Every piece of user-facing copy, so the components can be reused outside the docs. */+export interface SearchLabels {+ dialogTitle: string+ dialogDescription: string+ inputPlaceholder: string+ inputLabel: string+ resultsLabel: string+ clear: string+ searching: string+ noResults: string+ error: string+ resultCount: (count: number) => string+ navigate: string+ open: string+}diff --git a/packages/docs-search/src/components/useSearchShortcut.ts b/packages/docs-search/src/components/useSearchShortcut.tsnew file mode 100644index 00000000000..d68b32ce50c--- /dev/null+++ b/packages/docs-search/src/components/useSearchShortcut.ts@@ -0,0 +1,26 @@+'use client'++import { useEffect } from 'react'++/**+ * Calls `onTrigger` on Cmd+K, ahead of any other handler. It runs in the capture phase and+ * stops propagation, so another search dialog listening for the same shortcut doesn't open+ * too, and `preventDefault` stops the browser's own Cmd+K command.+ */+export function useSearchShortcut(onTrigger: () => void) {+ useEffect(() => {+ function onKeyDown(event: KeyboardEvent) {+ if (event.key === 'k' && event.metaKey) {+ event.stopImmediatePropagation()+ event.preventDefault()+ onTrigger()+ }+ }++ window.addEventListener('keydown', onKeyDown, { capture: true })++ return () => {+ window.removeEventListener('keydown', onKeyDown, { capture: true })+ }+ }, [onTrigger])+}diff --git a/apps/docs/features/SearchV2/SearchV2.utils.test.tsx b/packages/docs-search/src/components/utils.test.tsxsimilarity index 54%rename from apps/docs/features/SearchV2/SearchV2.utils.test.tsxrename to packages/docs-search/src/components/utils.test.tsxindex 632dafa905b..021ee8d26a7 100644--- a/apps/docs/features/SearchV2/SearchV2.utils.test.tsx+++ b/packages/docs-search/src/components/utils.test.tsx@@ -2,7 +2,14 @@ import { load } from 'cheerio'import { renderToStaticMarkup } from 'react-dom/server'import { describe, expect, it } from 'vitest'-import { formatHeadingPath, highlightMatches } from './SearchV2.utils'+import type { SearchState } from './types'+import {+ formatHeadingPath,+ getHighlightQuery,+ getIsSearching,+ getVisibleResults,+ highlightMatches,+} from './utils'describe('formatHeadingPath', () => {it('joins multiple headings with " > "', () => {@@ -77,3 +84,67 @@ describe('highlightMatches', () => {expect(result).toBe('The best MCP server')})})++const result = {+ path: '/guides/auth',+ title: 'Auth',+ heading: 'Auth',+ excerpt: '',+ headingPath: ['Auth'],+ score: 1,+}++describe('getVisibleResults / getHighlightQuery', () => {+ it('uses the settled results and query', () => {+ const state: SearchState = { status: 'results', key: 1, results: [result], query: 'auth' }+ expect(getVisibleResults(state)).toEqual([result])+ expect(getHighlightQuery(state)).toBe('auth')+ })++ it('keeps the previous results and query while a new search is loading', () => {+ const state: SearchState = {+ status: 'loading',+ key: 2,+ staleResults: [result],+ staleQuery: 'auth',+ }+ expect(getVisibleResults(state)).toEqual([result])+ expect(getHighlightQuery(state)).toBe('auth')+ })++ it('is empty before the first search and after an error', () => {+ for (const state of [+ { status: 'initial', key: 0 },+ { status: 'error', key: 1, message: 'nope' },+ ] satisfies SearchState[]) {+ expect(getVisibleResults(state)).toEqual([])+ expect(getHighlightQuery(state)).toBe('')+ }+ })+})++describe('getIsSearching', () => {+ it('is on while a request is in flight', () => {+ const state: SearchState = { status: 'loading', key: 1, staleResults: [], staleQuery: '' }+ expect(getIsSearching({ searchState: state, query: 'auth' })).toBe(true)+ })++ it('is off after an error', () => {+ const state: SearchState = { status: 'error', key: 1, message: 'nope' }+ expect(getIsSearching({ searchState: state, query: 'auth' })).toBe(false)+ })++ it('starts on the keystroke, before the request for the typed query is sent', () => {+ const state: SearchState = { status: 'results', key: 1, results: [result], query: 'aut' }+ expect(getIsSearching({ searchState: state, query: 'auth' })).toBe(true)+ })++ it('is off once the typed query has settled', () => {+ const state: SearchState = { status: 'results', key: 1, results: [result], query: 'auth' }+ expect(getIsSearching({ searchState: state, query: ' auth ' })).toBe(false)+ })++ it('is off for an empty query', () => {+ expect(getIsSearching({ searchState: { status: 'initial', key: 0 }, query: ' ' })).toBe(false)+ })+})diff --git a/apps/docs/features/SearchV2/SearchV2.utils.tsx b/packages/docs-search/src/components/utils.tsxsimilarity index 80%rename from apps/docs/features/SearchV2/SearchV2.utils.tsxrename to packages/docs-search/src/components/utils.tsxindex b309ec1f7df..35139a07e7a 100644--- a/apps/docs/features/SearchV2/SearchV2.utils.tsx+++ b/packages/docs-search/src/components/utils.tsx@@ -1,10 +1,9 @@-import type { useDocsSearchV2 } from 'common'import type { ReactNode } from 'react'-type DocsSearchV2State = ReturnType<typeof useDocsSearchV2>['searchState']+import type { SearchResult, SearchState } from './types'interface GetIsSearchingParams {- searchState: DocsSearchV2State+ searchState: SearchStatequery: string}@@ -107,4 +106,18 @@ function getIsSearching({ searchState, query }: GetIsSearchingParams): boolean {return trimmedQuery !== '' && trimmedQuery !== settledQuery}-export { formatHeadingPath, getIsSearching, highlightMatches }+/** The results to show: the settled ones, or the previous ones while a new search is loading. */+function getVisibleResults(searchState: SearchState): SearchResult[] {+ if ('results' in searchState) return searchState.results+ if ('staleResults' in searchState) return searchState.staleResults+ return []+}++/** The query the visible results belong to, not the one being typed. */+function getHighlightQuery(searchState: SearchState): string {+ if ('query' in searchState) return searchState.query+ if ('staleQuery' in searchState) return searchState.staleQuery+ return ''+}++export { formatHeadingPath, getHighlightQuery, getIsSearching, getVisibleResults, highlightMatches }diff --git a/packages/docs-search/src/css-modules.d.ts b/packages/docs-search/src/css-modules.d.tsnew file mode 100644index 00000000000..e0fa3b6f191--- /dev/null+++ b/packages/docs-search/src/css-modules.d.ts@@ -0,0 +1,5 @@+// `ui` is consumed as source and imports CSS modules; this lets it typecheck here.+declare module '*.module.css' {+ const classes: Record<string, string>+ export default classes+}diff --git a/packages/docs-search/src/styles.css b/packages/docs-search/src/styles.cssnew file mode 100644index 00000000000..7e514caff0b--- /dev/null+++ b/packages/docs-search/src/styles.css@@ -0,0 +1,3 @@+/* Styles the search components rely on. Import once from the consuming app's Tailwind entry. */+@import './styles/loading-beam.css';+@import './styles/scroll-fade.css';diff --git a/apps/docs/styles/loading-beam.css b/packages/docs-search/src/styles/loading-beam.csssimilarity index 100%rename from apps/docs/styles/loading-beam.cssrename to packages/docs-search/src/styles/loading-beam.cssdiff --git a/apps/docs/styles/scroll-fade.css b/packages/docs-search/src/styles/scroll-fade.csssimilarity index 100%rename from apps/docs/styles/scroll-fade.cssrename to packages/docs-search/src/styles/scroll-fade.cssdiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 603e618d7aa..b59cc5e854a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -2581,12 +2581,21 @@ importers:packages/docs-search:dependencies:+ common:+ specifier: workspace:*+ version: link:../commonfast-glob:specifier: ^3.3.3version: 3.3.3+ lucide-react:+ specifier: 'catalog:'+ version: 1.55.0(@types/[email protected])([email protected])mdast-util-to-string:specifier: ^3.1.1version: 3.2.0+ radix-ui:+ specifier: 'catalog:'+ version: 1.4.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])remark-frontmatter:specifier: ^5.0.0version: 5.0.0([email protected])@@ -2596,6 +2605,9 @@ importers:remark-parse:specifier: ^11.0.0version: 11.0.0([email protected])+ ui:+ specifier: workspace:*+ version: link:../uiunified:specifier: ^11.0.5version: 11.0.5@@ -2609,9 +2621,24 @@ importers:'@types/node':specifier: 'catalog:'version: 22.13.14+ '@types/react':+ specifier: 'catalog:'+ version: 19.2.14+ '@types/react-dom':+ specifier: 'catalog:'+ version: 19.2.3(@types/[email protected])'@typescript/native':specifier: 'catalog:'version: [email protected]+ cheerio:+ specifier: ^1.0.0-rc.12+ version: 1.2.0+ react:+ specifier: 'catalog:'+ version: 19.2.6+ react-dom:+ specifier: 'catalog:'+ version: 19.2.6([email protected])tsconfig:specifier: workspace:*version: link:../tsconfig