|
| 1 | +'use client'; |
| 2 | +import Link from 'next/link'; |
| 3 | +import { useCallback, useRef, useState } from 'react'; |
| 4 | +import { createPortal } from 'react-dom'; |
| 5 | +import { DocSearchModal, useDocSearchKeyboardEvents } from '@docsearch/react'; |
| 6 | +import siteConfig from '~/config/siteConfig'; |
| 7 | +import { Button } from '~/components/ui/button'; |
| 8 | +import '@docsearch/css'; |
| 9 | + |
| 10 | +export default function AlgoliaDocSearch() { |
| 11 | + const [isOpen, setIsOpen] = useState(false); |
| 12 | + const searchButtonRef = useRef<HTMLButtonElement>(null); |
| 13 | + |
| 14 | + const onOpen = useCallback(() => { |
| 15 | + setIsOpen(true); |
| 16 | + }, [setIsOpen]); |
| 17 | + |
| 18 | + const onClose = useCallback(() => { |
| 19 | + setIsOpen(false); |
| 20 | + }, [setIsOpen]); |
| 21 | + |
| 22 | + useDocSearchKeyboardEvents({ |
| 23 | + isOpen, |
| 24 | + onOpen, |
| 25 | + onClose, |
| 26 | + searchButtonRef, |
| 27 | + }); |
| 28 | + |
| 29 | + return ( |
| 30 | + <> |
| 31 | + <Button |
| 32 | + onClick={() => setIsOpen(true)} |
| 33 | + variant="outline" |
| 34 | + className="relative h-8 w-full justify-start rounded-[0.5rem] bg-muted/50 text-sm font-normal text-muted-foreground shadow-none sm:pr-12 md:w-32 lg:w-48 xl:w-56" |
| 35 | + > |
| 36 | + <span className="inline-flex">Try Search</span> |
| 37 | + <kbd className="pointer-events-none absolute right-[0.3rem] top-[0.3rem] hidden h-5 select-none items-center gap-1 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium opacity-100 sm:flex"> |
| 38 | + <span className="text-xs">⌘</span>K |
| 39 | + </kbd> |
| 40 | + </Button> |
| 41 | + {isOpen && |
| 42 | + createPortal( |
| 43 | + <DocSearchModal |
| 44 | + initialScrollY={window.scrollY} |
| 45 | + appId={siteConfig.docSearch.appId} |
| 46 | + apiKey={siteConfig.docSearch.apiKey} |
| 47 | + indexName={siteConfig.docSearch.indexName} |
| 48 | + onClose={onClose} |
| 49 | + placeholder="搜索文章内容" |
| 50 | + hitComponent={({ hit, children }) => <Link href={hit.url}>{children}</Link>} |
| 51 | + />, |
| 52 | + document.body, |
| 53 | + )} |
| 54 | + </> |
| 55 | + ); |
| 56 | +} |
0 commit comments