import { useCallback, useEffect, useReducer, useRef } from 'react'; import type { SnackbarCreationProps } from './Snackbar.types'; type SnackbarInstance = { id: number; props: SnackbarCreationProps; }; type SnackbarManagerState = { /** The instance currently entering, visible or exiting. `null` means the provider is idle. */ active: SnackbarInstance | null; /** Marks the active provider render as committed, not its entry animation as finished. */ activeHasRendered: boolean; /** Changes when a new instance becomes active so repeated message text can be announced. */ announcementKey: number; /** The latest replacement waiting for active to exit. `null` means no replacement is waiting. */ pending: SnackbarInstance | null; /** Whether active should enter/stay visible; false requests its exit or indicates idle state. */ visible: boolean; }; type SnackbarManagerAction = | { type: 'show'; instance: SnackbarInstance } | { /** Ends pre-render coalescing; subsequent creates must wait for the committed instance to exit. */ type: 'rendered'; instanceId: number; } | { type: 'dismiss' } | { /** Like `dismiss`, but also cancels a queued replacement. Sent when `createSnackbar` gets empty text. */ type: 'clear'; } | { type: 'exited'; instanceId: number }; const emptyState: SnackbarManagerState = { active: null, activeHasRendered: false, announcementKey: 0, pending: null, visible: false, }; /** * Coalesces creates before the first commit, then keeps active content until its exit finishes. * Only the latest pending replacement is retained. Exited promotes pending or returns to idle. * Instance IDs prevent stale exit callbacks from affecting a newer Snackbar. */ const snackbarManagerReducer = ( state: SnackbarManagerState, action: SnackbarManagerAction, ): SnackbarManagerState => { switch (action.type) { case 'show': if (!state.active || !state.activeHasRendered) { // Batched creates collapse to the latest instance before anything has entered. return { active: action.instance, activeHasRendered: false, announcementKey: state.announcementKey + 1, pending: null, visible: true, }; } // Keep the active content until it exits; newer creates replace only the pending instance. return { ...state, pending: action.instance, visible: false }; case 'rendered': if (state.active?.id !== action.instanceId || state.activeHasRendered) { return state; } return { ...state, activeHasRendered: true }; case 'dismiss': case 'clear': if (!state.active) { return state; } if (!state.activeHasRendered) { return { ...emptyState, announcementKey: state.announcementKey }; } // Dismissal lets a queued replacement show next; clearing cancels it as well. return { ...state, pending: action.type === 'clear' ? null : state.pending, visible: false }; case 'exited': // Ignore callbacks from an instance that has already been replaced. if (state.active?.id !== action.instanceId) { return state; } if (state.pending) { return { active: state.pending, activeHasRendered: false, announcementKey: state.announcementKey + 1, pending: null, visible: true, }; } return { ...emptyState, announcementKey: state.announcementKey }; default: return state; } }; /** * Owns latest-wins replacement through reducer actions, separate from rendering and animation. * Stable create/dismiss callbacks request state changes; the surface's onExited callback completes * dismissal. The provider uses this state to mount/unmount the portal without a notification queue. */ const useSnackbarManager = () => { const [state, dispatch] = useReducer(snackbarManagerReducer, emptyState); const nextInstanceId = useRef(0); const createSnackbar = useCallback((props: SnackbarCreationProps) => { const { text } = props; if ( text == null || typeof text === 'boolean' || (typeof text === 'string' && text.trim() === '') ) { // A clear request must dismiss active and cancel pending, never create a blank replacement. dispatch({ type: 'clear' }); return; } nextInstanceId.current += 1; dispatch({ type: 'show', instance: { id: nextInstanceId.current, props } }); }, []); const dismissSnackbar = useCallback(() => dispatch({ type: 'dismiss' }), []); const handleExited = useCallback(() => { if (!state.active) { return; } try { state.active.props.onDismiss?.(); } catch (error) { // This runs in a transition commit; an escaping error could unmount the provider. // eslint-disable-next-line no-console console.error('Snackbar onDismiss callback failed:', error); } finally { dispatch({ type: 'exited', instanceId: state.active.id }); } }, [state.active]); useEffect(() => { if (state.active && state.visible && !state.activeHasRendered) { // Later creates can now wait for this instance's exit instead of coalescing before render. dispatch({ type: 'rendered', instanceId: state.active.id }); } }, [state.active, state.activeHasRendered, state.visible]); return { active: state.active, announcementKey: state.announcementKey, createSnackbar, dismissSnackbar, handleExited, visible: state.visible, }; }; export default useSnackbarManager;