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
feat: refactor invoice form to improve item totals synchronization (#280)
Vlad Sazonaucdd49ffe7b3e
diff --git a/src/app/(main)/(app)/components/invoice-form/__tests__/item-totals-sync.test.tsx b/src/app/(main)/(app)/components/invoice-form/__tests__/item-totals-sync.test.tsxnew file mode 100644index 0000000..34d2202--- /dev/null+++ b/src/app/(main)/(app)/components/invoice-form/__tests__/item-totals-sync.test.tsx@@ -0,0 +1,231 @@+// @vitest-environment happy-dom++import { act, cleanup, render } from "@testing-library/react";+import { useCallback, useEffect, type RefObject } from "react";+import {+ type UseFormReturn,+ type UseFormSetValue,+ useForm,+} from "react-hook-form";+import { afterEach, describe, expect, it, vi, type Mock } from "vitest";++import { getInitialInvoiceData } from "@/app/constants";+import type { InvoiceData, InvoiceItemData } from "@/app/schema";+import { MOCK_INVOICE_ITEM_DATA } from "@/utils/__tests__/data";+import "@testing-library/jest-dom/vitest";++import { ItemTotalsSync } from "../item-totals-sync";++afterEach(() => {+ cleanup();+});++describe("ItemTotalsSync", () => {+ it("renders nothing", () => {+ const { container } = renderItemTotalsSync({+ items: [createItem()],+ total: 247.23,+ });++ expect(container).toBeEmptyDOMElement();+ });++ it("recalculates stale item amounts and the invoice total on mount", () => {+ const { formRef } = renderItemTotalsSync({+ items: [+ createItem({+ amount: 3,+ netPrice: 100,+ vat: 23,+ netAmount: 0,+ vatAmount: 0,+ preTaxAmount: 0,+ }),+ ],+ total: 0,+ });++ const { getValues } = getForm(formRef);++ expect(getValues("items.0")).toMatchObject({+ netAmount: 300,+ vatAmount: 69,+ preTaxAmount: 369,+ });+ expect(getValues("total")).toBe(369);+ });++ it("recalculates the edited item and sums every item into the total", () => {+ const { formRef } = renderItemTotalsSync({+ items: [createItem(), createItem()],+ total: 494.46,+ });++ const { getValues, setValue } = getForm(formRef);++ // 2 x 50 = 100 net, 23% VAT = 23, 123 pre-tax+ act(() => {+ setValue("items.1.netPrice", 50);+ });++ expect(getValues("items.1")).toMatchObject({+ netAmount: 100,+ vatAmount: 23,+ preTaxAmount: 123,+ });+ expect(getValues("items.0.preTaxAmount")).toBe(247.23);+ expect(getValues("total")).toBe(370.23);+ });++ it("writes the total with validation when it changes", () => {+ const { formRef, setValueSpy } = renderItemTotalsSync({+ items: [createItem()],+ total: 247.23,+ });++ setValueSpy.mockClear();++ act(() => {+ getForm(formRef).setValue("items.0.amount", 4);+ });++ expect(setValueSpy).toHaveBeenCalledWith("total", 494.46, {+ shouldValidate: true,+ });+ });++ /**+ * The re-render fix: a validating `setValue("total")` publishes new `formState.errors`,+ * which re-renders all of `InvoiceForm`. Edits that don't move the total -- a "Show in+ * PDF" switch, the item name -- must not write it at all.+ */+ it.each([+ { field: "amountFieldIsVisible", value: false },+ { field: "vatFieldIsVisible", value: false },+ { field: "name", value: "Renamed product" },+ ] as const)(+ "does not write the total when $field changes and the total stays the same",+ ({ field, value }) => {+ const { formRef, setValueSpy } = renderItemTotalsSync({+ items: [createItem()],+ total: 247.23,+ });++ setValueSpy.mockClear();++ act(() => {+ getForm(formRef).setValue(`items.0.${field}`, value);+ });++ expect(setValueSpy).not.toHaveBeenCalledWith(+ "total",+ expect.anything(),+ expect.anything(),+ );+ expect(getForm(formRef).getValues("total")).toBe(247.23);+ },+ );++ it.each([+ { case: "an amount cleared mid-edit", field: "amount", value: "" },+ { case: "a VAT rate above the allowed range", field: "vat", value: 500 },+ ] as const)(+ "leaves the totals alone while an item holds $case",+ ({ field, value }) => {+ const { formRef, setValueSpy } = renderItemTotalsSync({+ items: [createItem()],+ total: 247.23,+ });++ setValueSpy.mockClear();++ act(() => {+ getForm(formRef).setValue(`items.0.${field}`, value);+ });++ expect(setValueSpy).not.toHaveBeenCalled();+ expect(getForm(formRef).getValues("items.0")).toMatchObject({+ netAmount: 201,+ vatAmount: 46.23,+ preTaxAmount: 247.23,+ });+ expect(getForm(formRef).getValues("total")).toBe(247.23);+ },+ );+});++interface RenderItemTotalsSyncParams {+ items: InvoiceItemData[];+ total: number;+}++function renderItemTotalsSync({ items, total }: RenderItemTotalsSyncParams) {+ const formRef: RefObject<UseFormReturn<InvoiceData> | null> = {+ current: null,+ };+ const setValueSpy = vi.fn();++ const result = render(+ <ItemTotalsSyncTestHarness+ defaultValues={{ ...getInitialInvoiceData(), items, total }}+ formRef={formRef}+ setValueSpy={setValueSpy}+ />,+ );++ return { ...result, formRef, setValueSpy };+}++interface ItemTotalsSyncTestHarnessProps {+ defaultValues: InvoiceData;+ /** Filled in with the form, so tests can edit values and read them back. */+ formRef: RefObject<UseFormReturn<InvoiceData> | null>;+ /** Called with every `setValue` the component makes, before it reaches the form. */+ setValueSpy: Mock;+}++function ItemTotalsSyncTestHarness({+ defaultValues,+ formRef,+ setValueSpy,+}: ItemTotalsSyncTestHarnessProps) {+ const form = useForm<InvoiceData>({ defaultValues });++ // `render` wraps mount in `act`, so this has run by the time it returns+ useEffect(() => {+ formRef.current = form;+ }, [form, formRef]);++ const { setValue: formSetValue } = form;++ // Stable like the real `setValue`, since it is an effect dependency.+ const setValue = useCallback(+ (...args: Parameters<UseFormSetValue<InvoiceData>>) => {+ setValueSpy(...args);+ formSetValue(...args);+ },+ [formSetValue, setValueSpy],+ ) as UseFormSetValue<InvoiceData>;++ return (+ <ItemTotalsSync+ control={form.control}+ getValues={form.getValues}+ setValue={setValue}+ />+ );+}++function getForm(+ formRef: RefObject<UseFormReturn<InvoiceData> | null>,+): UseFormReturn<InvoiceData> {+ if (!formRef.current) {+ throw new Error("The test harness has not rendered the form yet");+ }++ return formRef.current;+}++function createItem(overrides: Partial<InvoiceItemData> = {}): InvoiceItemData {+ return { ...MOCK_INVOICE_ITEM_DATA, ...overrides };+}diff --git a/src/app/(main)/(app)/components/invoice-form/index.tsx b/src/app/(main)/(app)/components/invoice-form/index.tsxindex 11aa147..b5b7fe4 100644--- a/src/app/(main)/(app)/components/invoice-form/index.tsx+++ b/src/app/(main)/(app)/components/invoice-form/index.tsx@@ -22,7 +22,6 @@ import {resolveNumberFormatLocale,type AccordionState,type InvoiceData,- type InvoiceItemData,} from "@/app/schema";import { Legend } from "@/components/legend";import {@@ -39,21 +38,17 @@ import { ReadOnlyMoneyInput } from "@/components/ui/money-input";import { Switch } from "@/components/ui/switch";import { Textarea } from "@/components/ui/textarea";import { CustomTooltip } from "@/components/ui/tooltip";-import { debugLog } from "@/lib/debug-log";import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";import { zodResolverForOutput } from "@/lib/zod-resolver-for-output";import type { NonReadonly, Prettify } from "@/types";import { AlertIcon, ErrorMessage } from "./common";+import { ItemTotalsSync } from "./item-totals-sync";import { BuyerInformation } from "./sections/buyer-information";import { GeneralInformation } from "./sections/general-information";import { InvoiceItems } from "./sections/invoice-items";import { SellerInformation } from "./sections/seller-information";-import { calculateInvoiceTotal } from "./utils/calculate-invoice-total";-import { calculateItemTotals } from "./utils/calculate-item-totals";import { formErrorsToToast } from "./utils/form-errors-to-toast";-import { hasAnyItemTotalsChanged } from "./utils/has-item-totals-changed";-import { parseValidatedInvoiceItems } from "./utils/validated-invoice-items";/*** Time in milliseconds to debounce updates in the invoice form,@@ -119,7 +114,6 @@ export const InvoiceForm = memo(function InvoiceForm({} = form;const currency = useWatch({ control, name: "currency" });- const invoiceItems = useWatch({ control, name: "items" });const dateOfIssue = useWatch({ control, name: "dateOfIssue" });@@ -154,57 +148,6 @@ export const InvoiceForm = memo(function InvoiceForm({name: "items",});- // calculate totals and other values when invoice items change- useEffect(() => {- // Bail out while the user is mid-edit with input the schema rejects, so we- // never turn half-typed values into totals and write them back. Clearing the- // amount field to retype it would otherwise zero out the item's totals, and- // a VAT of 500 would persist a bogus tax amount.- // `zodResolver` does not do this for us: it populates `errors`, but form- // state (and so `useWatch`) still holds the raw, unvalidated input.- const validatedItemsResult = parseValidatedInvoiceItems(invoiceItems);-- if (!validatedItemsResult.success) {- // Not reported to Sentry on purpose, and not a `console.error` either: this branch is- // the expected state while someone is still typing (a cleared amount field, a- // half-entered VAT), so it fires constantly and says nothing about a broken app.- debugLog("Invalid items:", validatedItemsResult.error);-- return;- }-- const total = calculateInvoiceTotal(invoiceItems);-- debugLog("[useEffect] recalculating totals because invoice items changed", {- invoiceItems,- validatedItemsResult,- total,- });-- // Update total first- setValue("total", total, { shouldValidate: true });-- // Skip rest of calculations if no items- if (!invoiceItems?.length) return;-- // if no item totals changed (netAmount, vatAmount, preTaxAmount), skip the rest of the calculations- if (!hasAnyItemTotalsChanged(invoiceItems)) return;-- // Only update if there are actual changes- const updatedItems = invoiceItems- .map((item) => {- return calculateItemTotals(item);- })- .filter(Boolean) as InvoiceItemData[];-- // Batch updates- updatedItems.forEach((item, index) => {- setValue(`items.${index}`, item, {- shouldValidate: false, // Prevent validation during intermediate updates- });- });- }, [invoiceItems, setValue]);-// top level of componentconst debouncedShowFormErrorsToast = useDebouncedCallback(() => {@@ -346,9 +289,10 @@ export const InvoiceForm = memo(function InvoiceForm({*/const handleRemoveInvoiceItem = useCallback((index: number) => {+ // read at click time rather than watched, so item edits don't re-render the formsetValue("items",- invoiceItems.filter((_, i) => {+ getValues("items").filter((_, i) => {return i !== index;}),{@@ -368,7 +312,7 @@ export const InvoiceForm = memo(function InvoiceForm({// analytics track eventumamiTrackEvent("remove_invoice_item");},- [invoiceItems, setValue, isMobile],+ [getValues, setValue, isMobile],);const onSubmit = (data: InvoiceData) => {@@ -452,6 +396,11 @@ export const InvoiceForm = memo(function InvoiceForm({return (<form className="relative mb-4 space-y-3.5">+ <ItemTotalsSync+ control={control}+ getValues={getValues}+ setValue={setValue}+ /><Accordiontype="multiple"value={accordionValues}@@ -606,7 +555,7 @@ export const InvoiceForm = memo(function InvoiceForm({id={`paymentMethodFieldIsVisible`}checked={value}onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ size="sm"data-testid="paymentMethodFieldIsVisible"/>);@@ -736,7 +685,7 @@ export const InvoiceForm = memo(function InvoiceForm({id={`notesFieldIsVisible`}checked={value}onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ size="sm"/>);}}@@ -788,7 +737,7 @@ export const InvoiceForm = memo(function InvoiceForm({id={`qrCodeIsVisible`}checked={value}onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ size="sm"aria-label="Show QR Code in PDF"/>);@@ -884,7 +833,7 @@ export const InvoiceForm = memo(function InvoiceForm({id="personAuthorizedToReceiveFieldIsVisible"checked={value}onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ size="sm"aria-label="Show Person Authorized to Receive in PDF"/>);@@ -951,7 +900,7 @@ export const InvoiceForm = memo(function InvoiceForm({id="personAuthorizedToIssueFieldIsVisible"checked={value}onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ size="sm"aria-label="Show Person Authorized to Issue in PDF"/>);diff --git a/src/app/(main)/(app)/components/invoice-form/item-totals-sync.tsx b/src/app/(main)/(app)/components/invoice-form/item-totals-sync.tsxnew file mode 100644index 0000000..e6c33b0--- /dev/null+++ b/src/app/(main)/(app)/components/invoice-form/item-totals-sync.tsx@@ -0,0 +1,129 @@+import { useEffect } from "react";+import {+ type Control,+ type UseFormGetValues,+ type UseFormSetValue,+ useWatch,+} from "react-hook-form";++import type { InvoiceData, InvoiceItemData } from "@/app/schema";+import { debugLog } from "@/lib/debug-log";++import { calculateInvoiceTotal } from "./utils/calculate-invoice-total";+import { calculateItemTotals } from "./utils/calculate-item-totals";+import { hasAnyItemTotalsChanged } from "./utils/has-item-totals-changed";+import { parseValidatedInvoiceItems } from "./utils/validated-invoice-items";++interface ItemTotalsSyncProps {+ control: Control<InvoiceData>;+ getValues: UseFormGetValues<InvoiceData>;+ setValue: UseFormSetValue<InvoiceData>;+}++/**+ * Keeps the invoice total and each item's computed amounts (net, VAT, pre-tax) in step+ * with the items. Renders nothing.+ *+ * It lives in its own component so that it is the only thing subscribed to the whole+ * `items` array. When `InvoiceForm` watched `items` itself, any change inside an item --+ * down to flipping a "Show in PDF" switch -- re-rendered the entire form in the same+ * task as the click, 60-90ms in development, and the switch's thumb and track fell out+ * of step while the main thread was busy.+ *+ * Why a component and not a hook: a hook has no render of its own, it runs inside the+ * component that calls it. `useWatch` in a `useItemTotalsSync()` called from+ * `InvoiceForm` would subscribe `InvoiceForm`, and every item change would re-render+ * the whole form again. A component is the smallest unit React re-renders on its own,+ * and this one renders `null`, so its re-render costs next to nothing.+ *+ * A hook would work only if it never re-rendered, e.g. by listening through+ * `control.subscribe` / `watch(callback)` instead of `useWatch`. That moves the totals+ * into the change callback, during the event, and makes the `setValue` -> callback+ * loop easier to miss, so the component, which keeps the logic in an effect, is the+ * simpler of the two.+ */+export function ItemTotalsSync({+ control,+ getValues,+ setValue,+}: ItemTotalsSyncProps) {+ const invoiceItems = useWatch({ control, name: "items" });++ // calculate totals and other values when invoice items change+ useEffect(() => {+ // Bail out while the user is mid-edit with input the schema rejects, so we+ // never turn half-typed values into totals and write them back. Clearing the+ // amount field to retype it would otherwise zero out the item's totals, and+ // a VAT of 500 would persist a bogus tax amount.+ // `zodResolver` does not do this for us: it populates `errors`, but form+ // state (and so `useWatch`) still holds the raw, unvalidated input.+ const validatedItemsResult = parseValidatedInvoiceItems(invoiceItems);++ if (!validatedItemsResult.success) {+ // Not reported to Sentry on purpose, and not a `console.error` either: this branch is+ // the expected state while someone is still typing (a cleared amount field, a+ // half-entered VAT), so it fires constantly and says nothing about a broken app.+ debugLog("Invalid items:", validatedItemsResult.error);++ return;+ }++ const total = calculateInvoiceTotal(invoiceItems);++ debugLog("[useEffect] recalculating totals because invoice items changed", {+ invoiceItems,+ validatedItemsResult,+ total,+ });++ // Update total first+ setTotalIfChanged({ getValues, setValue, total });++ // Skip rest of calculations if no items+ if (!invoiceItems?.length) return;++ // if no item totals changed (netAmount, vatAmount, preTaxAmount), skip the rest of the calculations+ if (!hasAnyItemTotalsChanged(invoiceItems)) return;++ // Only update if there are actual changes+ const updatedItems = invoiceItems+ .map((item) => {+ return calculateItemTotals(item);+ })+ .filter(Boolean) as InvoiceItemData[];++ // Batch updates+ updatedItems.forEach((item, index) => {+ setValue(`items.${index}`, item, {+ shouldValidate: false, // Prevent validation during intermediate updates+ });+ });+ }, [invoiceItems, getValues, setValue]);++ return null;+}++interface SetTotalIfChangedParams {+ getValues: UseFormGetValues<InvoiceData>;+ setValue: UseFormSetValue<InvoiceData>;+ /** The total just calculated from the items. */+ total: number;+}++/**+ * Writes the invoice total only when it moved. Most item edits (a "Show in PDF" switch,+ * the item name) leave it as it is, and a validating `setValue` publishes new+ * `formState.errors`, which re-renders all of `InvoiceForm` -- the very re-render+ * `ItemTotalsSync` exists to keep off the root.+ */+function setTotalIfChanged({+ getValues,+ setValue,+ total,+}: SetTotalIfChangedParams) {+ if (getValues("total") === total) {+ return;+ }++ setValue("total", total, { shouldValidate: true });+}diff --git a/src/app/(main)/(app)/components/invoice-form/sections/buyer-information.tsx b/src/app/(main)/(app)/components/invoice-form/sections/buyer-information.tsxindex 9b2da5b..3a8599e 100644--- a/src/app/(main)/(app)/components/invoice-form/sections/buyer-information.tsx+++ b/src/app/(main)/(app)/components/invoice-form/sections/buyer-information.tsx@@ -147,7 +147,7 @@ export const BuyerInformation = memo(function BuyerInformation({id="buyerVatNoFieldIsVisible"checked={value}onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ size="sm"data-testid="buyerVatNoFieldIsVisible"aria-label="Show the 'Buyer Tax Number' Field in the PDF"/>@@ -246,7 +246,7 @@ export const BuyerInformation = memo(function BuyerInformation({id="buyerEmailFieldIsVisible"checked={value}onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ size="sm"data-testid="buyerEmailFieldIsVisible"aria-label="Show the 'Email' field in the PDF"/>@@ -300,7 +300,7 @@ export const BuyerInformation = memo(function BuyerInformation({id="buyerNotesFieldIsVisible"checked={value}onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ size="sm"data-testid="buyerNotesInvoiceFormFieldVisibilitySwitch"aria-label="Show the 'Notes' field in the PDF"/>diff --git a/src/app/(main)/(app)/components/invoice-form/sections/general-information.tsx b/src/app/(main)/(app)/components/invoice-form/sections/general-information.tsxindex 99c98b2..2a352df 100644--- a/src/app/(main)/(app)/components/invoice-form/sections/general-information.tsx+++ b/src/app/(main)/(app)/components/invoice-form/sections/general-information.tsx@@ -636,7 +636,7 @@ export const GeneralInformation = memo(function GeneralInformation({},);}}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ size="sm"/>);}}@@ -828,7 +828,7 @@ export const GeneralInformation = memo(function GeneralInformation({data-testid="servicePeriodFieldIsVisible"checked={value}onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ size="sm"aria-label='Show the "Service period" (Service period start and end) field in the PDF'/>);@@ -997,7 +997,7 @@ export const GeneralInformation = memo(function GeneralInformation({data-testid="dateOfServiceFieldIsVisible"checked={value}onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ size="sm"aria-label='Show the "Date of sales/of executing the service" field in the PDF'/>);@@ -1089,7 +1089,7 @@ export const GeneralInformation = memo(function GeneralInformation({id={`invoiceTypeFieldIsVisible`}checked={value}onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ size="sm"aria-label={`Show the "Header Notes" Field in the PDF`}/>);diff --git a/src/app/(main)/(app)/components/invoice-form/sections/invoice-items.tsx b/src/app/(main)/(app)/components/invoice-form/sections/invoice-items.tsxindex fe588b2..61e3a9b 100644--- a/src/app/(main)/(app)/components/invoice-form/sections/invoice-items.tsx+++ b/src/app/(main)/(app)/components/invoice-form/sections/invoice-items.tsx@@ -152,7 +152,7 @@ export const InvoiceItems = memo(function InvoiceItems({id={`itemNameFieldIsVisible${index}`}checked={value}onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ size="sm"aria-label={`Show the 'Name of Goods/Service' Column in the PDF for item ${index + 1}`}/>);@@ -217,7 +217,7 @@ export const InvoiceItems = memo(function InvoiceItems({id={`itemTypeOfGTUFieldIsVisible${index}`}checked={value}onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ size="sm"aria-label={`Show the 'Type of GTU' Column in the PDF for item ${index + 1}`}/>);@@ -282,7 +282,7 @@ export const InvoiceItems = memo(function InvoiceItems({id={`itemAmountFieldIsVisible${index}`}checked={value}onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ size="sm"aria-label={`Show the 'Amount' Column in the PDF for item ${index + 1}`}/>);@@ -362,7 +362,7 @@ export const InvoiceItems = memo(function InvoiceItems({id={`itemUnitFieldIsVisible${index}`}checked={value}onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ size="sm"aria-label={`Show the 'Unit' Column in the PDF for item ${index + 1}`}/>);@@ -424,7 +424,7 @@ export const InvoiceItems = memo(function InvoiceItems({id={`itemNetPriceFieldIsVisible${index}`}checked={value}onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ size="sm"aria-label={`Show the 'Net Price' Column in the PDF for item ${index + 1}`}/>);@@ -523,7 +523,7 @@ export const InvoiceItems = memo(function InvoiceItems({id={`itemVatFieldIsVisible${index}`}checked={value}onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ size="sm"aria-label={`Show the '${taxLabelText}' Column in the PDF for item ${index + 1}`}/>);@@ -629,7 +629,7 @@ export const InvoiceItems = memo(function InvoiceItems({id={`itemNetAmountFieldIsVisible${index}`}checked={value}onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ size="sm"aria-label={`Show the 'Net Amount' Column in the PDF for item ${index + 1}`}/>);@@ -703,7 +703,7 @@ export const InvoiceItems = memo(function InvoiceItems({id={`itemVatAmountFieldIsVisible${index}`}checked={value}onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ size="sm"aria-label={`Show the '${taxLabelText} Amount' Column in the PDF for item ${index + 1}`}/>);@@ -778,7 +778,7 @@ export const InvoiceItems = memo(function InvoiceItems({id={`itemPreTaxAmountFieldIsVisible${index}`}checked={value}onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ size="sm"aria-label={`Show the 'Pre-tax Amount' Column in the PDF for item ${index + 1}`}/>);@@ -904,7 +904,7 @@ export const InvoiceItems = memo(function InvoiceItems({id={`itemInvoiceItemNumberIsVisible0`}checked={value}onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ size="sm"/>);}}@@ -930,7 +930,7 @@ export const InvoiceItems = memo(function InvoiceItems({id={`vatTableSummaryIsVisible`}checked={value}onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ size="sm"/>);}}diff --git a/src/app/(main)/(app)/components/invoice-form/sections/seller-information.tsx b/src/app/(main)/(app)/components/invoice-form/sections/seller-information.tsxindex 8798ce8..7d1b4c9 100644--- a/src/app/(main)/(app)/components/invoice-form/sections/seller-information.tsx+++ b/src/app/(main)/(app)/components/invoice-form/sections/seller-information.tsx@@ -149,7 +149,7 @@ export const SellerInformation = memo(function SellerInformation({id="sellerVatNoFieldIsVisible"checked={value}onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ size="sm"data-testid="sellerVatNoFieldIsVisible"aria-label="Show the 'Seller Tax Number' Field in the PDF"/>@@ -250,7 +250,7 @@ export const SellerInformation = memo(function SellerInformation({id="sellerEmailFieldIsVisible"checked={value}onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ size="sm"data-testid="sellerEmailFieldIsVisible"aria-label="Show the 'Email' field in the PDF"/>@@ -306,7 +306,7 @@ export const SellerInformation = memo(function SellerInformation({id="sellerAccountNumberFieldIsVisible"checked={value}onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ size="sm"data-testid="sellerAccountNumberFieldIsVisible"aria-label="Show the 'Account Number' Field in the PDF"/>@@ -364,7 +364,7 @@ export const SellerInformation = memo(function SellerInformation({id="sellerSwiftBicFieldIsVisible"checked={value}onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ size="sm"data-testid="sellerSwiftBicFieldIsVisible"aria-label="Show the 'SWIFT/BIC' Field in the PDF"/>@@ -420,7 +420,7 @@ export const SellerInformation = memo(function SellerInformation({id="sellerNotesFieldIsVisible"checked={value}onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ size="sm"data-testid="sellerNotesInvoiceFormFieldVisibilitySwitch"aria-label="Show the 'Notes' field in the PDF"/>diff --git a/src/components/ui/switch.tsx b/src/components/ui/switch.tsxindex 39a16e4..699d0c8 100644--- a/src/components/ui/switch.tsx+++ b/src/components/ui/switch.tsx@@ -1,36 +1,41 @@"use client";import * as SwitchPrimitives from "@radix-ui/react-switch";-import * as React from "react";+import type * as React from "react";import { cn } from "@/lib/utils";+interface SwitchProps extends React.ComponentProps<+ typeof SwitchPrimitives.Root+> {+ /** `sm` is the compact switch used next to form fields, `default` the larger one. */+ size?: "default" | "sm";+}+/*** https://originui.com/checks-radios-switches+ *+ * The track keeps its unchecked color, and the checked color is a `before:` layer that+ * fades in with `opacity`, instead of a `background-color` transition on the track.+ * The browser repaints a `background-color` transition on the main thread every frame,+ * and on the first toggle after load one stale repaint sometimes reached the screen+ * just after the animation ended (knob already off, track still the dark checked color).+ * An `opacity` fade runs on the compositor with no repaint, like the thumb's transform.*/-const Switch = React.memo(- React.forwardRef<- React.ComponentRef<typeof SwitchPrimitives.Root>,- React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>- >(({ className, ...props }, ref) => {- return (- <SwitchPrimitives.Root- className={cn(- "focus-visible:outline-ring/70 peer inline-flex h-6 w-10 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent outline-offset-2 transition-colors duration-200 ease-out-strong focus-visible:outline focus-visible:outline-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-slate-900 data-[state=unchecked]:bg-slate-200 dark:data-[state=checked]:bg-slate-50 dark:data-[state=unchecked]:bg-slate-800",- className,- )}- {...props}- ref={ref}- >- <SwitchPrimitives.Thumb- className={cn(- "pointer-events-none block size-5 rounded-full bg-white shadow-sm shadow-black/5 ring-0 transition-transform duration-200 ease-out-strong data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0 dark:bg-slate-950 rtl:data-[state=checked]:-translate-x-4",- )}- />- </SwitchPrimitives.Root>- );- }),-);-Switch.displayName = SwitchPrimitives.Root.displayName;+function Switch({ className, size = "default", ...props }: SwitchProps) {+ return (+ <SwitchPrimitives.Root+ data-size={size}+ className={cn(+ "focus-visible:outline-ring/70 group/switch peer relative inline-flex h-6 w-10 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent bg-slate-200 outline-offset-2 before:absolute before:-inset-0.5 before:rounded-full before:bg-slate-900 before:opacity-0 before:transition-opacity before:duration-200 before:ease-out-strong focus-visible:outline focus-visible:outline-2 disabled:cursor-not-allowed disabled:opacity-50 data-[size=sm]:h-5 data-[size=sm]:w-8 data-[state=checked]:before:opacity-100 dark:bg-slate-800 dark:before:bg-slate-50",+ className,+ )}+ {...props}+ >+ {/* travel = thumb width minus the 2px border on each side, so it fits both sizes */}+ <SwitchPrimitives.Thumb className="pointer-events-none relative block size-5 rounded-full bg-white shadow-sm shadow-black/5 ring-0 transition-transform duration-200 ease-out-strong data-[state=checked]:translate-x-[calc(100%-4px)] data-[state=unchecked]:translate-x-0 group-data-[size=sm]/switch:size-4 dark:bg-slate-950 rtl:data-[state=checked]:-translate-x-[calc(100%-4px)]" />+ </SwitchPrimitives.Root>+ );+}export { Switch };