import { useCallback } from "react"; import useNextFocusable from "../useNextFocusable"; import { useWindows } from "@/contexts/windows"; import { useSession } from "@/contexts/session"; import { useWindowsRef } from "@/hooks/useWindowsRef"; import { PREVENT_SCROLL } from "@/utils/constants"; type WindowActions = { onClose: () => void; onMaximize: () => void; onMinimize: (keepForegroundId?: boolean) => void; }; const useWindowActions = (id: string): WindowActions => { const nextFocusableId = useNextFocusable(id); const { setForegroundId, removeFromStack } = useSession(); const { closeWithTransition, maximize, minimize, setSnap } = useWindows(); const windowsRef = useWindowsRef(); const onMinimize = useCallback( (keepForegroundId?: boolean): void => { minimize(id); // Make sure we disable snap state: setSnap(id, false); if (!keepForegroundId) setForegroundId(nextFocusableId); }, [id, minimize, setSnap, nextFocusableId, setForegroundId] ); const onMaximize = useCallback((): void => { const triggerMaximize = (): void => { maximize(id); setForegroundId(id); windowsRef.current[id]?.componentWindow?.focus(PREVENT_SCROLL); // Make sure we disable snap state: setSnap(id, false); }; const [currentAnimation] = windowsRef.current[id]?.componentWindow?.getAnimations() || []; if (currentAnimation?.finished) { currentAnimation.finished.then(triggerMaximize); } else { triggerMaximize(); } }, [id, setSnap, maximize, windowsRef, setForegroundId]); const onClose = useCallback((): void => { removeFromStack(id); closeWithTransition(id); setForegroundId(nextFocusableId); }, [ closeWithTransition, id, nextFocusableId, removeFromStack, setForegroundId, ]); return { onClose, onMaximize, onMinimize }; }; export default useWindowActions;