aboutsummaryrefslogtreecommitdiffhomepage
path: root/frontend/src/modules/modals/hooks.ts
blob: 667e429d32f9af4a5fa07eb7fbbcc8850992242f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/* eslint-disable @typescript-eslint/ban-types */
import { useCallback, useContext, useMemo } from "react";
import { useModals as useMantineModals } from "@mantine/modals";
import { ModalSettings } from "@mantine/modals/lib/context";
import { ModalComponent, ModalIdContext } from "./WithModal";

export function useModals() {
  const { openContextModal: openMantineContextModal, ...rest } =
    useMantineModals();

  const openContextModal = useCallback(
    <ARGS extends {}>(
      modal: ModalComponent<ARGS>,
      props: ARGS,
      settings?: ModalSettings,
    ) => {
      openMantineContextModal(modal.modalKey, {
        ...modal.settings,
        ...settings,
        innerProps: props,
      });
    },
    [openMantineContextModal],
  );

  const closeContext = useCallback(
    (modal: ModalComponent) => {
      rest.closeModal(modal.modalKey);
    },
    [rest],
  );

  const id = useContext(ModalIdContext);

  const closeSelf = useCallback(() => {
    if (id) {
      rest.closeModal(id);
    }
  }, [id, rest]);

  // TODO: Performance
  return useMemo(
    () => ({ openContextModal, closeContext, closeSelf, ...rest }),
    [closeContext, closeSelf, openContextModal, rest],
  );
}