From b214baab3e17d92f784b4f782863deafc5558ee4 Mon Sep 17 00:00:00 2001
From: Armand Philippot <git@armandphilippot.com>
Date: Wed, 18 May 2022 14:27:11 +0200
Subject: chore: close toolbar modals on click/focus outside

---
 src/components/organisms/toolbar/toolbar.tsx | 18 ++++++++++++++++--
 1 file changed, 16 insertions(+), 2 deletions(-)

(limited to 'src/components/organisms/toolbar/toolbar.tsx')

diff --git a/src/components/organisms/toolbar/toolbar.tsx b/src/components/organisms/toolbar/toolbar.tsx
index 6593055..e4188fe 100644
--- a/src/components/organisms/toolbar/toolbar.tsx
+++ b/src/components/organisms/toolbar/toolbar.tsx
@@ -1,4 +1,5 @@
-import { FC, useState } from 'react';
+import useClickOutside from '@utils/hooks/use-click-outside';
+import { FC, useRef, useState } from 'react';
 import MainNav, { type MainNavProps } from '../toolbar/main-nav';
 import Search, { type SearchProps } from '../toolbar/search';
 import Settings from '../toolbar/settings';
@@ -22,8 +23,18 @@ export type ToolbarProps = Pick<SearchProps, 'searchPage'> & {
  */
 const Toolbar: FC<ToolbarProps> = ({ className = '', nav, searchPage }) => {
   const [isNavOpened, setIsNavOpened] = useState<boolean>(false);
-  const [isSettingsOpened, setIsSettingsOpened] = useState<boolean>(false);
   const [isSearchOpened, setIsSearchOpened] = useState<boolean>(false);
+  const [isSettingsOpened, setIsSettingsOpened] = useState<boolean>(false);
+  const mainNavRef = useRef<HTMLDivElement>(null);
+  const searchRef = useRef<HTMLDivElement>(null);
+  const settingsRef = useRef<HTMLDivElement>(null);
+
+  useClickOutside(mainNavRef, () => isNavOpened && setIsNavOpened(false));
+  useClickOutside(searchRef, () => isSearchOpened && setIsSearchOpened(false));
+  useClickOutside(
+    settingsRef,
+    () => isSettingsOpened && setIsSettingsOpened(false)
+  );
 
   return (
     <div className={`${styles.wrapper} ${className}`}>
@@ -32,18 +43,21 @@ const Toolbar: FC<ToolbarProps> = ({ className = '', nav, searchPage }) => {
         isActive={isNavOpened}
         setIsActive={setIsNavOpened}
         className={styles.modal}
+        ref={mainNavRef}
       />
       <Search
         searchPage={searchPage}
         isActive={isSearchOpened}
         setIsActive={setIsSearchOpened}
         className={`${styles.modal} ${styles['modal--search']}`}
+        ref={searchRef}
       />
       <Settings
         isActive={isSettingsOpened}
         setIsActive={setIsSettingsOpened}
         className={`${styles.modal} ${styles['modal--settings']}`}
         tooltipClassName={styles.tooltip}
+        ref={settingsRef}
       />
     </div>
   );
-- 
cgit v1.2.3

