From 9f81c955270dea1f789dd09cc5e07b8772a9810f Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Mon, 16 Nov 2026 11:19:28 +0100 Subject: [PATCH 1/2] JSE-7: javascript-excel/dom (fromTable, download) - fromTable: thead, then tbody and bare rows, then tfoot. colspan and rowspan are laid out on an occupancy grid and become merges, including rowspan=0. Hints are data-value, data-type (number, boolean, ISO date) and data-numfmt. Hidden and data-export-ignore rows and cells are skipped. In cells,
becomes a newline and turns on wrapping, and the first link becomes the hyperlink, resolved and checked against the scheme allowlist (HYPERLINK_DROPPED otherwise). Computed-style mapping is optional. There are header, freeze, autofilter and auto-width options, a cell hook and onWarning. - download: object URL plus a temporary . The URL is revoked after 40 s, or when the click throws. The MIME type comes from the data or the extension. No dependencies, no globals at import, and a structural DOM typing so the declarations need no DOM lib. - Tests: happy-dom for unit tests (separate tsconfig with the DOM lib, so src/ still compiles without it), a golden round trip through the writer and openpyxl, a plain-Node SSR test, and Vitest browser mode with Playwright Chromium (test:browser), run by a new, non-required Browser CI job. --- .changeset/dom-from-table-download.md | 11 + .github/workflows/ci.yml | 24 + docs/api.md | 52 +- package-lock.json | 320 ++++++++++++ packages/javascript-excel/README.md | 14 +- packages/javascript-excel/package.json | 8 +- .../javascript-excel/scripts/consumer.mjs | 19 +- packages/javascript-excel/src/auto-width.ts | 34 ++ packages/javascript-excel/src/dom.ts | 478 +++++++++++++++++- packages/javascript-excel/src/index.ts | 1 + .../src/internal/css-color.ts | 33 ++ .../src/internal/dom-types.ts | 45 ++ packages/javascript-excel/src/warnings.ts | 1 + .../test/browser/dom.browser.test.ts | 98 ++++ .../javascript-excel/test/dom-ssr.test.ts | 23 + .../test/dom/download.test.ts | 82 +++ .../test/dom/from-table.test.ts | 267 ++++++++++ .../javascript-excel/test/dom/golden.test.ts | 68 +++ .../javascript-excel/test/entries.test.ts | 8 +- packages/javascript-excel/tsconfig.dom.json | 11 + packages/javascript-excel/tsconfig.json | 11 +- .../javascript-excel/vitest.browser.config.ts | 23 + packages/javascript-excel/vitest.config.ts | 2 + 23 files changed, 1610 insertions(+), 23 deletions(-) create mode 100644 .changeset/dom-from-table-download.md create mode 100644 packages/javascript-excel/src/auto-width.ts create mode 100644 packages/javascript-excel/src/internal/css-color.ts create mode 100644 packages/javascript-excel/src/internal/dom-types.ts create mode 100644 packages/javascript-excel/test/browser/dom.browser.test.ts create mode 100644 packages/javascript-excel/test/dom-ssr.test.ts create mode 100644 packages/javascript-excel/test/dom/download.test.ts create mode 100644 packages/javascript-excel/test/dom/from-table.test.ts create mode 100644 packages/javascript-excel/test/dom/golden.test.ts create mode 100644 packages/javascript-excel/tsconfig.dom.json create mode 100644 packages/javascript-excel/vitest.browser.config.ts diff --git a/.changeset/dom-from-table-download.md b/.changeset/dom-from-table-download.md new file mode 100644 index 0000000..201b881 --- /dev/null +++ b/.changeset/dom-from-table-download.md @@ -0,0 +1,11 @@ +--- +"javascript-excel": minor +--- + +Add `javascript-excel/dom`: +- `fromTable(table, options)` turns an HTML `` into a sheet. It reads the rows of ``, then ``, then ``, and turns `colspan`/`rowspan` into merges (including `rowspan="0"`). It understands `data-type`, `data-value` and `data-numfmt` hints, and skips hidden and `data-export-ignore` rows and cells. +- In a cell, `
` becomes a newline with wrapping, and the first link becomes the cell's hyperlink, limited to `http`, `https` and `mailto` unless `hyperlinkSchemes` allows more. +- Optional computed-style mapping covers bold, italic, underline, strike, colour, background (including a row's background) and explicit alignment. There are also header, freeze, autofilter and auto-width options, a per-cell hook, and `onWarning` for data that cannot be coerced or for dropped links. +- `download(data, filename)` saves bytes, a Blob or a string through a temporary `` and an object URL, with no dependencies. The module never touches globals at import. + +Also adds the `HYPERLINK_DROPPED` warning code and the `AutoWidthOptions` type. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d08ba26..1ffbe51 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -67,6 +67,30 @@ jobs: JSE_REQUIRE_LIBREOFFICE: "1" run: npm -w packages/javascript-excel exec -- vitest run test/write/libreoffice.test.ts test/read/libreoffice.test.ts + # javascript-excel/dom in a real browser (test/browser, Vitest browser mode + + # Playwright Chromium). Not a required check. + browser: + name: Browser + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: 24 + cache: npm + - run: npm ci + - name: Playwright version + id: pw + run: echo "version=$(npm -w packages/javascript-excel exec -- playwright --version | awk '{print $2}')" >> "$GITHUB_OUTPUT" + - uses: actions/cache@v6 + with: + path: ~/.cache/ms-playwright + key: playwright-${{ runner.os }}-${{ steps.pw.outputs.version }}-chromium-headless-shell + - name: Install Chromium (headless shell) and its system libraries + run: npm -w packages/javascript-excel exec -- playwright install --with-deps --only-shell chromium + - name: Browser tests + run: npm -w packages/javascript-excel run test:browser + consumer-ts: name: Consumer TS runs-on: ubuntu-latest diff --git a/docs/api.md b/docs/api.md index 76ef5ec..1fec055 100644 --- a/docs/api.md +++ b/docs/api.md @@ -901,8 +901,13 @@ export interface CsvWriteOptions { ### 5.4 DOM (`javascript-excel/dom`) ```ts -export function fromTable(table: HTMLTableElement, options?: FromTableOptions): Sheet; -export function download(data: Uint8Array | Blob | string, filename: string, options?: { mimeType?: string }): void; +export function fromTable(table: TableElement, options?: FromTableOptions): Sheet; +export function download(data: Uint8Array | BlobType | string, filename: string, options?: DownloadOptions): void; +export const DOWNLOAD_REVOKE_DELAY_MS: number; // 40 000 + +/** HTMLTableElement / HTMLTableCellElement when the consumer has DOM types, else `object`. */ +export type TableElement = typeof globalThis extends { HTMLTableElement: { prototype: infer T } } ? T : object; +export type TableCellElement = typeof globalThis extends { HTMLTableCellElement: { prototype: infer T } } ? T : object; export interface FromTableOptions { name?: string; // sheet name, default 'Sheet1'; an invalid name throws (§12 Q19) @@ -918,22 +923,48 @@ export interface FromTableOptions { styles?: 'none' | 'computed'; /** Infer numbers/booleans from text (default false: text stays text unless a data-type hint says otherwise). */ inferTypes?: boolean; - /** becomes Cell.hyperlink (default true). Scheme allowlist as in WriteOptions. */ + /** The first in a cell becomes Cell.hyperlink (default true). */ links?: boolean; + /** Link schemes kept (default ['http', 'https', 'mailto']); others are dropped with HYPERLINK_DROPPED. */ + hyperlinkSchemes?: string[]; freezeHeader?: boolean; autoFilter?: boolean; autoWidth?: boolean | AutoWidthOptions; /** Per-cell hook: return a CellInput to override, or undefined to keep the default mapping. */ - cell?: (el: HTMLTableCellElement, ctx: { row: number; col: number; header: boolean }) => CellInput | undefined; + cell?: (el: TableCellElement, ctx: { row: number; col: number; header: boolean }) => CellInput | undefined; + /** Data problems that do not stop the conversion: COERCION_FAILED, HYPERLINK_DROPPED (§7.3). */ + onWarning?: (w: ExcelWarning) => void; +} + +export interface DownloadOptions { + /** Default: a Blob keeps its type; otherwise from the extension (.xlsx, .csv), else text/plain;charset=utf-8 for strings and application/octet-stream for bytes. */ + mimeType?: string; } ``` -- **Structure.** Rows come from ``, then each `` (and bare ``), then ``. `colspan`/`rowspan` are laid out on an occupancy grid and become `merges` (issue #28). Nested tables are read as text of their cell, not as rows. -- **Hints on `
`/``:** `data-type="string|number|boolean|date"`, `data-value="..."` (raw value instead of `textContent`), `data-numfmt="0.00"`. `data-export-ignore` on a row or cell skips it. -- **Text:** `textContent`, whitespace collapsed; `
` becomes a newline and turns on `wrapText`. -- **`styles: 'computed'`** maps `font-weight >= 600` to bold, `font-style: italic`, `text-decoration` underline and line-through, `color`, a non-transparent `background-color` (solid fill), `text-align`, `vertical-align` and `white-space`. Borders are not mapped in 2.0. -- **RTL:** `dir="rtl"` on the table (or computed `direction: rtl`) sets `view.rightToLeft`. -- **`download`** creates an object URL, clicks a temporary `` and revokes the URL after a delay `[placeholder, set in JSE-7]`. A string `data` is encoded as UTF-8 (`mimeType` default `text/plain;charset=utf-8`). Without a DOM it throws `ENVIRONMENT_UNSUPPORTED`. +- **No globals at import.** The module is safe to import during SSR. `fromTable` reads styles through the table's own window (`ownerDocument.defaultView`), so tables in iframes work. Calling either function without a DOM throws `ENVIRONMENT_UNSUPPORTED`. A non-`` element throws `TypeError`. +- **Structure.** Rows come from ``, then each `` (and bare ``), then ``, whatever their order in the markup. `colspan`/`rowspan` are laid out on an occupancy grid and become `merges` (issue #28). `rowspan="0"` spans to the end of its row group. Spans are clamped to HTML's limits (1000 / 65534) and to the table. Nested tables are read as text of their cell, not as rows. Skipped cells (hidden, ignored) are left out, so the cells after them move left. +- **Hints on `
`/``:** + - `data-value="..."` gives the raw value instead of the text. + - `data-type="string|number|boolean|date"` coerces it. `number` takes plain decimals and `1,234.5`-style grouping. `boolean` takes true/false, yes/no and 1/0. `date` takes ISO 8601: date-only and zone-less values are local wall-clock time, and `Z` or `±hh:mm` are honoured. A value that doesn't fit stays text with warning `COERCION_FAILED`. + - `data-numfmt="0.00"` sets the number format; all digits means a built-in id (`data-numfmt="14"`). + - `data-export-ignore` on a row or cell skips it. +- **Text:** child text, ignoring ` 
`); + const [a, b, c, d] = s.rows[0]!; + expect(a).toBe("a b"); + expect(b).toEqual({ value: "line 1\nline 2", style: { alignment: { wrapText: true } } }); + expect(c).toBe("x"); + expect(d).toBe(""); + }); + + it("data-value, data-type and data-numfmt hints", () => { + const s = read(` + + + + + + + + +
1.234,50 €1,234,567.89Yes2024-01-1515 Jan0.2562024-02-29007
`); + const r = s.rows[0]!; + expect(r.slice(0, 3)).toEqual([1234.5, 1234567.89, true]); + expect(r[3]).toEqual(new Date(2024, 0, 15)); + expect(r[4]).toEqual(new Date(Date.UTC(2024, 0, 15, 10, 30))); + expect(r[5]).toEqual({ value: 0.256, style: { numFmt: "0.00%" } }); + expect(r[6]).toEqual({ value: new Date(2024, 1, 29), style: { numFmt: 14 } }); + expect(r[7]).toBe("007"); + }); + + it("values that do not fit their data-type stay text, with COERCION_FAILED", () => { + const warnings: ExcelWarning[] = []; + const s = read(`
n/a2024-02-30maybe5
`, { + onWarning: (w) => warnings.push(w), + }); + expect(s.rows[0]).toEqual(["n/a", "2024-02-30", "maybe", "5"]); + expect(warnings.map((w) => [w.code, w.ref])).toEqual([["COERCION_FAILED", "A1"], ["COERCION_FAILED", "B1"], ["COERCION_FAILED", "C1"], ["COERCION_FAILED", "D1"]]); + }); + + it("inferTypes turns plain numbers and TRUE/FALSE into values, nothing else", () => { + const s = read(`
42-3.5e2true1,234007x2024-01-15
`, { inferTypes: true }); + expect(s.rows[0]).toEqual([42, -350, true, "1,234", "007x", "2024-01-15"]); + expect(read(`
42
`).rows[0]).toEqual(["42"]); + }); + + it("the cell hook overrides the default mapping", () => { + const s = read(`
h
xy
`, { + cell: (el, ctx) => ((el as HTMLElement).dataset["id"] ? { value: Number((el as HTMLElement).dataset["id"]), style: { font: { italic: true } } } : ctx.header ? "H!" : undefined), + }); + expect(s.rows).toEqual([["H!"], [{ value: 7, style: { font: { italic: true } } }, "y"]]); + }); +}); + +describe("fromTable: skipping", () => { + it("skips hidden and data-export-ignore rows and cells; cells shift left", () => { + const s = read(` + + + + + +
ab
gone too
ignored
xc
`); + expect(values(s.rows)).toEqual([["a", "b"], ["c"]]); + }); + + it("skipHidden: false keeps hidden rows; a custom ignore selector", () => { + const s = read(`
s
i
`, { skipHidden: false, ignore: ".skip" }); + expect(values(s.rows)).toEqual([["h"], ["i"]]); + }); + + it("with computed styles, CSS display:none also skips", () => { + const s = read(`
gone
kept
`, { styles: "computed" }, ".x { display: none }"); + expect(values(s.rows)).toEqual([["kept"]]); + }); +}); + +describe("fromTable: header, freeze, filter, widths, RTL", () => { + const html = `
Group
NameQty
Pens10
A much longer name2
`; + + it("thead rows get headerStyle (bold by default), and freeze/filter use them", () => { + const s = read(html, { freezeHeader: true, autoFilter: true }); + expect(s.rows[0]![0]).toEqual({ value: "Group", style: { font: { bold: true } } }); + expect(s.rows[1]![1]).toEqual({ value: "Qty", style: { font: { bold: true } } }); + expect(s.rows[2]![0]).toBe("Pens"); + expect(s.view).toEqual({ freeze: { rows: 2 } }); + expect(s.autoFilter).toBe("A2:B4"); + expect(s.merges).toEqual(["A1:B1"]); + }); + + it("header: a number of rows, or false; a custom headerStyle", () => { + const s = read(html, { header: 1, headerStyle: { fill: "DDEBF7" } }); + expect(s.rows[0]![0]).toEqual({ value: "Group", style: { fill: "DDEBF7" } }); + expect(s.rows[1]![0]).toBe("Name"); + const none = read(html, { header: false, freezeHeader: true, autoFilter: true }); + expect(none.rows[0]![0]).toBe("Group"); + expect(none.view).toBeUndefined(); + expect(none.autoFilter).toBeUndefined(); + }); + + it("autoWidth estimates widths from the text, within bounds", () => { + expect(read(html, { autoWidth: true }).colProps).toEqual([{ width: 20 }, { width: 8.43 }]); + expect(read(html, { autoWidth: { min: 3, max: 10 } }).colProps).toEqual([{ width: 10 }, { width: 5 }]); + }); + + it("dir=rtl on the table or an ancestor sets rightToLeft", () => { + expect(read(`
a
`).view).toEqual({ rightToLeft: true }); + document.body.innerHTML = `
a
`; + expect(fromTable(document.querySelector("table")!).view).toEqual({ rightToLeft: true }); + }); +}); + +describe("fromTable: links", () => { + it("the first
becomes the hyperlink, resolved to an absolute URL", () => { + const s = read(`
sitemailrelanchor
`); + const r = s.rows[0]! as Cell[]; + expect(r[0]).toEqual({ value: "site", hyperlink: "https://example.com/a" }); + expect(r[1]).toEqual({ value: "mail", hyperlink: "mailto:x@example.com" }); + expect(r[2]).toEqual({ value: "rel", hyperlink: `${location.origin}/rel?q=1` }); + expect(r[3]).toBe("anchor"); + }); + + it("drops links with other schemes, with HYPERLINK_DROPPED; links: false keeps text only", () => { + const warnings: ExcelWarning[] = []; + const s = read(`
xftp
`, { onWarning: (w) => warnings.push(w) }); + expect(s.rows[0]).toEqual(["x", "ftp"]); + expect(warnings.map((w) => w.code)).toEqual(["HYPERLINK_DROPPED", "HYPERLINK_DROPPED"]); + expect(read(`
ftp
`, { hyperlinkSchemes: ["ftp"] }).rows[0]).toEqual([{ value: "ftp", hyperlink: "ftp://f.example/x" }]); + expect(read(`
x
`, { links: false }).rows[0]).toEqual(["x"]); + }); +}); + +describe("fromTable: computed styles", () => { + const cssText = ` + .bold { font-weight: 700 } .heavy { font-weight: bolder } .it { font-style: italic } + .u { text-decoration: underline } .s { text-decoration: line-through } + .red { color: rgb(192, 0, 0) } tr.band { background-color: #ddebf7 } .clear { background-color: rgba(0, 0, 0, 0) } + .c { text-align: center } .r { text-align: right } .top { vertical-align: top } .mid { vertical-align: middle } + .pre { white-space: pre-wrap }`; + + it("maps weight, style, decoration, colour, background (from the row), alignment and white-space", () => { + const s = read( + `
abcde
plain
`, + { styles: "computed" }, + cssText, + ); + const r = s.rows[0]! as Cell[]; + expect(r[0]!.style).toEqual({ font: { bold: true, italic: true }, fill: "DDEBF7" }); + expect(r[1]!.style).toEqual({ font: { underline: true, color: "C00000" }, fill: "DDEBF7" }); + expect(r[2]!.style).toEqual({ font: { strike: true }, fill: "DDEBF7", alignment: { horizontal: "center", vertical: "top" } }); + // A transparent cell background shows the row's colour. + // vertical-align: middle is the HTML table default and is not mapped. + expect(r[3]!.style).toEqual({ fill: "DDEBF7", alignment: { horizontal: "right", wrapText: true } }); + expect(r[4]!.style).toEqual({ font: { bold: true }, fill: "DDEBF7" }); + expect(s.rows[1]).toEqual(["plain"]); + }); + + it("header style and computed style merge; computed wins field by field", () => { + const s = read(`
h
`, { styles: "computed", headerStyle: { font: { bold: true, size: 14 } } }, ".it { font-style: italic }"); + expect(s.rows[0]![0]).toEqual({ value: "h", style: { font: { bold: true, size: 14, italic: true } } }); + }); + + it("styles: 'none' (default) maps nothing", () => { + expect(read(`
a
`, {}, ".bold { font-weight: 700 }").rows[0]).toEqual(["a"]); + }); +}); + +describe("cssColor", () => { + it.each([ + ["rgb(255, 0, 0)", "FF0000"], + ["rgb(255 128 0)", "FF8000"], + ["rgba(0, 0, 255, 0.5)", "0000FF"], + ["rgb(0 0 255 / 50%)", "0000FF"], + ["rgba(0, 0, 0, 0)", undefined], + ["transparent", undefined], + ["#abc", "AABBCC"], + ["#AABBCC", "AABBCC"], + ["#aabbcc80", "AABBCC"], + ["#aabbcc00", undefined], + ["red", "FF0000"], + ["rebeccapurple", undefined], + ["", undefined], + ])("%j → %j", (input, expected) => { + expect(cssColor(input)).toBe(expected); + }); +}); diff --git a/packages/javascript-excel/test/dom/golden.test.ts b/packages/javascript-excel/test/dom/golden.test.ts new file mode 100644 index 0000000..765c0a4 --- /dev/null +++ b/packages/javascript-excel/test/dom/golden.test.ts @@ -0,0 +1,68 @@ +// @vitest-environment happy-dom +/// +// Golden round trip: HTML table → fromTable → toUint8Array → openpyxl. +import { execFileSync, spawnSync } from "node:child_process"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterAll, describe, expect, it } from "vitest"; +import { fromTable } from "../../src/dom"; +import { toUint8Array } from "../../src/index"; + +const PY = process.env["JSE_PYTHON"] ?? "python3"; +// (Under happy-dom, import.meta.url is not a file: URL; Vitest runs from the package directory.) +const script = join(process.cwd(), "test", "interop", "xlsx_dump.py"); +const hasOpenpyxl = spawnSync(PY, ["-I", "-c", "import openpyxl"], { stdio: "ignore" }).status === 0; +if (process.env["CI"] && !hasOpenpyxl) throw new Error(`CI must provide openpyxl (python: ${PY})`); +const dir = mkdtempSync(join(tmpdir(), "jse-dom-golden-")); +afterAll(() => rmSync(dir, { recursive: true, force: true })); + +describe.skipIf(!hasOpenpyxl)("fromTable → xlsx (openpyxl)", () => { + it("keeps values, merges, header style, hints, links, computed styles and RTL", { timeout: 60_000 }, async () => { + document.head.innerHTML = ``; + document.body.innerHTML = ` + + + + + + + + + + + +
ProductSales
Q1Q2
Pens1,200.50980
Pads
(new)
8602024-01-15
internal
Total4,040.50
`; + const sheet = fromTable(document.querySelector("table")!, { name: "Sales", styles: "computed", freezeHeader: true, autoFilter: true, autoWidth: true }); + const file = join(dir, "table.xlsx"); + writeFileSync(file, await toUint8Array({ sheets: [sheet] })); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const d = JSON.parse(execFileSync(PY, ["-I", script, file], { encoding: "utf8" })) as any; + const c = d.cells["Sales"]; + const info = d.sheetInfo["Sales"]; + + expect(info.merges).toEqual(["A1:A2", "B1:C1", "B5:C5"]); + expect(info.freeze).toBe("A3"); + expect(info.autoFilter).toBe("A2:C5"); + expect(info.view.rightToLeft).toBe(true); + expect(c["A1"].value).toBe("Product"); + expect(c["A1"].font.bold).toBe(true); // header style + expect(c["B2"].value).toBe("Q1"); + expect(c["A3"].value).toBe("Pens"); + expect(info.hyperlinks["A3"].target).toBe("https://example.com/pens"); + expect(c["B3"]).toMatchObject({ value: 1200.5, numFmt: "#,##0.00" }); + expect(c["B3"].alignment.horizontal).toBe("right"); + expect(c["A4"].value).toBe("Pads\n(new)"); + expect(c["A4"].alignment.wrapText).toBe(true); + expect(c["A4"].font).toMatchObject({ italic: true, color: { rgb: "FFC00000" } }); + expect(c["C4"]).toMatchObject({ value: { datetime: "2024-01-15T00:00:00" }, numFmt: "yyyy-mm-dd" }); + // Hidden and ignored rows are gone; the footer follows the body. + expect(c["A5"].value).toBe("Total"); + expect(c["A5"].font.bold).toBe(true); + expect(c["A5"].fill.fgColor).toEqual({ rgb: "FFDDEBF7" }); + expect(c["B5"].value).toBe(4040.5); + expect(Object.keys(info.cols)).toEqual(["A", "B", "C"]); + }); +}); diff --git a/packages/javascript-excel/test/entries.test.ts b/packages/javascript-excel/test/entries.test.ts index ce3fede..047fc20 100644 --- a/packages/javascript-excel/test/entries.test.ts +++ b/packages/javascript-excel/test/entries.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest"; import pkg from "../package.json" with { type: "json" }; import { VERSION } from "../src/index"; import * as csv from "../src/csv"; -import { ENTRY as DOM } from "../src/dom"; +import * as dom from "../src/dom"; import * as read from "../src/read"; import { ENTRY as WORKER } from "../src/worker"; @@ -12,13 +12,17 @@ describe("entries", () => { }); it("each placeholder subpath module names itself", () => { - expect([DOM, WORKER]).toEqual(["javascript-excel/dom", "javascript-excel/worker"]); + expect([WORKER]).toEqual(["javascript-excel/worker"]); }); it("/read exports the documented API", () => { expect(Object.keys(read).sort()).toEqual(["DEFAULT_READ_LIMITS", "detectFormat", "read", "readSheetNames"]); }); + it("/dom exports the documented API", () => { + expect(Object.keys(dom).sort()).toEqual(["DOWNLOAD_REVOKE_DELAY_MS", "download", "fromTable"]); + }); + it("/csv exports the documented API", () => { expect(Object.keys(csv).sort()).toEqual(["CSV_MIME", "parseCsv", "readCsv", "toCsv", "toCsvBlob"]); }); diff --git a/packages/javascript-excel/tsconfig.dom.json b/packages/javascript-excel/tsconfig.dom.json new file mode 100644 index 0000000..d5a092c --- /dev/null +++ b/packages/javascript-excel/tsconfig.dom.json @@ -0,0 +1,11 @@ +{ + // DOM and browser tests: the only files type-checked with the DOM lib, so + // src/ keeps compiling without DOM types (its declarations must not need them). + "extends": "./tsconfig.json", + "compilerOptions": { + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "types": [] + }, + "include": ["test/dom", "test/browser", "vitest.browser.config.ts"], + "exclude": [] +} diff --git a/packages/javascript-excel/tsconfig.json b/packages/javascript-excel/tsconfig.json index a2176a5..1fd42d4 100644 --- a/packages/javascript-excel/tsconfig.json +++ b/packages/javascript-excel/tsconfig.json @@ -4,5 +4,14 @@ "types": [], "resolveJsonModule": true }, - "include": ["src", "test", "tsdown.config.ts", "vitest.config.ts"] + "include": [ + "src", + "test", + "tsdown.config.ts", + "vitest.config.ts" + ], + "exclude": [ + "test/dom", + "test/browser" + ] } diff --git a/packages/javascript-excel/vitest.browser.config.ts b/packages/javascript-excel/vitest.browser.config.ts new file mode 100644 index 0000000..80a0f53 --- /dev/null +++ b/packages/javascript-excel/vitest.browser.config.ts @@ -0,0 +1,23 @@ +/// +// Real-browser tests (test/browser) with Vitest browser mode and Playwright Chromium. +// npm run test:browser +// JSE_CHROMIUM points Playwright at a local Chromium binary instead of its own download. +import { playwright } from "@vitest/browser-playwright"; +import { defineConfig, type ViteUserConfig } from "vitest/config"; + +const executablePath = process.env["JSE_CHROMIUM"]; + +const config: ViteUserConfig = defineConfig({ + test: { + include: ["test/browser/**/*.test.ts"], + browser: { + enabled: true, + headless: true, + provider: playwright(executablePath ? { launchOptions: { executablePath } } : {}), + instances: [{ browser: "chromium" }], + screenshotFailures: false, + }, + }, +}); + +export default config; diff --git a/packages/javascript-excel/vitest.config.ts b/packages/javascript-excel/vitest.config.ts index 34b00fb..bd90a40 100644 --- a/packages/javascript-excel/vitest.config.ts +++ b/packages/javascript-excel/vitest.config.ts @@ -3,6 +3,8 @@ import { defineConfig, type ViteUserConfig } from "vitest/config"; const config: ViteUserConfig = defineConfig({ test: { include: ["test/**/*.test.ts"], + // Real-browser tests run with vitest.browser.config.ts (npm run test:browser). + exclude: ["test/browser/**", "**/node_modules/**"], }, }); From 66895bc13111da7b4f2d873ff03132b6abb86da0 Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Mon, 16 Nov 2026 11:23:29 +0100 Subject: [PATCH 2/2] JSE-7: DOM golden test also reads the file back with the xlsx reader --- .../javascript-excel/test/dom/golden.test.ts | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/packages/javascript-excel/test/dom/golden.test.ts b/packages/javascript-excel/test/dom/golden.test.ts index 765c0a4..661c00d 100644 --- a/packages/javascript-excel/test/dom/golden.test.ts +++ b/packages/javascript-excel/test/dom/golden.test.ts @@ -7,7 +7,8 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterAll, describe, expect, it } from "vitest"; import { fromTable } from "../../src/dom"; -import { toUint8Array } from "../../src/index"; +import { toUint8Array, type Cell } from "../../src/index"; +import { read } from "../../src/read"; const PY = process.env["JSE_PYTHON"] ?? "python3"; // (Under happy-dom, import.meta.url is not a file: URL; Vitest runs from the package directory.) @@ -37,7 +38,8 @@ describe.skipIf(!hasOpenpyxl)("fromTable → xlsx (openpyxl)", () => {
`; const sheet = fromTable(document.querySelector("table")!, { name: "Sales", styles: "computed", freezeHeader: true, autoFilter: true, autoWidth: true }); const file = join(dir, "table.xlsx"); - writeFileSync(file, await toUint8Array({ sheets: [sheet] })); + const bytes = await toUint8Array({ sheets: [sheet] }); + writeFileSync(file, bytes); // eslint-disable-next-line @typescript-eslint/no-explicit-any const d = JSON.parse(execFileSync(PY, ["-I", script, file], { encoding: "utf8" })) as any; const c = d.cells["Sales"]; @@ -64,5 +66,18 @@ describe.skipIf(!hasOpenpyxl)("fromTable → xlsx (openpyxl)", () => { expect(c["A5"].fill.fgColor).toEqual({ rgb: "FFDDEBF7" }); expect(c["B5"].value).toBe(4040.5); expect(Object.keys(info.cols)).toEqual(["A", "B", "C"]); + + // And back through our own reader. + const { workbook, warnings } = await read(bytes); + expect(warnings).toEqual([]); + const back = workbook.sheets[0]!; + expect(back.merges).toEqual(["A1:A2", "B1:C1", "B5:C5"]); + expect(back.view).toMatchObject({ rightToLeft: true, freeze: { rows: 2 } }); + expect(back.autoFilter).toBe("A2:C5"); + const cell = (r: number, c: number): Cell => back.rows[r]![c] as Cell; + expect(cell(2, 0)).toMatchObject({ value: "Pens", hyperlink: { target: "https://example.com/pens" } }); // the reader normalises the shorthand + expect(cell(2, 1)).toMatchObject({ value: 1200.5, style: { numFmt: "#,##0.00" } }); + expect(cell(3, 0).value).toBe("Pads\n(new)"); + expect(cell(3, 2).value).toEqual(new Date(2024, 0, 15)); }); });