Files
zellyy-finance/src/hooks/toast/toastManager.ts
gpt-engineer-app[bot] 14c3fac824 Fix toast and sync settings
- Fix issue where toast notifications were not disappearing.
- Ensure sync settings are turned off upon logout.
2025-03-16 10:37:26 +00:00

73 lines
2.0 KiB
TypeScript

import { Action, actionTypes } from './types'
import { TOAST_LIMIT } from './constants'
import { reducer } from './reducer'
import { listeners } from './store'
// 전역 상태 관리
let memoryState = { toasts: [] };
let lastAction = null;
// ID 생성기
let count = 0
export function genId() {
count = (count + 1) % Number.MAX_SAFE_INTEGER
return count.toString()
}
export function dispatch(action: Action) {
// 마지막 액션 정보 추출
let actionId: string | undefined = undefined;
if ('toast' in action && action.toast) {
actionId = action.toast.id;
} else if ('toastId' in action) {
actionId = action.toastId;
}
// 동일한 토스트에 대한 중복 액션 방지
const now = Date.now();
const isSameAction = lastAction &&
lastAction.type === action.type &&
((action.type === actionTypes.ADD_TOAST &&
lastAction.time > now - 1000) || // ADD 액션은 1초 내 중복 방지
(action.type !== actionTypes.ADD_TOAST &&
actionId === lastAction.id &&
lastAction.time > now - 300)); // 다른 액션은 300ms 내 중복 방지
if (isSameAction) {
console.log('중복 토스트 액션 무시:', action.type);
return;
}
// 액션 추적 업데이트
lastAction = {
type: action.type,
id: actionId,
time: now
};
// REMOVE_TOAST 액션 우선순위 높임
if (action.type === actionTypes.REMOVE_TOAST) {
// 즉시 처리
memoryState = reducer(memoryState, action);
listeners.forEach((listener) => {
listener(memoryState);
});
return;
}
// 실제 상태 업데이트 및 리스너 호출
memoryState = reducer(memoryState, action);
listeners.forEach((listener) => {
listener(memoryState);
});
}
// 토스트 모두 제거 헬퍼 함수
export function clearAllToasts() {
dispatch({ type: actionTypes.REMOVE_TOAST });
}
export { memoryState };