Skip to content

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

feat: fixing e2e tests and some other improvements (#265)

Vlad Sazonauae464991229e
diff --git a/e2e/invoice-form.test.ts b/e2e/invoice-form.test.ts
index 245e66f..317bf71 100644
--- a/e2e/invoice-form.test.ts
+++ b/e2e/invoice-form.test.ts
@@ -904,9 +904,13 @@ test.describe("Invoice Generator Page", () => {
page.getByTestId("delete-invoice-item-confirmation-dialog"),
).toBeVisible();
+ await expect(
+ page.getByRole("alertdialog", { name: "Delete Item 2?" }),
+ ).toBeVisible();
+
await expect(
page.getByText(
- 'Are you sure you want to delete the invoice item "TEST INVOICE ITEM"?',
+ '"TEST INVOICE ITEM" will be removed from this invoice, and the totals recalculated.',
),
).toBeVisible();
@@ -921,9 +925,7 @@ test.describe("Invoice Generator Page", () => {
).toBeHidden();
await expect(
- page.getByText(
- 'Are you sure you want to delete the invoice item "TEST INVOICE ITEM"?',
- ),
+ page.getByRole("alertdialog", { name: "Delete Item 2?" }),
).toBeHidden();
// Item should still be present
@@ -931,6 +933,13 @@ test.describe("Invoice Generator Page", () => {
invoiceItemsSection.getByText("Item 2", { exact: true }),
).toBeVisible();
+ // Cancelling puts focus back on the button that opened the dialog
+ await expect(
+ invoiceItemsSection.getByRole("button", {
+ name: "Delete Invoice Item 2",
+ }),
+ ).toBeFocused();
+
// --- Now confirm deletion flow ---
// Open the dialog again
@@ -943,13 +952,19 @@ test.describe("Invoice Generator Page", () => {
).toBeVisible();
// Confirm deletion
- await page.getByRole("button", { name: "Delete" }).click();
+ await page.getByRole("button", { name: "Delete Item 2" }).click();
// Verify success message
await expect(
page.getByText("Invoice item removed successfully", { exact: true }),
).toBeVisible();
+ // The field that had focus was inside the deleted item, so focus moves to a control that
+ // still exists rather than being dropped on <body>
+ await expect(
+ page.getByRole("button", { name: "Add invoice item" }),
+ ).toBeFocused();
+
// Verify item is removed
await expect(
invoiceItemsSection.getByText("Item 2", { exact: true }),
@@ -1182,25 +1197,25 @@ test.describe("Invoice Generator Page", () => {
page.getByText("Invoice last updated:", { exact: false }),
).toBeVisible();
- // Wait a moment for any debounced localStorage updates
- // eslint-disable-next-line playwright/no-wait-for-timeout
- await page.waitForTimeout(500);
-
- // Verify data is actually saved in localStorage
- const storedData = (await page.evaluate((key) => {
- return localStorage.getItem(key);
- }, PDF_DATA_LOCAL_STORAGE_KEY)) as string;
-
- expect(storedData).toBeTruthy();
-
- const parsedData = JSON.parse(storedData) as InvoiceData;
- expect(parsedData).toMatchObject({
- invoiceNumberObject: {
- label: "Invoice No. of:",
- value: "TEST/2024",
- },
- notes: "Test note",
- } satisfies Pick<InvoiceData, "notes" | "invoiceNumberObject">);
+ // The form only writes to localStorage after DEBOUNCE_TIMEOUT (500ms), and a
+ // loaded CI machine can push that write past a fixed 500ms wait, which is what
+ // made this flaky (localStorage still empty when it was read). Poll until the
+ // stored payload matches instead of sleeping for exactly one debounce.
+ await expect
+ .poll(async () => {
+ const storedData = await page.evaluate((key) => {
+ return localStorage.getItem(key);
+ }, PDF_DATA_LOCAL_STORAGE_KEY);
+
+ return storedData ? (JSON.parse(storedData) as InvoiceData) : null;
+ })
+ .toMatchObject({
+ invoiceNumberObject: {
+ label: "Invoice No. of:",
+ value: "TEST/2024",
+ },
+ notes: "Test note",
+ } satisfies Pick<InvoiceData, "notes" | "invoiceNumberObject">);
// Reload page
await page.reload();
diff --git a/src/app/(main)/(app)/__tests__/robots-meta-sync.test.tsx b/src/app/(main)/(app)/__tests__/robots-meta-sync.test.tsx
new file mode 100644
index 0000000..886e315
--- /dev/null
+++ b/src/app/(main)/(app)/__tests__/robots-meta-sync.test.tsx
@@ -0,0 +1,124 @@
+// @vitest-environment happy-dom
+
+import { cleanup, render } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+let currentSearchParams = new URLSearchParams();
+
+vi.mock("next/navigation", () => {
+ return {
+ useSearchParams: () => {
+ return currentSearchParams;
+ },
+ };
+});
+
+import { RobotsMetaSync } from "../robots-meta-sync";
+
+/**
+ * Renders the robots meta tags the way `generateMetadata` does on the server, so the
+ * component has something to patch.
+ *
+ * @param content - The `content` value both tags start out with.
+ */
+function renderServerRobotsMeta(content: string) {
+ for (const name of ["robots", "googlebot"]) {
+ const meta = document.createElement("meta");
+ meta.setAttribute("name", name);
+ meta.setAttribute("content", content);
+ document.head.append(meta);
+ }
+}
+
+function robotsMetaContents() {
+ return [...document.head.querySelectorAll("meta[name]")].map((meta) => {
+ return [meta.getAttribute("name"), meta.getAttribute("content")];
+ });
+}
+
+describe("RobotsMetaSync", () => {
+ beforeEach(() => {
+ currentSearchParams = new URLSearchParams();
+ document.head.innerHTML = "";
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ it("marks a shared invoice as noindex, nofollow", () => {
+ renderServerRobotsMeta("index, follow");
+ currentSearchParams = new URLSearchParams("template=stripe&data=abc123");
+
+ render(<RobotsMetaSync isIndexableEnvironment={true} />);
+
+ expect(robotsMetaContents()).toEqual([
+ ["robots", "noindex, nofollow"],
+ ["googlebot", "noindex, nofollow"],
+ ]);
+ });
+
+ it("leaves the page indexable when there is no shared data", () => {
+ renderServerRobotsMeta("index, follow");
+ currentSearchParams = new URLSearchParams("template=stripe");
+
+ render(<RobotsMetaSync isIndexableEnvironment={true} />);
+
+ expect(robotsMetaContents()).toEqual([
+ ["robots", "index, follow"],
+ ["googlebot", "index, follow"],
+ ]);
+ });
+
+ it("keeps non-production deployments out of the index entirely", () => {
+ renderServerRobotsMeta("noindex, nofollow");
+
+ render(<RobotsMetaSync isIndexableEnvironment={false} />);
+
+ expect(robotsMetaContents()).toEqual([
+ ["robots", "noindex, nofollow"],
+ ["googlebot", "noindex, nofollow"],
+ ]);
+ });
+
+ it("re-indexes the page when the shared data is dropped from the URL", () => {
+ renderServerRobotsMeta("index, follow");
+ currentSearchParams = new URLSearchParams("data=abc123");
+
+ const { rerender } = render(
+ <RobotsMetaSync isIndexableEnvironment={true} />,
+ );
+
+ expect(robotsMetaContents()).toEqual([
+ ["robots", "noindex, nofollow"],
+ ["googlebot", "noindex, nofollow"],
+ ]);
+
+ // the app drops `?data=` in place too (corrupted link, edits to a shared invoice),
+ // which leaves the visitor on `/` -- the canonical page we do want indexed
+ currentSearchParams = new URLSearchParams();
+ rerender(<RobotsMetaSync isIndexableEnvironment={true} />);
+
+ expect(robotsMetaContents()).toEqual([
+ ["robots", "index, follow"],
+ ["googlebot", "index, follow"],
+ ]);
+ });
+
+ it("adds the tags when the document was rendered without them", () => {
+ currentSearchParams = new URLSearchParams("data=abc123");
+
+ render(<RobotsMetaSync isIndexableEnvironment={true} />);
+
+ expect(robotsMetaContents()).toEqual([
+ ["robots", "noindex, nofollow"],
+ ["googlebot", "noindex, nofollow"],
+ ]);
+ });
+
+ it("does not add tags to an indexable page that has none", () => {
+ render(<RobotsMetaSync isIndexableEnvironment={true} />);
+
+ expect(robotsMetaContents()).toEqual([]);
+ });
+});
diff --git a/src/app/(main)/(app)/components/invoice-form/index.tsx b/src/app/(main)/(app)/components/invoice-form/index.tsx
index 24e0487..ff8df2b 100644
--- a/src/app/(main)/(app)/components/invoice-form/index.tsx
+++ b/src/app/(main)/(app)/components/invoice-form/index.tsx
@@ -110,6 +110,7 @@ export const InvoiceForm = memo(function InvoiceForm({
const {
control,
setValue,
+ getValues,
formState: { errors },
watch,
trigger,
@@ -531,7 +532,7 @@ export const InvoiceForm = memo(function InvoiceForm({
append={append}
template={template}
taxLabelText={taxLabelText}
- invoiceData={invoiceData}
+ getValues={getValues}
/>
</AccordionContent>
</AccordionItem>
diff --git a/src/app/(main)/(app)/components/invoice-form/sections/__tests__/invoice-items.test.tsx b/src/app/(main)/(app)/components/invoice-form/sections/__tests__/invoice-items.test.tsx
index e86690d..78d33b3 100644
--- a/src/app/(main)/(app)/components/invoice-form/sections/__tests__/invoice-items.test.tsx
+++ b/src/app/(main)/(app)/components/invoice-form/sections/__tests__/invoice-items.test.tsx
@@ -5,8 +5,8 @@ import userEvent from "@testing-library/user-event";
import { useMemo } from "react";
import {
type Control,
- type FieldArrayWithId,
type UseFieldArrayAppend,
+ useFieldArray,
useForm,
} from "react-hook-form";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -20,7 +20,7 @@ import "@testing-library/jest-dom/vitest";
const { MOCK_MAX_INVOICE_ITEMS } = vi.hoisted(() => {
return {
- MOCK_MAX_INVOICE_ITEMS: 3,
+ MOCK_MAX_INVOICE_ITEMS: 5,
};
});
@@ -55,47 +55,56 @@ interface InvoiceItemsTestHarnessProps {
itemCount: number;
append?: UseFieldArrayAppend<InvoiceData, "items">;
onRemove?: (index: number) => void;
+ /** Overrides the name of the item at each given index. */
+ itemNames?: Record<number, string>;
}
function InvoiceItemsTestHarness({
itemCount,
- append = vi.fn(),
+ append,
onRemove = vi.fn(),
+ itemNames,
}: InvoiceItemsTestHarnessProps) {
const invoiceData = useMemo(() => {
return {
...getInitialInvoiceData(),
- items: Array.from({ length: itemCount }, () => {
+ items: Array.from({ length: itemCount }, (_, index) => {
return {
...MOCK_INVOICE_ITEM_DATA,
+ name: itemNames?.[index] ?? MOCK_INVOICE_ITEM_DATA.name,
};
}),
};
- }, [itemCount]);
+ }, [itemCount, itemNames]);
- const { control } = useForm<InvoiceData>({
+ const { control, getValues } = useForm<InvoiceData>({
defaultValues: invoiceData,
});
- const fields = Array.from({ length: itemCount }, (_, index) => {
- return {
- id: `item-${index}`,
- };
- }) as FieldArrayWithId<InvoiceData, "items">[];
+ // A real field array, so confirming a delete actually drops the item and re-indexes the
+ // ones after it, the way `useFieldArray` does in the form.
+ const {
+ fields,
+ append: appendField,
+ remove,
+ } = useFieldArray({ control, name: "items" });
return (
<TooltipProvider delayDuration={0}>
<InvoiceItems
control={control as Control<InvoiceData>}
fields={fields}
- handleRemoveInvoiceItem={onRemove}
- append={append}
+ handleRemoveInvoiceItem={(index) => {
+ onRemove(index);
+ remove(index);
+ }}
+ append={append ?? appendField}
errors={{}}
currency="EUR"
language="en"
template="default"
taxLabelText="VAT"
- invoiceData={invoiceData}
+ getValues={getValues}
/>
</TooltipProvider>
);
@@ -109,6 +118,20 @@ function getAddInvoiceItemButton() {
return screen.getByRole("button", { name: "Add invoice item" });
}
+function getDeleteItemButton(itemNumber: number) {
+ return screen.getByRole("button", {
+ name: `Delete Invoice Item ${itemNumber}`,
+ });
+}
+
+function getDialog() {
+ return screen.getByRole("alertdialog");
+}
+
+function getItemFieldsets() {
+ return screen.getAllByRole("group", { name: /^Item \d+$/ });
+}
+
describe("InvoiceItems max invoice items", () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -215,3 +238,245 @@ describe("InvoiceItems max invoice items", () => {
expect(within(fieldsets[1]).getByText("Item 2")).toBeInTheDocument();
});
});
+
+describe("InvoiceItems delete confirmation dialog", () => {
+ // The dialog's own copy, truncation and focus behaviour is covered directly in
+ // `sections/components/__tests__/delete-invoice-item-dialog.test.tsx`. What is left here is
+ // the wiring: that the trash buttons open it for the right item, name it from the *form*
+ // rather than from a debounced copy of the data, and hand the right index back on confirm.
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ it("does not render the dialog until an item's delete button is pressed", () => {
+ renderInvoiceItems({ itemCount: 2 });
+
+ expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument();
+ });
+
+ it("has no delete button for the first item, which cannot be removed", () => {
+ renderInvoiceItems({ itemCount: 2 });
+
+ expect(
+ screen.queryByRole("button", { name: "Delete Invoice Item 1" }),
+ ).not.toBeInTheDocument();
+ expect(getDeleteItemButton(2)).toBeInTheDocument();
+ });
+
+ it("names the item the user is deleting, reading the name from the form", async () => {
+ const user = userEvent.setup();
+
+ renderInvoiceItems({ itemCount: 2, itemNames: { 1: "Consulting" } });
+
+ // Rename the item, then delete it straight away: the dialog has to pick up the edit that
+ // is still sitting in the form rather than the name the invoice data was created with.
+ const itemNameInput = screen.getByLabelText("Name", {
+ selector: "#itemName1",
+ });
+ await user.clear(itemNameInput);
+ await user.type(itemNameInput, "Renamed just now");
+
+ await user.click(getDeleteItemButton(2));
+
+ expect(getDialog()).toHaveTextContent('"Renamed just now"');
+ });
+
+ it("passes the pressed item's index to the remove handler", async () => {
+ const user = userEvent.setup();
+ const onRemove = vi.fn();
+
+ renderInvoiceItems({ itemCount: 3, onRemove });
+
+ await user.click(getDeleteItemButton(3));
+ await user.click(screen.getByRole("button", { name: "Delete Item 3" }));
+
+ expect(onRemove).toHaveBeenCalledExactlyOnceWith(2);
+ });
+
+ it("does not remove anything when the dialog is cancelled", async () => {
+ const user = userEvent.setup();
+ const onRemove = vi.fn();
+
+ renderInvoiceItems({ itemCount: 2, onRemove });
+
+ await user.click(getDeleteItemButton(2));
+ await user.click(screen.getByRole("button", { name: "Cancel" }));
+
+ expect(onRemove).not.toHaveBeenCalled();
+ });
+});
+
+describe("InvoiceItems with several invoice items", () => {
+ /** Distinct names, so a test can tell which item the UI actually acted on. */
+ const ITEM_NAMES = {
+ 0: "Design work",
+ 1: "Backend work",
+ 2: "QA work",
+ 3: "Docs work",
+ };
+
+ const ITEM_COUNT = 4;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ it("gives every item but the first its own delete button", () => {
+ renderInvoiceItems({ itemCount: ITEM_COUNT, itemNames: ITEM_NAMES });
+
+ expect(getItemFieldsets()).toHaveLength(ITEM_COUNT);
+ expect(
+ screen.queryByRole("button", { name: "Delete Invoice Item 1" }),
+ ).not.toBeInTheDocument();
+
+ for (const itemNumber of [2, 3, 4]) {
+ expect(getDeleteItemButton(itemNumber)).toBeInTheDocument();
+ }
+ });
+
+ it.each([
+ [2, "Backend work"],
+ [3, "QA work"],
+ [4, "Docs work"],
+ ])(
+ "opens the dialog for item %i and names it %s",
+ async (itemNumber, expectedName) => {
+ const user = userEvent.setup();
+
+ renderInvoiceItems({ itemCount: ITEM_COUNT, itemNames: ITEM_NAMES });
+
+ await user.click(getDeleteItemButton(itemNumber));
+
+ const dialog = getDialog();
+
+ expect(
+ within(dialog).getByRole("heading", {
+ name: `Delete Item ${itemNumber}?`,
+ }),
+ ).toBeInTheDocument();
+ expect(dialog).toHaveTextContent(`"${expectedName}"`);
+ },
+ );
+
+ it("removes a middle item and renumbers the ones after it", async () => {
+ const user = userEvent.setup();
+ const onRemove = vi.fn();
+
+ renderInvoiceItems({
+ itemCount: ITEM_COUNT,
+ itemNames: ITEM_NAMES,
+ onRemove,
+ });
+
+ await user.click(getDeleteItemButton(2));
+ await user.click(screen.getByRole("button", { name: "Delete Item 2" }));
+
+ expect(onRemove).toHaveBeenCalledExactlyOnceWith(1);
+ expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument();
+
+ // Three items remain, numbered without a gap
+ expect(getItemFieldsets()).toHaveLength(3);
+ expect(
+ screen.queryByRole("button", { name: "Delete Invoice Item 4" }),
+ ).not.toBeInTheDocument();
+
+ // ...and what used to be item 3 has slid into position 2, name and all
+ await user.click(getDeleteItemButton(2));
+
+ expect(getDialog()).toHaveTextContent('"QA work"');
+ });
+
+ it("removes the last item without disturbing the ones before it", async () => {
+ const user = userEvent.setup();
+ const onRemove = vi.fn();
+
+ renderInvoiceItems({
+ itemCount: ITEM_COUNT,
+ itemNames: ITEM_NAMES,
+ onRemove,
+ });
+
+ await user.click(getDeleteItemButton(ITEM_COUNT));
+ await user.click(
+ screen.getByRole("button", { name: `Delete Item ${ITEM_COUNT}` }),
+ );
+
+ expect(onRemove).toHaveBeenCalledExactlyOnceWith(ITEM_COUNT - 1);
+ expect(getItemFieldsets()).toHaveLength(3);
+
+ await user.click(getDeleteItemButton(3));
+
+ expect(getDialog()).toHaveTextContent('"QA work"');
+ });
+
+ it("keeps every item when the dialog is cancelled", async () => {
+ const user = userEvent.setup();
+ const onRemove = vi.fn();
+
+ renderInvoiceItems({
+ itemCount: ITEM_COUNT,
+ itemNames: ITEM_NAMES,
+ onRemove,
+ });
+
+ await user.click(getDeleteItemButton(3));
+ await user.click(screen.getByRole("button", { name: "Cancel" }));
+
+ expect(onRemove).not.toHaveBeenCalled();
+ expect(getItemFieldsets()).toHaveLength(ITEM_COUNT);
+ });
+
+ it("deletes repeatedly, targeting the right item each time", async () => {
+ const user = userEvent.setup();
+ const onRemove = vi.fn();
+
+ renderInvoiceItems({
+ itemCount: ITEM_COUNT,
+ itemNames: ITEM_NAMES,
+ onRemove,
+ });
+
+ // Delete "Backend work" (item 2), then "QA work" which takes its place
+ await user.click(getDeleteItemButton(2));
+ await user.click(screen.getByRole("button", { name: "Delete Item 2" }));
+
+ await user.click(getDeleteItemButton(2));
+ expect(getDialog()).toHaveTextContent('"QA work"');
+ await user.click(screen.getByRole("button", { name: "Delete Item 2" }));
+
+ expect(onRemove).toHaveBeenNthCalledWith(1, 1);
+ expect(onRemove).toHaveBeenNthCalledWith(2, 1);
+ expect(getItemFieldsets()).toHaveLength(2);
+
+ // "Design work" and "Docs work" are what survive
+ await user.click(getDeleteItemButton(2));
+
+ expect(getDialog()).toHaveTextContent('"Docs work"');
+ });
+
+ it("only offers the 'Show in PDF' column switches on the first item", () => {
+ renderInvoiceItems({ itemCount: ITEM_COUNT, itemNames: ITEM_NAMES });
+
+ const fieldsets = getItemFieldsets();
+
+ expect(
+ within(fieldsets[0]).getAllByRole("switch", {
+ name: /Show the .* Column/,
+ }).length,
+ ).toBeGreaterThan(0);
+
+ for (const fieldset of fieldsets.slice(1)) {
+ expect(
+ within(fieldset).queryByRole("switch", { name: /Show the .* Column/ }),
+ ).not.toBeInTheDocument();
+ }
+ });
+});
diff --git a/src/app/(main)/(app)/components/invoice-form/sections/components/__tests__/delete-invoice-item-dialog.test.tsx b/src/app/(main)/(app)/components/invoice-form/sections/components/__tests__/delete-invoice-item-dialog.test.tsx
new file mode 100644
index 0000000..bf833dd
--- /dev/null
+++ b/src/app/(main)/(app)/components/invoice-form/sections/components/__tests__/delete-invoice-item-dialog.test.tsx
@@ -0,0 +1,289 @@
+// @vitest-environment happy-dom
+
+import { cleanup, render, screen, within } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { useRef, useState } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import {
+ DeleteInvoiceItemDialog,
+ type ItemPendingDeletion,
+} from "../delete-invoice-item-dialog";
+import "@testing-library/jest-dom/vitest";
+
+interface DialogTestHarnessProps {
+ item: ItemPendingDeletion;
+ onConfirm?: (index: number) => void;
+ onClose?: () => void;
+}
+
+/**
+ * Mirrors how `InvoiceItems` drives the dialog: a trash button per item opens it, and an
+ * "Add invoice item" button sits below the list as the post-delete focus target.
+ */
+function DialogTestHarness({
+ item,
+ onConfirm = vi.fn(),
+ onClose,
+}: DialogTestHarnessProps) {
+ const addItemButtonRef = useRef<HTMLButtonElement>(null);
+ const deleteTriggerRef = useRef<HTMLButtonElement>(null);
+ const [itemPendingDeletion, setItemPendingDeletion] =
+ useState<ItemPendingDeletion | null>(null);
+
+ return (
+ <>
+ <button
+ type="button"
+ ref={deleteTriggerRef}
+ onClick={() => {
+ return setItemPendingDeletion(item);
+ }}
+ >
+ Delete Invoice Item {item.index + 1}
+ </button>
+ <button type="button" ref={addItemButtonRef}>
+ Add invoice item
+ </button>
+ <DeleteInvoiceItemDialog
+ itemPendingDeletion={itemPendingDeletion}
+ onClose={() => {
+ onClose?.();
+ setItemPendingDeletion(null);
+ }}
+ onConfirm={onConfirm}
+ addItemButtonRef={addItemButtonRef}
+ deleteTriggerRef={deleteTriggerRef}
+ />
+ </>
+ );
+}
+
+function getTriggerButton(itemNumber: number) {
+ return screen.getByRole("button", {
+ name: `Delete Invoice Item ${itemNumber}`,
+ });
+}
+
+function getDialog() {
+ return screen.getByRole("alertdialog");
+}
+
+describe("DeleteInvoiceItemDialog", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ it("renders nothing until it is opened", () => {
+ render(<DialogTestHarness item={{ index: 1, name: "Product A" }} />);
+
+ expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument();
+ });
+
+ it("names the item in the title, the description and the confirm button", async () => {
+ const user = userEvent.setup();
+
+ render(
+ <DialogTestHarness item={{ index: 1, name: "Consulting retainer" }} />,
+ );
+
+ await user.click(getTriggerButton(2));
+
+ const dialog = getDialog();
+
+ expect(
+ within(dialog).getByRole("heading", { name: "Delete Item 2?" }),
+ ).toBeInTheDocument();
+ expect(dialog).toHaveTextContent(
+ '"Consulting retainer" will be removed from this invoice, and the totals recalculated. This action cannot be undone.',
+ );
+ expect(
+ within(dialog).getByRole("button", { name: "Delete Item 2" }),
+ ).toBeInTheDocument();
+ });
+
+ describe("item name preview", () => {
+ it("collapses newlines and repeated spaces onto one line", async () => {
+ const user = userEvent.setup();
+
+ render(
+ <DialogTestHarness
+ item={{ index: 0, name: " Design\n\n work for Q3 " }}
+ />,
+ );
+
+ await user.click(getTriggerButton(1));
+
+ expect(getDialog()).toHaveTextContent('"Design work for Q3"');
+ });
+
+ it("keeps a name that is exactly at the length limit intact", async () => {
+ const user = userEvent.setup();
+ const name = "x".repeat(60);
+
+ render(<DialogTestHarness item={{ index: 0, name }} />);
+
+ await user.click(getTriggerButton(1));
+
+ expect(getDialog()).toHaveTextContent(`"${name}"`);
+ expect(getDialog()).not.toHaveTextContent("…");
+ });
+
+ it("truncates a name one character past the limit", async () => {
+ const user = userEvent.setup();
+
+ render(<DialogTestHarness item={{ index: 0, name: "x".repeat(61) }} />);
+
+ await user.click(getTriggerButton(1));
+
+ expect(getDialog()).toHaveTextContent(`"${"x".repeat(60)}…"`);
+ });
+
+ it("truncates a name far past the limit, as the schema's 500 characters allows", async () => {
+ const user = userEvent.setup();
+
+ render(
+ <DialogTestHarness
+ item={{
+ index: 1,
+ name: `Senior backend engineering consultancy\n retainer for Q3, ${"x".repeat(440)}`,
+ }}
+ />,
+ );
+
+ await user.click(getTriggerButton(2));
+
+ expect(getDialog()).toHaveTextContent(
+ '"Senior backend engineering consultancy retainer for Q3, xxxx…"',
+ );
+ });
+
+ it("does not leave a dangling space before the ellipsis", async () => {
+ const user = userEvent.setup();
+
+ render(
+ <DialogTestHarness
+ item={{ index: 0, name: `${"x".repeat(59)} tail end` }}
+ />,
+ );
+
+ await user.click(getTriggerButton(1));
+
+ expect(getDialog()).toHaveTextContent(`"${"x".repeat(59)}…"`);
+ });
+
+ it.each([
+ ["an undefined name", undefined],
+ ["an empty name", ""],
+ ["a whitespace-only name", " \n "],
+ ])("falls back to the item number for %s", async (_label, name) => {
+ const user = userEvent.setup();
+
+ render(<DialogTestHarness item={{ index: 1, name }} />);
+
+ await user.click(getTriggerButton(2));
+
+ expect(getDialog()).toHaveTextContent(
+ "Item 2 has no name yet. It will be removed from this invoice, and the totals recalculated. This action cannot be undone.",
+ );
+ });
+ });
+
+ describe("confirming and cancelling", () => {
+ it("removes the item when the deletion is confirmed", async () => {
+ const user = userEvent.setup();
+ const onConfirm = vi.fn();
+
+ render(
+ <DialogTestHarness
+ item={{ index: 2, name: "Product C" }}
+ onConfirm={onConfirm}
+ />,
+ );
+
+ await user.click(getTriggerButton(3));
+ await user.click(screen.getByRole("button", { name: "Delete Item 3" }));
+
+ expect(onConfirm).toHaveBeenCalledExactlyOnceWith(2);
+ });
+
+ it("keeps the item when the dialog is cancelled", async () => {
+ const user = userEvent.setup();
+ const onConfirm = vi.fn();
+ const onClose = vi.fn();
+
+ render(
+ <DialogTestHarness
+ item={{ index: 1, name: "Product B" }}
+ onConfirm={onConfirm}
+ onClose={onClose}
+ />,
+ );
+
+ await user.click(getTriggerButton(2));
+ await user.click(screen.getByRole("button", { name: "Cancel" }));
+
+ expect(onConfirm).not.toHaveBeenCalled();
+ expect(onClose).toHaveBeenCalledOnce();
+ expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument();
+ });
+
+ it("closes without removing the item when dismissed with Escape", async () => {
+ const user = userEvent.setup();
+ const onConfirm = vi.fn();
+
+ render(
+ <DialogTestHarness
+ item={{ index: 1, name: "Product B" }}
+ onConfirm={onConfirm}
+ />,
+ );
+
+ await user.click(getTriggerButton(2));
+ await user.keyboard("{Escape}");
+
+ expect(onConfirm).not.toHaveBeenCalled();
+ expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument();
+ });
+ });
+
+ describe("focus handling", () => {
+ it("autofocuses Cancel rather than the destructive action when it opens", async () => {
+ const user = userEvent.setup();
+
+ render(<DialogTestHarness item={{ index: 1, name: "Product B" }} />);
+
+ await user.click(getTriggerButton(2));
+
+ expect(screen.getByRole("button", { name: "Cancel" })).toHaveFocus();
+ });
+
+ it("returns focus to the button that opened it after a cancel", async () => {
+ const user = userEvent.setup();
+
+ render(<DialogTestHarness item={{ index: 1, name: "Product B" }} />);
+
+ await user.click(getTriggerButton(2));
+ await user.click(screen.getByRole("button", { name: "Cancel" }));
+
+ expect(getTriggerButton(2)).toHaveFocus();
+ });
+
+ it("moves focus to 'Add invoice item' after a confirmed delete, since the trigger goes away with its item", async () => {
+ const user = userEvent.setup();
+
+ render(<DialogTestHarness item={{ index: 1, name: "Product B" }} />);
+
+ await user.click(getTriggerButton(2));
+ await user.click(screen.getByRole("button", { name: "Delete Item 2" }));
+
+ expect(
+ screen.getByRole("button", { name: "Add invoice item" }),
+ ).toHaveFocus();
+ });
+ });
+});
diff --git a/src/app/(main)/(app)/components/invoice-form/sections/components/delete-invoice-item-dialog.tsx b/src/app/(main)/(app)/components/invoice-form/sections/components/delete-invoice-item-dialog.tsx
new file mode 100644
index 0000000..2df1a66
--- /dev/null
+++ b/src/app/(main)/(app)/components/invoice-form/sections/components/delete-invoice-item-dialog.tsx
@@ -0,0 +1,151 @@
+import { useRef, useState, type RefObject } from "react";
+
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { buttonVariants } from "@/components/ui/button";
+
+/**
+ * How much of an item name the dialog shows before truncating.
+ */
+const MAX_ITEM_NAME_PREVIEW_LENGTH = 60;
+
+export interface ItemPendingDeletion {
+ /** Index of the item in the `items` field array. */
+ index: number;
+ /**
+ * The item's name as it read when the user pressed delete. Captured then, rather than
+ * watched, so the dialog names the item the user is actually looking at and keeps naming
+ * it while the dialog animates closed.
+ */
+ name: string | undefined;
+}
+
+interface DeleteInvoiceItemDialogProps {
+ /** The item awaiting confirmation, or `null` while the dialog is closed. */
+ itemPendingDeletion: ItemPendingDeletion | null;
+ /** Closes the dialog (cancel, Escape, overlay click, or after a confirmed delete). */
+ onClose: () => void;
+ /** Removes the item at the given index. */
+ onConfirm: (index: number) => void;
+ /** The "Add invoice item" button, where focus lands after a confirmed delete. */
+ addItemButtonRef: RefObject<HTMLButtonElement | null>;
+ /** The trash button that opened the dialog, where focus lands after a cancel. */
+ deleteTriggerRef: RefObject<HTMLButtonElement | null>;
+}
+
+/**
+ * A confirmation dialog for deleting an invoice item.
+ */
+export function DeleteInvoiceItemDialog({
+ itemPendingDeletion,
+ onClose,
+ onConfirm,
+ addItemButtonRef,
+ deleteTriggerRef,
+}: DeleteInvoiceItemDialogProps) {
+ // Radix keeps the content mounted until its exit animation finishes, so rendering straight
+ // from `itemPendingDeletion` would blank the dialog out mid-fade. Hold on to the last item
+ // and keep showing it on the way out ("storing information from previous renders").
+ const [lastItem, setLastItem] = useState(itemPendingDeletion);
+
+ if (itemPendingDeletion !== null && itemPendingDeletion !== lastItem) {
+ setLastItem(itemPendingDeletion);
+ }
+
+ const didConfirmRef = useRef(false);
+
+ const item = itemPendingDeletion ?? lastItem;
+
+ if (!item) return null;
+
+ const itemLabel = `Item ${item.index + 1}`;
+ const namePreview = toItemNamePreview(item.name);
+
+ return (
+ <AlertDialog
+ open={itemPendingDeletion !== null}
+ onOpenChange={(open) => {
+ if (!open) {
+ onClose();
+ }
+ }}
+ >
+ <AlertDialogContent
+ data-testid="delete-invoice-item-confirmation-dialog"
+ // Radix hands focus back to its `Trigger`, but this dialog is controlled rather than
+ // triggered, so there is no trigger to hand it to and focus would land on `<body>`.
+ // Place it ourselves: back on the trash button after a cancel, and -- since that
+ // button has just been unmounted along with its item -- on "Add invoice item" after
+ // a confirmed delete.
+ onCloseAutoFocus={(event) => {
+ event.preventDefault();
+
+ const didConfirm = didConfirmRef.current;
+ didConfirmRef.current = false;
+
+ const trigger = deleteTriggerRef.current;
+ const focusTarget =
+ !didConfirm && trigger?.isConnected
+ ? trigger
+ : addItemButtonRef.current;
+
+ focusTarget?.focus();
+ }}
+ >
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete {itemLabel}?</AlertDialogTitle>
+ <AlertDialogDescription className="text-balance">
+ {namePreview ? (
+ <>
+ <strong className="font-semibold text-slate-900 dark:text-slate-100">
+ &quot;{namePreview}&quot;
+ </strong>{" "}
+ will be removed from this invoice, and the totals recalculated.
+ </>
+ ) : (
+ <>
+ {itemLabel} has no name yet. It will be removed from this
+ invoice, and the totals recalculated.
+ </>
+ )}{" "}
+ This action cannot be undone.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ onClick={() => {
+ didConfirmRef.current = true;
+ onConfirm(item.index);
+ }}
+ className={buttonVariants({ variant: "destructive" })}
+ >
+ Delete {itemLabel}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+}
+
+/**
+ * Item names allow up to 500 characters across multiple lines (the field is a `<textarea>`),
+ * but the dialog only has room to identify the item. Collapse the whitespace and cut it short.
+ *
+ * Returns an empty string when the item has no usable name.
+ */
+function toItemNamePreview(itemName: string | undefined) {
+ const collapsed = itemName?.replaceAll(/\s+/g, " ").trim() ?? "";
+
+ return collapsed.length > MAX_ITEM_NAME_PREVIEW_LENGTH
+ ? `${collapsed.slice(0, MAX_ITEM_NAME_PREVIEW_LENGTH).trimEnd()}…`
+ : collapsed;
+}
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.tsx
index 58de358..5b262d7 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
@@ -1,14 +1,19 @@
import { Plus, Trash2 } from "lucide-react";
-import { memo, useState } from "react";
+import { memo, useRef, useState } from "react";
import {
type Control,
Controller,
type FieldArrayWithId,
type FieldErrors,
type UseFieldArrayAppend,
+ type UseFormGetValues,
} from "react-hook-form";
import { inputErrorClassName } from "@/app/(main)/(app)/components/invoice-form/common";
+import {
+ DeleteInvoiceItemDialog,
+ type ItemPendingDeletion,
+} from "@/app/(main)/(app)/components/invoice-form/sections/components/delete-invoice-item-dialog";
import { INVOICE_PDF_TRANSLATIONS } from "@/app/(main)/(app)/pdf-i18n-translations/pdf-translations";
import {
type InvoiceData,
@@ -17,16 +22,6 @@ import {
MAX_INVOICE_ITEMS,
} from "@/app/schema";
import { Legend } from "@/components/legend";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
-} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { InputHelperMessage } from "@/components/ui/input-helper-message";
@@ -56,7 +51,7 @@ interface InvoiceItemsSettingsProps {
language: SupportedLanguages;
template: InvoiceData["template"];
taxLabelText: string;
- invoiceData: InvoiceData;
+ getValues: UseFormGetValues<InvoiceData>;
}
export const InvoiceItems = memo(function InvoiceItems({
@@ -69,9 +64,12 @@ export const InvoiceItems = memo(function InvoiceItems({
append,
template,
taxLabelText,
- invoiceData,
+ getValues,
}: InvoiceItemsSettingsProps) {
- const [deleteItemIndex, setDeleteItemIndex] = useState<number | null>(null);
+ const [itemPendingDeletion, setItemPendingDeletion] =
+ useState<ItemPendingDeletion | null>(null);
+ const addItemButtonRef = useRef<HTMLButtonElement>(null);
+ const deleteTriggerRef = useRef<HTMLButtonElement | null>(null);
const hasReachedItemLimit = fields.length >= MAX_INVOICE_ITEMS;
return (
@@ -102,8 +100,17 @@ export const InvoiceItems = memo(function InvoiceItems({
onMouseDown={(event) => {
event.preventDefault();
}}
- onClick={() => {
- return setDeleteItemIndex(index);
+ onClick={(event) => {
+ // Radix returns focus to its `Trigger` on close, and this dialog is
+ // controlled rather than triggered, so remember the button ourselves.
+ deleteTriggerRef.current = event.currentTarget;
+
+ // Read the name from the form rather than from the parent's debounced
+ // copy of it, so the dialog names what the user is actually looking at.
+ return setItemPendingDeletion({
+ index,
+ name: getValues(`items.${index}.name`),
+ });
}}
className="flex items-center justify-center rounded-full bg-red-600 p-2 transition-colors hover:bg-red-700 active:scale-[98%] active:transition-transform"
>
@@ -824,6 +831,7 @@ export const InvoiceItems = memo(function InvoiceItems({
<CustomTooltip
trigger={
<Button
+ ref={addItemButtonRef}
onClick={() => {
append({
invoiceItemNumberIsVisible: true,
@@ -923,68 +931,15 @@ export const InvoiceItems = memo(function InvoiceItems({
</div>
) : null}
- <DeleteInvoiceItemConfirmationDialog
- deleteItemIndex={deleteItemIndex}
- setDeleteItemIndex={setDeleteItemIndex}
- handleRemoveInvoiceItem={handleRemoveInvoiceItem}
- invoiceData={invoiceData}
+ <DeleteInvoiceItemDialog
+ itemPendingDeletion={itemPendingDeletion}
+ onClose={() => {
+ return setItemPendingDeletion(null);
+ }}
+ onConfirm={handleRemoveInvoiceItem}
+ addItemButtonRef={addItemButtonRef}
+ deleteTriggerRef={deleteTriggerRef}
/>
</>
);
});
-
-interface DeleteInvoiceItemConfirmationDialogProps {
- deleteItemIndex: number | null;
- setDeleteItemIndex: (index: number | null) => void;
- handleRemoveInvoiceItem: (index: number) => void;
- invoiceData: InvoiceData;
-}
-
-/**
- * A confirmation dialog for deleting an invoice item.
- */
-function DeleteInvoiceItemConfirmationDialog({
- deleteItemIndex = 0,
- setDeleteItemIndex,
- handleRemoveInvoiceItem,
- invoiceData,
-}: DeleteInvoiceItemConfirmationDialogProps) {
- const itemNumber = deleteItemIndex ?? 0;
-
- const itemName =
- invoiceData?.items?.[itemNumber]?.name || `#${itemNumber + 1}`;
-
- return (
- <AlertDialog
- open={deleteItemIndex !== null}
- onOpenChange={(open) => {
- if (!open) setDeleteItemIndex(null);
- }}
- >
- <AlertDialogContent data-testid="delete-invoice-item-confirmation-dialog">
- <AlertDialogHeader>
- <AlertDialogTitle>Delete Invoice Item</AlertDialogTitle>
- <AlertDialogDescription className="text-balance">
- Are you sure you want to delete the invoice item{" "}
- <strong>&quot;{itemName}&quot;</strong>? This action cannot be
- undone.
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>Cancel</AlertDialogCancel>
- <AlertDialogAction
- onClick={() => {
- if (deleteItemIndex !== null) {
- handleRemoveInvoiceItem(deleteItemIndex);
- setDeleteItemIndex(null);
- }
- }}
- className="bg-red-500 text-red-50 hover:bg-red-500/90"
- >
- Delete
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- );
-}
diff --git a/src/app/(main)/(app)/page.tsx b/src/app/(main)/(app)/page.tsx
index 3a25105..da1b0b4 100644
--- a/src/app/(main)/(app)/page.tsx
+++ b/src/app/(main)/(app)/page.tsx
@@ -9,6 +9,7 @@ import { computeIndexingFlags } from "@/lib/seo/indexing-utils";
import { CTAToastProvider } from "./contexts/cta-toast-context";
import { HomeJsonLd } from "./home-json-ld";
import { AppPageClient } from "./page.client";
+import { RobotsMetaSync } from "./robots-meta-sync";
const APP_PAGE_DESCRIPTION =
"Create professional PDF invoices online for free. Customize invoice templates, add your logo, download instantly, and send invoices without signup.";
@@ -157,7 +158,9 @@ export default async function AppPage({
}: {
searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
}) {
- const { shouldIndex } = computeIndexingFlags(await searchParams);
+ const { isIndexableEnvironment, shouldIndex } = computeIndexingFlags(
+ await searchParams,
+ );
const [githubStarsCount, latestChangelog] = await Promise.all([
fetchGithubStars(),
@@ -177,6 +180,9 @@ export default async function AppPage({
return (
<CTAToastProvider>
+ {/* sharing an invoice adds `?data=` without a navigation, so the server-rendered
+ robots metadata has to be re-applied on the client */}
+ <RobotsMetaSync isIndexableEnvironment={isIndexableEnvironment} />
{shouldIndex ? <HomeJsonLd /> : null}
<AppPageClient
githubStarsCount={githubStarsCount}
diff --git a/src/app/(main)/(app)/robots-meta-sync.tsx b/src/app/(main)/(app)/robots-meta-sync.tsx
new file mode 100644
index 0000000..3e396bf
--- /dev/null
+++ b/src/app/(main)/(app)/robots-meta-sync.tsx
@@ -0,0 +1,86 @@
+"use client";
+
+import { useSearchParams } from "next/navigation";
+import { useEffect } from "react";
+
+import { ROBOTS_META_CONTENT } from "@/lib/seo/indexing-utils";
+
+/**
+ * The meta tags Next.js emits from `Metadata.robots` on this page.
+ *
+ * `robots` comes from `robots.index`/`robots.follow`, `googlebot` from `robots.googleBot`.
+ */
+const ROBOTS_META_NAMES = ["robots", "googlebot"] as const;
+
+/**
+ * Writes `content` to every robots meta tag in the document.
+ *
+ * A tag Next.js did not render is created only for restrictive directives -- an absent
+ * tag already means "index, follow", so there is nothing to add in the permissive case.
+ *
+ * @param content - The crawler directives to apply, e.g. `"noindex, nofollow"`.
+ */
+function applyRobotsMetaContent(content: string) {
+ const isRestrictive = content === ROBOTS_META_CONTENT.nonIndexable;
+
+ for (const name of ROBOTS_META_NAMES) {
+ const existingMeta = document.querySelector(`meta[name="${name}"]`);
+
+ if (existingMeta) {
+ existingMeta.setAttribute("content", content);
+ continue;
+ }
+
+ if (!isRestrictive) {
+ continue;
+ }
+
+ const meta = document.createElement("meta");
+ meta.setAttribute("name", name);
+ meta.setAttribute("content", content);
+ document.head.append(meta);
+ }
+}
+
+/**
+ * Keeps the crawler directives in sync with the `?data=` share param.
+ *
+ * `generateMetadata` already renders `noindex, nofollow` for any request that arrives with
+ * `?data=`, but sharing an invoice adds that param through `window.history.replaceState`
+ * (see `replaceUrlQuery` in `page.client.tsx`) -- a deliberate, navigation-free rewrite, so
+ * the server never re-renders the metadata and the document keeps whatever directives it
+ * was loaded with. On production that is `index, follow`, which would let a crawler that
+ * picked the shared link up index someone's invoice data.
+ *
+ * The tags are patched in place rather than rendered: Next already owns a `meta[name="robots"]`
+ * in the document, and a second one would leave crawlers with two conflicting directives.
+ *
+ * @returns Nothing -- this component only writes to `document.head`.
+ */
+export function RobotsMetaSync({
+ isIndexableEnvironment,
+}: {
+ /**
+ * Whether this deployment is indexable at all -- i.e. the canonical production
+ * deployment. Preview deployments are never indexable, with or without `?data=`.
+ */
+ isIndexableEnvironment: boolean;
+}) {
+ const searchParams = useSearchParams();
+ const hasShareableData = searchParams.get("data") !== null;
+
+ // mirrors what `generateMetadata` would render for the URL currently in the address bar,
+ // in both directions -- the app drops `?data=` in place too (a corrupted link, an edit to
+ // a shared invoice), and `/` on its own is the canonical page we do want indexed
+ const shouldIndex = isIndexableEnvironment && !hasShareableData;
+
+ useEffect(() => {
+ applyRobotsMetaContent(
+ shouldIndex
+ ? ROBOTS_META_CONTENT.indexable
+ : ROBOTS_META_CONTENT.nonIndexable,
+ );
+ }, [shouldIndex]);
+
+ return null;
+}
diff --git a/src/app/[locale]/about/components/__tests__/legacy-video-fallback.test.tsx b/src/app/[locale]/about/components/__tests__/legacy-video-fallback.test.tsx
index dec963e..5ff3248 100644
--- a/src/app/[locale]/about/components/__tests__/legacy-video-fallback.test.tsx
+++ b/src/app/[locale]/about/components/__tests__/legacy-video-fallback.test.tsx
@@ -3,7 +3,7 @@
import { cleanup, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";
-import { VIDEO_DEMO_FALLBACK_IMG, VIDEO_DEMO_YOUTUBE_URL } from "@/config";
+import { VIDEO_DEMO_FALLBACK_IMG, VIDEO_DEMO_HERO_YOUTUBE_URL } from "@/config";
import { FeaturesCarousel } from "../features-carousel";
import { HeroDemoVideo } from "../hero-demo-video";
@@ -126,13 +126,15 @@ describe("HeroDemoVideo", () => {
const src = new URL(embed.getAttribute("src") ?? "");
expect(src.origin + src.pathname).toBe(
- new URL(VIDEO_DEMO_YOUTUBE_URL).origin +
- new URL(VIDEO_DEMO_YOUTUBE_URL).pathname,
+ new URL(VIDEO_DEMO_HERO_YOUTUBE_URL).origin +
+ new URL(VIDEO_DEMO_HERO_YOUTUBE_URL).pathname,
);
// the clip it stands in for starts on its own, so this one does too
expect(src.searchParams.get("autoplay")).toBe("1");
expect(src.searchParams.get("mute")).toBe("1");
expect(src.searchParams.get("playsinline")).toBe("1");
+ // ...and carries no player chrome, like the MP4 it replaces
+ expect(src.searchParams.get("controls")).toBe("1");
expect(screen.queryByTestId("hero-about-page-video")).toBeNull();
});
});
diff --git a/src/app/[locale]/about/components/hero-demo-video.tsx b/src/app/[locale]/about/components/hero-demo-video.tsx
index 29689a9..6b83cf1 100644
--- a/src/app/[locale]/about/components/hero-demo-video.tsx
+++ b/src/app/[locale]/about/components/hero-demo-video.tsx
@@ -4,8 +4,8 @@ import { AutoPlayVideo } from "@/components/video";
import { YouTubeEmbed } from "@/components/youtube-embed";
import {
VIDEO_DEMO_FALLBACK_IMG,
+ VIDEO_DEMO_HERO_YOUTUBE_URL,
VIDEO_DEMO_URL,
- VIDEO_DEMO_YOUTUBE_URL,
} from "@/config";
import { useSupportsInlineVideo } from "@/hooks/use-supports-inline-video";
@@ -13,9 +13,9 @@ const VIDEO_DESCRIPTION =
"How to create and download an invoice as a PDF in EasyInvoicePDF.com";
/**
- * The demo in the hero's browser frame: the self-hosted MP4 normally, and the same
- * demo on YouTube on browsers that cannot play it inline (iOS 15 and older, where
- * the `<video>` sat on its poster and never started).
+ * The demo in the hero's browser frame: the self-hosted MP4 normally, and the demo
+ * on YouTube on browsers that cannot play it inline (iOS 15 and older, where the
+ * `<video>` sat on its poster and never started).
*
* Fills its positioned parent, like `AutoPlayVideo` does on its own.
*/
@@ -25,11 +25,12 @@ export function HeroDemoVideo() {
if (!canPlayInlineVideo) {
return (
<YouTubeEmbed
- src={VIDEO_DEMO_YOUTUBE_URL}
+ src={VIDEO_DEMO_HERO_YOUTUBE_URL}
title={VIDEO_DESCRIPTION}
- // the hero demo runs by itself on every other browser, and this is the same
- // clip standing in for it
+ // the hero demo runs by itself on every other browser, and this clip stands
+ // in for it — chrome-less and looping, like the MP4 it replaces
autoPlay
+ showControls={true}
className="absolute left-0 top-0"
testId="hero-about-page-video-youtube"
/>
@@ -42,6 +43,9 @@ export function HeroDemoVideo() {
posterImg={VIDEO_DEMO_FALLBACK_IMG}
testId="hero-about-page-video"
description={VIDEO_DESCRIPTION}
+ // the browser frame is wide and short of the fold on a phone, where half of it is
+ // never on screen at once; a sliver is enough to mean the demo is being looked at
+ inViewThreshold={0.15}
/>
);
}
diff --git a/src/components/__tests__/video.test.tsx b/src/components/__tests__/video.test.tsx
index 1dc2faa..897b057 100644
--- a/src/components/__tests__/video.test.tsx
+++ b/src/components/__tests__/video.test.tsx
@@ -136,6 +136,35 @@ describe("AutoPlayVideo", () => {
expect(screen.queryByTestId("demo-play-button")).toBeNull();
});
+ it("starts on a sliver of the video when the threshold asks for one", () => {
+ render(
+ <AutoPlayVideo
+ src={SRC}
+ posterImg={POSTER}
+ testId="demo"
+ inViewThreshold={0.15}
+ />,
+ );
+
+ // a fifth of the hero frame is all a phone ever has on screen at once, and the
+ // default half would leave the demo sitting on its poster there
+ act(() => {
+ return mockAllIsIntersecting(0.2);
+ });
+
+ expect(play).toHaveBeenCalledWith();
+ });
+
+ it("waits for half the video by default", () => {
+ render(<AutoPlayVideo src={SRC} posterImg={POSTER} testId="demo" />);
+
+ act(() => {
+ return mockAllIsIntersecting(0.2);
+ });
+
+ expect(play).not.toHaveBeenCalled();
+ });
+
it("starts the video and drops the button when it is pressed", async () => {
play.mockRejectedValue(NOT_ALLOWED);
diff --git a/src/components/__tests__/youtube-embed.test.tsx b/src/components/__tests__/youtube-embed.test.tsx
index 9171483..f378ff9 100644
--- a/src/components/__tests__/youtube-embed.test.tsx
+++ b/src/components/__tests__/youtube-embed.test.tsx
@@ -58,6 +58,26 @@ describe("YouTubeEmbed", () => {
expect(src.searchParams.get("playlist")).toBe("iAROeCIcZ40");
});
+ it("keeps the player's controls by default", () => {
+ render(<YouTubeEmbed src={SRC} title="Demo" autoPlay testId="embed" />);
+
+ expect(getSrc().searchParams.get("controls")).toBe("1");
+ });
+
+ it("drops the controls where the embed is decoration", () => {
+ render(
+ <YouTubeEmbed
+ src={SRC}
+ title="Demo"
+ autoPlay
+ showControls={false}
+ testId="embed"
+ />,
+ );
+
+ expect(getSrc().searchParams.get("controls")).toBe("0");
+ });
+
it("keeps the parameters the url arrived with", () => {
render(<YouTubeEmbed src={SRC} title="Demo" autoPlay testId="embed" />);
diff --git a/src/components/video.tsx b/src/components/video.tsx
index 9669844..cc5471e 100644
--- a/src/components/video.tsx
+++ b/src/components/video.tsx
@@ -23,6 +23,14 @@ interface AutoPlayVideoProps extends SharedVideoProps {
* video on its own. Falls back to `description`, then to a generic label.
*/
playButtonLabel?: string;
+ /**
+ * How much of the video has to be on screen before it starts, as a fraction of the
+ * element's area. A frame that is large next to the viewport — the hero demo on a
+ * phone — never reaches the default half, so lower it there.
+ *
+ * @default 0.5
+ */
+ inViewThreshold?: number;
}
/**
@@ -48,6 +56,7 @@ export function AutoPlayVideo({
prefersReducedMotion = false,
renderReducedMotionFallback,
playButtonLabel,
+ inViewThreshold = 0.5,
testId = "",
...props
}: AutoPlayVideoProps) {
@@ -64,7 +73,7 @@ export function AutoPlayVideo({
const descriptionID = useId();
const { ref, inView } = useInView({
- threshold: 0.5,
+ threshold: inViewThreshold,
rootMargin: "50px",
});
diff --git a/src/components/youtube-embed.tsx b/src/components/youtube-embed.tsx
index ab324ad..c9af51c 100644
--- a/src/components/youtube-embed.tsx
+++ b/src/components/youtube-embed.tsx
@@ -13,6 +13,17 @@ interface YouTubeEmbedProps {
* should wait to be asked.
*/
autoPlay?: boolean;
+ /**
+ * Show the player's own controls.
+ *
+ * Part of the `autoPlay` parameter set, so it does nothing without it — a URL that
+ * is not rewritten keeps whatever it arrived with.
+ *
+ * Turn it off where the embed stands in for a chrome-less looping video, like the
+ * hero demo. Note that this also takes away the only way to unmute, pause or go
+ * fullscreen, which is only acceptable for decoration.
+ */
+ showControls?: boolean;
className?: string;
testId?: string;
}
@@ -29,12 +40,13 @@ export function YouTubeEmbed({
src,
title,
autoPlay = false,
+ showControls = true,
className,
testId,
}: YouTubeEmbedProps) {
return (
<iframe
- src={autoPlay ? buildAutoPlayUrl(src) : src}
+ src={autoPlay ? buildAutoPlayUrl({ src, showControls }) : src}
title={title}
// `autoplay` here is the Permissions Policy delegation: without it the player is
// not allowed to start itself, whatever the URL asks for
@@ -47,6 +59,13 @@ export function YouTubeEmbed({
);
}
+interface BuildAutoPlayUrlArgs {
+ /** The `https://www.youtube.com/embed/...` URL to rewrite. */
+ src: string;
+ /** Whether the player keeps its own controls. */
+ showControls: boolean;
+}
+
/**
* The same URL with the parameters that make the player behave like the muted, looping
* demo it replaces.
@@ -58,7 +77,7 @@ export function YouTubeEmbed({
*
* @see https://developers.google.com/youtube/player_parameters
*/
-function buildAutoPlayUrl(src: string) {
+function buildAutoPlayUrl({ src, showControls }: BuildAutoPlayUrlArgs) {
let url: URL;
try {
@@ -73,8 +92,9 @@ function buildAutoPlayUrl(src: string) {
url.searchParams.set("mute", "1");
// without this iOS takes the video fullscreen the moment it starts
url.searchParams.set("playsinline", "1");
- // the only way to pause, scrub, unmute or go fullscreen once it is running
- url.searchParams.set("controls", "1");
+ // the only way to pause, scrub, unmute or go fullscreen once it is running, so it
+ // stays on unless the caller wants a plain looping picture
+ url.searchParams.set("controls", showControls ? "1" : "0");
url.searchParams.set("rel", "0");
url.searchParams.set("modestbranding", "1");
// no annotations over the demo
diff --git a/src/config.ts b/src/config.ts
index b4556a3..1ce036e 100644
--- a/src/config.ts
+++ b/src/config.ts
@@ -20,11 +20,19 @@ export const VIDEO_DEMO_URL = `${STATIC_ASSETS_URL}/demo-videos/easy-invoice-dem
export const VIDEO_DEMO_FALLBACK_IMG = `${STATIC_ASSETS_URL}/demo-videos/easy-invoice-demo-01-2026-fallback-img-v1.png`;
/**
- * YouTube URL for main demo video on marketing page and "How it works" dialog
+ * YouTube URL for main demo video on "How it works" dialog
*/
export const VIDEO_DEMO_YOUTUBE_URL =
"https://www.youtube.com/embed/iAROeCIcZ40?si=EyJKCsUr43Z8zY1f";
+/**
+ * YouTube URL for the hero demo video on the marketing page — the stand-in shown to
+ * browsers that cannot play the self-hosted MP4 inline. It is its own upload, cut for
+ * the hero's browser frame, rather than the longer walkthrough above.
+ */
+export const VIDEO_DEMO_HERO_YOUTUBE_URL =
+ "https://www.youtube.com/embed/wkecHuXWLSQ";
+
export const YOUTUBE_VIDEO_HOW_TO_ADD_SELLER =
"https://www.youtube.com/embed/xfSF35c0vfU";
diff --git a/src/lib/seo/indexing-utils.ts b/src/lib/seo/indexing-utils.ts
index 160e599..4e508b6 100644
--- a/src/lib/seo/indexing-utils.ts
+++ b/src/lib/seo/indexing-utils.ts
@@ -6,19 +6,41 @@ import { PROD_WEBSITE_URL } from "@/config";
* @param searchParams - Query params from request URL.
* @returns Object with:
* hasShareableData: Whether query contains 'data' parameter (shareable invoice).
- * isProd: True if running on canonical production deployment.
- * shouldIndex: True if page should be indexed (prod, no share data).
+ * isIndexableEnvironment: True if this deployment is allowed to be indexed at all.
+ * shouldIndex: True if page should be indexed (indexable environment, no share data).
*/
export function computeIndexingFlags(searchParams: {
[key: string]: string | string[] | undefined;
}) {
- const hasShareableData = Boolean(searchParams?.data);
+ const hasShareableData = searchParams?.data !== undefined;
const isProd =
process.env.VERCEL_ENV === "production" &&
`https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}` === PROD_WEBSITE_URL;
- const shouldIndex = isProd && !hasShareableData;
+ /**
+ * The local dev server renders the same directives production does, so the difference
+ * between an indexable page and a shared one can be seen (and tested) on localhost.
+ *
+ * Nothing crawls localhost, and a deployed build never runs with `NODE_ENV`
+ * `development` -- preview deployments stay `noindex, nofollow` either way.
+ */
+ const isLocalDevServer = process.env.NODE_ENV === "development";
- return { hasShareableData, isProd, shouldIndex };
+ const isIndexableEnvironment = isProd || isLocalDevServer;
+
+ const shouldIndex = isIndexableEnvironment && !hasShareableData;
+
+ return { hasShareableData, isIndexableEnvironment, shouldIndex };
}
+
+/**
+ * The `content` values Next.js renders for `Metadata.robots` on the invoice app page.
+ *
+ * Kept here so the client-side sync in `RobotsMetaSync` writes exactly what
+ * `resolveAppPageRobots` would have rendered for the same state.
+ */
+export const ROBOTS_META_CONTENT = {
+ indexable: "index, follow",
+ nonIndexable: "noindex, nofollow",
+} as const;