All files / src/hooks useDonationPrompt.ts

100% Statements 14/14
85.71% Branches 6/7
100% Functions 3/3
100% Lines 13/13

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            2x                     2x 20x 20x 7x 7x     2x     57x 57x   57x 4x 4x     57x    
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 Max Boksem. See NOTICE for additional terms under GPLv3 section 7.
 
import { useState, useCallback } from "react";
import { DONATION_LAST_SHOWN_KEY, readStorage, writeStorage } from "@/lib/storage";
 
const THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1000;
 
interface UseDonationPromptOptions {
	enabled: boolean;
}
 
interface DonationPromptState {
	shouldShow: boolean;
	dismiss: () => void;
}
 
const shouldShowNow = (): boolean => {
	const stored = readStorage(DONATION_LAST_SHOWN_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 => {
	// Whether it's time is read once, as the app starts. The prompt then waits
	// for `enabled`, which turns on when the splash screen goes.
	const [due] = useState(shouldShowNow);
	const [dismissed, setDismissed] = useState(false);
 
	const dismiss = useCallback(() => {
		writeStorage(DONATION_LAST_SHOWN_KEY, String(Date.now()));
		setDismissed(true);
	}, []);
 
	return { shouldShow: enabled && due && !dismissed, dismiss };
};