xref: /MusicFree/src/components/panels/usePanel.ts (revision 378a6099e3563e7a689fac0fd988de338a1d1de8)
1*378a6099S猫头猫import { BottomSheetMethods } from '@gorhom/bottom-sheet/lib/typescript/types';
2*378a6099S猫头猫import {atom, useAtom} from 'jotai';
3*378a6099S猫头猫import {MutableRefObject, useEffect, useRef} from 'react';
4*378a6099S猫头猫import {BackHandler, NativeEventSubscription} from 'react-native';
5*378a6099S猫头猫import panels from './types';
6*378a6099S猫头猫
7*378a6099S猫头猫type IPanel = typeof panels;
8*378a6099S猫头猫type IPanelkeys = keyof IPanel;
9*378a6099S猫头猫
10*378a6099S猫头猫const panelNameAtom = atom<IPanelkeys | null>(null);
11*378a6099S猫头猫const payloadAtom = atom<any>(null);
12*378a6099S猫头猫
13*378a6099S猫头猫export function _usePanel(ref?: MutableRefObject<BottomSheetMethods | undefined | null>) {
14*378a6099S猫头猫  const [panelName, setPanelName] = useAtom(panelNameAtom);
15*378a6099S猫头猫  const [payload, setPayload] = useAtom(payloadAtom);
16*378a6099S猫头猫  const backHandlerRef = useRef<NativeEventSubscription>();
17*378a6099S猫头猫
18*378a6099S猫头猫  function showPanel<T extends IPanelkeys>(
19*378a6099S猫头猫    name: T,
20*378a6099S猫头猫    payload?: Parameters<IPanel[T]>[0],
21*378a6099S猫头猫  ) {
22*378a6099S猫头猫    setPanelName(name);
23*378a6099S猫头猫    setPayload(payload);
24*378a6099S猫头猫  }
25*378a6099S猫头猫
26*378a6099S猫头猫  useEffect(() => {
27*378a6099S猫头猫    if (backHandlerRef.current) {
28*378a6099S猫头猫      backHandlerRef.current?.remove();
29*378a6099S猫头猫      backHandlerRef.current = undefined;
30*378a6099S猫头猫    }
31*378a6099S猫头猫    if (ref) {
32*378a6099S猫头猫      backHandlerRef.current = BackHandler.addEventListener(
33*378a6099S猫头猫        'hardwareBackPress',
34*378a6099S猫头猫        () => {
35*378a6099S猫头猫          ref.current?.close();
36*378a6099S猫头猫          return true;
37*378a6099S猫头猫        },
38*378a6099S猫头猫      );
39*378a6099S猫头猫    }
40*378a6099S猫头猫    return () => {
41*378a6099S猫头猫      if (backHandlerRef.current) {
42*378a6099S猫头猫        backHandlerRef.current?.remove();
43*378a6099S猫头猫        backHandlerRef.current = undefined;
44*378a6099S猫头猫      }
45*378a6099S猫头猫    };
46*378a6099S猫头猫  }, []);
47*378a6099S猫头猫
48*378a6099S猫头猫  function unmountPanel() {
49*378a6099S猫头猫    setPanelName(null);
50*378a6099S猫头猫    setPayload(null);
51*378a6099S猫头猫  }
52*378a6099S猫头猫
53*378a6099S猫头猫  return {payload, panelName, showPanel, unmountPanel};
54*378a6099S猫头猫}
55*378a6099S猫头猫
56*378a6099S猫头猫export default function usePanel() {
57*378a6099S猫头猫  const {showPanel, unmountPanel} = _usePanel();
58*378a6099S猫头猫  return {showPanel, unmountPanel};
59*378a6099S猫头猫}
60