All files / src/hooks useLeaveFullscreenOnUnmount.ts

100% Statements 12/12
100% Branches 6/6
100% Functions 3/3
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32                            2x 1904x 1904x   1904x 1904x 247x 247x     1904x   236x          
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 Max Boksem. See NOTICE for additional terms under GPLv3 section 7.
 
import { useEffect, useRef } from "react";
import { useFullscreen } from "@/lib/fullscreen-context";
 
/**
 * Leaves fullscreen when the player closes, whether by Stop or by a link to
 * another page such as the OMDb hint in an info sheet. The player's own
 * fullscreen controls go with it, so the next page would otherwise be left
 * in a fullscreen window. A window that was already fullscreen when the
 * player opened, such as from the green button on macOS, stays that way
 * unless it left fullscreen while the player was open.
 */
export const useLeaveFullscreenOnUnmount = () => {
	const { isFullscreen, setFullscreen } = useFullscreen();
	const isFullscreenRef = useRef(isFullscreen);
	// Whether the window has been fullscreen since the player opened.
	const wasFullscreenRef = useRef(isFullscreen);
	useEffect(() => {
		isFullscreenRef.current = isFullscreen;
		if (!isFullscreen) wasFullscreenRef.current = false;
	}, [isFullscreen]);
 
	useEffect(
		() => () => {
			if (isFullscreenRef.current && !wasFullscreenRef.current) setFullscreen(false);
		},
		[setFullscreen]
	);
};