All files / src/hooks useSubtitleNudge.ts

100% Statements 14/14
100% Branches 6/6
100% Functions 5/5
100% Lines 10/10

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                      2x       1908x 241x 7x 8x 6x 6x 6x   7x 7x      
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 Max Boksem. See NOTICE for additional terms under GPLv3 section 7.
 
import { useEffect, type Dispatch, type SetStateAction } from "react";
import { hasOpenFocusTrap } from "@/hooks/useFocusTrap";
import { isSubtitleNudgeKey, nudgeSubtitle, type SubtitlePosition } from "@/lib/subtitle-position";
 
/**
 * While `active`, the arrow keys move the subtitles a step at a time. A modal
 * open over the player, such as a confirm, keeps its keys.
 */
export const useSubtitleNudge = (
	active: boolean,
	setPosition: Dispatch<SetStateAction<SubtitlePosition>>
): void => {
	useEffect(() => {
		if (!active) return;
		const handleKey = (e: KeyboardEvent) => {
			if (!isSubtitleNudgeKey(e.key) || hasOpenFocusTrap()) return;
			e.preventDefault();
			const key = e.key;
			setPosition((p) => nudgeSubtitle(p, key));
		};
		window.addEventListener("keydown", handleKey);
		return () => window.removeEventListener("keydown", handleKey);
	}, [active, setPosition]);
};