From 8f2b6dfdb8d9e2e02ac29abd91101d1900859041 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Komorowski?= Date: Fri, 7 Apr 2023 11:42:47 +0200 Subject: [PATCH] Added Role Selector close functionality when clicking outside of it (#211) * Added dropdown close functionality when clicking outside. Added an event listener to the document that checks if the user clicks outside the dropdown and closes it if so. This behavior is implemented using a useRef hook and a mousedown event. The cleanup function is also added to remove the event listener when the component unmounts. * Optimized event listener in RoleSelector component for improved performance. Updated event listener for RoleSelector component to only be added when the dropdown is opened and removed when the dropdown is closed. * Removed package-lock.json and yarn.lock * Revert "Removed package-lock.json and yarn.lock" This reverts commit f9dbf056b6003377d5bcf4f3a731afe7324f000b. * Remove yarn.lock, package-lock.json from PR * revert yarn.lock * optimisation * change React.useRef to useRef --------- Co-authored-by: Jing Hua --- .../Chat/ChatContent/Message/RoleSelector.tsx | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/src/components/Chat/ChatContent/Message/RoleSelector.tsx b/src/components/Chat/ChatContent/Message/RoleSelector.tsx index 24b63d9..a5f43cc 100644 --- a/src/components/Chat/ChatContent/Message/RoleSelector.tsx +++ b/src/components/Chat/ChatContent/Message/RoleSelector.tsx @@ -1,4 +1,4 @@ -import React, { useState } from 'react'; +import React, { useState, useEffect, useCallback, useRef } from 'react'; import { useTranslation } from 'react-i18next'; import useStore from '@store/store'; @@ -21,6 +21,28 @@ const RoleSelector = React.memo( const currentChatIndex = useStore((state) => state.currentChatIndex); const [dropDown, setDropDown] = useState(false); + const dropDownRef = useRef(null); + + const handleClickOutside = useCallback( + (event: any) => { + if (dropDownRef.current && !dropDownRef.current.contains(event.target)) + setDropDown(false); + }, + [dropDownRef, setDropDown, messageIndex] + ); + + useEffect(() => { + // Bind the event listener only if the dropdown is open. + if (dropDown) { + document.addEventListener('mousedown', handleClickOutside); + } else { + document.removeEventListener('mousedown', handleClickOutside); + } + + return () => { + document.removeEventListener('mousedown', handleClickOutside); + }; + }, [dropDownRef, dropDown]); return (
@@ -33,6 +55,7 @@ const RoleSelector = React.memo(