aboutsummaryrefslogtreecommitdiffhomepage
path: root/frontend/src/modules/modals/hooks.ts
blob: 40e891b8ee2d429275c11891642d10ef8c011d38 (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
47
48
49
/* eslint-disable @typescript-eslint/ban-types */
import { useModals as useMantineModals } from "@mantine/modals";
import { ModalSettings } from "@mantine/modals/lib/context";
import { useCallback, useContext, useMemo } from "react";
import { ModalComponent, ModalIdContext } from "./WithModal";

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

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

  const closeContextModal = 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, closeContextModal, closeSelf, ...rest }),
    [closeContextModal, closeSelf, openContextModal, rest],
  );
}