import React, { ComponentProps, useCallback, useEffect, useRef, useState } from 'react'; import { StyleSheet, View } from 'react-native'; import { ToastManagerConnector } from './ToastManager'; import { useSafeAreaInsets } from 'react-native-safe-area-context'; import Animated, { Easing, FadeInUp, FadeOut, LinearTransition, ReduceMotion } from 'react-native-reanimated'; import { Toast } from './Toast'; export type ShowToastOption = { /** * SafeArea 하단에서 얼만큼 떨어뜨려 표시할지 설정합니다. * - 디자인 시스템 기본값 `10` */ offset?: number; /** * 토스트 표시 시간 * - 기본값 `3000`ms */ duration?: number; } & ( | { /** * 버튼을 표시하는 (action 타입) 경우, 'default' 상태만 가능 */ state?: 'default'; /** * 버튼 텍스트 */ buttonLabel: string; /** * 버튼 클릭 시 실행할 함수 */ onPressButton: () => void; } | { /** * 토스트에 특정 상태를 나타낼 때 사용 * - 'default' 아닌 경우 왼쪽에 아이콘을 붙임 */ state?: ToastProps['state']; } ); /** * # ToastManageView 컴포넌트 * * Toast 컴포넌트를 표시/제거하는 UI 로직을 담당합니다. * - 토스트 표시/제거 애니메이션, 화면 배치 담당 * - 다수의 토스트 표시 지원 * * `ToastManager`를 사용해 토스트를 표시하거나 숨길 수 있습니다. */ export function ToastManageView(): React.JSX.Element { const MAX_TOASTS = 2; const DEFAULT_DURATION = 4000; const DEFAULT_OFFSET = 60; const GAP_BETWEEN_TOASTS = 12; const safeAreaInsets = useSafeAreaInsets(); const { toastList, toastOffset, show, hideAll, hide } = useToastListState( MAX_TOASTS, DEFAULT_OFFSET, DEFAULT_DURATION, ); // 토스트 매니저 연동 useEffect(() => { ToastManagerConnector.init(show, hideAll); return () => { ToastManagerConnector.destroy(); }; }, [hideAll, show]); return ( {toastList.map((item) => ( { hide(item.id); item.onPressButton?.(); }} /> ))} ); } type ToastProps = ComponentProps; type ToastId = number; type ToastItem = ToastProps & { id: ToastId }; /** * 토스트 목록 상태를 관리하는 훅 */ function useToastListState(maxToasts: number, defaultOffset: number, defaultDuration: number) { const [toastList, setToastList] = useState([]); const [toastOffset, setToastOffset] = useState(defaultOffset); const incrementalId = useRef(0); const timerIdPerToast = useRef>(new Map()); const show = useCallback( (text: string, options?: ShowToastOption) => { const { offset = defaultOffset } = options ?? {}; setToastOffset(offset); incrementalId.current += 1; const id: ToastId = incrementalId.current; setToastList((prevList) => { if (prevList.length < maxToasts) { return prevList.concat([{ text, id, ...options }]); } else { // 최대 갯수를 초과하면 오래된 토스트부터 제거 (선입선출) const [first, ...rest] = prevList; clearTimeout(timerIdPerToast.current.get(first.id)); return rest.concat([{ text, id, ...options }]); } }); const duration = options?.duration ?? defaultDuration; const timerId = setTimeout(() => { setToastList((prevList) => prevList.filter((toast) => toast.id !== id)); }, duration); timerIdPerToast.current.set(id, timerId); }, [defaultDuration, defaultOffset, maxToasts], ); const hideAll = useCallback(() => { setToastList([]); timerIdPerToast.current.forEach((timerId) => clearTimeout(timerId)); }, []); /** * 특정 id 토스트 숨기기 * @internal */ const hide = useCallback((id: number) => { setToastList((prevList) => prevList.filter((toast) => toast.id !== id)); clearTimeout(timerIdPerToast.current.get(id)); }, []); return { toastList, toastOffset, show, hideAll, hide }; }