import { useEffect, useRef } from 'react'; import DSAutocomplete from '@scottish-government/design-system/dist/scripts/components/autocomplete/autocomplete'; import Button from '../Button'; import { SiteSearchProps, SuggestionMappingFunctionProps } from './types'; import clsx from 'clsx'; const SiteSearch = function ({ action = '/search', autocompleteEndpoint, autocompleteSuggestionMappingFunction, className, id = 'site-search', method = 'GET', minLength = 3, name = 'q', placeholder = 'Search', ...props }: SiteSearchProps) { const ref = useRef(null); const hasAutocomplete = !!autocompleteEndpoint; const autocompleteId = hasAutocomplete ? id + '-autocomplete' : ''; type AutoCompleteOptions = { minLength?: number, suggestionMappingFunction?: SuggestionMappingFunctionProps, throttleDelay?: number } useEffect(() => { const autocompleteElement = document.getElementById(autocompleteId); if (hasAutocomplete && autocompleteElement && ref.current) { const options: AutoCompleteOptions = {}; if (minLength) { options.minLength = minLength; } if (autocompleteSuggestionMappingFunction) { options.suggestionMappingFunction = autocompleteSuggestionMappingFunction } const autocomplete = new DSAutocomplete( autocompleteElement, autocompleteEndpoint, options ); autocomplete.init(); } }, [ref, autocompleteEndpoint, autocompleteId, hasAutocomplete, minLength, autocompleteSuggestionMappingFunction]); return (
{hasAutocomplete && (
)}
{hasAutocomplete && (
    )}
    ); }; SiteSearch.displayName = 'SiteSearch'; export default SiteSearch;