diff options
author | 2021-08-26 15:04:19 -0700 | |
---|---|---|
committer | 2021-08-26 15:04:44 -0700 | |
commit | fdd701dd88529ee0d4911283e35be86b000ed1fc (patch) | |
tree | 61d450d04633eece1c12b350b9ef3512dc2fa7b7 /examples/docs/src/components/Header/Search.tsx | |
parent | 84c18d3030c98b2770144a8a27d1cca7bbfedc1d (diff) | |
parent | 2e8db7ad2384b756894eac6be72bcf720f7f28fa (diff) | |
download | astro-fdd701dd88529ee0d4911283e35be86b000ed1fc.tar.gz astro-fdd701dd88529ee0d4911283e35be86b000ed1fc.tar.zst astro-fdd701dd88529ee0d4911283e35be86b000ed1fc.zip |
Merge branch 'okikio/main' (#1111)
Diffstat (limited to 'examples/docs/src/components/Header/Search.tsx')
-rw-r--r-- | examples/docs/src/components/Header/Search.tsx | 77 |
1 files changed, 77 insertions, 0 deletions
diff --git a/examples/docs/src/components/Header/Search.tsx b/examples/docs/src/components/Header/Search.tsx new file mode 100644 index 000000000..19ee513f1 --- /dev/null +++ b/examples/docs/src/components/Header/Search.tsx @@ -0,0 +1,77 @@ +/* jsxImportSource: react */ +import { useState, useCallback, useRef } from 'react'; +import { createPortal } from 'react-dom'; +import { DocSearchModal, useDocSearchKeyboardEvents } from '@docsearch/react'; +import * as CONFIG from '../../config.js'; +import '@docsearch/css/dist/style.css'; +import './Search.css'; + +export default 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={(CONFIG as any).ALGOLIA.indexName} + apiKey={(CONFIG as any).ALGOLIA.apiKey} + 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; + const hash = a.hash === '#overview' ? '' : a.hash; + return { + ...item, + url: `${a.pathname}${hash}`, + }; + }); + }} + />, + document.body + )} + </> + ); +} |