From 72824647f79dcfcf5a0f89207c34a2128527981a Mon Sep 17 00:00:00 2001 From: "Sofian A. Thibaut" Date: Fri, 29 Nov 2024 15:35:06 +0100 Subject: [PATCH] Fix search bar click --- .../scripts/components/widgets/SearchBar.tsx | 28 +++++++++++++++---- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/assets/scripts/components/widgets/SearchBar.tsx b/assets/scripts/components/widgets/SearchBar.tsx index 18ec3dd2f..2af02d8e1 100644 --- a/assets/scripts/components/widgets/SearchBar.tsx +++ b/assets/scripts/components/widgets/SearchBar.tsx @@ -1,4 +1,4 @@ -import React, { useEffect, ChangeEvent, useState } from 'react'; +import React, { useEffect, ChangeEvent, useState, useRef } from 'react'; import styled from 'styled-components'; import { useSearchTerritoryQuery } from '@services/api'; import useDebounce from '@hooks/useDebounce'; @@ -123,6 +123,7 @@ const NoResultsMessage = styled.div` `; const SearchBar: React.FC = ({ createUrl, origin }) => { + const searchContainerRef = useRef(null); const [query, setQuery] = useState(''); const [isFocused, setIsFocused] = useState(false); const [data, setData] = useState(undefined); @@ -142,6 +143,20 @@ const SearchBar: React.FC = ({ createUrl, origin }) => { } }, [isFetching, queryData, debouncedQuery, shouldQueryBeSkipped]); + useEffect(() => { + const handleClickOutside = (event: MouseEvent) => { + if (searchContainerRef.current && !searchContainerRef.current.contains(event.target as Node)) { + setIsFocused(false); + setData(undefined); + } + }; + + document.addEventListener('mousedown', handleClickOutside); + return () => { + document.removeEventListener('mousedown', handleClickOutside); + }; + }, []); + const handleInputChange = (event: ChangeEvent) => { const newQuery = event.target.value; setQuery(newQuery); @@ -149,9 +164,11 @@ const SearchBar: React.FC = ({ createUrl, origin }) => { const handleBlur = () => { setTimeout(() => { - setQuery(''); - setIsFocused(false); - setData(undefined); + if (!isSubmitting) { + setQuery(''); + setIsFocused(false); + setData(undefined); + } }, 150); }; @@ -207,7 +224,7 @@ const SearchBar: React.FC = ({ createUrl, origin }) => { return ( <> - + = ({ createUrl, origin }) => { e.preventDefault()} onClick={() => createDiagnostic(territory.public_key, isDisabled)} >