import React, { FC, useCallback, useEffect, useRef, useState } from 'react' import { createUseStyles } from 'react-jss' import { QuickSearchSection, QuickSearchLink, QuickSearchResult } from '../../quick-search.types' import { ResultsSection } from '../results-section/ResultsSection' import { v4 as uuid } from 'uuid' import { matchSorter } from 'match-sorter' import { LoadingOverlay } from '../loading-overlay/LoadingOverlay' import { InlineLoading } from '../inline-loading/InlineLoading' import { AdditionalLinksSection } from '../additional-links-section/AdditionalLinksSection' import { OptionButtonContext } from '../option-button/OptionButton' export type QuickSearchMenuContentsProps = { searchQuery: string sections: QuickSearchSection[] maxResultsPerSection?: number additionalLinks?: QuickSearchLink[] debounceTime?: number onSelectResult: (section: QuickSearchSection, result: QuickSearchResult) => void onShowMore: (section: QuickSearchSection, searchQuery: string) => void onSelectAdditionalLink: (link: QuickSearchLink) => void } export const QuickSearchMenuContents: FC = ({ searchQuery, sections, maxResultsPerSection, debounceTime = 300, additionalLinks, onSelectResult, onShowMore, onSelectAdditionalLink, }) => { // TODO: // - set max height for scrolling based on window // styles const styles = useStyles() // state const [loadingResults, setLoadingResults] = useState(false) const [sectionsWithResults, setSectionsWithResults] = useState<{ section: QuickSearchSection baseSelectionIndex: number results: QuickSearchResult[] }[]>() const [selectionIndex, setSelectionIndex] = useState() // refs const searchIdRef = useRef(uuid()) const containerRef = useRef(null) // constants const lastSection = sectionsWithResults ? sectionsWithResults[sectionsWithResults.length - 1] : undefined const footerBaseSelectionIndex = lastSection ? lastSection.baseSelectionIndex + lastSection.results.length + 1 : undefined const lastSelectionIndex = (footerBaseSelectionIndex ?? 0) + (additionalLinks?.length ?? 0) - 1 const totalResultCount = sectionsWithResults?.reduce((previousValue, section) => previousValue += section.results.length, 0) ?? 0 // event handlers const handleSearch = useCallback(async (searchId: string, searchQuery: string) => { if (!searchQuery) { setSectionsWithResults([]) setLoadingResults(false) return } const newSectionsWithResults = await Promise.all(sections.map(async section => { const sectionResults = await section.resolveResults(searchQuery) const sortedResults = matchSorter(sectionResults, searchQuery.trim(), { keys: ['label'], baseSort: (a, b) => sectionResults.indexOf(a.item) - sectionResults.indexOf(b.item) }).slice(0, section.maxResults ?? maxResultsPerSection) return { section, results: sortedResults, } })) let totalResultsCount = 0 let sectionsWithResultsCount = 0 const newSectionsWithResultsAndSelectionIndices = newSectionsWithResults.map(({ section, results }) => { const baseSelectionIndex = totalResultsCount + sectionsWithResultsCount; totalResultsCount += results.length if (results.length > 0) { sectionsWithResultsCount += 1 } return { section, results, baseSelectionIndex, } }) if (searchId !== searchIdRef.current) return setSectionsWithResults(newSectionsWithResultsAndSelectionIndices) setSelectionIndex(0) setLoadingResults(false) }, [maxResultsPerSection, sections]) const handleFocusNextOption = useCallback(() => { setSelectionIndex(oldSelectionIndex => { if (oldSelectionIndex === undefined) return 0 if (oldSelectionIndex + 1 > lastSelectionIndex) return 0 return oldSelectionIndex + 1 }) }, [lastSelectionIndex]) const handleFocusPreviousOption = useCallback(() => { setSelectionIndex(oldSelectionIndex => { if (oldSelectionIndex === undefined) return lastSelectionIndex if (oldSelectionIndex - 1 < 0) return lastSelectionIndex return oldSelectionIndex - 1 }) }, [lastSelectionIndex]) const handleFocusIndex = useCallback((index: number) => { setSelectionIndex(index) }, []) const handleClearSelection = useCallback(() => { setSelectionIndex(undefined) }, []) const handleMouseLeave = useCallback(() => { setSelectionIndex(undefined) }, []) const handleShowMore = useCallback((section: QuickSearchSection) => { onShowMore(section, searchQuery) }, [onShowMore, searchQuery]) // side effects useEffect(() => { setLoadingResults(true) containerRef.current?.scroll({ left: 0, top: 0 }) const timeout = setTimeout(() => { const newSearchId = uuid() searchIdRef.current = newSearchId; handleSearch(newSearchId, searchQuery) }, debounceTime); return () => { clearTimeout(timeout) } // eslint-disable-next-line react-hooks/exhaustive-deps }, [searchQuery]) useEffect(() => { const handleDocumentKeyDown = (event: KeyboardEvent) => { if (event.key === 'ArrowUp') { event.preventDefault() handleFocusPreviousOption() } else if (event.key === 'ArrowDown') { event.preventDefault() handleFocusNextOption() } } document.addEventListener('keydown', handleDocumentKeyDown) return () => { document.removeEventListener('keydown', handleDocumentKeyDown) } }, [handleFocusNextOption, handleFocusPreviousOption]) if (!searchQuery) { return (
Search to see results
) } return (
{sectionsWithResults?.map(({ section, results, baseSelectionIndex }) => ( ))} {!loadingResults && totalResultCount < 1 && (
No results
)} {sectionsWithResults && sectionsWithResults.length > 0 && footerBaseSelectionIndex && additionalLinks && additionalLinks.length > 0 && ( )} {loadingResults && ( sectionsWithResults?.length ? ( Searching... ) : (
Searching...
) )}
) } const useStyles = createUseStyles({ quickSearchMenuContents: { backgroundColor: 'white', boxShadow: '0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23)', borderRadius: 4, display: 'grid', gridAutoFlow: 'row', cursor: 'default', minHeight: 35, minWidth: 275, overflow: 'hidden', overflowY: 'auto', zIndex: 100, position: 'relative', userSelect: 'none', maxHeight: 700, '& mark': { padding: 0, } }, loneItem: { display: 'grid', alignItems: 'center', paddingLeft: 8, }, })