Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(docs): restore search on the documentation site (#8554)
Thinh Le61106b06d2a1
diff --git a/docs/src/components/DocSearch/index.tsx b/docs/src/components/DocSearch/index.tsxnew file mode 100644index 000000000..94406280f--- /dev/null+++ b/docs/src/components/DocSearch/index.tsx@@ -0,0 +1,231 @@+import { useEffect, useMemo, useRef, useState } from 'react'+import { useRouter } from 'next/router'+import { Search as SearchIcon } from 'lucide-react'+import { cn } from '@/lib/utils'+import {+ SEARCH_INDEX_URL,+ searchIndex,+ type Hit,+ type NextraIndex,+} from './searchIndex'++// The index is only emitted by `next build`, so `next dev` has no file to fetch.+// A failed load hides the field entirely rather than leaving a box that silently+// returns nothing.+type IndexState =+ | { status: 'idle' }+ | { status: 'loading' }+ | { status: 'ready'; index: NextraIndex }+ | { status: 'failed' }++let cachedIndex: NextraIndex | null = null++type DocSearchProps = {+ /** `navbar` is the inline desktop field; `panel` is the full-width mobile one. */+ variant?: 'navbar' | 'panel'+ className?: string+ /** Called after a result is picked, so the mobile menu can close itself. */+ onNavigate?: () => void+}++const DocSearch = ({+ variant = 'navbar',+ className,+ onNavigate,+}: DocSearchProps) => {+ const router = useRouter()+ const inputRef = useRef<HTMLInputElement>(null)+ const containerRef = useRef<HTMLDivElement>(null)++ const [state, setState] = useState<IndexState>(+ cachedIndex ? { status: 'ready', index: cachedIndex } : { status: 'idle' }+ )+ const [query, setQuery] = useState('')+ const [open, setOpen] = useState(false)+ const [active, setActive] = useState(0)++ const loadIndex = () => {+ if (state.status !== 'idle') return+ setState({ status: 'loading' })+ fetch(SEARCH_INDEX_URL)+ .then((res) => {+ if (!res.ok) throw new Error(`${res.status}`)+ return res.json()+ })+ .then((index: NextraIndex) => {+ cachedIndex = index+ setState({ status: 'ready', index })+ })+ .catch(() => setState({ status: 'failed' }))+ }++ // Derived, not stored: re-ranks the moment the index lands, so a query typed+ // while it was still downloading doesn't stay stuck on "No results".+ const hits = useMemo<Hit[]>(+ () =>+ state.status === 'ready' && query.trim()+ ? searchIndex(state.index, query)+ : [],+ [state, query]+ )++ useEffect(() => setActive(0), [query])++ // `/` and Cmd/Ctrl+K focus the field from anywhere on the page.+ useEffect(() => {+ const onKeyDown = (e: KeyboardEvent) => {+ const el = document.activeElement+ const tag = el?.tagName.toLowerCase()+ if (+ tag === 'input' ||+ tag === 'textarea' ||+ tag === 'select' ||+ (el as HTMLElement | null)?.isContentEditable+ )+ return+ if (e.key === '/' || (e.key.toLowerCase() === 'k' && (e.metaKey || e.ctrlKey))) {+ e.preventDefault()+ inputRef.current?.focus()+ }+ }+ document.addEventListener('keydown', onKeyDown)+ return () => document.removeEventListener('keydown', onKeyDown)+ }, [])++ useEffect(() => {+ const onPointerDown = (e: MouseEvent) => {+ if (!containerRef.current?.contains(e.target as Node)) setOpen(false)+ }+ document.addEventListener('mousedown', onPointerDown)+ return () => document.removeEventListener('mousedown', onPointerDown)+ }, [])++ const go = (hit: Hit) => {+ setOpen(false)+ setQuery('')+ inputRef.current?.blur()+ onNavigate?.()+ router.push(hit.href)+ }++ const onInputKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {+ if (e.key === 'Escape') {+ setOpen(false)+ inputRef.current?.blur()+ return+ }+ if (!hits.length) return+ if (e.key === 'ArrowDown') {+ e.preventDefault()+ setActive((i) => (i + 1) % hits.length)+ } else if (e.key === 'ArrowUp') {+ e.preventDefault()+ setActive((i) => (i - 1 + hits.length) % hits.length)+ } else if (e.key === 'Enter') {+ e.preventDefault()+ const hit = hits[active]+ if (hit) go(hit)+ }+ }++ if (state.status === 'failed') return null++ const showPanel = open && query.trim().length > 0++ return (+ <div+ ref={containerRef}+ className={cn(+ 'relative',+ variant === 'navbar' ? 'w-56' : 'w-full',+ className+ )}+ >+ <div className="relative flex items-center">+ <SearchIcon className="absolute left-3 size-4 text-gray-400 pointer-events-none" />+ <input+ ref={inputRef}+ type="search"+ value={query}+ spellCheck={false}+ autoComplete="off"+ placeholder="Search docs…"+ aria-label="Search documentation"+ onFocus={() => {+ loadIndex()+ setOpen(true)+ }}+ onChange={(e) => {+ setQuery(e.target.value)+ setOpen(true)+ }}+ onKeyDown={onInputKeyDown}+ className={cn(+ 'w-full rounded-lg border border-gray-200 bg-gray-50 py-2 pl-9 pr-12',+ 'text-sm text-black placeholder:text-gray-400',+ 'transition-colors focus:border-gray-300 focus:bg-white focus:outline-none',+ '[&::-webkit-search-cancel-button]:appearance-none'+ )}+ />+ <kbd className="absolute right-2 hidden rounded border border-gray-200 bg-white px-1.5 py-0.5 text-[10px] font-medium text-gray-400 sm:block">+ ⌘K+ </kbd>+ </div>++ {showPanel && (+ <div+ data-doc-search-results=""+ className={cn(+ 'absolute left-0 z-50 mt-2 max-h-[70vh] overflow-y-auto',+ 'rounded-xl border border-gray-200 bg-white py-2 shadow-xl',+ // Widen past the input, but never past the viewport.+ variant === 'navbar'+ ? 'w-[34rem] max-w-[calc(100vw-3rem)]'+ : 'w-full'+ )}+ >+ {state.status === 'loading' && (+ <p className="px-4 py-3 text-sm text-gray-500">Loading…</p>+ )}++ {state.status === 'ready' && !hits.length && (+ <p className="px-4 py-3 text-sm text-gray-500">+ No results for “{query.trim()}”.+ </p>+ )}++ {hits.map((hit, i) => (+ <button+ key={hit.href}+ type="button"+ onMouseEnter={() => setActive(i)}+ onClick={() => go(hit)}+ className={cn(+ 'block w-full px-4 py-2.5 text-left transition-colors',+ i === active ? 'bg-gray-100' : 'hover:bg-gray-50'+ )}+ >+ <span className="flex items-baseline gap-2">+ <span className="truncate text-sm font-semibold text-black">+ {hit.heading || hit.title}+ </span>+ {hit.heading && (+ <span className="truncate text-xs text-gray-400">+ {hit.title}+ </span>+ )}+ </span>+ {hit.excerpt && (+ <span className="mt-0.5 block line-clamp-2 text-xs leading-snug text-gray-500">+ {hit.excerpt}+ </span>+ )}+ </button>+ ))}+ </div>+ )}+ </div>+ )+}++export default DocSearchdiff --git a/docs/src/components/DocSearch/searchIndex.ts b/docs/src/components/DocSearch/searchIndex.tsnew file mode 100644index 000000000..742f5f158--- /dev/null+++ b/docs/src/components/DocSearch/searchIndex.ts@@ -0,0 +1,112 @@+// Nextra emits a search index at `nextra-data-<locale>.json` during the+// production build. `en-US` is nextra-theme-docs' DEFAULT_LOCALE and this site+// configures no i18n, so that is the only locale ever built.+//+// We read that artifact directly rather than rendering Nextra's own <Search />:+// theme.config.tsx replaces the default navbar with our custom <Navbar />, and+// nextra-theme-docs v2 does not export Search, so there is nothing to mount.+// Scoring 125 routes in plain JS is fast enough that flexsearch buys us nothing.+export const SEARCH_INDEX_URL = '/_next/static/chunks/nextra-data-en-US.json'++// Section keys are `"<anchor>#<Heading>"`, or `""` for the page's own intro.+export type NextraIndex = Record<+ string,+ { title: string; data: Record<string, string> }+>++export type Hit = {+ /** Route with the section anchor already appended. */+ href: string+ /** Page title, always present. */+ title: string+ /** Section heading, empty when the hit is the page intro. */+ heading: string+ excerpt: string+ score: number+}++const EXCERPT_LEN = 140++/** Pull a window of `content` around the earliest matching token. */+function buildExcerpt(content: string, tokens: string[]): string {+ const flat = content.replace(/\s+/g, ' ').trim()+ const lower = flat.toLowerCase()++ let at = -1+ for (const token of tokens) {+ const i = lower.indexOf(token)+ if (i !== -1 && (at === -1 || i < at)) at = i+ }+ if (at === -1) return flat.slice(0, EXCERPT_LEN)++ const start = Math.max(0, at - Math.floor(EXCERPT_LEN / 3))+ const slice = flat.slice(start, start + EXCERPT_LEN)+ return `${start > 0 ? '…' : ''}${slice}${+ start + EXCERPT_LEN < flat.length ? '…' : ''+ }`+}++/**+ * Rank index sections against `query`. Every token must appear somewhere in the+ * section (AND, not OR) so that multi-word queries narrow rather than widen.+ */+export function searchIndex(+ index: NextraIndex,+ query: string,+ limit = 8+): Hit[] {+ const phrase = query.toLowerCase().trim()+ const tokens = phrase.split(/\s+/).filter(Boolean)+ if (!tokens.length) return []++ const hits: Hit[] = []++ for (const [route, page] of Object.entries(index)) {+ const title = page?.title || route+ const lowerTitle = title.toLowerCase()++ for (const [key, rawContent] of Object.entries(page?.data ?? {})) {+ const [anchor, headingText] = key.split('#')+ const heading = headingText ?? ''+ const content = rawContent ?? ''+ const lowerHeading = heading.toLowerCase()+ const lowerContent = content.toLowerCase()++ let score = 0+ let matchesEveryToken = true+ for (const token of tokens) {+ const inTitle = lowerTitle.includes(token)+ const inHeading = lowerHeading.includes(token)+ const inContent = lowerContent.includes(token)+ if (!inTitle && !inHeading && !inContent) {+ matchesEveryToken = false+ break+ }+ score += (inTitle ? 8 : 0) + (inHeading ? 4 : 0) + (inContent ? 1 : 0)+ }+ if (!matchesEveryToken) continue++ // Whole-phrase hits beat scattered-token hits.+ if (lowerTitle.includes(phrase)) score += 12+ if (lowerHeading.includes(phrase)) score += 6+ // The search lives in the docs; keep changelog/blog below reference pages.+ if (route.startsWith('/docs')) score += 3++ hits.push({+ href: anchor ? `${route}#${anchor}` : route,+ title,+ heading,+ excerpt: buildExcerpt(content, tokens),+ score,+ })+ }+ }++ // One entry per anchor already, but a page intro and its first section can+ // collapse onto the same href — keep the best-scoring one.+ const bestByHref = new Map<string, Hit>()+ for (const hit of hits.sort((a, b) => b.score - a.score)) {+ if (!bestByHref.has(hit.href)) bestByHref.set(hit.href, hit)+ }+ return Array.from(bestByHref.values()).slice(0, limit)+}diff --git a/docs/src/components/Navbar.tsx b/docs/src/components/Navbar.tsxindex abe689b22..8686f4d47 100644--- a/docs/src/components/Navbar.tsx+++ b/docs/src/components/Navbar.tsx@@ -6,6 +6,7 @@ import { FaDiscord, FaGithub } from 'react-icons/fa'import { FiDownload } from 'react-icons/fi'import { FaXTwitter, FaLinkedinIn } from 'react-icons/fa6'import { Button } from './ui/button'+import DocSearch from './DocSearch'import LogoJanSVG from '@/assets/icons/logo-jan.svg'const MENU_ITEMS = [@@ -93,6 +94,13 @@ const Navbar = ({ noScroll }: { noScroll?: boolean }) => {</li>)})}+ {/* Landing page keeps the navbar transparent over artwork, where a+ filled input would read as a stray form field. */}+ {!isLanding && (+ <li>+ <DocSearch />+ </li>+ )}<li><ahref="https://github.com/janhq/jan/releases/latest"@@ -227,6 +235,15 @@ const Navbar = ({ noScroll }: { noScroll?: boolean }) => {</button></div>+ {/* Nextra's own sidebar search is unreachable here: our custom+ hamburger drives this modal, not Nextra's sidebar state. */}+ <div className="mb-6">+ <DocSearch+ variant="panel"+ onNavigate={() => setIsMobileMenuOpen(false)}+ />+ </div>+{/* Menu Items */}<nav className="mb-6"><ul className="space-y-4">