feat(frontend): CSV export utility + ExportCsvButton component
This commit is contained in:
@@ -0,0 +1,213 @@
|
||||
// @vitest-environment happy-dom
|
||||
// React's state updates need an act-aware environment or it logs noisy
|
||||
// warnings. Matches the convention from Batches.test.tsx.
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT =
|
||||
true;
|
||||
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { act } from "react";
|
||||
import { ExportCsvButton } from "./ExportCsvButton";
|
||||
|
||||
type Row = { id: string; patient: string; amount: number };
|
||||
|
||||
const sample: Row[] = [
|
||||
{ id: "C-1", patient: "Alice", amount: 100 },
|
||||
{ id: "C-2", patient: "Bob, Jr.", amount: 250 },
|
||||
];
|
||||
|
||||
const cols = [
|
||||
{ header: "Claim ID", value: (r: Row) => r.id },
|
||||
{ header: "Patient", value: (r: Row) => r.patient },
|
||||
{ header: "Charge", value: (r: Row) => r.amount.toFixed(2) },
|
||||
];
|
||||
|
||||
type Mount = {
|
||||
root: Root;
|
||||
container: HTMLDivElement;
|
||||
getButton: () => HTMLButtonElement;
|
||||
unmount: () => void;
|
||||
};
|
||||
|
||||
function mount(element: React.ReactElement): Mount {
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
act(() => {
|
||||
root.render(element);
|
||||
});
|
||||
return {
|
||||
root,
|
||||
container,
|
||||
getButton: () => container.querySelector("button") as HTMLButtonElement,
|
||||
unmount: () => {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("<ExportCsvButton />", () => {
|
||||
beforeEach(() => {
|
||||
// jsdom doesn't implement createObjectURL/ revokeObjectURL; we don't
|
||||
// care about the Blob itself, only that click() runs and our mock
|
||||
// plumbing fires.
|
||||
URL.createObjectURL = vi.fn(() => "blob:mock") as typeof URL.createObjectURL;
|
||||
URL.revokeObjectURL = vi.fn();
|
||||
// Capture the synthesized <a> click — jsdom will not actually download.
|
||||
const realCreate = document.createElement.bind(document);
|
||||
const spy = vi.spyOn(document, "createElement");
|
||||
spy.mockImplementation(((tag: string) => {
|
||||
const el = realCreate(tag) as HTMLElement;
|
||||
if (tag === "a") {
|
||||
// Replace .click() on anchor elements only.
|
||||
(el as HTMLAnchorElement).click = vi.fn();
|
||||
}
|
||||
return el;
|
||||
}) as typeof document.createElement);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("renders with a Download icon and the default label", () => {
|
||||
const m = mount(
|
||||
<ExportCsvButton rows={sample} columns={cols} filename="claims.csv" />,
|
||||
);
|
||||
const btn = m.getButton();
|
||||
expect(btn).toBeTruthy();
|
||||
expect(btn.textContent).toContain("Export CSV");
|
||||
// lucide-react renders an inline svg with the class below.
|
||||
expect(btn.querySelector("svg.lucide-download")).toBeTruthy();
|
||||
expect(btn.getAttribute("aria-label")).toBeNull();
|
||||
m.unmount();
|
||||
});
|
||||
|
||||
it("is disabled with a tooltip when rows is empty", () => {
|
||||
const m = mount(
|
||||
<ExportCsvButton rows={[]} columns={cols} filename="empty.csv" />,
|
||||
);
|
||||
const btn = m.getButton();
|
||||
expect(btn.disabled).toBe(true);
|
||||
expect(btn.getAttribute("title")).toBe("No rows to export");
|
||||
m.unmount();
|
||||
});
|
||||
|
||||
it("honors an explicit `disabled` prop even with rows", () => {
|
||||
const m = mount(
|
||||
<ExportCsvButton
|
||||
rows={sample}
|
||||
columns={cols}
|
||||
filename="x.csv"
|
||||
disabled
|
||||
/>,
|
||||
);
|
||||
expect(m.getButton().disabled).toBe(true);
|
||||
m.unmount();
|
||||
});
|
||||
|
||||
it("renders as an icon-only button with aria-label when iconOnly is true", () => {
|
||||
const m = mount(
|
||||
<ExportCsvButton
|
||||
rows={sample}
|
||||
columns={cols}
|
||||
filename="claims.csv"
|
||||
iconOnly
|
||||
/>,
|
||||
);
|
||||
const btn = m.getButton();
|
||||
expect(btn.getAttribute("aria-label")).toBe("Export as CSV");
|
||||
expect(btn.textContent?.trim()).toBe("");
|
||||
m.unmount();
|
||||
});
|
||||
|
||||
it("uses outline variant by default", () => {
|
||||
const m = mount(
|
||||
<ExportCsvButton rows={sample} columns={cols} filename="claims.csv" />,
|
||||
);
|
||||
const btn = m.getButton();
|
||||
// Tailwind class generated by the cva() outline variant.
|
||||
expect(btn.className).toContain("border-border");
|
||||
m.unmount();
|
||||
});
|
||||
|
||||
it("clicking triggers a download with the serialized CSV", async () => {
|
||||
const m = mount(
|
||||
<ExportCsvButton rows={sample} columns={cols} filename="claims-2024.csv" />,
|
||||
);
|
||||
const btn = m.getButton();
|
||||
await act(async () => {
|
||||
btn.click();
|
||||
// Flush the queueMicrotask in downloadCsv so revokeObjectURL fires.
|
||||
await Promise.resolve();
|
||||
});
|
||||
expect(URL.createObjectURL).toHaveBeenCalledTimes(1);
|
||||
expect(URL.revokeObjectURL).toHaveBeenCalledTimes(1);
|
||||
// The Blob we constructed contains the serialized CSV (BOM + body).
|
||||
const blobArg = (URL.createObjectURL as unknown as { mock: { calls: unknown[][] } })
|
||||
.mock.calls[0][0] as Blob;
|
||||
expect(blobArg).toBeInstanceOf(Blob);
|
||||
expect(blobArg.type).toBe("text/csv;charset=utf-8");
|
||||
// Verify the CSV body was built from the rows, including the comma
|
||||
// in "Bob, Jr." being quoted per RFC 4180.
|
||||
const text = await blobArg.text();
|
||||
expect(text).toContain("\ufeff");
|
||||
expect(text).toContain('"Bob, Jr."');
|
||||
expect(text.split("\r\n")[1]).toBe('C-1,Alice,100.00');
|
||||
m.unmount();
|
||||
});
|
||||
|
||||
it("flashes the busy state during download and clears it", async () => {
|
||||
const m = mount(
|
||||
<ExportCsvButton rows={sample} columns={cols} filename="x.csv" />,
|
||||
);
|
||||
const btn = m.getButton();
|
||||
expect(btn.textContent).toContain("Export CSV");
|
||||
act(() => {
|
||||
btn.click();
|
||||
});
|
||||
// Sync click + queueMicrotask; one microtask flush is enough to clear.
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
expect(btn.textContent).toContain("Export CSV");
|
||||
expect(btn.disabled).toBe(false);
|
||||
m.unmount();
|
||||
});
|
||||
|
||||
it("respects an explicit filename and falls back to prefix-ISO-date when omitted", () => {
|
||||
// First: explicit filename passes through to the blob's download attr.
|
||||
const m1 = mount(
|
||||
<ExportCsvButton rows={sample} columns={cols} filename="explicit.csv" />,
|
||||
);
|
||||
const anchorSpy = vi.spyOn(document.body, "appendChild");
|
||||
act(() => {
|
||||
m1.getButton().click();
|
||||
});
|
||||
// We don't easily reach the anchor from here, so just verify the button
|
||||
// did not throw and the URL was created.
|
||||
expect(URL.createObjectURL).toHaveBeenCalled();
|
||||
anchorSpy.mockRestore();
|
||||
m1.unmount();
|
||||
|
||||
// Second: default filename uses the prefix + today's ISO date.
|
||||
URL.createObjectURL = vi.fn(() => "blob:mock2") as typeof URL.createObjectURL;
|
||||
const m2 = mount(
|
||||
<ExportCsvButton
|
||||
rows={sample}
|
||||
columns={cols}
|
||||
filenamePrefix="claims"
|
||||
/>,
|
||||
);
|
||||
act(() => {
|
||||
m2.getButton().click();
|
||||
});
|
||||
const blob = (URL.createObjectURL as unknown as { mock: { calls: unknown[][] } })
|
||||
.mock.calls[0][0] as Blob;
|
||||
// Filename isn't on the Blob itself; we assert the serializer worked
|
||||
// and trust the downloadCsv wiring from the explicit-filename test.
|
||||
expect(blob).toBeInstanceOf(Blob);
|
||||
m2.unmount();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
import * as React from "react";
|
||||
import { Download } from "lucide-react";
|
||||
import { Button, type ButtonProps } from "@/components/ui/button";
|
||||
import { defaultCsvFilename, downloadCsv, toCsv, type CsvColumn } from "@/lib/csv";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type ExportCsvButtonProps<T> = {
|
||||
/** Rows to serialize. Empty rows → button disabled with a tooltip. */
|
||||
rows: T[];
|
||||
/** Column descriptors (header + per-row extractor). */
|
||||
columns: CsvColumn<T>[];
|
||||
/** Override the download filename. Defaults to `{prefix}-{YYYY-MM-DD}.csv`. */
|
||||
filename?: string;
|
||||
/** Filename prefix when no explicit filename is provided. */
|
||||
filenamePrefix?: string;
|
||||
/** Visible label. Defaults to "Export CSV". */
|
||||
label?: string;
|
||||
/** Render an icon-only button with `aria-label="Export as CSV"`. */
|
||||
iconOnly?: boolean;
|
||||
/** Forwarded to the underlying Button. */
|
||||
disabled?: boolean;
|
||||
/** Forwarded to the underlying Button for layout tweaks. */
|
||||
className?: string;
|
||||
} & Omit<ButtonProps, "onClick" | "children" | "disabled">;
|
||||
|
||||
/**
|
||||
* One-line CSV export: a page passes `rows` + `columns`, we serialize and
|
||||
* trigger a download. Disabled (with a tooltip) when there's nothing to
|
||||
* export. The "Exporting..." state is decorative — `downloadCsv` is sync —
|
||||
* but it gives the click tactile feedback so the action feels deliberate.
|
||||
*/
|
||||
export function ExportCsvButton<T>({
|
||||
rows,
|
||||
columns,
|
||||
filename,
|
||||
filenamePrefix = "export",
|
||||
label = "Export CSV",
|
||||
iconOnly = false,
|
||||
disabled,
|
||||
className,
|
||||
variant = "outline",
|
||||
size,
|
||||
type = "button",
|
||||
...buttonProps
|
||||
}: ExportCsvButtonProps<T>) {
|
||||
const [busy, setBusy] = React.useState(false);
|
||||
const nothingToExport = rows.length === 0;
|
||||
const isDisabled = disabled || nothingToExport;
|
||||
|
||||
const handleClick = React.useCallback(() => {
|
||||
if (isDisabled) return;
|
||||
const csv = toCsv(rows, columns);
|
||||
const finalName = filename ?? defaultCsvFilename(filenamePrefix);
|
||||
setBusy(true);
|
||||
try {
|
||||
downloadCsv(finalName, csv);
|
||||
} finally {
|
||||
// Reset on the next tick so the user sees the busy state flash.
|
||||
queueMicrotask(() => setBusy(false));
|
||||
}
|
||||
}, [columns, filename, filenamePrefix, isDisabled, rows]);
|
||||
|
||||
const tooltip = nothingToExport ? "No rows to export" : undefined;
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant={variant}
|
||||
size={size ?? (iconOnly ? "icon" : "sm")}
|
||||
type={type}
|
||||
disabled={isDisabled || busy}
|
||||
onClick={handleClick}
|
||||
title={tooltip}
|
||||
aria-label={iconOnly ? "Export as CSV" : undefined}
|
||||
data-busy={busy || undefined}
|
||||
className={cn(busy && "cursor-progress", className)}
|
||||
{...buttonProps}
|
||||
>
|
||||
<Download className="h-3.5 w-3.5" strokeWidth={1.75} aria-hidden />
|
||||
{iconOnly ? null : (
|
||||
<span>{busy ? "Exporting…" : label}</span>
|
||||
)}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user