Skip to content

Free & Open-Source Invoice Generator - No Sign-Up, No Ads, Instant PDF Export, 100% In-Browser, and Fully Customizable Templates.

feat: implement CTA toast context and enhance toast display logic (#152)

Vlad Sazonauccac646ca565
diff --git a/src/app/(app)/components/cta-toasts/index.tsx b/src/app/(app)/components/cta-toasts/index.tsx
index 498e95d..dfed3cb 100644
--- a/src/app/(app)/components/cta-toasts/index.tsx
+++ b/src/app/(app)/components/cta-toasts/index.tsx
@@ -240,21 +240,40 @@ function DefaultToastFeedbackButton(
);
}
+export const CTA_TOASTS = [
+ {
+ id: "premium-donation-toast-client-page",
+ title: "Support My Work",
+ description:
+ "Your contribution helps me maintain and improve this project for everyone! πŸš€",
+ show: customPremiumToast,
+ },
+ {
+ id: "default-donation-toast-client-page",
+ title: "Love this project?",
+ description:
+ "Help me keep this free tool running! Your support enables me to add new features and maintain the service. πŸ™",
+ show: customDefaultToast,
+ },
+] as const satisfies {
+ id: string;
+ title: string;
+ description: string;
+ show: (toast: ToastProps) => void;
+}[];
+
export const showRandomCTAToast = () => {
- // Randomly show either default or premium donation toast
- if (Math.random() <= 0.5) {
- customPremiumToast({
- id: "premium-donation-toast-client-page",
- title: "Support My Work",
- description:
- "Your contribution helps me maintain and improve this project for everyone! πŸš€",
- });
- } else {
- customDefaultToast({
- id: "default-donation-toast-client-page",
- title: "Love this project?",
- description:
- "Help me keep this free tool running! Your support enables me to add new features and maintain the service. πŸ™",
- });
- }
+ // Randomly show a CTA toast
+ const variant = CTA_TOASTS[Math.floor(Math.random() * CTA_TOASTS.length)];
+
+ variant.show({
+ id: variant.id,
+ title: variant.title,
+ description: variant.description,
+ });
};
+
+/**
+ * Slight delay to prevent the toast from appearing too quickly
+ */
+export const CTA_TOAST_TIMEOUT = 3_000; // in ms
diff --git a/src/app/(app)/components/invoice-pdf-download-link.tsx b/src/app/(app)/components/invoice-pdf-download-link.tsx
index a41ccdd..d98fa17 100644
--- a/src/app/(app)/components/invoice-pdf-download-link.tsx
+++ b/src/app/(app)/components/invoice-pdf-download-link.tsx
@@ -16,9 +16,12 @@ import { LOADING_BUTTON_TEXT, LOADING_BUTTON_TIMEOUT } from "./invoice-form";
import { StripeInvoicePdfTemplate } from "./invoice-pdf-stripe-template";
import { InvoicePdfTemplate } from "./invoice-pdf-template";
-import { customDefaultToast, customPremiumToast } from "./cta-toasts";
+import { showRandomCTAToast } from "./cta-toasts";
import { useDeviceContext } from "@/contexts/device-context";
import { isTelegramInAppBrowser } from "@/utils/is-telegram-in-app-browser";
+import { CTA_TOAST_LAST_SHOWN_STORAGE_KEY } from "../hooks/use-show-random-cta-toast";
+import { useCTAToast } from "../contexts/cta-toast-context";
+import { CTA_TOAST_TIMEOUT } from "./cta-toasts";
// Separate button states into a memoized component
const ButtonContent = ({
@@ -52,6 +55,7 @@ export function InvoicePDFDownloadLink({
setErrorWhileGeneratingPdfIsShown: (error: boolean) => void;
}) {
const { inAppInfo } = useDeviceContext();
+ const { markToastAsShown } = useCTAToast();
const [{ loading: pdfLoading, url, error }, updatePdfInstance] = usePDF();
const [isLoading, setIsLoading] = useState(false);
@@ -106,24 +110,19 @@ export function InvoicePDFDownloadLink({
// close all other toasts (if any)
toast.dismiss();
- // Randomly show either default or premium donation toast after 2.5 seconds
+ // Show a CTA toast
setTimeout(() => {
- if (Math.random() <= 0.5) {
- customPremiumToast({
- id: "premium-donation-toast",
- title: "Support My Work",
- description:
- "Your contribution helps me maintain and improve this project for everyone! πŸš€",
- });
- } else {
- customDefaultToast({
- id: "default-donation-toast",
- title: "Love this project?",
- description:
- "Your support helps me keep this free tool running and build even better features! πŸ™",
- });
- }
- }, 3000);
+ showRandomCTAToast();
+
+ // Mark toast as shown in session to prevent duplicate toasts
+ markToastAsShown();
+
+ // Update timestamp to prevent other CTA toasts from showing for 7 days
+ localStorage.setItem(
+ CTA_TOAST_LAST_SHOWN_STORAGE_KEY,
+ String(Date.now()),
+ );
+ }, CTA_TOAST_TIMEOUT);
}
},
[
@@ -134,6 +133,7 @@ export function InvoicePDFDownloadLink({
error,
trackDownload,
isTelegramPreviewBrowser,
+ markToastAsShown,
],
);
diff --git a/src/app/(app)/contexts/cta-toast-context.tsx b/src/app/(app)/contexts/cta-toast-context.tsx
new file mode 100644
index 0000000..8892947
--- /dev/null
+++ b/src/app/(app)/contexts/cta-toast-context.tsx
@@ -0,0 +1,38 @@
+"use client";
+
+import { createContext, useContext, useState, useCallback } from "react";
+
+interface CTAToastContextValue {
+ isToastShownInSession: boolean;
+ markToastAsShown: () => void;
+}
+
+const CTAToastContext = createContext<CTAToastContextValue | undefined>(
+ undefined,
+);
+
+export function CTAToastProvider({ children }: { children: React.ReactNode }) {
+ const [isToastShownInSession, setIsToastShownInSession] = useState(false);
+
+ const markToastAsShown = useCallback(() => {
+ setIsToastShownInSession(true);
+ }, []);
+
+ return (
+ <CTAToastContext.Provider
+ value={{ isToastShownInSession, markToastAsShown }}
+ >
+ {children}
+ </CTAToastContext.Provider>
+ );
+}
+
+export function useCTAToast() {
+ const context = useContext(CTAToastContext);
+
+ if (context === undefined) {
+ throw new Error("useCTAToast must be used within a CTAToastProvider");
+ }
+
+ return context;
+}
diff --git a/src/app/(app)/hooks/use-show-random-cta-toast.tsx b/src/app/(app)/hooks/use-show-random-cta-toast.tsx
index ed15e2c..713011e 100644
--- a/src/app/(app)/hooks/use-show-random-cta-toast.tsx
+++ b/src/app/(app)/hooks/use-show-random-cta-toast.tsx
@@ -3,26 +3,35 @@
import { useEffect } from "react";
import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";
import { showRandomCTAToast } from "../components/cta-toasts";
+import { useCTAToast } from "../contexts/cta-toast-context";
import dayjs from "dayjs";
import duration from "dayjs/plugin/duration";
dayjs.extend(duration);
-const STORAGE_KEY = "EASY_INVOICE_CTA_LAST_SHOWN_AT";
+export const CTA_TOAST_LAST_SHOWN_STORAGE_KEY =
+ "EASY_INVOICE_CTA_LAST_SHOWN_AT";
const COOLDOWN_DAYS = 7;
-const MIN_TIME_ON_PAGE = 15_000; // in milliseconds
-const IDLE_TIME = 5_000; // in milliseconds
+const MIN_TIME_ON_PAGE = 10_000; // in ms
+const IDLE_TIME = 7_000; // in ms
/**
* This hook is used to show a CTA toast after a certain number of interactions with the page.
*
- * - User stays on page 10s (MIN_TIME_ON_PAGE) β†’ we consider them β€œpresent”.
+ * - User stays on page Xs (MIN_TIME_ON_PAGE) β†’ we consider them "present".
* - Any real interaction (type, click) β†’ we mark them engaged.
* - Once they stop interacting for X seconds (IDLE_TIME) β†’ toast appears.
*/
export function useShowRandomCTAToast() {
+ const { isToastShownInSession, markToastAsShown } = useCTAToast();
+
useEffect(() => {
- const last = localStorage.getItem(STORAGE_KEY);
+ // Skip if a CTA toast was already shown in this session (e.g., from PDF download)
+ if (isToastShownInSession) {
+ umamiTrackEvent("cta_toast_skipped_session");
+ return;
+ }
+ const last = localStorage.getItem(CTA_TOAST_LAST_SHOWN_STORAGE_KEY);
// Check if the last time the CTA toast was shown was less than 7 days ago
// Parse and validate the stored timestamp
@@ -31,7 +40,7 @@ export function useShowRandomCTAToast() {
// If invalid timestamp, clear it from storage and treat as not in cooldown
if (last && !isValidTimestamp) {
- localStorage.removeItem(STORAGE_KEY);
+ localStorage.removeItem(CTA_TOAST_LAST_SHOWN_STORAGE_KEY);
}
const isWithinCooldownPeriod =
@@ -39,7 +48,8 @@ export function useShowRandomCTAToast() {
dayjs().diff(dayjs(parsedLast)) <
dayjs.duration(COOLDOWN_DAYS, "day").asMilliseconds();
- // If the last time the CTA toast was shown was less than 7 days ago, skip showing the toast
+ // If the last time any CTA toast was shown was less than 7 days ago, skip showing the toast
+ // This includes both the random CTA toast and the PDF download donation toast
if (last && isWithinCooldownPeriod) {
umamiTrackEvent("cta_toast_skipped_recently");
return;
@@ -59,8 +69,14 @@ export function useShowRandomCTAToast() {
triggered = true;
showRandomCTAToast();
+ // mark toast as shown in session to prevent duplicate toasts
+ markToastAsShown();
+
// save last shown timestamp to localStorage
- localStorage.setItem(STORAGE_KEY, String(Date.now()));
+ localStorage.setItem(
+ CTA_TOAST_LAST_SHOWN_STORAGE_KEY,
+ String(Date.now()),
+ );
// track event
umamiTrackEvent("cta_toast_shown");
@@ -108,5 +124,5 @@ export function useShowRandomCTAToast() {
window.removeEventListener("pointerdown", resetIdle);
window.removeEventListener("keydown", resetIdle);
};
- }, []);
+ }, [isToastShownInSession, markToastAsShown]);
}
diff --git a/src/app/(app)/page.client.tsx b/src/app/(app)/page.client.tsx
index 490cd88..ea3fcf6 100644
--- a/src/app/(app)/page.client.tsx
+++ b/src/app/(app)/page.client.tsx
@@ -46,7 +46,13 @@ import { z } from "zod";
import { InvoiceClientPage } from "./components";
import { InvoicePDFDownloadLink } from "./components/invoice-pdf-download-link";
import { handleInvoiceNumberBreakingChange } from "./utils/invoice-number-breaking-change";
-import { useShowRandomCTAToast } from "./hooks/use-show-random-cta-toast";
+import {
+ CTA_TOAST_LAST_SHOWN_STORAGE_KEY,
+ useShowRandomCTAToast,
+} from "./hooks/use-show-random-cta-toast";
+import { CTA_TOAST_TIMEOUT, showRandomCTAToast } from "./components/cta-toasts";
+import { useCTAToast } from "./contexts/cta-toast-context";
+
// import { DevLocalStorageView } from "./components/dev/dev-local-storage-view";
// import { InvoicePDFDownloadMultipleLanguages } from "./components/invoice-pdf-download-multiple-languages";
@@ -66,6 +72,8 @@ export function AppPageClient({
const router = useRouter();
const searchParams = useSearchParams();
+ const { markToastAsShown } = useCTAToast();
+
const urlTemplateSearchParam = searchParams.get("template");
// Validate template parameter with zod
@@ -369,6 +377,20 @@ export function AppPageClient({
// analytics track event
umamiTrackEvent("share_invoice_link");
+
+ // Show a CTA toast
+ setTimeout(() => {
+ showRandomCTAToast();
+
+ // Mark toast as shown in session to prevent duplicate toasts
+ markToastAsShown();
+
+ // Update timestamp to prevent other CTA toasts from showing
+ localStorage.setItem(
+ CTA_TOAST_LAST_SHOWN_STORAGE_KEY,
+ String(Date.now()),
+ );
+ }, CTA_TOAST_TIMEOUT);
} catch (error) {
console.error("Failed to share invoice:", error);
toast.error("Failed to generate shareable link");
diff --git a/src/app/(app)/page.tsx b/src/app/(app)/page.tsx
index 187898c..9ddb669 100644
--- a/src/app/(app)/page.tsx
+++ b/src/app/(app)/page.tsx
@@ -2,6 +2,7 @@ import type { Metadata } from "next";
import { AppPageClient } from "./page.client";
import { APP_URL, STATIC_ASSETS_URL } from "@/config";
import { fetchGithubStars } from "@/actions/fetch-github-stars";
+import { CTAToastProvider } from "./contexts/cta-toast-context";
// we generate metadata here, because we need access to searchParams (in layout we don't have it)
export async function generateMetadata({
@@ -125,5 +126,9 @@ export async function generateMetadata({
export default async function AppPage() {
const githubStarsCount = await fetchGithubStars();
- return <AppPageClient githubStarsCount={githubStarsCount} />;
+ return (
+ <CTAToastProvider>
+ <AppPageClient githubStarsCount={githubStarsCount} />
+ </CTAToastProvider>
+ );
}
diff --git a/src/app/[locale]/about/components/landing-cta-toast.tsx b/src/app/[locale]/about/components/landing-cta-toast.tsx
index 9801ee0..ba31fbb 100644
--- a/src/app/[locale]/about/components/landing-cta-toast.tsx
+++ b/src/app/[locale]/about/components/landing-cta-toast.tsx
@@ -1,49 +1,21 @@
"use client";
-import {
- customDefaultToast,
- customPremiumToast,
-} from "@/app/(app)/components/cta-toasts";
+import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";
import { useEffect } from "react";
+import { showRandomCTAToast } from "@/app/(app)/components/cta-toasts";
/**
* This component is used to show a CTA toast on the landing page.
- *
- * It is used to encourage users to support the project.
- *
- * It is only shown on the production environment.
- *
- * It is shown after 7 seconds on the page.
- *
*/
export const LandingCtaToast = () => {
- // Show CTA toast every minute
useEffect(() => {
- // only show on production
- if (process.env.NODE_ENV !== "production") {
- return;
- }
-
const showCTAToast = () => {
- // Randomly show either default or premium donation toast
- if (Math.random() <= 0.5) {
- customPremiumToast({
- id: "premium-donation-toast-landing-page",
- title: "Support My Work",
- description:
- "Your contribution helps me maintain and improve this project for everyone! πŸš€",
- });
- } else {
- customDefaultToast({
- id: "default-donation-toast-landing-page",
- title: "Love this project?",
- description:
- "Help me keep building amazing tools! Your support means the world to me. ✨",
- });
- }
+ showRandomCTAToast();
+
+ umamiTrackEvent("cta_toast_shown_landing_page");
};
- // Show cta toast after 15 seconds on the page
+ // Show cta toast after X seconds on the page
const initialTimer = setTimeout(showCTAToast, 15_000);
return () => {
diff --git a/src/components/ui/dialog.tsx b/src/components/ui/dialog.tsx
index e5b9ccb..5453797 100644
--- a/src/components/ui/dialog.tsx
+++ b/src/components/ui/dialog.tsx
@@ -44,7 +44,10 @@ const DialogContent = React.forwardRef<
{...props}
>
{children}
- <DialogPrimitive.Close className="focus-visible:outline-ring/70 group absolute right-3 top-3 flex size-7 items-center justify-center rounded-lg outline-offset-2 transition-colors focus-visible:outline focus-visible:outline-2 disabled:pointer-events-none">
+ <DialogPrimitive.Close
+ className="focus-visible:outline-ring/70 group absolute right-3 top-3 flex size-7 items-center justify-center rounded-lg outline-offset-2 transition-colors focus-visible:outline focus-visible:outline-2 disabled:pointer-events-none"
+ title="Close"
+ >
<X
size={16}
strokeWidth={2}