All files / src/hooks useHasOmdbKey.ts

90.9% Statements 20/22
72.72% Branches 8/11
85.71% Functions 6/7
94.73% Lines 18/19

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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58                6x     6x 75x                   6x 215x 215x 85x 16x 16x   12x 12x           16x 16x     215x                 6x       215x 215x 215x    
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 Max Boksem. See NOTICE for additional terms under GPLv3 section 7.
 
import { useEffect, useState } from "react";
import { getOmdbApiKey } from "@/lib/tauri";
import type { OmdbData } from "@/lib/types";
 
// The last answer, so a sheet that opens again shows it at once while it checks.
let lastKnown: boolean | null = null;
 
/** Records whether a key is saved. Settings calls this when it saves one. */
export const rememberHasOmdbKey = (hasKey: boolean | null) => {
	lastKnown = hasKey;
};
 
/**
 * Whether an OMDb API key is saved, or null until the first check answers.
 * Only the yes or no leaves this hook, never the key. It starts from the last
 * answer and checks again once `needed` is true, so a sheet that mounts when
 * it opens sees a key added since it last opened. A sheet that already has
 * OMDb details passes false and skips the check.
 */
const useHasOmdbKey = (needed: boolean): boolean | null => {
	const [hasKey, setHasKey] = useState<boolean | null>(lastKnown);
	useEffect(() => {
		if (!needed) return;
		let cancelled = false;
		getOmdbApiKey()
			.then((key) => {
				lastKnown = Boolean(key);
				Eif (!cancelled) setHasKey(lastKnown);
			})
			// If the store can't be read, act as if a key is set so nothing changes.
			.catch(() => {
				if (!cancelled) setHasKey(true);
			});
		return () => {
			cancelled = true;
		};
	}, [needed]);
	return hasKey;
};
 
/**
 * What a movie or series sheet needs to know about OMDb. The key only matters
 * when OMDb came back with nothing, so it isn't checked while OMDb loads or
 * once it has details. Without details the sheet keeps loading until the key
 * check answers too, so the hint about adding a key doesn't flash.
 */
export const useOmdbInfoState = (
	omdbData: OmdbData | null,
	omdbLoading: boolean
): { hasOmdbKey: boolean | null; infoLoading: boolean } => {
	const hasOmdbKey = useHasOmdbKey(!omdbLoading && !omdbData);
	const infoLoading = omdbLoading || (!omdbData && hasOmdbKey === null);
	return { hasOmdbKey, infoLoading };
};