merge: ui/csv-export

This commit is contained in:
Tyler
2026-06-20 17:29:00 -06:00
4 changed files with 503 additions and 0 deletions
+108
View File
@@ -0,0 +1,108 @@
import { describe, expect, it } from "vitest";
import { defaultCsvFilename, toCsv } from "./csv";
describe("toCsv", () => {
it("emits a header row with column labels", () => {
const out = toCsv<{ id: string }>([], [
{ header: "Claim ID", value: (r) => r.id },
]);
expect(out).toBe("Claim ID\r\n");
});
it("serializes primitive cell values verbatim", () => {
const out = toCsv(
[{ a: "hello", b: 42, c: 3.14 }],
[
{ header: "A", value: (r) => r.a },
{ header: "B", value: (r) => r.b },
{ header: "C", value: (r) => r.c },
],
);
// 42 and 3.14 both serialize without quotes, no locale formatting.
expect(out).toBe("A,B,C\r\nhello,42,3.14\r\n");
});
it("quotes fields containing commas", () => {
const out = toCsv([{ name: "Smith, John" }], [
{ header: "Name", value: (r) => r.name },
]);
expect(out).toBe('Name\r\n"Smith, John"\r\n');
});
it("escapes embedded quotes by doubling them", () => {
const out = toCsv([{ note: 'she said "hi"' }], [
{ header: "Note", value: (r) => r.note },
]);
expect(out).toBe('Note\r\n"she said ""hi"""\r\n');
});
it("quotes fields containing newlines", () => {
const out = toCsv([{ note: "line1\nline2" }], [
{ header: "Note", value: (r) => r.note },
]);
expect(out).toBe('Note\r\n"line1\nline2"\r\n');
});
it("quotes fields containing carriage returns", () => {
const out = toCsv([{ note: "line1\rline2" }], [
{ header: "Note", value: (r) => r.note },
]);
expect(out).toBe('Note\r\n"line1\rline2"\r\n');
});
it("renders null and undefined as empty cells", () => {
const out = toCsv(
[{ a: null, b: undefined, c: "kept" }],
[
{ header: "A", value: (r) => r.a },
{ header: "B", value: (r) => r.b },
{ header: "C", value: (r) => r.c },
],
);
expect(out).toBe("A,B,C\r\n,,kept\r\n");
});
it("renders an empty-string cell as a bare empty field", () => {
const out = toCsv([{ a: "" }], [{ header: "A", value: (r) => r.a }]);
expect(out).toBe("A\r\n\r\n");
});
it("serializes multiple rows separated by CRLF", () => {
const out = toCsv(
[{ id: 1 }, { id: 2 }, { id: 3 }],
[{ header: "id", value: (r) => r.id }],
);
expect(out).toBe("id\r\n1\r\n2\r\n3\r\n");
});
it("quotes a header that itself contains a comma", () => {
const out = toCsv([], [{ header: "Last, First", value: () => "" }]);
expect(out).toBe('"Last, First"\r\n');
});
it("forces a string around non-string inputs (booleans, dates)", () => {
const out = toCsv(
[{ on: true as const, at: new Date("2024-01-02T03:04:05.000Z") }],
[
{ header: "On", value: (r) => String(r.on) },
{ header: "At", value: (r) => r.at.toISOString() },
],
);
expect(out).toBe("On,At\r\ntrue,2024-01-02T03:04:05.000Z\r\n");
});
it("returns only the header when rows is empty (no trailing body CRLF doubled)", () => {
const out = toCsv<{ id: string }>([], [
{ header: "ID", value: (r) => r.id },
{ header: "Name", value: () => "x" },
]);
expect(out).toBe("ID,Name\r\n");
});
});
describe("defaultCsvFilename", () => {
it("formats a prefix + ISO date suffix as .csv", () => {
const fixed = new Date("2024-03-05T22:00:00.000Z");
expect(defaultCsvFilename("claims", fixed)).toBe("claims-2024-03-05.csv");
});
});
+98
View File
@@ -0,0 +1,98 @@
/**
* Minimal RFC 4180 CSV serialization + browser-side download helper.
*
* The serializer handles the four awkward cases that show up in real data:
* - commas inside a field (quote it)
* - quotes inside a field (double them, then quote it)
* - newlines inside a field (quote it)
* - null / undefined / empty values (render as empty cell)
*
* Anything that isn't a primitive is coerced via String(); numeric inputs are
* emitted verbatim (no locale formatting — the caller is responsible for
* `toFixed(2)` and friends).
*
* `downloadCsv` is intentionally synchronous: the browser serializes the blob
* in the same tick and we revoke the object URL on the next microtask so the
* download dialog still gets a live URL. No setTimeout needed.
*/
export type CsvColumn<T> = {
/** Display label written to the header row. */
header: string;
/** Cell extractor. Return primitives only. */
value: (row: T) => string | number | null | undefined;
};
const NEEDS_QUOTING = /[",\r\n]/;
function escapeField(raw: string | number | null | undefined): string {
if (raw === null || raw === undefined) return "";
const s = typeof raw === "string" ? raw : String(raw);
if (NEEDS_QUOTING.test(s)) {
return `"${s.replace(/"/g, '""')}"`;
}
return s;
}
/**
* Serialize an array of rows to an RFC 4180 CSV string.
*
* Lines are joined with `\r\n` per the spec. The output ends with a trailing
* CRLF so the last row is terminated identically to the rest — Excel and
* Numbers both prefer this for auto-detecting row count.
*/
export function toCsv<T>(
rows: T[],
columns: CsvColumn<T>[],
): string {
const header = columns.map((c) => escapeField(c.header)).join(",");
if (rows.length === 0) {
// No body rows: emit header + CRLF only. The two CRLFs that would
// appear from "empty body + terminator" are dropped — a trailing blank
// line confuses Excel's row-count heuristics.
return `${header}\r\n`;
}
const body = rows
.map((row) => columns.map((c) => escapeField(c.value(row))).join(","))
.join("\r\n");
// RFC 4180: every record (including the header) is CRLF-terminated.
// A row that serializes to "" still produces a CRLF in body plus the
// terminator CRLF, yielding two CRLFs after the header.
return `${header}\r\n${body}\r\n`;
}
/**
* Default filename for a CSV download: `{prefix}-{YYYY-MM-DD}.csv` using the
* local date. We slice an ISO string instead of constructing the date with
* `getFullYear` etc. because the ISO format matches the rest of the codebase.
*/
export function defaultCsvFilename(prefix: string, now: Date = new Date()): string {
const isoDay = now.toISOString().slice(0, 10);
return `${prefix}-${isoDay}.csv`;
}
/**
* Trigger a browser download of `csvText` as a file. Creates an in-memory
* Blob, attaches it to a hidden `<a download>`, clicks the link, then revokes
* the object URL on the next tick so the download still has a live handle.
*
* Safe to call from SSR/Node — guards against a missing `document`.
*/
export function downloadCsv(filename: string, csvText: string): void {
if (typeof document === "undefined" || typeof URL === "undefined") return;
// Prepend BOM so Excel auto-detects UTF-8 on Windows. Tools that already
// understand UTF-8 (Numbers, Google Sheets, every CSV parser in this repo)
// ignore the leading bytes silently.
const blob = new Blob(["\ufeff", csvText], { type: "text/csv;charset=utf-8" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
// Some browsers require the link to be in the DOM before .click() works.
a.style.display = "none";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
// Defer revoke so the browser has the URL handle when the download kicks off.
queueMicrotask(() => URL.revokeObjectURL(url));
}