Free & Open-Source Invoice Generator - No Sign-Up, No Ads, Instant PDF Export, 100% In-Browser, and Fully Customizable Templates.
TypeScript fintechinvoiceinvoice-generatorinvoice-pdfinvoice-templateinvoicesnextjsopen-sourcequotesreactreact-pdf-rendererself-hostedshadcn-uitailwindcsstypescript
fix: double re-rerender during edit seller and check if local storage is available, add umami analytics (#61)
Vlad Sazonau39d47a9619d9
diff --git a/next.config.mjs b/next.config.mjsindex 6cc8493..38488b1 100644--- a/next.config.mjs+++ b/next.config.mjs@@ -6,6 +6,15 @@ const nextConfig = {eslint: {ignoreDuringBuilds: true,},+ async rewrites() {+ return [+ {+ // proxy umami analytics https://umami.is/docs/guides/running-on-vercel+ source: "/stats/:match*",+ destination: "https://cloud.umami.is/:match*",+ },+ ];+ },};export default nextConfig;diff --git a/src/app/components/invoice-form.tsx b/src/app/components/invoice-form.tsxindex 11cf66c..a581b78 100644--- a/src/app/components/invoice-form.tsx+++ b/src/app/components/invoice-form.tsx@@ -37,6 +37,7 @@ import {AccordionItem,AccordionTrigger,} from "@/components/ui/accordion";+import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";export const PDF_DATA_LOCAL_STORAGE_KEY = "EASY_INVOICE_PDF_DATA";export const PDF_DATA_FORM_ID = "pdfInvoiceForm";@@ -256,6 +257,7 @@ export function InvoiceForm({// analytics track eventopenPanel.track("remove_invoice_item");+ umamiTrackEvent("remove_invoice_item");// Manually trigger form submission after removalconst currentFormData = watch();diff --git a/src/app/components/invoice-pdf-download-link.tsx b/src/app/components/invoice-pdf-download-link.tsxindex 870d4da..5d5343e 100644--- a/src/app/components/invoice-pdf-download-link.tsx+++ b/src/app/components/invoice-pdf-download-link.tsx@@ -9,6 +9,7 @@ import { Loader2 } from "lucide-react";import { LOADING_BUTTON_TEXT, LOADING_BUTTON_TIMEOUT } from "./invoice-form";import { toast } from "sonner";import { useOpenPanel } from "@openpanel/nextjs";+import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";export function InvoicePDFDownloadLink({invoiceData,@@ -72,6 +73,7 @@ export function InvoicePDFDownloadLink({);openPanel.track("error_generating_document_link");+ umamiTrackEvent("error_generating_document_link");}}, [error, openPanel]);@@ -83,6 +85,7 @@ export function InvoicePDFDownloadLink({onClick={() => {if (!isLoading && url) {openPanel.track("download_invoice");+ umamiTrackEvent("download_invoice");// Show donation toast after 3 secondssetTimeout(() => {@@ -91,12 +94,16 @@ export function InvoicePDFDownloadLink({"If you find this tool helpful, please consider making a small donation to support our work.",action: {label: "Donate",- onClick: () =>+ onClick: () => {window.open("https://dub.sh/easyinvoice-donate","_blank","noopener,noreferrer"- ),+ );++ openPanel.track("donate_button_clicked_download_pdf_toast");+ umamiTrackEvent("donate_button_clicked_download_pdf_toast");+ },},duration: Infinity, // Show indefinitely until the user closes itcloseButton: true,diff --git a/src/app/components/regenerate-invoice-button.tsx b/src/app/components/regenerate-invoice-button.tsxindex 8afd00d..6c9f693 100644--- a/src/app/components/regenerate-invoice-button.tsx+++ b/src/app/components/regenerate-invoice-button.tsx@@ -13,6 +13,8 @@ import type { InvoiceData } from "../schema";import { useEffect, useState } from "react";import { toast } from "sonner";import { Loader2 } from "lucide-react";+import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";+import { useOpenPanel } from "@openpanel/nextjs";export function RegenerateInvoiceButton({invoiceData,@@ -23,6 +25,7 @@ export function RegenerateInvoiceButton({document: <InvoicePdfTemplate invoiceData={invoiceData} />,});const [isLoading, setIsLoading] = useState(false);+ const openPanel = useOpenPanel();useEffect(() => {if (pdfLoading) {@@ -51,6 +54,11 @@ export function RegenerateInvoiceButton({_variant="outline"className="mt-2 w-full"disabled={isLoading}+ onClick={() => {+ // analytics events+ openPanel.track("regenerate_invoice");+ umamiTrackEvent("regenerate_invoice");+ }}>{isLoading ? (<span className="inline-flex items-center">diff --git a/src/app/error.tsx b/src/app/error.tsxindex 0ceec08..90654e4 100644--- a/src/app/error.tsx+++ b/src/app/error.tsx@@ -7,6 +7,7 @@ import { toast } from "sonner";import { PDF_DATA_LOCAL_STORAGE_KEY } from "./components/invoice-form";import { INITIAL_INVOICE_DATA } from "./constants";import { useOpenPanel } from "@openpanel/nextjs";+import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";export default function Error({error,@@ -52,7 +53,9 @@ export default function Error({// Attempt to recover by trying to re-render the segment() => {reset();+openPanel.track("error_button_try_again_clicked");+ umamiTrackEvent("error_button_try_again_clicked");}}_variant="outline"@@ -77,6 +80,7 @@ export default function Error({});openPanel.track("error_button_start_from_scratch_clicked");+ umamiTrackEvent("error_button_start_from_scratch_clicked");} catch (error) {console.error(error);diff --git a/src/app/layout.tsx b/src/app/layout.tsxindex ccb7b3a..a62fa70 100644--- a/src/app/layout.tsx+++ b/src/app/layout.tsx@@ -1,6 +1,7 @@import type { Metadata, Viewport } from "next";import { NuqsAdapter } from "nuqs/adapters/next/app";import { OpenPanelComponent } from "@openpanel/nextjs";+import Script from "next/script";import "./globals.css";import { Toaster } from "sonner";@@ -67,6 +68,14 @@ export default function RootLayout({)}{/* https://sonner.emilkowal.ski/ */}<Toaster visibleToasts={1} richColors />+ {process.env.NODE_ENV === "production" && (+ <Script+ // we proxy umami check next.config.mjs rewrites+ src="/stats/script.js"+ data-website-id="1914352c-5ebb-4806-bfc3-f494712bb4a4"+ defer+ />+ )}</body></html>);diff --git a/src/app/page.tsx b/src/app/page.tsxindex ed9a8c8..ac35a78 100644--- a/src/app/page.tsx+++ b/src/app/page.tsx@@ -21,6 +21,8 @@ import { InvoicePdfTemplate } from "./components/invoice-pdf-template";import { RegenerateInvoiceButton } from "./components/regenerate-invoice-button";import { INITIAL_INVOICE_DATA } from "./constants";import { useOpenPanel } from "@openpanel/nextjs";+import { isLocalStorageAvailable } from "@/lib/check-local-storage";+import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";const InvoicePDFViewer = dynamic(() =>@@ -53,11 +55,14 @@ export default function Home() {// Initialize data from URL or localStorage on mountuseEffect(() => {- const urlData = searchParams.get("data");+ const compressedInvoiceDataInUrl = searchParams.get("data");- if (urlData) {+ // first try to load from url+ if (compressedInvoiceDataInUrl) {try {- const decompressed = decompressFromEncodedURIComponent(urlData);+ const decompressed = decompressFromEncodedURIComponent(+ compressedInvoiceDataInUrl+ );const parsed = JSON.parse(decompressed);const validated = invoiceSchema.parse(parsed);@@ -95,7 +100,8 @@ export default function Home() {// Save to localStorage whenever data changes on form updateuseEffect(() => {- if (invoiceDataState) {+ // Only save to localStorage if it's available+ if (invoiceDataState && isLocalStorageAvailable) {try {const newInvoiceDataValidated = invoiceSchema.parse(invoiceDataState);@@ -168,10 +174,14 @@ export default function Home() {const newFullUrl = `${window.location.origin}/?data=${compressed}`;await navigator.clipboard.writeText(newFullUrl);- toast.success("URL copied to clipboard!");+ toast.success("Invoice link copied to clipboard!", {+ description:+ "Share this link to let others view and edit this invoice",+ });// analytics track eventopenPanel.track("share_invoice_link");+ umamiTrackEvent("share_invoice_link");} catch (error) {console.error("Failed to share invoice:", error);toast.error("Failed to generate shareable link");@@ -197,17 +207,22 @@ export default function Home() {<ButtonclassName="w-full bg-blue-500 text-white transition-all hover:scale-105 hover:bg-blue-600 hover:no-underline lg:w-auto"_variant="link"+ onClick={() => {+ window.open(+ "https://dub.sh/easyinvoice-donate",+ "_blank",+ "noopener noreferrer"+ );++ // analytics track event+ openPanel.track("donate_to_project_button_clicked_header");+ umamiTrackEvent("donate_to_project_button_clicked_header");+ }}>- <a- href="https://dub.sh/easyinvoice-donate"- target="_blank"- rel="noopener noreferrer"- >- <span className="flex items-center gap-1.5">- <span className="animate-heartbeat">❤️</span>- <span>Support Project</span>- </span>- </a>+ <span className="flex items-center space-x-1.5">+ <span className="animate-heartbeat">❤️</span>+ <span>Support Project</span>+ </span></Button><CustomTooltiptrigger={diff --git a/src/components/seller-dialog.tsx b/src/components/seller-dialog.tsxindex bfd9f05..ca064fc 100644--- a/src/components/seller-dialog.tsx+++ b/src/components/seller-dialog.tsx@@ -395,7 +395,21 @@ export function SellerDialog({Cancel</Button></DialogClose>- <Button type="submit" form={SELLER_FORM_ID}>+ <Button+ // we don't want to use type="submit" because it will cause unnecessary re-render of the invoice pdf preview+ type="button"+ onClick={async () => {+ // we manually trigger the form validation and submit the form++ // validate the form+ const isValid = await form.trigger();+ if (!isValid) return;++ // submit the form+ onSubmit(form.getValues());+ }}+ form={SELLER_FORM_ID}+ >Save Seller</Button></DialogFooter>diff --git a/src/components/seller-management.tsx b/src/components/seller-management.tsxindex a2e1497..1dd0c15 100644--- a/src/components/seller-management.tsx+++ b/src/components/seller-management.tsx@@ -28,6 +28,8 @@ import { toast } from "sonner";import { cn } from "@/lib/utils";import { Label } from "./ui/label";import { useOpenPanel } from "@openpanel/nextjs";+import { isLocalStorageAvailable } from "@/lib/check-local-storage";+import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";export const SELLERS_LOCAL_STORAGE_KEY = "EASY_INVOICE_PDF_SELLERS";@@ -40,7 +42,10 @@ export function SellerManagement({}) {const [isSellerDialogOpen, setIsSellerDialogOpen] = useState(false);const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);- const [sellers, setSellers] = useState<SellerData[]>([]);++ const [sellersSelectOptions, setSellersSelectOptions] = useState<+ SellerData[]+ >([]);const [selectedSellerIndex, setSelectedSellerIndex] = useState("");const [editingSeller, setEditingSeller] = useState<SellerData | null>(null);@@ -70,7 +75,7 @@ export function SellerManagement({});- setSellers(validationResult.data);+ setSellersSelectOptions(validationResult.data);setSelectedSellerIndex(selectedSeller?.id ?? "");} catch (error) {console.error("Failed to load sellers:", error);@@ -91,7 +96,7 @@ export function SellerManagement({id: Date.now().toString(),};- const newSellers = [...sellers, newSellerWithId];+ const newSellers = [...sellersSelectOptions, newSellerWithId];// Save to localStoragelocalStorage.setItem(@@ -100,7 +105,7 @@ export function SellerManagement({);// Update the sellers state- setSellers(newSellers);+ setSellersSelectOptions(newSellers);// Apply the new seller to the invoice if the user wants to, otherwise just add it to the list and use it later if neededif (shouldApplyNewSellerToInvoice) {@@ -114,6 +119,7 @@ export function SellerManagement({// analytics track eventopenPanel.track("add_seller_success");+ umamiTrackEvent("add_seller_success");} catch (error) {console.error("Failed to add seller:", error);@@ -126,19 +132,19 @@ export function SellerManagement({// Update sellers when editedconst handleSellerEdit = (editedSeller: SellerData) => {try {- setSellers((prevSellers) => {- const updatedSellers = prevSellers.map((seller) =>- seller.id === editedSeller.id ? editedSeller : seller- );+ const updatedSellers = sellersSelectOptions.map((seller) =>+ seller.id === editedSeller.id ? editedSeller : seller+ );- localStorage.setItem(- SELLERS_LOCAL_STORAGE_KEY,- JSON.stringify(updatedSellers)- );- return updatedSellers;- });+ localStorage.setItem(+ SELLERS_LOCAL_STORAGE_KEY,+ JSON.stringify(updatedSellers)+ );+ setSellersSelectOptions(updatedSellers);setValue("seller", editedSeller);++ // end edit modesetEditingSeller(null);toast.success("Seller updated successfully", {@@ -147,6 +153,7 @@ export function SellerManagement({// analytics track eventopenPanel.track("edit_seller_success");+ umamiTrackEvent("edit_seller_success");} catch (error) {console.error("Failed to edit seller:", error);@@ -161,7 +168,9 @@ export function SellerManagement({if (id) {setSelectedSellerIndex(id);- const selectedSeller = sellers.find((seller) => seller.id === id);+ const selectedSeller = sellersSelectOptions.find(+ (seller) => seller.id === id+ );if (selectedSeller) {setValue("seller", selectedSeller);@@ -174,11 +183,12 @@ export function SellerManagement({// analytics track eventopenPanel.track("change_seller");+ umamiTrackEvent("change_seller");};const handleDeleteSeller = () => {try {- setSellers((prevSellers) => {+ setSellersSelectOptions((prevSellers) => {const updatedSellers = prevSellers.filter((seller) => seller.id !== selectedSellerIndex);@@ -203,6 +213,7 @@ export function SellerManagement({// analytics track eventopenPanel.track("delete_seller_success");+ umamiTrackEvent("delete_seller_success");} catch (error) {console.error("Failed to delete seller:", error);@@ -212,14 +223,14 @@ export function SellerManagement({}};- const activeSeller = sellers.find(+ const activeSeller = sellersSelectOptions.find((seller) => seller.id === selectedSellerIndex);return (<><div className="flex flex-col gap-2">- {sellers.length > 0 ? (+ {sellersSelectOptions.length > 0 ? (<div className="space-y-1"><div className="flex items-center gap-1"><Label htmlFor={sellerSelectId} className="">@@ -238,7 +249,7 @@ export function SellerManagement({title={activeSeller?.name}><option value="">No seller selected (default)</option>- {sellers.map((seller) => (+ {sellersSelectOptions.map((seller) => (<option key={seller.id} value={seller.id}>{seller.name}</option>@@ -255,6 +266,7 @@ export function SellerManagement({onClick={() => {if (activeSeller) {setEditingSeller(activeSeller);+ setIsSellerDialogOpen(true);}}}className="h-8 px-2"@@ -291,19 +303,31 @@ export function SellerManagement({_variant="outline"_size="sm"onClick={() => {- setIsSellerDialogOpen(true);+ if (isLocalStorageAvailable) {+ setIsSellerDialogOpen(true);+ }}}+ aria-disabled={!isLocalStorageAvailable}+ className={cn(+ !isLocalStorageAvailable && "cursor-not-allowed opacity-40"+ )}>New Seller<Plus className="ml-1 h-3 w-3" /></Button>}- content="You can save multiple sellers to use them later"+ content={+ isLocalStorageAvailable+ ? "You can save multiple sellers to use them later"+ : "Local storage is not available in your browser. Please enable it or try another browser"+ }/></div><SellerDialog- isOpen={isSellerDialogOpen || isEditMode}+ // we need to rerender the dialog when the editingSeller changes+ key={editingSeller?.id}+ isOpen={isSellerDialogOpen}onClose={() => {setIsSellerDialogOpen(false);setEditingSeller(null);@@ -311,7 +335,6 @@ export function SellerManagement({handleSellerAdd={handleSellerAdd}handleSellerEdit={handleSellerEdit}initialData={editingSeller}- key={editingSeller?.id}isEditMode={isEditMode}/>diff --git a/src/lib/check-local-storage.ts b/src/lib/check-local-storage.tsnew file mode 100644index 0000000..f1ddddf--- /dev/null+++ b/src/lib/check-local-storage.ts@@ -0,0 +1,27 @@+/**+ * https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API#testing_for_availability+ */+function storageAvailable(type: "localStorage" | "sessionStorage") {+ let storage;+ try {+ storage = window[type];+ const x = "__storage_test__";+ storage.setItem(x, x);+ storage.removeItem(x);++ return true;+ } catch (e) {+ return (+ e instanceof DOMException &&+ e.name === "QuotaExceededError" &&+ // acknowledge QuotaExceededError only if there's something already stored+ storage &&+ storage.length !== 0+ );+ }+}++/**+ * Check if localStorage is available+ */+export const isLocalStorageAvailable = storageAvailable("localStorage");diff --git a/src/lib/umami-analytics-track-event.tsx b/src/lib/umami-analytics-track-event.tsxnew file mode 100644index 0000000..fbe50d0--- /dev/null+++ b/src/lib/umami-analytics-track-event.tsx@@ -0,0 +1,50 @@+"use client";++import { z } from "zod";++interface UmamiEventData {+ [key: string]: string | number | boolean | undefined;+}++interface UmamiTrackOptions {+ url?: string;+ website?: string;+ data?: UmamiEventData;+}++declare global {+ interface Window {+ umami?: {+ track: (eventName: string, options?: UmamiTrackOptions) => void;+ };+ }+}++/**+ * Track events with Umami Analytics+ * https://umami.is/docs/track-events+ * @returns Object containing track function+ */+export const umamiTrackEvent = (+ eventName: string,+ options?: UmamiTrackOptions+) => {+ if (typeof window === "undefined") return;++ const eventNameSchema = z.string().min(1).max(50);++ try {+ eventNameSchema.parse(eventName);+ } catch (error) {+ if (error instanceof z.ZodError) {+ console.error("Invalid event name:", error.errors[0].message);+ return;+ }+ }++ try {+ window.umami?.track(eventName, options);+ } catch (error) {+ console.error("Failed to track event:", error);+ }+};diff --git a/tailwind.config.ts b/tailwind.config.tsindex 3b5861f..8b60a76 100644--- a/tailwind.config.ts+++ b/tailwind.config.ts@@ -37,19 +37,20 @@ const config: Config = {},heartbeat: {"0%": { transform: "scale(1)" },- "25%": { transform: "scale(1.3)" },+ "25%": { transform: "scale(1.4)" },"50%": { transform: "scale(1)" },- "75%": { transform: "scale(1.3)" },+ "75%": { transform: "scale(1.4)" },"100%": { transform: "scale(1)" },},},animation: {"accordion-down": "accordion-down 0.2s ease-out","accordion-up": "accordion-up 0.2s ease-out",- heartbeat: "heartbeat 3s ease-in-out infinite 30s", // 3s = duration of animation, infinite = repeat forever, 30s = delay before starting animation+ heartbeat: "heartbeat 3s ease-in-out infinite 25s", // 3s = duration of animation, infinite = repeat forever, 25s = delay before starting animation},},},+ // eslint-disable-next-line @typescript-eslint/no-require-importsplugins: [require("tailwindcss-animate")],};export default config;