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
refactor: currency searchable combobox (#183)
Vlad Sazonau5ffef437569f
diff --git a/TODO.md b/TODO.mdindex 23fe211..2373307 100644--- a/TODO.md+++ b/TODO.md@@ -1,6 +1,6 @@TODO list-- [ ] replace native select for currencies with Combobox (https://ui.shadcn.com/docs/components/radix/combobox) i.e. make it searchable? (also add Groups - Major, EU, Africa, Asia, Latin America, etc.)+- [] on mobile, when switching between tabs, scroll to the last position of the invoice form section for better UXIMPORTANT:diff --git a/e2e/default-invoice-template/default-invoice-template.test.ts b/e2e/default-invoice-template/default-invoice-template.test.tsindex dbc0547..f974104 100644--- a/e2e/default-invoice-template/default-invoice-template.test.ts+++ b/e2e/default-invoice-template/default-invoice-template.test.ts@@ -389,8 +389,19 @@ test.describe("Default Invoice Template", () => {}, testInfo) => {const DATE_FORMAT = "MMMM D, YYYY";- // Switch to another currency- await page.getByRole("combobox", { name: "Currency" }).selectOption("GBP");+ // Switch to another currency via combobox+ const currencyCombobox = page.getByRole("combobox", { name: "Currency" });++ // Open the combobox to select the currency+ await currencyCombobox.click();++ // Select the GBP currency+ await page.getByRole("option", { name: /^GBP\s/ }).click();++ await expect(currencyCombobox).toContainText("GBP");++ // check that value is saved in the hidden input+ await expect(page.locator('input[name="currency"]')).toHaveValue("GBP");// Switch to another date formatawait page@@ -663,8 +674,17 @@ test.describe("Default Invoice Template", () => {.getByRole("combobox", { name: "Invoice PDF Language" }).selectOption("fr");- // Switch currency to GBP- await page.getByRole("combobox", { name: "Currency" }).selectOption("GBP");+ // Switch currency to GBP via combobox+ const mobileCurrencyCombobox = page.getByRole("combobox", {+ name: "Currency",+ });+ await mobileCurrencyCombobox.click();+ await page.getByRole("option", { name: /^GBP\s/ }).click();++ await expect(mobileCurrencyCombobox).toContainText("GBP");++ // check that value is saved in the hidden input+ await expect(page.locator('input[name="currency"]')).toHaveValue("GBP");const invoiceNumberFieldset = page.getByRole("group", {name: "Invoice Number",@@ -1007,10 +1027,14 @@ test.describe("Default Invoice Template", () => {// fill once again the invoice numberawait invoiceNumberLabelInput.fill("Faktura TEST:");- // Switch currency to CHF- const currencySelect = page.getByRole("combobox", { name: "Currency" });- await currencySelect.selectOption("CHF");- await expect(currencySelect).toHaveValue("CHF");+ // Switch currency to CHF via combobox+ const currencyCombobox2 = page.getByRole("combobox", { name: "Currency" });+ await currencyCombobox2.click();+ await page.getByRole("option", { name: /^CHF\s/ }).click();+ await expect(currencyCombobox2).toContainText("CHF");++ // check that value is saved in the hidden input+ await expect(page.locator('input[name="currency"]')).toHaveValue("CHF");const notesFinalSection = page.getByTestId(`final-section`);// for better debugging screenshots, we fill in the notes field with a test note =)@@ -1066,10 +1090,15 @@ test.describe("Default Invoice Template", () => {}),).toBeVisible();- const newCurrencySelect = page.getByRole("combobox", { name: "Currency" });+ const newCurrencyCombobox = page.getByRole("combobox", {+ name: "Currency",+ });// Verify CHF currency is selected- await expect(newCurrencySelect).toHaveValue("CHF");+ await expect(newCurrencyCombobox).toContainText("CHF");++ // check that value is saved in the hidden input+ await expect(page.locator('input[name="currency"]')).toHaveValue("CHF");// wait for debounce timeout// eslint-disable-next-line playwright/no-wait-for-timeout@@ -1144,8 +1173,11 @@ test.describe("Default Invoice Template", () => {await expect(templateSelect).toHaveValue("stripe");// Currency should be CHF after navigating back to the previous page- const currencySelect2 = page.getByRole("combobox", { name: "Currency" });- await expect(currencySelect2).toHaveValue("CHF");+ const currencyCombobox3 = page.getByRole("combobox", { name: "Currency" });+ await expect(currencyCombobox3).toContainText("CHF");++ // check that value is saved in the hidden input+ await expect(page.locator('input[name="currency"]')).toHaveValue("CHF");const newNotesFinalSection = page.getByTestId(`final-section`);diff --git a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/displays-qr-code-in-pdf-default-template-Desktop-Chrome-darwin.png b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/displays-qr-code-in-pdf-default-template-Desktop-Chrome-darwin.pngindex d97143a..bbeb677 100644Binary files a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/displays-qr-code-in-pdf-default-template-Desktop-Chrome-darwin.png and b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/displays-qr-code-in-pdf-default-template-Desktop-Chrome-darwin.png differdiff --git a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/displays-qr-code-in-pdf-default-template-Mobile-Chrome-darwin.png b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/displays-qr-code-in-pdf-default-template-Mobile-Chrome-darwin.pngindex 8cf85ca..a7b8b43 100644Binary files a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/displays-qr-code-in-pdf-default-template-Mobile-Chrome-darwin.png and b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/displays-qr-code-in-pdf-default-template-Mobile-Chrome-darwin.png differdiff --git a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/displays-qr-code-in-pdf-default-template-Mobile-Safari-darwin.png b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/displays-qr-code-in-pdf-default-template-Mobile-Safari-darwin.pngindex 6005bc0..2cde4fd 100644Binary files a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/displays-qr-code-in-pdf-default-template-Mobile-Safari-darwin.png and b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/displays-qr-code-in-pdf-default-template-Mobile-Safari-darwin.png differdiff --git a/e2e/invoice-form.test.ts b/e2e/invoice-form.test.tsindex 5d524d0..551ed81 100644--- a/e2e/invoice-form.test.ts+++ b/e2e/invoice-form.test.ts@@ -210,14 +210,24 @@ test.describe("Invoice Generator Page", () => {).toHaveText(languageName);}- // Currency selection- const currencySelect = generalInfoSection.getByRole("combobox", {+ // Currency selection (combobox with popover)+ const currencyCombobox = generalInfoSection.getByRole("combobox", {name: "Currency",});- await expect(currencySelect).toHaveValue(INITIAL_INVOICE_DATA.currency);+ const defaultCurrency = INITIAL_INVOICE_DATA.currency;+ const defaultCurrencyLabel =+ `${defaultCurrency} ${CURRENCY_SYMBOLS[defaultCurrency]} ${CURRENCY_TO_LABEL[defaultCurrency]}`.trim();+ await expect(currencyCombobox).toContainText(defaultCurrencyLabel);++ // check that value is saved in the hidden input+ await expect(page.locator('input[name="currency"]')).toHaveValue(+ INITIAL_INVOICE_DATA.currency,+ );++ // Open the combobox to verify all supported currencies are listed+ await currencyCombobox.click();- // Verify all supported currencies are available as options with correct labelsfor (const currency of SUPPORTED_CURRENCIES) {const currencySymbol = CURRENCY_SYMBOLS[currency];const currencyFullName = CURRENCY_TO_LABEL[currency];@@ -226,10 +236,13 @@ test.describe("Invoice Generator Page", () => {`${currency} ${currencySymbol} ${currencyFullName}`.trim();await expect(- currencySelect.locator(`option[value="${currency}"]`),- ).toHaveText(expectedLabel);+ page.getByRole("option", { name: expectedLabel }),+ ).toBeVisible();}+ // Close the combobox+ await currencyCombobox.click();+// Date Format selectionconst dateFormatSelect = generalInfoSection.getByRole("combobox", {name: "Date Format",@@ -604,11 +617,44 @@ test.describe("Invoice Generator Page", () => {.click();// Verify confirmation dialog appears- await expect(page.getByRole("alertdialog")).toBeVisible();+ await expect(+ page.getByTestId("delete-invoice-item-confirmation-dialog"),+ ).toBeVisible();+await expect(page.getByText('Are you sure you want to delete the invoice item "#2"?'),).toBeVisible();+ // --- Test cancel flow first ---++ // Click cancel button in dialog+ await page.getByRole("button", { name: "Cancel" }).click();++ // Dialog should disappear+ await expect(+ page.getByTestId("delete-invoice-item-confirmation-dialog"),+ ).toBeHidden();++ await expect(+ page.getByText('Are you sure you want to delete the invoice item "#2"?'),+ ).toBeHidden();++ // Item should still be present+ await expect(+ invoiceItemsSection.getByText("Item 2", { exact: true }),+ ).toBeVisible();++ // --- Now confirm deletion flow ---++ // Open the dialog again+ await invoiceItemsSection+ .getByRole("button", { name: "Delete Invoice Item 2" })+ .click();++ await expect(+ page.getByTestId("delete-invoice-item-confirmation-dialog"),+ ).toBeVisible();+// Confirm deletionawait page.getByRole("button", { name: "Delete" }).click();@@ -897,11 +943,16 @@ test.describe("Invoice Generator Page", () => {invoiceItemsSection.getByText("Preview: €0.00 (zero EUR 00/100)"),).toBeVisible();- const currencySelect = page.getByRole("combobox", { name: "Currency" });+ const currencyCombobox = page.getByRole("combobox", { name: "Currency" });++ // Switch currency via combobox+ await currencyCombobox.click();+ await page.getByRole("option", { name: /^USD\s/ }).click();++ await expect(currencyCombobox).toContainText("USD");- // Switch currency- await currencySelect.selectOption("USD");- await expect(currencySelect).toHaveValue("USD");+ // check that value is saved in the hidden input+ await expect(page.locator('input[name="currency"]')).toHaveValue("USD");// Verify calculations with new currencyawait invoiceItemsSectiondiff --git a/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/displays-qr-code-in-pdf-stripe-template-Desktop-Chrome-darwin.png b/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/displays-qr-code-in-pdf-stripe-template-Desktop-Chrome-darwin.pngindex 11f3df7..f6aa5aa 100644Binary files a/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/displays-qr-code-in-pdf-stripe-template-Desktop-Chrome-darwin.png and b/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/displays-qr-code-in-pdf-stripe-template-Desktop-Chrome-darwin.png differdiff --git a/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/displays-qr-code-in-pdf-stripe-template-Mobile-Chrome-darwin.png b/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/displays-qr-code-in-pdf-stripe-template-Mobile-Chrome-darwin.pngindex 6fedaa2..2de1247 100644Binary files a/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/displays-qr-code-in-pdf-stripe-template-Mobile-Chrome-darwin.png and b/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/displays-qr-code-in-pdf-stripe-template-Mobile-Chrome-darwin.png differdiff --git a/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/displays-qr-code-in-pdf-stripe-template-Mobile-Safari-darwin.png b/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/displays-qr-code-in-pdf-stripe-template-Mobile-Safari-darwin.pngindex 58cc3a8..3f436d1 100644Binary files a/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/displays-qr-code-in-pdf-stripe-template-Mobile-Safari-darwin.png and b/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/displays-qr-code-in-pdf-stripe-template-Mobile-Safari-darwin.png differdiff --git a/playwright.config.ts b/playwright.config.tsindex f37bae9..83cdb12 100644--- a/playwright.config.ts+++ b/playwright.config.ts@@ -33,7 +33,7 @@ export default defineConfig({workers: process.env.CI ? 1 : undefined, // IMPORTANT: if tests are flaky locally, make `workers: 1` or `workers: 2`/* timeout for expect assertions */expect: {- timeout: isLocal ? 15_000 : 25_000,+ timeout: isLocal ? 15_000 : 35_000,},// /* timeout for test execution */diff --git a/src/app/(app)/components/index.tsx b/src/app/(app)/components/index.tsxindex 5489f33..a44cdb7 100644--- a/src/app/(app)/components/index.tsx+++ b/src/app/(app)/components/index.tsx@@ -263,6 +263,7 @@ export function InvoiceClientPage({setErrorWhileGeneratingPdfIsShown}qrCodeDataUrl={qrCodeDataUrl}+ isMobile={isMobile}/></div>{invoiceLastUpdatedAtFormatted && (diff --git a/src/app/(app)/components/invoice-form/index.tsx b/src/app/(app)/components/invoice-form/index.tsxindex 127ec6c..a25db46 100644--- a/src/app/(app)/components/invoice-form/index.tsx+++ b/src/app/(app)/components/invoice-form/index.tsx@@ -35,6 +35,7 @@ import React, {memo,useCallback,useEffect,+ useRef,useState,type Dispatch,type SetStateAction,@@ -127,6 +128,8 @@ export const InvoiceForm = memo(function InvoiceForm({name: "items",});+ const isDeletingInvoiceItemRef = useRef(false);+// calculate totals and other values when invoice items changeuseEffect(() => {// run validations before calculations because user can input invalid data@@ -194,8 +197,14 @@ export const InvoiceForm = memo(function InvoiceForm({// regenerate pdf on every input change with debounceconst debouncedRegeneratePdfOnFormChange = useDebouncedCallback(async (data: InvoiceData) => {- // close all other toasts (if any)- toast.dismiss();+ // if we are deleting an invoice item, we don't want to close success notification+ if (isDeletingInvoiceItemRef.current) {+ isDeletingInvoiceItemRef.current = false;+ } else {+ // close all other toasts, for example when user is updating the invoice form and we are showing the info notification that the invoice has been updated, we want to close the info notification for better UX+ toast.dismiss();+ }+setInvoiceFormHasErrors(false);// TODO: double check if we need this code, because we already save to local storage in the page.client.tsx (parent component) (line: 267) useEffect "Save to localStorage whenever data changes on form update"@@ -260,6 +269,8 @@ export const InvoiceForm = memo(function InvoiceForm({*/const handleRemoveInvoiceItem = useCallback((index: number) => {+ isDeletingInvoiceItemRef.current = true;+setValue("items",invoiceItems.filter((_, i) => i !== index),diff --git a/src/app/(app)/components/invoice-form/sections/general-information.tsx b/src/app/(app)/components/invoice-form/sections/general-information.tsxindex 45b0131..f712fd8 100644--- a/src/app/(app)/components/invoice-form/sections/general-information.tsx+++ b/src/app/(app)/components/invoice-form/sections/general-information.tsx@@ -1,25 +1,16 @@+import { INVOICE_PDF_TRANSLATIONS } from "@/app/(app)/pdf-i18n-translations/pdf-translations";import {- type Control,- Controller,- type FieldErrors,- type UseFormSetValue,- useWatch,-} from "react-hook-form";-import {- CURRENCY_SYMBOLS,- CURRENCY_TO_LABEL,DEFAULT_DATE_FORMAT,+ type InvoiceData,LANGUAGE_TO_LABEL,STRIPE_DEFAULT_DATE_FORMAT,- SUPPORTED_TEMPLATES,- TEMPLATE_TO_LABEL,- type InvoiceData,-} from "@/app/schema";-import {- SUPPORTED_CURRENCIES,SUPPORTED_DATE_FORMATS,SUPPORTED_LANGUAGES,+ SUPPORTED_TEMPLATES,+ TEMPLATE_TO_LABEL,} from "@/app/schema";+import { CurrencyCombobox } from "@/components/currency-combobox";+import { Button } from "@/components/ui/button";import { ButtonHelper } from "@/components/ui/button-helper";import { Input } from "@/components/ui/input";import { InputHelperMessage } from "@/components/ui/input-helper-message";@@ -28,11 +19,16 @@ import { SelectNative } from "@/components/ui/select-native";import { Switch } from "@/components/ui/switch";import { Textarea } from "@/components/ui/textarea";import { CustomTooltip } from "@/components/ui/tooltip";-import { INVOICE_PDF_TRANSLATIONS } from "@/app/(app)/pdf-i18n-translations/pdf-translations";-import { Button } from "@/components/ui/button";import dayjs from "dayjs";-import { AlertTriangle, Upload, X, InfoIcon } from "lucide-react";+import { AlertTriangle, InfoIcon, Upload, X } from "lucide-react";import { memo, useCallback, useRef } from "react";+import {+ type Control,+ Controller,+ type FieldErrors,+ type UseFormSetValue,+ useWatch,+} from "react-hook-form";import { toast } from "sonner";const AlertIcon = () => {@@ -405,30 +401,14 @@ export const GeneralInformation = memo(function GeneralInformation({<Controllername="currency"control={control}- render={({ field }) => {- return (- <SelectNative {...field} id={`currency`} className="block">- {SUPPORTED_CURRENCIES.map((currency) => {- const currencySymbol = CURRENCY_SYMBOLS[currency] || null;-- const currencyFullName =- CURRENCY_TO_LABEL[currency] || null;-- return (- <option- key={currency}- value={currency}- defaultValue={SUPPORTED_CURRENCIES[0]}- >- {currency} {currencySymbol} {currencyFullName}- </option>- );- })}- </SelectNative>- );- }}+ render={({ field }) => (+ <CurrencyCombobox+ id={`currency`}+ value={field.value}+ onChange={field.onChange}+ />+ )}/>-{errors.currency ? (<ErrorMessage>{errors.currency.message}</ErrorMessage>) : (diff --git a/src/app/(app)/components/invoice-form/sections/invoice-items.tsx b/src/app/(app)/components/invoice-form/sections/invoice-items.tsxindex 3710857..c03bd0f 100644--- a/src/app/(app)/components/invoice-form/sections/invoice-items.tsx+++ b/src/app/(app)/components/invoice-form/sections/invoice-items.tsx@@ -859,7 +859,7 @@ function DeleteInvoiceItemConfirmationDialog({if (!open) setDeleteItemIndex(null);}}>- <AlertDialogContent>+ <AlertDialogContent data-testid="delete-invoice-item-confirmation-dialog"><AlertDialogHeader><AlertDialogTitle>Delete Invoice Item</AlertDialogTitle><AlertDialogDescription className="text-balance">diff --git a/src/app/(app)/components/invoice-page-header.tsx b/src/app/(app)/components/invoice-page-header.tsxindex f0ba99a..3b4140a 100644--- a/src/app/(app)/components/invoice-page-header.tsx+++ b/src/app/(app)/components/invoice-page-header.tsx@@ -40,6 +40,7 @@ export function InvoicePageHeader({errorWhileGeneratingPdfIsShown,setErrorWhileGeneratingPdfIsShown,qrCodeDataUrl,+ isMobile,}: {canShareInvoice: boolean;handleShareInvoice: () => void;@@ -48,6 +49,7 @@ export function InvoicePageHeader({errorWhileGeneratingPdfIsShown: boolean;setErrorWhileGeneratingPdfIsShown: (value: boolean) => void;qrCodeDataUrl: string;+ isMobile: boolean;}) {return (<div data-testid="header">@@ -148,6 +150,7 @@ export function InvoicePageHeader({setErrorWhileGeneratingPdfIsShown}qrCodeDataUrl={qrCodeDataUrl}+ isMobile={isMobile}/></>) : null}diff --git a/src/app/(app)/components/invoice-pdf-download-link.tsx b/src/app/(app)/components/invoice-pdf-download-link.tsxindex c797faf..87f6465 100644--- a/src/app/(app)/components/invoice-pdf-download-link.tsx+++ b/src/app/(app)/components/invoice-pdf-download-link.tsx@@ -50,11 +50,13 @@ export function InvoicePDFDownloadLink({errorWhileGeneratingPdfIsShown,setErrorWhileGeneratingPdfIsShown,qrCodeDataUrl,+ isMobile,}: {invoiceData: InvoiceData;errorWhileGeneratingPdfIsShown: boolean;setErrorWhileGeneratingPdfIsShown: (error: boolean) => void;qrCodeDataUrl: string;+ isMobile: boolean;}) {const { inAppInfo } = useDeviceContext();const { markCTAActionTriggered } = useCTAToast();@@ -75,6 +77,7 @@ export function InvoicePDFDownloadLink({"File not available. Please try again in different browser.",{id: "file-not-available-error-toast",+ position: isMobile ? "top-center" : "bottom-right",},);return;@@ -85,7 +88,11 @@ export function InvoicePDFDownloadLink({toast(`Downloads are blocked inside ${inAppInfo?.name ?? "this app"}. Open in your browser to save.`,- { icon: "📱", id: "downloads-blocked-inside-app-toast" },+ {+ icon: "📱",+ id: "downloads-blocked-inside-app-toast",+ position: isMobile ? "top-center" : "bottom-right",+ },);return;@@ -95,7 +102,11 @@ export function InvoicePDFDownloadLink({e.preventDefault();toast(`Downloads are blocked inside Telegram. Open in your browser to save.`,- { icon: "📱", id: "downloads-blocked-inside-telegram-toast" },+ {+ icon: "📱",+ id: "downloads-blocked-inside-telegram-toast",+ position: isMobile ? "top-center" : "bottom-right",+ },);return;@@ -133,6 +144,7 @@ export function InvoicePDFDownloadLink({isTelegramPreviewBrowser,isLoading,error,+ isMobile,invoiceData.template,markCTAActionTriggered,],@@ -221,10 +233,16 @@ export function InvoicePDFDownloadLink({id: "in-app-browser-toast", // To prevent duplicate toastsduration: Infinity,icon: "⚠️",+ position: isMobile ? "top-center" : "bottom-right",});setInAppBrowserToastShown(true);}- }, [inAppInfo?.isInApp, inAppBrowserToastShown, isTelegramPreviewBrowser]);+ }, [+ inAppInfo?.isInApp,+ inAppBrowserToastShown,+ isTelegramPreviewBrowser,+ isMobile,+ ]);return (<>diff --git a/src/app/(app)/page.client.tsx b/src/app/(app)/page.client.tsxindex f660c78..3972873 100644--- a/src/app/(app)/page.client.tsx+++ b/src/app/(app)/page.client.tsx@@ -701,6 +701,7 @@ export function AppPageClient({setErrorWhileGeneratingPdfIsShown}qrCodeDataUrl={qrCodeDataUrl}+ isMobile={isMobile}/><div className="grid grid-cols-1 gap-4 lg:grid-cols-12"><InvoiceClientPagediff --git a/src/app/(app)/utils/generate-qr-code-data-url.ts b/src/app/(app)/utils/generate-qr-code-data-url.tsindex 09b2caf..8d15309 100644--- a/src/app/(app)/utils/generate-qr-code-data-url.ts+++ b/src/app/(app)/utils/generate-qr-code-data-url.ts@@ -1,4 +1,54 @@-import QRCode from "qrcode";+import QRCode, { type QRCodeErrorCorrectionLevel } from "qrcode";++/**+ * The minimum pixel width for the generated QR code image.+ * Ensures that the QR code is always large enough to be easily scannable,+ * regardless of how short the encoded data is.+ */+const MIN_WIDTH = 300;++/**+ * The maximum pixel width for the generated QR code image.+ * Prevents the QR code from becoming overly large for very long strings,+ * balancing file size and readability.+ */+const MAX_WIDTH = 500;++/**+ * The length threshold (number of characters) to determine when to lower the+ * QR code's error correction level.+ * For inputs longer than this value, a lower error correction level ("L") is used+ * to prevent the QR code from becoming too dense and difficult to scan.+ */+const LONG_INPUT_THRESHOLD = 300;++/**+ * Calculates the pixel width for the QR code image based on the length of the input data.+ * Ensures that the QR code maintains module size (pixels per module) so the code remains scannable,+ * especially for longer inputs which require more modules.+ *+ * @param {number} dataLength - The length of the data string to be encoded in the QR code.+ * @returns {number} The calculated width (in pixels) for the QR code image, clamped between MIN_WIDTH and MAX_WIDTH.+ */+function getQrPixelWidth(dataLength: number): number {+ const scaled = Math.ceil((dataLength / 100) * 100) + 200;+ return Math.min(Math.max(scaled, MIN_WIDTH), MAX_WIDTH);+}++/**+ * Determines the QR code error correction level based on the length of input data.+ *+ * Uses a lower error correction level ("L") for very long input to prevent the QR code from becoming unreasonably dense,+ * and medium level ("M") for normal-length data to balance robustness and code size.+ *+ * @param dataLength - The length of the data string to be encoded in the QR code.+ * @returns The error correction level ("L" or "M") for QR code generation.+ */+function getErrorCorrectionLevel(+ dataLength: number,+): QRCodeErrorCorrectionLevel {+ return dataLength > LONG_INPUT_THRESHOLD ? "L" : "M";+}/*** Generate a QR code as a base64 data URL@@ -12,10 +62,14 @@ export async function generateQrCodeDataUrl(data: string): Promise<string> {}try {+ const errorCorrectionLevel = getErrorCorrectionLevel(data.length);+ const pixelWidth = getQrPixelWidth(data.length);+const dataUrl = await QRCode.toDataURL(data, {- errorCorrectionLevel: "M",+ type: "image/png",+ errorCorrectionLevel,margin: 2,- width: 200, // Generate at 2x resolution for crisp rendering+ width: pixelWidth,color: {dark: "#000000",light: "#ffffff",diff --git a/src/app/schema/index.ts b/src/app/schema/index.tsindex a0700c9..998a95a 100644--- a/src/app/schema/index.ts+++ b/src/app/schema/index.ts@@ -471,6 +471,181 @@ export const CURRENCY_TO_LABEL = {export type CurrencyLabels =(typeof CURRENCY_TO_LABEL)[keyof typeof CURRENCY_TO_LABEL];+interface CurrencyGroup {+ label: string;+ currencies: SupportedCurrencies[];+}++export const CURRENCY_GROUPS = [+ { label: "Most Popular", currencies: ["EUR", "USD", "PLN", "GBP"] },+ {+ label: "Major Global",+ currencies: [+ "JPY",+ "AUD",+ "CAD",+ "CHF",+ "CNY",+ "HKD",+ "SGD",+ "SEK",+ "NOK",+ "DKK",+ "NZD",+ ],+ },+ {+ label: "Europe",+ currencies: [+ "CZK",+ "HUF",+ "RON",+ "BGN",+ "HRK",+ "RSD",+ "UAH",+ "BYN",+ "MDL",+ "ALL",+ "MKD",+ "BAM",+ "ISK",+ "RUB",+ "TRY",+ ],+ },+ {+ label: "Asia & Pacific",+ currencies: [+ "INR",+ "KRW",+ "THB",+ "MYR",+ "IDR",+ "PHP",+ "VND",+ "MMK",+ "KHR",+ "LAK",+ "PKR",+ "BDT",+ "LKR",+ "NPR",+ "MNT",+ "TWD",+ "GEL",+ "KZT",+ "UZS",+ "TJS",+ "TMT",+ "FJD",+ "PGK",+ "WST",+ "TOP",+ ],+ },+ {+ label: "Middle East & Gulf",+ currencies: [+ "AED",+ "SAR",+ "ILS",+ "QAR",+ "KWD",+ "BHD",+ "OMR",+ "JOD",+ "EGP",+ "LBP",+ "IQD",+ ],+ },+ {+ label: "Latin America & Caribbean",+ currencies: [+ "MXN",+ "BRL",+ "ARS",+ "CLP",+ "COP",+ "PEN",+ "UYU",+ "BOB",+ "PYG",+ "SRD",+ "GYD",+ "GTQ",+ "CRC",+ "PAB",+ "HNL",+ "NIO",+ "BZD",+ "SVC",+ "DOP",+ "JMD",+ "TTD",+ "BBD",+ "BSD",+ "XCD",+ "HTG",+ "AWG",+ "ANG",+ "KYD",+ ],+ },+ {+ label: "Africa",+ currencies: [+ "ZAR",+ "NGN",+ "KES",+ "GHS",+ "ETB",+ "MAD",+ "TND",+ "DZD",+ "LYD",+ "SDG",+ "SSP",+ "AOA",+ "XOF",+ "XAF",+ "CDF",+ "UGX",+ "TZS",+ "RWF",+ "ZMW",+ "MWK",+ "BWP",+ "NAD",+ "SZL",+ "LSL",+ "MUR",+ "MZN",+ "GMD",+ "MRU",+ ],+ },+] as const satisfies CurrencyGroup[];++export interface CurrencyComboboxItem {+ code: SupportedCurrencies;+ searchLabel: string;+}++export interface CurrencyComboboxGroup {+ value: string;+ items: CurrencyComboboxItem[];+}++export const CURRENCY_COMBOBOX_GROUPS = CURRENCY_GROUPS.map((group) => ({+ value: group.label,+ items: group.currencies.map((code) => ({+ code,+ searchLabel: `${code} ${CURRENCY_SYMBOLS[code]} ${CURRENCY_TO_LABEL[code]}`,+ })),+})) satisfies CurrencyComboboxGroup[];+export const SUPPORTED_TEMPLATES = ["default", "stripe"] as const;export type SupportedTemplates = (typeof SUPPORTED_TEMPLATES)[number];@@ -1054,6 +1229,7 @@ export const METADATA_LOCAL_STORAGE_KEY = "EASY_INVOICE_METADATA";// __________________________________________________________// Validate that currencies are unique// __________________________________________________________+const uniqueCurrencies = new Set(SUPPORTED_CURRENCIES);if (uniqueCurrencies.size !== SUPPORTED_CURRENCIES.length) {@@ -1071,3 +1247,27 @@ if (uniqueCurrencies.size !== SUPPORTED_CURRENCIES.length) {`SUPPORTED_CURRENCIES contains duplicate entries: ${currencyFullNames.join(", ")}`,);}++// Validate that all supported currencies are in exactly one group+const currenciesInGroups = CURRENCY_GROUPS.flatMap((g) => g.currencies);+const currenciesInGroupsSet = new Set(currenciesInGroups);++// Check for duplicates within groups+if (currenciesInGroupsSet.size !== currenciesInGroups.length) {+ const duplicates = currenciesInGroups.filter(+ (currency, index) => currenciesInGroups.indexOf(currency) !== index,+ );+ throw new Error(+ `CURRENCY_GROUPS contains duplicate entries: ${duplicates.join(", ")}`,+ );+}++// Check for missing currencies+const missingCurrencies = SUPPORTED_CURRENCIES.filter(+ (c) => !currenciesInGroupsSet.has(c),+);+if (missingCurrencies.length > 0) {+ throw new Error(+ `CURRENCY_GROUPS is missing currencies: ${missingCurrencies.join(", ")}`,+ );+}diff --git a/src/components/currency-combobox.tsx b/src/components/currency-combobox.tsxnew file mode 100644index 0000000..528dd1f--- /dev/null+++ b/src/components/currency-combobox.tsx@@ -0,0 +1,193 @@+"use client";++import {+ CURRENCY_COMBOBOX_GROUPS,+ CURRENCY_SYMBOLS,+ CURRENCY_TO_LABEL,+ type SupportedCurrencies,+} from "@/app/schema";+import { Button } from "@/components/ui/button";+import {+ Command,+ CommandEmpty,+ CommandGroup,+ CommandInput,+ CommandItem,+ CommandList,+} from "@/components/ui/command";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/components/ui/popover";+import { cn } from "@/lib/utils";+import { CheckIcon, ChevronsUpDownIcon } from "lucide-react";+import { Fragment, useCallback, useEffect, useRef, useState } from "react";++/**+ * Currency Combobox component+ * allows to select and search for currencies from a list of groups+ * - https://ui.shadcn.com/docs/components/radix/combobox+ * - https://v3.shadcn.com/docs/components/combobox+ *+ */+export function CurrencyCombobox({+ id = "",+ value,+ onChange,+}: {+ id: string;+ value: string;+ onChange: (value: string) => void;+}) {+ const [open, setOpen] = useState(false);++ // State to keep track of the currently highlighted currency in the combobox list (for keyboard navigation and focus handling)+ const [highlightedValue, setHighlightedValue] = useState("");++ const listRef = useRef<HTMLDivElement>(null);++ /**+ * Effect: Scrolls the currently selected currency into view when the combobox popover is opened (better UX).+ *+ * - When the popover is open and a currency is selected (`value`), this effect finds the+ * selected currency item in the list and scrolls it into the center of the visible area.+ * - Uses `requestAnimationFrame` to ensure the DOM is ready for manipulation, providing a smooth UI experience.+ * - Relies on a `data-selected-currency="true"` attribute to identify the correct item.+ *+ * Dependencies: Runs on changes to `open` or `value`.+ */+ useEffect(() => {+ if (!open || !value) return;++ requestAnimationFrame(() => {+ const list = listRef.current;+ if (!list) return;++ const selected = list.querySelector<HTMLElement>(+ `[data-selected-currency="true"]`,+ );+ selected?.scrollIntoView({ block: "center" });+ });+ }, [open, value]);++ /**+ * Scrolls the list of currencies to the top (better UX).+ *+ * This function is used to reset the CommandList scroll position to the top,+ * such as after changing the search query in the currency combobox.+ * It schedules the scroll using requestAnimationFrame for smooth UI updates.+ */+ const scrollListToTop = useCallback(() => {+ requestAnimationFrame(() => {+ listRef.current?.scrollTo({ top: 0 });+ });+ }, []);++ return (+ <>+ {/* hidden input to save the currency value in the form (for better testing) */}+ <input type="hidden" name="currency" value={value ?? ""} />+ <Popover+ open={open}+ onOpenChange={(isOpen) => {+ setOpen(isOpen);++ // When the popover opens and a currency is already selected (`value` is truthy), we want the search box to have that currency's "search label" highlighted so it's in view.+ // We create a label in the expected display format: "{currency code} {symbol} {full name}".+ // This helps keyboard users by focusing the current selection, and gives visual feedback as soon as the picker opens.+ if (isOpen && value) {+ const currencySymbol =+ CURRENCY_SYMBOLS[value as SupportedCurrencies];+ const currencyFullName =+ CURRENCY_TO_LABEL[value as SupportedCurrencies];+ // Example searchLabel for USD: "USD $ US Dollar"+ const searchLabel = `${value} ${currencySymbol} ${currencyFullName}`;+ setHighlightedValue(searchLabel);+ }+ }}+ >+ <PopoverTrigger asChild>+ <Button+ id={id}+ variant="outline"+ role="combobox"+ aria-expanded={open}+ className="w-full !scale-100 justify-between rounded-md border border-gray-300 bg-white pl-3 pr-2 text-sm font-normal text-slate-950 shadow-sm shadow-black/5 !outline-none transition-all hover:bg-slate-100/80 focus-visible:!border-2 focus-visible:!border-indigo-600 focus-visible:!ring-2 focus-visible:!ring-indigo-200 focus-visible:!ring-opacity-50 focus-visible:!ring-offset-1"+ >+ {value ? (+ <span className="flex min-w-0 items-center gap-2">+ <span className="truncate">+ {value} {CURRENCY_SYMBOLS[value as SupportedCurrencies]}{" "}+ {CURRENCY_TO_LABEL[value as SupportedCurrencies]}+ </span>+ </span>+ ) : (+ <span className="text-slate-500">Select currency</span>+ )}+ <ChevronsUpDownIcon+ className="shrink-0 text-slate-500/80 peer-disabled:opacity-50 dark:text-slate-400/80"+ size={16}+ strokeWidth={2}+ aria-hidden="true"+ />+ </Button>+ </PopoverTrigger>+ <PopoverContent+ className="w-full min-w-[var(--radix-popper-anchor-width)] border border-slate-300 p-0"+ align="start"+ >+ <Command+ loop+ value={highlightedValue}+ onValueChange={setHighlightedValue}+ >+ <CommandInput+ placeholder="Search currency..."+ onValueChange={scrollListToTop}+ />+ <CommandList ref={listRef}>+ <CommandEmpty>No currencies found.</CommandEmpty>+ {CURRENCY_COMBOBOX_GROUPS.map((group) => {+ return (+ <Fragment key={group.value}>+ <CommandGroup heading={group.value}>+ {group.items.map((item) => {+ const isSelectedCurrency = value === item.code;++ return (+ <CommandItem+ key={item.code}+ value={item.searchLabel}+ onSelect={() => {+ onChange(item.code);+ setOpen(false);+ }}+ data-selected-currency={+ isSelectedCurrency || undefined+ }+ className={cn(+ "mb-0.5 active:bg-slate-200/80",+ isSelectedCurrency &&+ "!bg-indigo-50 !text-indigo-900 hover:!bg-indigo-50/80 hover:!text-indigo-900/90 active:!bg-indigo-100",+ )}+ >+ {item.code} {CURRENCY_SYMBOLS[item.code]}{" "}+ {CURRENCY_TO_LABEL[item.code]}+ {isSelectedCurrency ? (+ <CheckIcon size={16} className="ml-auto" />+ ) : null}+ </CommandItem>+ );+ })}+ </CommandGroup>+ </Fragment>+ );+ })}+ </CommandList>+ </Command>+ </PopoverContent>+ </Popover>+ </>+ );+}diff --git a/src/components/ui/select-native.tsx b/src/components/ui/select-native.tsxindex 9eae9c3..9b4959c 100644--- a/src/components/ui/select-native.tsx+++ b/src/components/ui/select-native.tsx@@ -16,7 +16,7 @@ const SelectNative = React.forwardRef<HTMLSelectElement, SelectPropsNative>(<div className="relative"><selectclassName={cn(- "peer block w-full cursor-pointer appearance-none items-center rounded-md border border-gray-300 bg-white text-sm text-slate-950 shadow-sm shadow-black/5 transition-shadow focus-visible:border-indigo-500 focus-visible:ring focus-visible:ring-indigo-200 focus-visible:ring-opacity-50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 has-[option[disabled]:checked]:text-slate-500 dark:border-slate-800 dark:bg-slate-950 dark:text-slate-50 dark:focus-visible:border-slate-300 dark:focus-visible:ring-slate-300/20 dark:has-[option[disabled]:checked]:text-slate-400",+ "peer block w-full cursor-pointer appearance-none items-center rounded-md border border-gray-300 bg-white text-sm text-slate-950 shadow-sm shadow-black/5 transition-all hover:bg-slate-100/80 focus-visible:border-indigo-500 focus-visible:ring focus-visible:ring-indigo-200 focus-visible:ring-opacity-50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 has-[option[disabled]:checked]:text-slate-500 dark:border-slate-800 dark:bg-slate-950 dark:text-slate-50 dark:focus-visible:border-slate-300 dark:focus-visible:ring-slate-300/20 dark:has-[option[disabled]:checked]:text-slate-400",props.multiple? "py-1 [&>*]:px-3 [&>*]:py-1 [&_option:checked]:bg-slate-100 dark:[&_option:checked]:bg-slate-800": "h-9 pe-8 ps-3",