From a84b2f9f2f64b1d434c5adbb12af6f7d76ba42ea Mon Sep 17 00:00:00 2001
From: Paul Frazee <pfrazee@gmail.com>
Date: Thu, 16 Nov 2023 08:18:59 -0800
Subject: Close active elems (react-query refactor) (#1926)

* Refactor closeAny and closeAllActiveElements

* Add close lightbox

* Switch to hooks

* Fixes
---
 src/state/modals/index.tsx | 30 ++++++++++++++++++++++++------
 1 file changed, 24 insertions(+), 6 deletions(-)

(limited to 'src/state/modals/index.tsx')

diff --git a/src/state/modals/index.tsx b/src/state/modals/index.tsx
index 9dd3e4195..fa86aaa31 100644
--- a/src/state/modals/index.tsx
+++ b/src/state/modals/index.tsx
@@ -213,10 +213,12 @@ const ModalContext = React.createContext<{
 
 const ModalControlContext = React.createContext<{
   openModal: (modal: Modal) => void
-  closeModal: () => void
+  closeModal: () => boolean
+  closeAllModals: () => void
 }>({
   openModal: () => {},
-  closeModal: () => {},
+  closeModal: () => false,
+  closeAllModals: () => {},
 })
 
 /**
@@ -226,6 +228,13 @@ export let unstable__openModal: (modal: Modal) => void = () => {
   throw new Error(`ModalContext is not initialized`)
 }
 
+/**
+ * @deprecated DO NOT USE THIS unless you have no other choice.
+ */
+export let unstable__closeModal: () => boolean = () => {
+  throw new Error(`ModalContext is not initialized`)
+}
+
 export function Provider({children}: React.PropsWithChildren<{}>) {
   const [isModalActive, setIsModalActive] = React.useState(false)
   const [activeModals, setActiveModals] = React.useState<Modal[]>([])
@@ -238,17 +247,25 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
     [setIsModalActive, setActiveModals],
   )
 
-  unstable__openModal = openModal
-
   const closeModal = React.useCallback(() => {
     let totalActiveModals = 0
+    let wasActive = isModalActive
     setActiveModals(activeModals => {
       activeModals = activeModals.slice(0, -1)
       totalActiveModals = activeModals.length
       return activeModals
     })
     setIsModalActive(totalActiveModals > 0)
-  }, [setIsModalActive, setActiveModals])
+    return wasActive
+  }, [setIsModalActive, setActiveModals, isModalActive])
+
+  const closeAllModals = React.useCallback(() => {
+    setActiveModals([])
+    setIsModalActive(false)
+  }, [setActiveModals, setIsModalActive])
+
+  unstable__openModal = openModal
+  unstable__closeModal = closeModal
 
   const state = React.useMemo(
     () => ({
@@ -262,8 +279,9 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
     () => ({
       openModal,
       closeModal,
+      closeAllModals,
     }),
-    [openModal, closeModal],
+    [openModal, closeModal, closeAllModals],
   )
 
   return (
-- 
cgit 1.4.1

