Skip to content

Commit

Permalink
Merge pull request #770 from MTES-MCT/fix/search-bar-click
Browse files Browse the repository at this point in the history
Bug fix: clique sur un résultat de recherche n'a aucun effet pour certains utilisateurs
  • Loading branch information
alexisig authored Dec 2, 2024
2 parents ea4a1fa + 7282464 commit 601ea9f
Showing 1 changed file with 23 additions and 5 deletions.
28 changes: 23 additions & 5 deletions assets/scripts/components/widgets/SearchBar.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -123,6 +123,7 @@ const NoResultsMessage = styled.div`
`;

const SearchBar: React.FC<SearchBarProps> = ({ createUrl, origin }) => {
const searchContainerRef = useRef<HTMLDivElement>(null);
const [query, setQuery] = useState<string>('');
const [isFocused, setIsFocused] = useState<boolean>(false);
const [data, setData] = useState<Territory[] | undefined>(undefined);
Expand All @@ -142,16 +143,32 @@ const SearchBar: React.FC<SearchBarProps> = ({ 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<HTMLInputElement>) => {
const newQuery = event.target.value;
setQuery(newQuery);
};

const handleBlur = () => {
setTimeout(() => {
setQuery('');
setIsFocused(false);
setData(undefined);
if (!isSubmitting) {
setQuery('');
setIsFocused(false);
setData(undefined);
}
}, 150);
};

Expand Down Expand Up @@ -207,7 +224,7 @@ const SearchBar: React.FC<SearchBarProps> = ({ createUrl, origin }) => {
return (
<>
<Overlay $visible={isFocused} />
<SearchContainer>
<SearchContainer ref={searchContainerRef}>
<Icon className="bi bi-search" />
<Input
type="text"
Expand All @@ -228,6 +245,7 @@ const SearchBar: React.FC<SearchBarProps> = ({ createUrl, origin }) => {
<ResultItem
key={territory.source_id}
$disabled={isDisabled}
onMouseDown={(e) => e.preventDefault()}
onClick={() => createDiagnostic(territory.public_key, isDisabled)}
>
<div>
Expand Down

0 comments on commit 601ea9f

Please sign in to comment.