All files / src/hooks useDonationPrompt.ts

100% Statements 20/20
87.5% Branches 7/8
100% Functions 2/2
100% Lines 20/20

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 371x   1x 1x                     1x 4x 4x 2x 4x 4x   1x 9x     9x 5x 9x   9x 1x 1x 9x   9x 9x  
import { useState, useCallback, useEffect } from "react";
 
const STORAGE_KEY = "donation-last-shown";
const THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1000;
 
interface UseDonationPromptOptions {
	enabled: boolean;
}
 
interface DonationPromptState {
	shouldShow: boolean;
	dismiss: () => void;
}
 
const shouldShowNow = (): boolean => {
	const stored = localStorage.getItem(STORAGE_KEY);
	if (!stored) return true;
	const lastShown = parseInt(stored, 10);
	return isNaN(lastShown) ? true : Date.now() - lastShown >= THIRTY_DAYS_MS;
};
 
export const useDonationPrompt = ({ enabled }: UseDonationPromptOptions): DonationPromptState => {
	const [shouldShow, setShouldShow] = useState(false);
 
	// Re-evaluate whenever enabled flips to true (i.e. splash just dismissed)
	useEffect(() => {
		if (enabled) setShouldShow(shouldShowNow());
	}, [enabled]);
 
	const dismiss = useCallback(() => {
		localStorage.setItem(STORAGE_KEY, String(Date.now()));
		setShouldShow(false);
	}, []);
 
	return { shouldShow, dismiss };
};