import React from 'react';
import { Animated, View } from 'react-native';
import { ShadowedView, shadowStyle } from 'react-native-fast-shadow';
import { Color, SemanticColor, Typo } from '../../foundation';
import { isNotEmpty } from '../../internal/utils/functions';
import { Spacer } from '../../internal/utilComponents/Spacer';
import { Button } from '../button/Button';
import { ConfirmResult } from './ConfirmResult';
const AnimatedShadowedView = Animated.createAnimatedComponent(ShadowedView);
type BaseProps = {
title: string;
description?: string;
confirmBtn: {
text: string;
onPress?: () => void;
};
cancelOnBackdropPress?: boolean;
/**
* @deprecated 이 prop은 외부에서 모달을 닫는 함수를 주입받아 사용합니다. 직접 사용할 수 없습니다.
*/
hide?: (v: ConfirmResult) => void;
};
type OneButtonTypeProps = BaseProps & {
type?: 'one_button';
cancelBtn?: {
text: string;
onPress?: () => void;
};
onBackdropPress?: () => void;
onBackButtonPress?: () => void;
};
type TwoButtonTypeProps = BaseProps & {
type: 'two_button_horizontal' | 'two_button_vertical';
cancelBtn: {
text: string;
onPress?: () => void;
};
state?: 'default' | 'danger';
};
type Props = OneButtonTypeProps | TwoButtonTypeProps;
export type ConfirmModalHandle = { hide: (v: ConfirmResult) => void };
type AnimatedProps = {
/**
* @deprecated 이 prop은 외부에서 모달을 닫는 함수를 주입받아 사용합니다. 직접 사용할 수 없습니다.
*/
opacity?: Animated.Value;
/**
* @deprecated 이 prop은 외부에서 모달을 닫는 함수를 주입받아 사용합니다. 직접 사용할 수 없습니다.
*/
scale?: Animated.Value;
};
/**
* # ConfirmModal 컴포넌트
*
* ### `type` optional
* - 'one_button', 'two_button_horizontal', 'two_button_vertical'
* - 'two_button_XX' 타입이면 `state`, `cancelBtn` prop 전달
*
* ### `title` (required)
* - 모달 상단의 제목 텍스트
*
* ### `description` (optional)
* - 모달 본문의 설명 텍스트
*
* ### `confirmBtn` (required)
* - 확인 버튼의 속성
* - `text`: 버튼에 표시될 텍스트
* - `onPress`: 버튼 선택 시 실행할 함수
*
* ### `onBackdropPress` optional (for 'one_button')
* - 백그라운드 딤영역 터치시 실행할 함수
*
* ### `onBackButtonPress` optional (for 'one_button')
* - Android 백버튼 눌렀을 때 실행할 함수
*
* ### `cancelBtn` (required for 'two_button_XX')
* - 취소 버튼의 속성
* - `text`: 버튼에 표시될 텍스트
* - `onPress`: 버튼 선택 시 실행할 함수
*
* ### `state` optional (for 'two_button_XX')
* - 'default' | 'danger'
* - 버튼 색상이나 스타일 구분에 사용
*
* ### `cancelOnBackdropPress` optional
* - true일 경우, 백드롭 선택 시 모달이 닫힘
*
* ### `hide` optional
* - 모달을 닫는 함수. 외부에서 주입받아 모달 내부에서 사용
*
* ### opacity, scale optional
* - 애니메이션 효과를 위한 Animated.Value
* - ConfirmModalWrapper 컴포넌트에서 주입받아 사용
*
* @deprecated 이 컴포넌트는 단독으로 사용하지 않습니다. reference를 통해 모달을 닫는 함수를 주입받아 사용합니다.
*
* ConfirmModal 사용법
* 1. `react-native-magic-modal` 패키지 설치
* 2. 프로젝트 상위 파일(App.tsx 또는 Main.tsx)내에, `react-native-magic-modal` 를 import 하고 다음 위치에 선언
* 3. ConfirmModalWrapper 컴포넌트 생성하여 ConfirmModal 컴포넌트를 감싸고, useMagicModalf 훅을 활용해 모달을 닫는 함수를 props로 전달 (아래 예시 참고)
* 4. ConfirmModalService.tsx 파일 생산하여 confirmModal을 노출하는 함수 작성 (아래 예시 참고)
* 5. 사용할 곳에서 ConfirmModalService.tsx 파일의 함수를 import 하여 사용 (아래 예시 참고)
*
* @example
*
* ```tsx
*
* // ConfirmModalWrapper.tsx 예시 (사용법 3번)
* import React, { ComponentProps, forwardRef, useImperativeHandle } from 'react';
* import { useMagicModal } from 'react-native-magic-modal';
* import { ConfirmModal, ConfirmModalHandle } from './ConfirmModal';
*
* type ConfirmModalWrapperProps = ComponentProps & {
* onResolve: (payload: ConfirmResult) => void;
* };
*
* export const ConfirmModalWrapper = forwardRef((props, ref) => {
* const { hide: hideModal } = useMagicModal();
*
* const scale = useRef(new Animated.Value(0.92)).current;
* const opacity = useRef(new Animated.Value(1)).current;
*
* useEffect(() => {
* Animated.spring(scale, {
* toValue: 1,
* friction: 7,
* useNativeDriver: true,
* }).start();
* }, [scale]);
*
* function hide(payload: ConfirmResult) {
* Animated.parallel([
* Animated.timing(opacity, {
* toValue: 0,
* duration: 100,
* useNativeDriver: true,
* }),
* Animated.timing(scale, {
* toValue: 0.92,
* duration: 100,
* easing: Easing.out(Easing.ease),
* useNativeDriver: true,
* }),
* ]).start(() => {
* hideModal();
* props.onResolve(payload);
* });
* }
*
* useImperativeHandle(ref, () => ({
* hide: hideModal,
* }));
*
* return ;
* });
*
*
* // ConfirmModalService.tsx 예시 (사용법 4번)
* import React, { ComponentProps, createRef } from 'react';
* import { magicModal } from 'react-native-magic-modal';
* import { FadeIn, FadeOut } from 'react-native-reanimated';
* import { SemanticColor, ConfirmModal } from '@bravemobile/mobile-ui';
*
* export function showConfirmModal(data: ComponentProps): Promise {
* const modalRef = createRef();
*
* return new Promise((resolve) => {
* return setTimeout(() => {
* magicModal.show( () => , {
* // 스와이프로 닫기 허용 방향 (예: 'down' | 'up' | undefined)
* swipeDirection: undefined,
* entering: FadeIn.duration(200),
* exiting: FadeOut.duration(100),
* // 백드롭 터치 시 호출될 콜백
* onBackdropPress: () => {
* if (data.cancelOnBackdropPress === true) {
* if (isOneButtonType) {
* data.onBackdropPress?.();
* modalRef.current?.hide('postpone');
* } else {
* data.cancelBtn?.onPress?.();
* modalRef.current?.hide('cancel');
* }
* }
* },
* // Android 백버튼 눌렀을 때 호출될 콜백
* onBackButtonPress: () => {
* if (isOneButtonType) {
* data.onBackButtonPress?.();
* modalRef.current?.hide('postpone');
* } else {
* data.cancelBtn?.onPress?.();
* modalRef.current?.hide('cancel');
* }
* },
* });
* }, 0);
* });
* }
*
*
* // ConfirmModalService.tsx 사용 예시 (사용법 5번)
* import { showConfirmModal } from '@services/ConfirmModalService';
*
* // type 'one_button' 예시
* showConfirmModal({
* title: '제목',
* description: '설명 텍스트',
* confirmBtn: {
* text: '확인',
* onPress: () => {
* console.log('확인 버튼 클릭');
* },
* },
* cancelOnBackdropPress: true,
* });
*
* // type 'two_button_horizontal' 예시
* showConfirmModal({
* type: 'two_button_horizontal',
* state: 'danger',
* title: '채팅방을 나가시겠어요?',
* description: '채팅방을 나가면 리뷰를 작성할 수 없으며, 대화 내용이 삭제되고 목록에서도 사라집니다.',
* confirmBtn: {
* text: '확인',
* onPress: () => {
* doSomethingOnConfirm();
* },
* },
* cancelBtn: {
* text: '취소',
* onPress: () => {
* doSomethingOnCancel();
* },
* },
* cancelOnBackdropPress: true,
* });
*
* // type 'two_button_vertical' 예시
* showConfirmModal({
* type: 'two_button_vertical',
* state: 'default', // 생략 가능
* title: '탈퇴가 불가능합니다',
* description: '진행 중인 1건의 안전거래를\n완료해야 탈퇴 할 수 있습니다.',
* confirmBtn: {
* text: '확인',
* onPress: () => {
* doSomethingOnConfirm();
* },
* },
* cancelBtn: {
* text: '취소',
* onPress: () => {
* doSomethingOnCancel();
* },
* },
* cancelOnBackdropPress: true,
* });
*
* // ConfirmModal promise 사용 예시
* async function foo() {
* const result = await showConfirmModal({
* title: '로그인 필요',
* description: '로그인 후 더 많은 기능을 이용해보세요.',
* type: 'two_button_horizontal',
* cancelOnBackdropPress: true,
* confirmBtn: {
* text: '확인',
* onPress: () => { doSomethingOnConfirm(); },
* },
* cancelBtn: {
* text: '닫기',
* onPress: () => { doSomethingOnCancel(); },
* },
* });
*
* if (result === 'confirm') {
* ToastService.showToast('confirm', { state: 'success' });
* } else if (result === 'cancel') {
* ToastService.showToast('cancel', { state: 'warning' });
* } else {
* ToastService.showToast('postpone', { state: 'default' });
* }
* }
*
* ```
*/
export function ConfirmModal(props: Props & AnimatedProps): React.JSX.Element {
const { title, description, type = 'one_button', confirmBtn } = props;
function handleConfirm() {
props.confirmBtn.onPress?.();
props.hide?.('confirm');
}
return (
{title}
{isNotEmpty(description) && (
{description}
)}
{type === 'one_button' ? (
// 영역 확보를 위해 View 로 감싸줌
) : (
)}
);
}
function TwoButton(props: TwoButtonTypeProps & { hide: (v: ConfirmResult) => void }) {
const { confirmBtn, cancelBtn, state = 'default', type = 'two_button_vertical', hide } = props;
const buttonType = state === 'default' ? 'primary' : 'danger';
function handleCancel() {
cancelBtn.onPress?.();
hide('cancel');
}
function handleConfirm() {
confirmBtn.onPress?.();
hide('confirm');
}
return type === 'two_button_vertical' ? (
) : (
);
}
const baseShadowStyles = [
shadowStyle({ color: Color.black, opacity: 0.1, radius: 6 }),
shadowStyle({ color: Color.black, opacity: 0.2, radius: 40, offset: [0, 4] }),
];