import React, { useState, useEffect, useRef } from 'react'; import { useSearch, AnchorLink } from 'dumi/theme'; import './SearchBar.less'; export const highlight = (key: string, title: string) => { const index = title.toLowerCase().indexOf(key.toLowerCase()); const l = key.length; return ( <> {title.substring(0, index)} {title.substring(index, index + l)} {title.substring(index + l, title.length)} > ); }; export default () => { const [keywords, setKeywords] = useState(''); const [items, setItems] = useState([]); const input = useRef(); const result = useSearch(keywords); const emptySvg = ( ); useEffect(() => { if (Array.isArray(result)) { setItems(result); } else if (typeof result === 'function') { result(`.${input.current.className}`); } }, [result]); return ( setKeywords(ev.target.value) } : {})} /> {items.length > 0 && items.map(meta => ( setKeywords('')}> {meta.parent?.title && {meta.parent.title}} {highlight(keywords, meta.title)} ))} {items.length === 0 && keywords && {emptySvg}} ); };