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
import dayjs from "dayjs";
import { FileTextIcon, PencilIcon } from "lucide-react";
import dynamic from "next/dynamic";
import Link from "next/link";
import { useRef, useState, type ReactNode, type RefObject } from "react";
import {
type InvoiceData,
type MobileTabsValues,
DEFAULT_MOBILE_TAB,
MOBILE_TABS_VALUES,
} from "@/app/schema";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { CustomTooltip } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
import { useAppMetadata } from "../hooks/use-app-metadata";
import { updateAppMetadata } from "../utils/get-app-metadata";
import { InvoiceForm } from "./invoice-form";
import { InvoicePDFDownloadLink } from "./invoice-pdf-download-link";
import { MobileFormScrollContainer } from "./mobile-form-scroll-container";
import { ShareInvoiceButton } from "./share-invoice-button";
const DesktopPDFViewerModuleLoading = () => {
return (
<div className="flex h-[580px] w-full items-center justify-center border border-gray-200 bg-gray-200 lg:h-[620px] 2xl:h-[700px]">
<div className="text-center">
<div className="mx-auto mb-4 h-8 w-8 animate-spin rounded-full border-4 border-blue-500 border-t-transparent" />
<p className="text-gray-600">Loading PDF viewer...</p>
</div>
</div>
);
};
const MobileInvoicePDFViewerModuleLoading = () => {
return (
<div className="flex h-[520px] w-[650px] items-center justify-center border border-gray-200 bg-gray-200 lg:h-[620px] 2xl:h-[700px]">
<div className="text-center">
<div className="mx-auto mb-4 h-8 w-8 animate-spin rounded-full border-4 border-blue-500 border-t-transparent" />
<p className="text-gray-600">Loading PDF viewer...</p>
</div>
</div>
);
};
const DesktopInvoicePDFViewer = dynamic(
() => {
return import("./invoice-pdf-preview/desktop-pdf-viewer").then((mod) => {
return mod.DesktopInvoicePDFViewer;
});
},
{
ssr: false,
loading: () => {
return <DesktopPDFViewerModuleLoading />;
},
},
);
const MobileInvoicePDFViewer = dynamic(
() => {
return import("./invoice-pdf-preview/mobile-pdf-viewer").then((mod) => {
return mod.MobileInvoicePDFViewer;
});
},
{
ssr: false,
loading: () => {
return <MobileInvoicePDFViewerModuleLoading />;
},
},
);
const PdfViewer = ({ isMobile }: { isMobile: boolean }) => {
// Both viewers read the single PDF generated by `InvoicePdfInstanceProvider`.
//
// Use Mobile PDF viewer for:
// 1. Mobile devices
// 2. Any in-app browser/WebView environment (new logic for platforms like X.com, LinkedIn, etc.)
// This is due to limitations of the standard PDF viewer in these environments
// https://github.com/diegomura/react-pdf/issues/714
if (isMobile) {
return <MobileInvoicePDFViewer />;
}
// Normal version for standard desktop browsers
return <DesktopInvoicePDFViewer />;
};
const TAB_INVOICE_FORM = MOBILE_TABS_VALUES[0];
const TAB_INVOICE_PREVIEW = MOBILE_TABS_VALUES[1];
/**
* "Made by Vlad Sazonau" with the avatar, linking to `/founder`.
*
* The mobile dock and the desktop column render the same credit; before this they held two
* copies of the same markup, differing only in a shade of grey and a top margin.
*/
function FounderCredit({ className }: { className?: string }) {
return (
<div
className={cn(
"flex items-center gap-1.5 text-xs text-zinc-700 duration-500 animate-in fade-in slide-in-from-bottom-2",
className,
)}
>
<a href={"/founder"}>
<img
src="https://ik.imagekit.io/fl2lbswwo/avatar.jpeg?updatedAt=1757456439459"
alt="Vlad Sazonau"
className="size-6 rounded-full"
height="24"
width="24"
loading="lazy"
decoding="async"
/>
</a>
<span>
Made by{" "}
<a href={"/founder"} className="underline hover:text-black">
Vlad Sazonau
</a>
</span>
</div>
);
}
function LocalStorageNotice() {
return (
<CustomTooltip
trigger={
<button
type="button"
className="cursor-default text-zinc-700 transition-colors hover:text-zinc-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2"
>
Saved locally in your browser
</button>
}
content="No data is uploaded to the server"
side="bottom"
popoverOnMobile
className="w-fit"
/>
);
}
export function InvoiceClientPage({
invoiceDataState,
handleInvoiceDataChange,
handleShareInvoice,
isMobile,
canShareInvoice,
currentInvoiceFormDataRef,
isUnmodifiedInvoiceFromLink,
mobileDockNotice,
onMobileTabChange,
}: {
invoiceDataState: InvoiceData;
handleInvoiceDataChange: (invoiceData: InvoiceData) => void;
handleShareInvoice: () => void;
isMobile: boolean;
canShareInvoice: boolean;
currentInvoiceFormDataRef: RefObject<(() => InvoiceData | null) | null>;
/**
* The invoice is still the one opened from a shared link. "Invoice last updated" is
* hidden then: it comes from this browser's metadata and says nothing about that invoice.
*/
isUnmodifiedInvoiceFromLink: boolean;
/**
* Rendered inside the mobile dock, which it positions itself against to float just above
* it -- the welcome popup on phones. Ignored on desktop, where the popup floats instead.
*/
mobileDockNotice?: ReactNode;
/** Called when the user switches between the Edit/Preview tabs on mobile */
onMobileTabChange?: () => void;
}) {
const appMetadata = useAppMetadata();
const invoiceLastUpdatedAtFormatted =
appMetadata?.invoiceLastUpdatedAt && !isUnmodifiedInvoiceFromLink
? dayjs(appMetadata.invoiceLastUpdatedAt)
.locale("en")
.format("MMM D, YYYY [at] HH:mm")
: null;
const defaultMobileTab =
appMetadata?.lastVisitedMobileTab || DEFAULT_MOBILE_TAB;
const [activeMobileTab, setActiveMobileTab] =
useState<MobileTabsValues>(defaultMobileTab);
// Tabs whose panel has been opened at least once. Radix unmounts the panel of the
// inactive tab, and both panels lose something real when that happens:
//
// - the preview threw away the rendered document, so `react-pdf` parsed and rasterized
// the very same PDF again (with its loading spinner in between) on every switch back
// - the form cancelled the debounced save that `InvoiceForm` schedules 500ms after a
// keystroke, so an edit followed by a quick tab switch was silently lost
//
// Once a panel has been opened we keep it mounted and hide it with CSS instead. Panels
// stay lazy until their first visit, so the preview costs nothing for a user who never
// opens it.
const [openedMobileTabs, setOpenedMobileTabs] = useState<MobileTabsValues[]>(
() => {
return [defaultMobileTab];
},
);
/**
* Determines if a given mobile tab should remain mounted.
*
* This is useful for maintaining state or performance optimizations where certain tabs
* should not be unmounted when inactive, such as when using libraries that unmount inactive panels by default.
*/
const keepMounted = (tab: MobileTabsValues) => {
// `forceMount` only accepts `true | undefined`, `false` would still force the mount
return openedMobileTabs.includes(tab) || undefined;
};
/**
* Filled in by `InvoiceForm`. The form only writes an edit through after a 500ms
* debounce, so leaving for the preview would otherwise show the previous version of the
* invoice for a moment.
*/
const flushPendingFormChangesRef = useRef<(() => void) | null>(null);
return (
<>
{isMobile ? (
<div>
<Tabs
value={activeMobileTab}
className="w-full"
onValueChange={(value) => {
const newValue = value as MobileTabsValues;
// commit whatever was typed just before the switch, so the preview opens on
// the current invoice instead of catching up half a second later
flushPendingFormChangesRef.current?.();
setActiveMobileTab(newValue);
onMobileTabChange?.();
setOpenedMobileTabs((current) => {
return current.includes(newValue)
? current
: [...current, newValue];
});
// update the last visited mobile tab in the app metadata
updateAppMetadata((current) => {
return {
...current,
lastVisitedMobileTab: newValue,
};
});
}}
>
<TabsContent
value={TAB_INVOICE_FORM}
forceMount={keepMounted(TAB_INVOICE_FORM)}
className="mt-1 data-[state=inactive]:hidden"
>
<MobileFormScrollContainer className="h-[520px] overflow-auto rounded-lg border-b px-3 shadow-sm">
<InvoiceForm
invoiceData={invoiceDataState}
handleInvoiceDataChange={handleInvoiceDataChange}
isMobile
currentInvoiceFormDataRef={currentInvoiceFormDataRef}
flushPendingChangesRef={flushPendingFormChangesRef}
/>
</MobileFormScrollContainer>
</TabsContent>
<TabsContent
value={TAB_INVOICE_PREVIEW}
// `forceMount` keeps the panel in the tree, but it also stops Radix from
// hiding it, so the inactive state is hidden with CSS here instead
forceMount={keepMounted(TAB_INVOICE_PREVIEW)}
className="mt-1 data-[state=inactive]:hidden"
>
<div className="flex h-[520px] w-full items-center justify-center">
<PdfViewer isMobile={isMobile} />
</div>
</TabsContent>
<div className="sticky bottom-0 z-50 flex flex-col items-center justify-center gap-3 rounded-lg border border-t border-gray-200 bg-white px-3 py-3 pb-[max(0.75rem,env(safe-area-inset-bottom))] shadow-[0_-4px_6px_-1px_rgba(0,0,0,0.1),0_-2px_4px_-2px_rgba(0,0,0,0.05)]">
{mobileDockNotice}
{/*
The switch lives in the dock rather than at the top of the page, so it sits
in the same thumb zone as the two buttons it belongs with.
Styled after HeroUI's tabs: a pill-shaped track and a single indicator that
slides between the two tabs, instead of a background that appears on the
active trigger. The indicator is a plain element Radix never sees — with
exactly two equal-width tabs it is half the track wide and moves by its own
width, so there are no magic offsets to keep in sync.
*/}
{/*
`gap-0` matters: the base `TabsList` spaces its triggers by 8px, which would
make each one 4px narrower than the indicator and leave the pill sitting
slightly off its label. With no gap, a trigger and the indicator are both
exactly half the track minus the 4px inset.
*/}
{/*
The track is 40px tall and inset by 4px, so a trigger's own box is only
32px high and stops 4px short of the pill's edge — under the 44px thumb
target, with dead pixels around it that swallow a tap. `hit-area-*` grows
each trigger's tap zone with an invisible pseudo-element instead of a
bigger box, so nothing moves:
- `hit-area-y-1.5` adds 6px above and below (32px -> 44px), half of the
12px that separates the track from the dock's top edge and from the
share button, so neither is stolen from.
- `hit-area-l-4` / `hit-area-r-4` reach 16px outward — the 4px track inset
plus the dock's 12px of padding — so the two tabs cover the dock's full
width. Only the outer side of each is grown: they already meet in the
middle, and growing both inward would overlap them there.
*/}
<TabsList className="relative h-10 w-full gap-0 rounded-full bg-slate-200 p-1">
<span
aria-hidden="true"
className={cn(
"pointer-events-none absolute inset-y-1 left-1 w-[calc(50%-0.25rem)] rounded-full bg-white",
"shadow-[0_2px_4px_rgba(0,0,0,0.04),0_1px_2px_rgba(0,0,0,0.06),0_0_1px_rgba(0,0,0,0.06)]",
"transition-transform duration-300 [transition-timing-function:cubic-bezier(0.32,0.72,0,1)] motion-reduce:transition-none",
activeMobileTab === TAB_INVOICE_PREVIEW &&
"translate-x-full",
)}
/>
<TabsTrigger
value={TAB_INVOICE_FORM}
// `bg-transparent` and `shadow-none` are load-bearing: without them the
// trigger paints its own white pill on top of the sliding indicator
className="z-10 flex-1 rounded-full text-slate-600 hit-area-l-4 hit-area-y-1.5 hover:bg-transparent hover:text-slate-900 data-[state=active]:bg-transparent data-[state=active]:text-slate-900 data-[state=active]:shadow-none"
data-testid="edit-invoice-tab"
>
<span className="flex items-center gap-1">
<PencilIcon className="h-4 w-4" />
Edit Invoice
</span>
</TabsTrigger>
<TabsTrigger
value={TAB_INVOICE_PREVIEW}
className="z-10 flex-1 rounded-full text-slate-600 hit-area-r-4 hit-area-y-1.5 hover:bg-transparent hover:text-slate-900 data-[state=active]:bg-transparent data-[state=active]:text-slate-900 data-[state=active]:shadow-none"
data-testid="preview-pdf-tab"
>
<span className="flex items-center gap-1">
<FileTextIcon className="h-4 w-4" />
Preview PDF
</span>
</TabsTrigger>
</TabsList>
<ShareInvoiceButton
canShareInvoice={canShareInvoice}
handleShareInvoice={handleShareInvoice}
className="mx-2 w-full"
/>
<InvoicePDFDownloadLink
invoiceData={invoiceDataState}
isMobile={isMobile}
/>
</div>
</Tabs>
{/** Mobile version */}
<div className="relative mx-2 mt-2 flex flex-wrap items-center justify-center gap-x-2 gap-y-1 text-center text-xs text-zinc-700 duration-500 animate-in fade-in slide-in-from-bottom-2">
{invoiceLastUpdatedAtFormatted ? (
<>
<span data-testid="mobile-invoice-last-updated">
<span className="font-semibold">Invoice last updated:</span>{" "}
{invoiceLastUpdatedAtFormatted}
</span>
</>
) : null}
{/* Separator */}
<span
className="hidden h-3 w-px bg-zinc-400 min-[453px]:block"
aria-hidden="true"
/>
<LocalStorageNotice />
</div>
<div
className="mt-5 flex flex-wrap justify-center gap-1 text-xs text-zinc-900"
data-testid="mobile-terms-of-service-link"
>
By using this tool, you agree to the{" "}
<Link href="/tos" className="underline hover:text-black">
Terms of Service
</Link>
</div>
{/* Founders info section (Mobile version) */}
<div className="mt-5 flex w-full justify-center">
<FounderCredit />
</div>
</div>
) : (
// Desktop View
<>
{/* Invoice form section i.e. left column (Desktop version) */}
<div className="col-span-4">
<div className="h-[620px] overflow-auto border-b px-3 pl-0 shadow-[0_4px_6px_-4px_rgba(0,0,0,0.1)] 2xl:h-[700px]">
<InvoiceForm
invoiceData={invoiceDataState}
handleInvoiceDataChange={handleInvoiceDataChange}
currentInvoiceFormDataRef={currentInvoiceFormDataRef}
/>
</div>
{/* Founders info section (Desktop version) */}
<FounderCredit className="mt-1 text-zinc-800" />
</div>
{/* Invoice preview section i.e. right column (Desktop version) */}
<div className="relative col-span-8 h-[620px] w-full max-w-full 2xl:h-[700px]">
<div className="relative">
<div className="absolute -top-5 right-0 z-10 flex items-center gap-x-2 text-center text-xs text-zinc-700 duration-500 animate-in fade-in slide-in-from-bottom-2 md:-mb-5 lg:text-right">
<LocalStorageNotice />
{invoiceLastUpdatedAtFormatted ? (
<>
<span
className="hidden h-3 w-px bg-zinc-400 sm:block"
aria-hidden="true"
/>
<span data-testid="desktop-invoice-last-updated">
<span className="font-semibold">
Invoice last updated:
</span>{" "}
{invoiceLastUpdatedAtFormatted}
</span>
</>
) : null}
</div>
</div>
<PdfViewer isMobile={false} />
<div
className="absolute -bottom-6 right-0 text-right text-xs text-zinc-800"
data-testid="desktop-terms-of-service-link"
>
By using this tool, you agree to the{" "}
<Link href="/tos" className="underline hover:text-black">
Terms of Service
</Link>
</div>
</div>
</>
)}
</>
);
}