diff options
author | 2021-07-29 13:31:41 -0700 | |
---|---|---|
committer | 2021-07-29 13:31:41 -0700 | |
commit | 6eeafac715aaa077f07dd12d0609301a807a0705 (patch) | |
tree | 0e163a45864794fbe2e926a0a85a189bb500f837 /docs/src/components/Search.tsx | |
parent | 908139642a7863ce38e567f791aee1972ab6ec1f (diff) | |
download | astro-6eeafac715aaa077f07dd12d0609301a807a0705.tar.gz astro-6eeafac715aaa077f07dd12d0609301a807a0705.tar.zst astro-6eeafac715aaa077f07dd12d0609301a807a0705.zip |
Add algolia-powered search bar to docs site (#917)
* add search bar
* replace cmd+k with slash hotkey
* update api key
* add localhost support for search
Diffstat (limited to 'docs/src/components/Search.tsx')
-rw-r--r-- | docs/src/components/Search.tsx | 97 |
1 files changed, 97 insertions, 0 deletions
diff --git a/docs/src/components/Search.tsx b/docs/src/components/Search.tsx new file mode 100644 index 000000000..066699fc1 --- /dev/null +++ b/docs/src/components/Search.tsx @@ -0,0 +1,97 @@ +/* jsxImportSource: react */ +import { useState, useCallback, useRef } from 'react' +import { createPortal } from 'react-dom' +import { DocSearchModal, useDocSearchKeyboardEvents } from '@docsearch/react' +import '@docsearch/css//dist/style.css'; +import './Search.css'; + + +export function Search() { + const [isOpen, setIsOpen] = useState(false) + const searchButtonRef = useRef() + const [initialQuery, setInitialQuery] = useState(null) + + const onOpen = useCallback(() => { + setIsOpen(true) + }, [setIsOpen]) + + const onClose = useCallback(() => { + setIsOpen(false) + }, [setIsOpen]) + + const onInput = useCallback( + (e) => { + setIsOpen(true) + setInitialQuery(e.key) + }, + [setIsOpen, setInitialQuery] + ) + + useDocSearchKeyboardEvents({ + isOpen, + onOpen, + onClose, + onInput, + searchButtonRef, + }) + + return ( + <> + <button + type="button" + ref={searchButtonRef} + onClick={onOpen} + className="search-input" + > + <svg + width="24" + height="24" + fill="none" + > + <path + d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" + stroke="currentColor" + strokeWidth="2" + strokeLinecap="round" + strokeLinejoin="round" + /> + </svg> + <span> + Search + </span> + <span + className="search-hint" + > + <span className="sr-only">Press </span> + <kbd>/</kbd> + <span className="sr-only"> to search</span> + </span> + </button> + {isOpen && + createPortal( + <DocSearchModal + initialQuery={initialQuery} + initialScrollY={window.scrollY} + onClose={onClose} + indexName="astro" + apiKey="0f387260ad74f9cbf4353facd29c919c" + transformItems={(items) => { + return items.map((item) => { + // We transform the absolute URL into a relative URL to + // work better on localhost, preview URLS. + const a = document.createElement('a') + a.href = item.url + console.log(a.hash); + const hash = a.hash === '#overview' ? '' : a.hash + return { + ...item, + url: `${a.pathname}${hash}`, + } + }) + }} + />, + document.body + )} + </> + ) +}
\ No newline at end of file |