From 02697408cea626021512a806d72e901c81ba7847 Mon Sep 17 00:00:00 2001 From: "Tindo N. Arsel" Date: Wed, 12 Apr 2023 11:47:32 +0100 Subject: [PATCH] Refact: hide dropdown prompt & palette when clicked outside (#223) * Refact: hide dropdown prompt when clicked outside Added an event listener to hide prompts, when anything other than the dropdown is clicked, implemented via a click event. * Refact: hide palette color when clicked outside Added an event listener to hide palette color, when anything other than the dropdown palette is clicked, implemented via a click event. * Refactor: event listener conditions for dropdown Changed the event listener conditions for mousedown events, so they are only added when dropdown menu or color palette is visible. * shift paletteRef position --------- Co-authored-by: Jing Hua --- .../Message/CommandPrompt/CommandPrompt.tsx | 26 ++++++++++++++++-- src/components/Menu/ChatFolder.tsx | 27 ++++++++++++++++++- 2 files changed, 50 insertions(+), 3 deletions(-) diff --git a/src/components/Chat/ChatContent/Message/CommandPrompt/CommandPrompt.tsx b/src/components/Chat/ChatContent/Message/CommandPrompt/CommandPrompt.tsx index f8af930..47cf653 100644 --- a/src/components/Chat/ChatContent/Message/CommandPrompt/CommandPrompt.tsx +++ b/src/components/Chat/ChatContent/Message/CommandPrompt/CommandPrompt.tsx @@ -1,4 +1,4 @@ -import React, { useEffect, useState } from 'react'; +import React, { useEffect, useRef, useState } from 'react'; import useStore from '@store/store'; import { useTranslation } from 'react-i18next'; import { matchSorter } from 'match-sorter'; @@ -14,6 +14,7 @@ const CommandPrompt = ({ const [dropDown, setDropDown] = useState(false); const [_prompts, _setPrompts] = useState(prompts); const [input, setInput] = useState(''); + const dropdownRef = useRef(null); useEffect(() => { const filteredPrompts = matchSorter(useStore.getState().prompts, input, { @@ -27,8 +28,29 @@ const CommandPrompt = ({ setInput(''); }, [prompts]); + useEffect(() => { + const handleClickOutside = (event: MouseEvent) => { + if ( + dropdownRef.current && + !dropdownRef.current.contains(event.target as Node) + ) { + setDropDown(false); + } + }; + + if (dropDown) { + document.addEventListener('mousedown', handleClickOutside); + } else { + document.removeEventListener('mousedown', handleClickOutside); + } + + return () => { + document.removeEventListener('mousedown', handleClickOutside); + }; + }, [dropdownRef, dropDown]); + return ( -
+