From d1297fb0b00ee5fddbc86516768dc9319a7b918f Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Mon, 16 Nov 2026 15:15:33 +0100 Subject: [PATCH] feat: react-data-export/legacy, the 0.x components on 1.0 (deprecated) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A separate entry with , , , the 0.x default export (ReactExport.ExcelFile.ExcelSheet ...), the dataSet shape with xSteps/ySteps and xlsx-style styles. It is a thin layer: sheets come from javascript-excel's fromDataset/fromDatasets, and writing and downloading go through the 1.0 path (startExport, writeAndSave, the shared runner), so StrictMode, abort and CSV behave as in 1.0. Output reproduces 0.6.0: plain headers, bold dataSet headers replaced by a column style, { wpx: 80 } widths applied from column A (last block wins), xSteps/ySteps placement, UTC dates with format 14, 0.6's empty-value rules, "Download" and an always-appended extension, and the trigger wrapper. Golden tests compare each scenario cell by cell with what the real react-data-export@0.6.0 built (scripts/legacy-goldens.mjs). Fixed on purpose: one download under StrictMode, real CSV for 'csv', xlsx with an .xlsx name and a warning for xls/txt/html, string dataSet headers keep their text (a 0.6.0 regression), falsy children skipped, invalid sheet names sanitized. Deprecated: one development warning pointing to docs/migration.md; supported for all of 1.x, removed in 2.0. convertLegacyStyle moves from the migration example into the entry. The smoke test checks that the main entry and its chunks contain no legacy code; attw now checks the node16 profile (node10 can't resolve subpath exports). Docs: README and migration.md §1.1 "Quick path", api.md §2. Minor changeset. --- .changeset/legacy-entry.md | 19 + README.md | 2 + docs/api.md | 1 + docs/migration.md | 173 +++---- examples/migration/legacy-quick-path.tsx | 22 + examples/migration/legacy-style.ts | 112 +---- examples/migration/tsconfig.json | 16 +- packages/react-data-export/README.md | 2 + packages/react-data-export/package.json | 12 +- packages/react-data-export/src/legacy.ts | 26 + .../react-data-export/src/legacy/build.ts | 125 +++++ .../src/legacy/components.ts | 164 ++++++ .../react-data-export/src/legacy/style.ts | 108 ++++ .../test/legacy/components.test.tsx | 246 +++++++++ .../test/legacy/goldens-0.6.json | 475 ++++++++++++++++++ .../test/legacy/goldens.test.ts | 130 +++++ .../test/legacy/scenarios.d.mts | 7 + .../test/legacy/scenarios.mjs | 118 +++++ packages/react-data-export/tsdown.config.ts | 6 +- scripts/consumer-ts.mjs | 23 + scripts/legacy-goldens.mjs | 57 +++ scripts/smoke.mjs | 39 +- 22 files changed, 1663 insertions(+), 220 deletions(-) create mode 100644 .changeset/legacy-entry.md create mode 100644 examples/migration/legacy-quick-path.tsx create mode 100644 packages/react-data-export/src/legacy.ts create mode 100644 packages/react-data-export/src/legacy/build.ts create mode 100644 packages/react-data-export/src/legacy/components.ts create mode 100644 packages/react-data-export/src/legacy/style.ts create mode 100644 packages/react-data-export/test/legacy/components.test.tsx create mode 100644 packages/react-data-export/test/legacy/goldens-0.6.json create mode 100644 packages/react-data-export/test/legacy/goldens.test.ts create mode 100644 packages/react-data-export/test/legacy/scenarios.d.mts create mode 100644 packages/react-data-export/test/legacy/scenarios.mjs create mode 100644 scripts/legacy-goldens.mjs diff --git a/.changeset/legacy-entry.md b/.changeset/legacy-entry.md new file mode 100644 index 0000000..b359ebd --- /dev/null +++ b/.changeset/legacy-entry.md @@ -0,0 +1,19 @@ +--- +"react-data-export": minor +--- + +Add `react-data-export/legacy`, a deprecated quick path for 0.x code: ``, ``, ``, the 0.x default export (`import ReactExport from 'react-data-export/legacy'`), the `dataSet` shape with `xSteps`/`ySteps`, and xlsx-style cell styles, built on 1.0's export code and javascript-excel. The files it writes match 0.6.0's (checked against the real 0.6.0): +- plain `` headers and bold `dataSet` headers +- 80 px default widths +- UTC dates +- the `Download` default name with the extension always appended +- the `` trigger wrapper + +0.6's bugs stay fixed: +- one download under StrictMode +- `fileExtension: 'csv'` writes real CSV +- `xls`/`txt`/`html` write `.xlsx` with a warning +- string `dataSet` columns keep their header text +- falsy children are skipped + +`convertLegacyStyle` converts 0.x styles to the 1.0 style model. The entry is supported for all of 1.x and removed in 2.0, and it logs one deprecation warning in development. It's a separate entry, so the main entry's bundle doesn't include it. diff --git a/README.md b/README.md index dd064fe..9d7f9f9 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,8 @@ Export data from React to `.xlsx` and `.csv`. ## Migrating from 0.x +**Quick path: `react-data-export/legacy`.** To run 0.x code on 1.0 without rewriting it yet, change the import to `import ReactExport from 'react-data-export/legacy'`. That entry has ``, ``, ``, the `dataSet` shape and xlsx-style styles. It writes the same files as 0.6.0, without 0.6's bugs: one download under StrictMode, and real CSV. It's **deprecated**: supported for all of 1.x, removed in 2.0, with one development warning. See the guide's [quick path](docs/migration.md#11-quick-path-react-data-exportlegacy). + The [migration guide](docs/migration.md) shows every 0.x pattern next to its 1.0 code: `ExcelFile` + `ExcelSheet` + `ExcelColumn`, `dataSet` with `xSteps`/`ySteps`, `hideElement`, `element`, `fileExtension`, and the xlsx-style cell styles (with a converter). It also lists every intentional behaviour difference. The most common change: ```jsx diff --git a/docs/api.md b/docs/api.md index 0dfb0bd..5e7621a 100644 --- a/docs/api.md +++ b/docs/api.md @@ -46,6 +46,7 @@ One entry, `react-data-export`, ESM + CJS + `.d.ts`, `sideEffects: false`. It ex | `exportTable`, `useTableExport`, `ExportTableButton` | function, hook, component | §13 | | `isExcelError`, `sanitizeSheetName` | re-exports from `javascript-excel` | §7, §4.2 | | `version` | `string` | | +| **`react-data-export/legacy`** (a separate entry): `ExcelFile`, `ExcelSheet`, `ExcelColumn`, the 0.x default export, `convertLegacyStyle` | **deprecated** 0.x components on this API; removed in 2.0 | [migration.md §1.1](migration.md#11-quick-path-react-data-exportlegacy) | | types: `Dataset`, `ColumnDef`, `LeafColumn`, `GroupColumn`, `DatasetOptions`, `Style`, `CellInput`, `CsvWriteOptions`, `WriteOptions`, `Progress`, `ExcelWarning` | type re-exports from `javascript-excel` (and `javascript-excel/csv`) | §3 | | types: `ExportOptions`, `ExportFormat`, `ExportResult`, `WorkbookSpec`, `SheetSpec`, `ExportStatus`, `UseExcelExport`, `ExcelExportProps` | react-data-export's own | §4–§6 | | types: `FromTableOptions`, `TableElement`, `TableCellElement` | type re-exports from `javascript-excel/dom` | §13 | diff --git a/docs/migration.md b/docs/migration.md index 8f7bd78..b333a79 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -1,6 +1,6 @@ # Migrating from 0.6 to 1.0 -react-data-export 1.0 is a rewrite on [javascript-excel](https://github.com/securedeveloper/javascript-excel) 2.0, and a clean break: the 0.x components ``, `` and `` are gone. This guide shows every 0.x pattern next to its 1.0 code, then lists the behaviour that changed on purpose. +react-data-export 1.0 is a rewrite on [javascript-excel](https://github.com/securedeveloper/javascript-excel) 2.0, and a clean break: the 0.x components ``, `` and `` are not in the 1.0 API. This guide shows every 0.x pattern next to its 1.0 code, then lists the behaviour that changed on purpose. If you need 0.x code to run on 1.0 first, there is a [quick path](#11-quick-path-react-data-exportlegacy): a deprecated `react-data-export/legacy` entry with the old components. **You don't have to move now.** 0.6.x stays on npm unchanged: `npm install react-data-export@0.6` keeps working, and nothing is unpublished or deprecated. Its docs are at the [`v0.6.0` tag](https://github.com/securedeveloper/react-data-export/tree/v0.6.0). @@ -9,6 +9,7 @@ Every 1.0 snippet below is a file in [`examples/migration/`](../examples/migrati ## Contents 1. [Install and imports](#1-install-and-imports) + - [1.1 Quick path: `react-data-export/legacy`](#11-quick-path-react-data-exportlegacy) 2. [Quick reference](#2-quick-reference) 3. [Side by side](#3-side-by-side) - [3.1 `ExcelFile` + `ExcelSheet` + `ExcelColumn`](#31-excelfile--excelsheet--excelcolumn) @@ -26,7 +27,7 @@ Every 1.0 snippet below is a file in [`examples/migration/`](../examples/migrati ```sh npm uninstall file-saver tempa-xlsx # only if you added them for 0.x -npm install react-data-export@next # 1.0 prereleases go to the `next` tag; none is out yet +npm install react-data-export@next # 1.0 prereleases are on the `next` tag ``` - **No peer libraries, no bundler setup.** 0.x needed `file-saver` and `tempa-xlsx`, and webpack settings for them (`node: { fs: 'empty' }`, `externals` for `./cptable` and `./jszip`). Delete those. 1.0's only dependency is javascript-excel, which has no dependencies of its own. @@ -39,6 +40,54 @@ npm install react-data-export@next # 1.0 prereleases go to the `next` tag; n - **Types ship with the package**, generated from the source, so they match the code. The hand-written 0.x `types/index.d.ts` is gone. - React 17, 18 and 19 are supported. Importing the package is safe during server rendering, and the entry is marked `"use client"`. +### 1.1 Quick path: `react-data-export/legacy` + +To get 0.x code running on 1.0 before you rewrite it, change the import to `react-data-export/legacy`. That's a separate, **deprecated** entry with ``, ``, ``, the 0.x default export and the `dataSet` shape with xlsx-style styles, built on 1.0's export code and javascript-excel. It is supported for all of 1.x and removed in 2.0. In development it logs one warning that points here. + + +```tsx +// 0.x code on 1.0 with one import change. Deprecated: supported for all of 1.x, removed in 2.0. +import ReactExport from 'react-data-export/legacy'; + +const ExcelFile = ReactExport.ExcelFile; +const ExcelSheet = ReactExport.ExcelFile.ExcelSheet; +const ExcelColumn = ReactExport.ExcelFile.ExcelColumn; + +interface Employee { + name: string; + is_married: boolean; +} + +export function Download({ employees }: { employees: Employee[] }) { + return ( + Download}> + + + (col.is_married ? 'Married' : 'Single')} /> + + + ); +} +``` + +The files it writes match 0.6.0's output. The tests compare it, cell by cell, with what the real 0.6.0 built. That covers: +- plain `` headers and bold `dataSet` headers (a column's `style` replaces the bold) +- `{ wpx: 80 }` for `dataSet` object columns without a width, applied from column A with the last block's widths, as 0.6 did +- `xSteps`/`ySteps` placement +- dates converted as UTC with the short-date format +- empty values (`undefined` and `NaN` → an empty text cell, `null` → no cell) +- the default file name `Download`, with the extension always appended (`report.xlsx` → `report.xlsx.xlsx`) +- `` around `element`, and the default `` + +What it does **not** reproduce, on purpose: +- **One download under StrictMode:** `hideElement` downloads after mount, not in the constructor. +- **`fileExtension: 'csv'`** writes real CSV (UTF-8 BOM, CRLF, formula-injection guard). With several sheets, it writes the first one and warns. +- **`'xls'`, `'txt'` and `'html'`** write an xlsx file with an `.xlsx` name and a development warning. 0.x wrote xlsx bytes under the other extension. +- **String `dataSet` columns** (`columns: ['Name', 'Dept']`) keep their header text. 0.6.0 left those headers empty, a regression in its last release. +- **Conditional children:** falsy `` and `` children are skipped, and an invalid sheet name is sanitized with a warning instead of producing a broken file. + +`convertLegacyStyle` ([3.7](#37-cell-styles)) is exported from the same entry. The legacy code is a separate entry, so it isn't in your bundle unless you import it. + ## 2. Quick reference | 0.x | 1.0 | section | @@ -488,116 +537,22 @@ export async function asTabSeparatedTxt(): Promise { Invalid styles now fail loudly, with some exceptions. A 0.x fill (`patternType` but no `pattern`), a string theme index, `auto: 1`, a boolean `vertAlign` or `horizontal: 'bottom'` throws `INVALID_STYLE`, naming the cell. But keys that 1.0 doesn't know, such as `font.sz` and `alignment.textRotation`, are ignored without an error. Convert them; don't rely on an error to find them. -If your app has many 0.x style objects, convert them in one place. This helper is type-checked with the rest of the examples. Copy it into your project: +If your app has many 0.x style objects, convert them in one place with `convertLegacyStyle` from `react-data-export/legacy`. It's the same entry as the [quick path](#11-quick-path-react-data-exportlegacy), and only this function ends up in your bundle: ```ts import type { Style } from 'react-data-export'; +import { convertLegacyStyle, type LegacyStyle } from 'react-data-export/legacy'; -/** A 0.x (xlsx-style) style object, as documented in the 0.6 README. */ -export interface LegacyColor { - auto?: number; - rgb?: string; - theme?: string | number; - tint?: string | number; - indexed?: number; -} -export interface LegacyBorderSide { - style: string; - color?: LegacyColor; -} -export interface LegacyStyle { - fill?: { patternType?: string; fgColor?: LegacyColor; bgColor?: LegacyColor }; - font?: { - name?: string; - sz?: string | number; - color?: LegacyColor; - bold?: boolean; - underline?: boolean; - italic?: boolean; - strike?: boolean; - outline?: boolean; - shadow?: boolean; - }; - numFmt?: string; - alignment?: { vertical?: string; horizontal?: string; wrapText?: boolean; readingOrder?: number; textRotation?: number }; - border?: { top?: LegacyBorderSide; bottom?: LegacyBorderSide; left?: LegacyBorderSide; right?: LegacyBorderSide; diagonal?: LegacyBorderSide; diagonalUp?: boolean; diagonalDown?: boolean }; -} - -type Font = NonNullable; -type Color = NonNullable; -type Alignment = NonNullable; -type Border = NonNullable; -type BorderSide = NonNullable; - -function color(c: LegacyColor | undefined): Color | undefined { - if (!c) return undefined; - if (c.rgb !== undefined) return { rgb: c.rgb }; - if (c.theme !== undefined) return { theme: Number(c.theme), ...(c.tint !== undefined ? { tint: Number(c.tint) } : {}) }; - if (c.indexed !== undefined) return { indexed: c.indexed }; - if (c.auto) return { auto: true }; - return undefined; -} - -// 0.x: 0–90 up, 91–180 down (135 = 45° down), 255 = stacked. 1.0: -90..90, or 'vertical'. -function rotation(r: number | undefined): Alignment['rotation'] { - if (r === undefined) return undefined; - if (r === 255) return 'vertical'; - return r > 90 ? 90 - r : r; -} - -const HORIZONTAL = ['general', 'left', 'center', 'right', 'fill', 'justify', 'centerContinuous', 'distributed'] as const; -const VERTICAL = ['top', 'center', 'bottom', 'justify', 'distributed'] as const; -const pick = (allowed: readonly T[], v: string | undefined): T | undefined => - allowed.find((a) => a === v); - -function side(s: LegacyBorderSide | undefined): BorderSide | undefined { - if (!s) return undefined; - const c = color(s.color); - return { style: s.style as BorderSide['style'], ...(c ? { color: c } : {}) }; -} +// A 0.x (xlsx-style) style object, as documented in the 0.6 README. +const header: LegacyStyle = { + font: { sz: '14', bold: true, color: { rgb: 'FFFF0000' } }, + fill: { patternType: 'solid', fgColor: { rgb: 'FFFFFF00' } }, + alignment: { horizontal: 'center', textRotation: 135 }, +}; -/** Converts a 0.x cell style to a react-data-export 1.0 (javascript-excel) style. */ -export function convertLegacyStyle(old: LegacyStyle): Style { - const style: Style = {}; - if (old.font) { - const { sz, color: c, name, bold, italic, underline, strike, outline, shadow } = old.font; - const font: Font = { name, bold, italic, underline, strike, outline, shadow }; - if (sz !== undefined) font.size = Number(sz); - if (c) font.color = color(c); - style.font = font; - } - // A fill with a colour becomes a solid fill; 'none' or no colour means no fill. - if (old.fill && old.fill.patternType !== 'none' && old.fill.fgColor) { - const fg = color(old.fill.fgColor); - const bg = color(old.fill.bgColor); - style.fill = { pattern: 'solid', ...(fg ? { fgColor: fg } : {}), ...(bg ? { bgColor: bg } : {}) }; - } - if (old.numFmt !== undefined) style.numFmt = old.numFmt; - if (old.alignment) { - const a = old.alignment; - style.alignment = { - horizontal: pick(HORIZONTAL, a.horizontal), - vertical: pick(VERTICAL, a.vertical), - wrapText: a.wrapText, - rotation: rotation(a.textRotation), - readingOrder: a.readingOrder === 2 ? 'rtl' : a.readingOrder === 1 ? 'ltr' : undefined, - }; - } - if (old.border) { - const b = old.border; - style.border = { - top: side(b.top), - bottom: side(b.bottom), - left: side(b.left), - right: side(b.right), - diagonal: side(b.diagonal), - diagonalUp: b.diagonalUp, - diagonalDown: b.diagonalDown, - }; - } - return style; -} +// { font: { size: 14, bold: true, color: { rgb: 'FFFF0000' } }, fill: { pattern: 'solid', … }, alignment: { horizontal: 'center', rotation: -45 } } +export const headerStyle: Style = convertLegacyStyle(header); ``` ```ts @@ -716,9 +671,9 @@ export async function exportLike0x(rows: Row[]): Promise { ## 5. Not carried over - **`.xls`, `.html` and `.txt` output**, and `fileExtension` itself. See the table in [3.6](#36-fileextension-and-filename). -- **`element` cloning.** Injecting `onClick` into an arbitrary element breaks with components that don't forward it, and with fragments. The render prop replaces it ([api.md §12 Q5](api.md#12-design-decisions)). -- **A `hideElement` prop.** It is a three-line effect instead ([3.4](#34-hideelement)). +- **`element` cloning** (kept only in [`react-data-export/legacy`](#11-quick-path-react-data-exportlegacy), as 0.6's `` wrapper). Injecting `onClick` into an arbitrary element breaks with components that don't forward it, and with fragments. The render prop replaces it ([api.md §12 Q5](api.md#12-design-decisions)). +- **A `hideElement` prop** in the 1.0 API. It is a three-line effect instead ([3.4](#34-hideelement)); `react-data-export/legacy` keeps the prop. - **`data` as a function** on a sheet. Pass the rows, or build them in your own handler. -- **The default export and `ExcelFile.ExcelSheet` / `ExcelFile.ExcelColumn`**, and PropTypes. 1.0 has named exports and TypeScript types. +- **The default export and `ExcelFile.ExcelSheet` / `ExcelFile.ExcelColumn`** in the 1.0 API, and PropTypes. 1.0 has named exports and TypeScript types; `react-data-export/legacy` keeps the 0.x default export (deprecated). Found a 0.x pattern this guide doesn't cover? Please open an issue with the snippet. diff --git a/examples/migration/legacy-quick-path.tsx b/examples/migration/legacy-quick-path.tsx new file mode 100644 index 0000000..1b004b4 --- /dev/null +++ b/examples/migration/legacy-quick-path.tsx @@ -0,0 +1,22 @@ +// 0.x code on 1.0 with one import change. Deprecated: supported for all of 1.x, removed in 2.0. +import ReactExport from 'react-data-export/legacy'; + +const ExcelFile = ReactExport.ExcelFile; +const ExcelSheet = ReactExport.ExcelFile.ExcelSheet; +const ExcelColumn = ReactExport.ExcelFile.ExcelColumn; + +interface Employee { + name: string; + is_married: boolean; +} + +export function Download({ employees }: { employees: Employee[] }) { + return ( + Download}> + + + (col.is_married ? 'Married' : 'Single')} /> + + + ); +} diff --git a/examples/migration/legacy-style.ts b/examples/migration/legacy-style.ts index b97988f..728ce99 100644 --- a/examples/migration/legacy-style.ts +++ b/examples/migration/legacy-style.ts @@ -1,106 +1,12 @@ import type { Style } from 'react-data-export'; +import { convertLegacyStyle, type LegacyStyle } from 'react-data-export/legacy'; -/** A 0.x (xlsx-style) style object, as documented in the 0.6 README. */ -export interface LegacyColor { - auto?: number; - rgb?: string; - theme?: string | number; - tint?: string | number; - indexed?: number; -} -export interface LegacyBorderSide { - style: string; - color?: LegacyColor; -} -export interface LegacyStyle { - fill?: { patternType?: string; fgColor?: LegacyColor; bgColor?: LegacyColor }; - font?: { - name?: string; - sz?: string | number; - color?: LegacyColor; - bold?: boolean; - underline?: boolean; - italic?: boolean; - strike?: boolean; - outline?: boolean; - shadow?: boolean; - }; - numFmt?: string; - alignment?: { vertical?: string; horizontal?: string; wrapText?: boolean; readingOrder?: number; textRotation?: number }; - border?: { top?: LegacyBorderSide; bottom?: LegacyBorderSide; left?: LegacyBorderSide; right?: LegacyBorderSide; diagonal?: LegacyBorderSide; diagonalUp?: boolean; diagonalDown?: boolean }; -} +// A 0.x (xlsx-style) style object, as documented in the 0.6 README. +const header: LegacyStyle = { + font: { sz: '14', bold: true, color: { rgb: 'FFFF0000' } }, + fill: { patternType: 'solid', fgColor: { rgb: 'FFFFFF00' } }, + alignment: { horizontal: 'center', textRotation: 135 }, +}; -type Font = NonNullable; -type Color = NonNullable; -type Alignment = NonNullable; -type Border = NonNullable; -type BorderSide = NonNullable; - -function color(c: LegacyColor | undefined): Color | undefined { - if (!c) return undefined; - if (c.rgb !== undefined) return { rgb: c.rgb }; - if (c.theme !== undefined) return { theme: Number(c.theme), ...(c.tint !== undefined ? { tint: Number(c.tint) } : {}) }; - if (c.indexed !== undefined) return { indexed: c.indexed }; - if (c.auto) return { auto: true }; - return undefined; -} - -// 0.x: 0–90 up, 91–180 down (135 = 45° down), 255 = stacked. 1.0: -90..90, or 'vertical'. -function rotation(r: number | undefined): Alignment['rotation'] { - if (r === undefined) return undefined; - if (r === 255) return 'vertical'; - return r > 90 ? 90 - r : r; -} - -const HORIZONTAL = ['general', 'left', 'center', 'right', 'fill', 'justify', 'centerContinuous', 'distributed'] as const; -const VERTICAL = ['top', 'center', 'bottom', 'justify', 'distributed'] as const; -const pick = (allowed: readonly T[], v: string | undefined): T | undefined => - allowed.find((a) => a === v); - -function side(s: LegacyBorderSide | undefined): BorderSide | undefined { - if (!s) return undefined; - const c = color(s.color); - return { style: s.style as BorderSide['style'], ...(c ? { color: c } : {}) }; -} - -/** Converts a 0.x cell style to a react-data-export 1.0 (javascript-excel) style. */ -export function convertLegacyStyle(old: LegacyStyle): Style { - const style: Style = {}; - if (old.font) { - const { sz, color: c, name, bold, italic, underline, strike, outline, shadow } = old.font; - const font: Font = { name, bold, italic, underline, strike, outline, shadow }; - if (sz !== undefined) font.size = Number(sz); - if (c) font.color = color(c); - style.font = font; - } - // A fill with a colour becomes a solid fill; 'none' or no colour means no fill. - if (old.fill && old.fill.patternType !== 'none' && old.fill.fgColor) { - const fg = color(old.fill.fgColor); - const bg = color(old.fill.bgColor); - style.fill = { pattern: 'solid', ...(fg ? { fgColor: fg } : {}), ...(bg ? { bgColor: bg } : {}) }; - } - if (old.numFmt !== undefined) style.numFmt = old.numFmt; - if (old.alignment) { - const a = old.alignment; - style.alignment = { - horizontal: pick(HORIZONTAL, a.horizontal), - vertical: pick(VERTICAL, a.vertical), - wrapText: a.wrapText, - rotation: rotation(a.textRotation), - readingOrder: a.readingOrder === 2 ? 'rtl' : a.readingOrder === 1 ? 'ltr' : undefined, - }; - } - if (old.border) { - const b = old.border; - style.border = { - top: side(b.top), - bottom: side(b.bottom), - left: side(b.left), - right: side(b.right), - diagonal: side(b.diagonal), - diagonalUp: b.diagonalUp, - diagonalDown: b.diagonalDown, - }; - } - return style; -} +// { font: { size: 14, bold: true, color: { rgb: 'FFFF0000' } }, fill: { pattern: 'solid', … }, alignment: { horizontal: 'center', rotation: -45 } } +export const headerStyle: Style = convertLegacyStyle(header); diff --git a/examples/migration/tsconfig.json b/examples/migration/tsconfig.json index 1452362..6bda147 100644 --- a/examples/migration/tsconfig.json +++ b/examples/migration/tsconfig.json @@ -3,10 +3,20 @@ "compilerOptions": { "declaration": false, "isolatedDeclarations": false, - "types": ["node"], + "types": [ + "node" + ], "paths": { - "react-data-export": ["../../packages/react-data-export/src/index.ts"] + "react-data-export": [ + "../../packages/react-data-export/src/index.ts" + ], + "react-data-export/legacy": [ + "../../packages/react-data-export/src/legacy.ts" + ] } }, - "include": ["*.ts", "*.tsx"] + "include": [ + "*.ts", + "*.tsx" + ] } diff --git a/packages/react-data-export/README.md b/packages/react-data-export/README.md index e70dee2..6f9a420 100644 --- a/packages/react-data-export/README.md +++ b/packages/react-data-export/README.md @@ -27,4 +27,6 @@ function Orders() { There are also plain async functions (`exportDataset`, `exportWorkbook`, `exportTable`) and hooks (`useExcelExport`, `useTableExport`). Every export resolves with `{ blob, filename, format, warnings }`. The full API is in [docs/api.md](https://github.com/securedeveloper/react-data-export/blob/main/docs/api.md). +Moving from 0.x in steps? `react-data-export/legacy` keeps ``, `` and `` working on 1.0 (deprecated, removed in 2.0); see the [quick path](https://github.com/securedeveloper/react-data-export/blob/main/docs/migration.md#11-quick-path-react-data-exportlegacy). + React 17, 18 and 19; TypeScript 5.0+. MIT licensed. diff --git a/packages/react-data-export/package.json b/packages/react-data-export/package.json index 67fdff9..5254ef7 100644 --- a/packages/react-data-export/package.json +++ b/packages/react-data-export/package.json @@ -37,6 +37,16 @@ "default": "./dist/index.cjs" } }, + "./legacy": { + "import": { + "types": "./dist/legacy.d.ts", + "default": "./dist/legacy.js" + }, + "require": { + "types": "./dist/legacy.d.cts", + "default": "./dist/legacy.cjs" + } + }, "./package.json": "./package.json" }, "files": [ @@ -53,7 +63,7 @@ "typecheck": "tsc -p tsconfig.json", "test": "vitest run", "test:watch": "vitest", - "lint:pkg": "publint --strict && attw --pack ." + "lint:pkg": "publint --strict && attw --pack . --profile node16" }, "devDependencies": { "@arethetypeswrong/cli": "^0.18.5", diff --git a/packages/react-data-export/src/legacy.ts b/packages/react-data-export/src/legacy.ts new file mode 100644 index 0000000..102a1d5 --- /dev/null +++ b/packages/react-data-export/src/legacy.ts @@ -0,0 +1,26 @@ +'use client'; + +// react-data-export/legacy: the 0.x API (, , +// , the `dataSet` shape and xlsx-style cell styles) on top of +// 1.0. Deprecated: supported for all of 1.x, removed in 2.0. See +// docs/migration.md, "Quick path: react-data-export/legacy". +// +// import ReactExport from 'react-data-export/legacy'; +// const { ExcelFile } = ReactExport; +// const { ExcelSheet, ExcelColumn } = ExcelFile; + +import { ExcelColumn, ExcelFile, ExcelSheet, type ExcelFileComponent } from './legacy/components'; + +export { ExcelColumn, ExcelFile, ExcelSheet } from './legacy/components'; +export type { ExcelColumnProps, ExcelFileComponent, ExcelFileProps, ExcelSheetProps } from './legacy/components'; +export type { ExcelCell, ExcelCellData, ExcelDataSetColumn, ExcelSheetData, ExcelValue } from './legacy/build'; +export { convertLegacyStyle } from './legacy/style'; +export type { LegacyBorderSide, LegacyColor, LegacyStyle, LegacyStyle as ExcelStyle } from './legacy/style'; + +/** The 0.x default export: `import ReactExport from 'react-data-export/legacy'`. */ +const ReactExport: { ExcelFile: ExcelFileComponent; ExcelSheet: typeof ExcelSheet; ExcelColumn: typeof ExcelColumn } = { + ExcelFile, + ExcelSheet, + ExcelColumn, +}; +export default ReactExport; diff --git a/packages/react-data-export/src/legacy/build.ts b/packages/react-data-export/src/legacy/build.ts new file mode 100644 index 0000000..342ae04 --- /dev/null +++ b/packages/react-data-export/src/legacy/build.ts @@ -0,0 +1,125 @@ +// Builds javascript-excel sheets from the 0.x shapes ( sheets and +// `dataSet` blocks), reproducing what react-data-export 0.6.0 wrote. The rules +// below were checked against the real 0.6.0 (test/legacy/goldens-0.6.json); +// the deliberate differences are marked FIX. +// +// No engine logic lives here: sheets come from javascript-excel's fromDataset / +// fromDatasets, and only 0.6's layout quirks (header styles, widths from +// column A) are expressed as options or a `colProps` array. +import { fromDataset, fromDatasets, type CellInput, type DatasetBlock, type ExcelWarning, type LeafColumn, type Sheet, type Style } from 'javascript-excel'; +import { convertLegacyStyle, type LegacyStyle } from './style'; + +/** A 0.x cell value. */ +export type ExcelValue = string | number | boolean | Date | null | undefined; +/** A 0.x styled cell. */ +export interface ExcelCell { + value: ExcelValue; + style?: LegacyStyle | undefined; +} +export type ExcelCellData = ExcelValue | ExcelCell; +/** A 0.x `dataSet` column: a title string, or an object with title, width and header style. */ +export type ExcelDataSetColumn = + | string + | { title?: string | undefined; width?: { wch: number } | { wpx: number } | undefined; style?: LegacyStyle | undefined }; +/** One 0.x `dataSet` block. */ +export interface ExcelSheetData { + /** Columns to skip on the left. */ + xSteps?: number | undefined; + /** Rows to skip before this block. */ + ySteps?: number | undefined; + columns: ExcelDataSetColumn[]; + data: ExcelCellData[][]; +} +/** A 0.x : `value` is a property name (or index) of the row, or a function of the row. */ +export interface LegacyColumnSpec { + label: string; + value: string | number | boolean | ((row: any) => unknown); +} + +const BOLD: Style = { font: { bold: true } }; + +/** + * 0.6 values: `isNaN(v) ? (v || '') : v`, so undefined, NaN and + * non-numeric falsy values become an empty text cell, null stays "no cell", + * numeric strings stay text. Objects other than Dates were written as text. + */ +function columnValue(v: unknown): CellInput { + if (v === null) return null; + if (v instanceof Date) return v; + if (typeof v === 'number') return Number.isNaN(v) ? '' : v; + if (typeof v === 'boolean' || typeof v === 'string') return v; + if (v === undefined) return ''; + return String(v); +} + +/** 0.6 `dataSet` cells: null is no cell, undefined an empty text cell, `{ value, style }` a styled cell. */ +function dataSetCell(v: ExcelCellData): CellInput { + if (v === null) return null; + if (v === undefined) return ''; + if (v instanceof Date || typeof v !== 'object') return v; + // FIX: 0.6 wrote a Date inside `{ value, style }` as text (it checked for a + // Date before unwrapping); here it is a date like any other Date. + const value = v.value === undefined ? '' : v.value; + return v.style ? { value, style: convertLegacyStyle(v.style) } : { value }; +} + +/** A sheet from + children: plain (not bold) headers, no widths. */ +export function sheetFromColumns( + name: string, + rows: readonly unknown[], + columns: LegacyColumnSpec[], + onWarning: (w: ExcelWarning) => void, +): Sheet { + return fromDataset( + { + columns: columns.map((c): LeafColumn => { + const get = typeof c.value === 'function' ? c.value : (row: any) => row?.[c.value as string]; + return { title: c.label, value: (row) => columnValue(get(row)) }; + }), + data: rows, + }, + { name, headerStyle: {}, onWarning }, + ); +} + +/** A sheet from a 0.x `dataSet`: blocks placed by xSteps/ySteps, bold headers, widths from column A. */ +export function sheetFromDataSet(name: string, dataSet: ExcelSheetData[], onWarning: (w: ExcelWarning) => void): Sheet { + let widths: Array<{ wch: number } | { wpx: number }> = []; + const blocks = dataSet.map((block): DatasetBlock => { + const cols = block.columns ?? []; + const rows = block.data ?? []; + // 0.6 wrote every cell of every row, header or not; columns beyond the + // headers get no header cell. An empty `columns` still took a header row. + const count = Math.max(cols.length, ...rows.map((r) => r.length), 1); + const blockWidths: Array<{ wch: number } | { wpx: number }> = []; + const columns = Array.from({ length: count }, (_, i): LeafColumn => { + const col = cols[i]; + const value = (row: ExcelCellData[]): CellInput => (i < row.length ? dataSetCell(row[i]) : null); + if (col === undefined) return { title: { value: null }, value }; + if (typeof col === 'string') { + // FIX: 0.6.0 left string headers empty (a regression in its last + // release; 0.5 and the 0.x README wrote the text). Written here. + return { title: col, headerStyle: BOLD, value }; + } + // Only object columns had a width in 0.6: theirs, or 80 px. + blockWidths.push(col.width ?? { wpx: 80 }); + return { + title: col.title ?? '', + // 0.6: a column's style replaced the bold header. + headerStyle: col.style ? convertLegacyStyle(col.style) : BOLD, + value, + }; + }); + // 0.6 assigned the widths per block, so the last block with object columns + // won, and they started at column A whatever its xSteps. + if (blockWidths.length > 0) widths = blockWidths; + return { + columns, + data: rows, + offset: { rows: typeof block.ySteps === 'number' ? block.ySteps : 0, cols: typeof block.xSteps === 'number' ? block.xSteps : 0 }, + }; + }); + const sheet = fromDatasets(blocks, { name, headerStyle: {}, gap: 0, onWarning }); + if (widths.length > 0) sheet.colProps = widths.map((width) => ({ width })); + return sheet; +} diff --git a/packages/react-data-export/src/legacy/components.ts b/packages/react-data-export/src/legacy/components.ts new file mode 100644 index 0000000..6d7297d --- /dev/null +++ b/packages/react-data-export/src/legacy/components.ts @@ -0,0 +1,164 @@ +// The 0.x components (, , ) on top of the +// 1.0 export path: same props, defaults and markup as react-data-export 0.6.0, +// written by javascript-excel through the shared write/download code. +import { + Children, + createElement, + isValidElement, + useCallback, + useEffect, + useRef, + type ReactElement, + type ReactNode, +} from 'react'; +import { sanitizeSheetName, type ExcelWarning, type Sheet } from 'javascript-excel'; +import { startExport, writeAndSave, type ExportFormat, type ExportOptions, type ExportResult } from '../export'; +import { runForTrigger } from '../excel-export'; +import { useExportRunner } from '../use-excel-export'; +import { sheetFromColumns, sheetFromDataSet, type ExcelSheetData, type LegacyColumnSpec } from './build'; + +export interface ExcelFileProps { + /** File name without the extension; the extension is always appended (0.x). Default "Download". */ + filename?: string | undefined; + /** 'xlsx' (default) or 'csv'. 'xls', 'txt' and 'html' write an .xlsx file. '' takes it from the filename. */ + fileExtension?: string | undefined; + /** The trigger, wrapped in a that handles the click. Default . */ + element?: ReactNode; + /** Download once when mounted and render nothing. */ + hideElement?: boolean | undefined; + /** elements. Falsy children are skipped. */ + children?: ReactNode; +} + +export interface ExcelSheetProps { + name: string; + /** Rows for the children, or a function returning them. */ + data?: readonly object[] | (() => readonly object[]) | undefined; + /** Blocks of `{ columns, data, xSteps?, ySteps? }`; used instead of `data` when not empty. */ + dataSet?: ExcelSheetData[] | undefined; + /** elements. Falsy children are skipped. */ + children?: ReactNode; +} + +export interface ExcelColumnProps { + label: string; + /** A property name (or index) of each row, or a function of the row. */ + value: LegacyColumnSpec['value']; +} + +/** Declares a sheet inside . Renders nothing. */ +export function ExcelSheet(_props: ExcelSheetProps): null { + return null; +} + +/** Declares a column inside . Renders nothing. */ +export function ExcelColumn(_props: ExcelColumnProps): null { + return null; +} + +const EXTENSIONS = ['xlsx', 'xls', 'csv', 'txt', 'html']; +const MIGRATION = 'https://github.com/securedeveloper/react-data-export/blob/main/docs/migration.md'; + +function isDev(): boolean { + return typeof process !== 'undefined' && process.env?.['NODE_ENV'] !== 'production'; +} + +const warned = new Set(); +function warnOnce(key: string, message: string): void { + if (!isDev() || warned.has(key)) return; + warned.add(key); + console.warn(`react-data-export/legacy: ${message}`); +} + +/** 0.6: fileExtension if known; '' takes the last part of the filename; anything else is xlsx. */ +function legacyExtension(filename: string, fileExtension: string | undefined): string { + let ext = fileExtension ?? 'xlsx'; + if (ext.length === 0) ext = filename.split('.').pop() ?? ''; + return EXTENSIONS.includes(ext) ? ext : 'xlsx'; +} + +function propsOf

(node: ReactNode): P[] { + return Children.toArray(node) + .filter((child): child is ReactElement

=> isValidElement(child)) + .map((child) => child.props); +} + +function buildSheets(children: ReactNode, onWarning: (w: ExcelWarning) => void): Sheet[] { + return propsOf(children).map((sheet) => { + const name = sanitizeSheetName(String(sheet.name ?? '')); + if (name !== sheet.name) { + warnOnce(`name:${String(sheet.name)}`, `sheet name ${JSON.stringify(sheet.name)} is not valid in Excel; written as ${JSON.stringify(name)}.`); + } + if (sheet.dataSet && sheet.dataSet.length > 0) return sheetFromDataSet(name, sheet.dataSet, onWarning); + const rows = typeof sheet.data === 'function' ? sheet.data() : (sheet.data ?? []); + const columns = propsOf(sheet.children).map((c) => ({ label: c.label, value: c.value })); + return sheetFromColumns(name, rows, columns, onWarning); + }); +} + +/** Internal: one 0.x export, through the 1.0 write and download path. */ +export async function exportLegacy(props: ExcelFileProps, options: ExportOptions): Promise { + const filename = props.filename === undefined ? 'Download' : props.filename; + if (typeof filename !== 'string') throw new Error('Invalid file name provided'); + const ext = legacyExtension(filename, props.fileExtension); + const format: ExportFormat = ext === 'csv' ? 'csv' : 'xlsx'; + if (ext !== format) { + warnOnce(`ext:${ext}`, `fileExtension "${ext}" is written as an .xlsx file named ${filename}.xlsx (0.x wrote xlsx content under a .${ext} name).`); + } + await startExport(options.signal); + const warnings: ExcelWarning[] = []; + const sheets = buildSheets(props.children, (w) => warnings.push(w)); + if (format === 'csv' && sheets.length > 1) { + warnOnce('csv-sheets', `a CSV file holds one sheet; only the first of ${sheets.length} is written.`); + } + return writeAndSave( + sheets, + undefined, + warnings, + { + ...options, + // 0.x always appended the extension ("report.xlsx" -> "report.xlsx.xlsx"). + filename: `${filename}.${format}`, + // 0.x converted dates as UTC. + write: { ...options.write, dateZone: 'utc' }, + csv: { ...options.csv, dateZone: 'utc' }, + }, + format, + ); +} + +function ExcelFileImpl(props: ExcelFileProps): ReactElement | null { + const { run } = useExportRunner(); + const latest = useRef(props); + latest.current = props; + + const download = useCallback((): void => { + void runForTrigger(() => run((options) => exportLegacy(latest.current, options), undefined), undefined, undefined); + }, [run]); + + useEffect(() => { + warnOnce( + 'deprecated', + `, and are deprecated. They are supported for all of 1.x and removed in 2.0. Move to the 1.0 API with the migration guide: ${MIGRATION}`, + ); + // 0.x downloaded in the constructor (twice under StrictMode). Here it runs + // after mount, and StrictMode's simulated unmount aborts the first run. + if (latest.current.hideElement) download(); + }, [download]); + + if (props.hideElement) return null; + const element = props.element === undefined ? createElement('button', null, 'Download') : props.element; + return createElement('span', { onClick: download }, element); +} + +export interface ExcelFileComponent { + (props: ExcelFileProps): ReactElement | null; + displayName?: string; + /** 0.x: `ReactExport.ExcelFile.ExcelSheet`. */ + ExcelSheet: typeof ExcelSheet; + /** 0.x: `ReactExport.ExcelFile.ExcelColumn`. */ + ExcelColumn: typeof ExcelColumn; +} + +/** The 0.x : deprecated, supported for all of 1.x. */ +export const ExcelFile: ExcelFileComponent = Object.assign(ExcelFileImpl, { ExcelSheet, ExcelColumn, displayName: 'ExcelFile' }); diff --git a/packages/react-data-export/src/legacy/style.ts b/packages/react-data-export/src/legacy/style.ts new file mode 100644 index 0000000..8b1f712 --- /dev/null +++ b/packages/react-data-export/src/legacy/style.ts @@ -0,0 +1,108 @@ +// The 0.x (xlsx-style) style converter, moved here from the migration guide's +// example so the legacy entry and users share one implementation. +import type { Style } from 'javascript-excel'; + +/** A 0.x (xlsx-style) style object, as documented in the 0.6 README. */ +export interface LegacyColor { + auto?: number; + rgb?: string; + theme?: string | number; + tint?: string | number; + indexed?: number; +} +export interface LegacyBorderSide { + style: string; + color?: LegacyColor; +} +export interface LegacyStyle { + fill?: { patternType?: string; fgColor?: LegacyColor; bgColor?: LegacyColor }; + font?: { + name?: string; + sz?: string | number; + color?: LegacyColor; + bold?: boolean; + underline?: boolean; + italic?: boolean; + strike?: boolean; + outline?: boolean; + shadow?: boolean; + }; + numFmt?: string; + alignment?: { vertical?: string; horizontal?: string; wrapText?: boolean; readingOrder?: number; textRotation?: number }; + border?: { top?: LegacyBorderSide; bottom?: LegacyBorderSide; left?: LegacyBorderSide; right?: LegacyBorderSide; diagonal?: LegacyBorderSide; diagonalUp?: boolean; diagonalDown?: boolean }; +} + +type Font = NonNullable; +type Color = NonNullable; +type Alignment = NonNullable; +type Border = NonNullable; +type BorderSide = NonNullable; + +function color(c: LegacyColor | undefined): Color | undefined { + if (!c) return undefined; + if (c.rgb !== undefined) return { rgb: c.rgb }; + if (c.theme !== undefined) return { theme: Number(c.theme), ...(c.tint !== undefined ? { tint: Number(c.tint) } : {}) }; + if (c.indexed !== undefined) return { indexed: c.indexed }; + if (c.auto) return { auto: true }; + return undefined; +} + +// 0.x: 0–90 up, 91–180 down (135 = 45° down), 255 = stacked. 1.0: -90..90, or 'vertical'. +function rotation(r: number | undefined): Alignment['rotation'] { + if (r === undefined) return undefined; + if (r === 255) return 'vertical'; + return r > 90 ? 90 - r : r; +} + +const HORIZONTAL = ['general', 'left', 'center', 'right', 'fill', 'justify', 'centerContinuous', 'distributed'] as const; +const VERTICAL = ['top', 'center', 'bottom', 'justify', 'distributed'] as const; +const pick = (allowed: readonly T[], v: string | undefined): T | undefined => + allowed.find((a) => a === v); + +function side(s: LegacyBorderSide | undefined): BorderSide | undefined { + if (!s) return undefined; + const c = color(s.color); + return { style: s.style as BorderSide['style'], ...(c ? { color: c } : {}) }; +} + +/** Converts a 0.x cell style to a react-data-export 1.0 (javascript-excel) style. */ +export function convertLegacyStyle(old: LegacyStyle): Style { + const style: Style = {}; + if (old.font) { + const { sz, color: c, name, bold, italic, underline, strike, outline, shadow } = old.font; + const font: Font = { name, bold, italic, underline, strike, outline, shadow }; + if (sz !== undefined) font.size = Number(sz); + if (c) font.color = color(c); + style.font = font; + } + // A fill with a colour becomes a solid fill; 'none' or no colour means no fill. + if (old.fill && old.fill.patternType !== 'none' && old.fill.fgColor) { + const fg = color(old.fill.fgColor); + const bg = color(old.fill.bgColor); + style.fill = { pattern: 'solid', ...(fg ? { fgColor: fg } : {}), ...(bg ? { bgColor: bg } : {}) }; + } + if (old.numFmt !== undefined) style.numFmt = old.numFmt; + if (old.alignment) { + const a = old.alignment; + style.alignment = { + horizontal: pick(HORIZONTAL, a.horizontal), + vertical: pick(VERTICAL, a.vertical), + wrapText: a.wrapText, + rotation: rotation(a.textRotation), + readingOrder: a.readingOrder === 2 ? 'rtl' : a.readingOrder === 1 ? 'ltr' : undefined, + }; + } + if (old.border) { + const b = old.border; + style.border = { + top: side(b.top), + bottom: side(b.bottom), + left: side(b.left), + right: side(b.right), + diagonal: side(b.diagonal), + diagonalUp: b.diagonalUp, + diagonalDown: b.diagonalDown, + }; + } + return style; +} diff --git a/packages/react-data-export/test/legacy/components.test.tsx b/packages/react-data-export/test/legacy/components.test.tsx new file mode 100644 index 0000000..e476195 --- /dev/null +++ b/packages/react-data-export/test/legacy/components.test.tsx @@ -0,0 +1,246 @@ +// behaviour: 0.6 markup and defaults, with the old bugs fixed. +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { StrictMode } from 'react'; +import { download } from 'javascript-excel/dom'; +import { read } from 'javascript-excel/read'; +import ReactExport, { ExcelColumn, ExcelFile, ExcelSheet, convertLegacyStyle } from '../../src/legacy'; +import * as main from '../../src/index'; + +vi.mock('javascript-excel/dom', async (importOriginal) => ({ + ...(await importOriginal()), + download: vi.fn(), +})); +const downloadMock = vi.mocked(download); +let warn: ReturnType; +beforeEach(() => { + downloadMock.mockClear(); + warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); +}); +afterEach(() => warn.mockRestore()); + +const rows = [{ name: 'Ada', joined: new Date(2024, 0, 15) }]; +// An element, not a component: like 0.x, reads its direct children's props. +const people = ( + + + + +); + +/** The file's bytes as text, keeping a BOM (Blob.text() strips it). */ +async function rawText(blob: Blob): Promise { + return new TextDecoder('utf-8', { ignoreBOM: true }).decode(await blob.arrayBuffer()); +} + +async function downloaded(n = 0): Promise<{ blob: Blob; name: string }> { + await waitFor(() => expect(downloadMock.mock.calls.length).toBeGreaterThan(n)); + const [blob, name] = downloadMock.mock.calls[n]!; + return { blob: blob as Blob, name: name as string }; +} + +describe('the 0.x API shape', () => { + it('default export and statics like 0.x', () => { + expect(ReactExport.ExcelFile).toBe(ExcelFile); + expect(ReactExport.ExcelFile.ExcelSheet).toBe(ExcelSheet); + expect(ReactExport.ExcelFile.ExcelColumn).toBe(ExcelColumn); + }); + + it('is not part of the main entry', () => { + expect('ExcelFile' in main).toBe(false); + expect('convertLegacyStyle' in main).toBe(false); + }); +}); + +describe('', () => { + it('renders around , and a click downloads Download.xlsx', async () => { + const { container } = render( + + {people} + , + ); + expect(container.innerHTML).toBe(''); + fireEvent.click(screen.getByRole('button', { name: 'Download' })); + const { name } = await downloaded(); + expect(name).toBe('Download.xlsx'); + expect(downloadMock).toHaveBeenCalledTimes(1); + }); + + it('wraps a custom element in the span', () => { + const { container } = render( + Get it}> + {people} + , + ); + expect(container.innerHTML).toBe('Get it'); + }); + + it('hideElement renders nothing and downloads once on mount', async () => { + const { container } = render( + + {people} + , + ); + expect(container.innerHTML).toBe(''); + expect((await downloaded()).name).toBe('auto.xlsx'); + }); + + it.each(['xlsx', 'csv'])('hideElement under StrictMode downloads exactly once (%s)', async (fileExtension) => { + render( + + + {people} + + , + ); + expect((await downloaded()).name).toBe(`strict.${fileExtension}`); + await act(async () => { + await new Promise((r) => setTimeout(r, 50)); + }); + expect(downloadMock).toHaveBeenCalledTimes(1); + }); + + it("fileExtension 'csv' writes real CSV", async () => { + render( + + + + + + , + ); + const { blob, name } = await downloaded(); + expect(name).toBe('people.csv'); + expect(await rawText(blob)).toBe('\uFEFFName,N\r\nAda,1\r\n'); + }); + + it("CSV with several sheets writes the first one, with a dev warning", async () => { + render( + + + + + + + + , + ); + expect(await rawText((await downloaded()).blob)).toBe('\uFEFFA\r\nfirst\r\n'); + expect(warn.mock.calls.some((c: unknown[]) => String(c[0]).includes('only the first of 2'))).toBe(true); + }); + + it.each(['xls', 'txt', 'html'])("fileExtension '%s' writes an .xlsx file with a dev warning", async (fileExtension) => { + render( + + {people} + , + ); + const { blob, name } = await downloaded(); + expect(name).toBe(`old-${fileExtension}.xlsx`); + const { workbook } = await read(blob); + expect(workbook.sheets[0]?.name).toBe('People'); + expect(warn.mock.calls.some((c: unknown[]) => String(c[0]).includes(`fileExtension "${fileExtension}"`))).toBe(true); + }); + + it('writes dates as UTC, like 0.x', async () => { + const local = new Date(2024, 0, 15); // local midnight + render( + + + + + , + ); + const { workbook } = await read((await downloaded()).blob, { dates: 'serial' }); + const serial = (local.getTime() - Date.UTC(1899, 11, 30)) / 86_400_000; // 0.6's dateToNumber + expect(workbook.sheets[0]?.rows[1]?.[0]?.value as number).toBeCloseTo(serial, 9); + }); + + it('skips falsy sheets and columns (conditional rendering)', async () => { + const showSecret = false; + render( + + {showSecret && } + + + {showSecret && } + + , + ); + const { workbook } = await read((await downloaded()).blob); + expect(workbook.sheets.map((s) => s.name)).toEqual(['Shown']); + expect(workbook.sheets[0]?.rows[0]?.map((c) => c?.value)).toEqual(['Name']); + }); + + it('writes an invalid sheet name sanitized, with a dev warning', async () => { + render( + + + + + , + ); + const { workbook } = await read((await downloaded()).blob); + expect(workbook.sheets[0]?.name).toBe('Q1_Q2'); + expect(warn.mock.calls.some((c: unknown[]) => String(c[0]).includes('"Q1/Q2"'))).toBe(true); + }); + + it('a non-string filename is reported, nothing is downloaded', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined); + render( + + {people} + , + ); + fireEvent.click(screen.getByRole('button')); + await waitFor(() => expect(error).toHaveBeenCalled()); + expect(String(error.mock.calls[0]![0])).toMatch(/Invalid file name provided/); + expect(downloadMock).not.toHaveBeenCalled(); + error.mockRestore(); + }); + + it('warns once per page that the legacy API is deprecated, pointing to the migration guide', async () => { + vi.resetModules(); + const fresh = await import('../../src/legacy'); + render( + <> + + {people} + + + {people} + + , + ); + const deprecations = warn.mock.calls.filter((c: unknown[]) => String(c[0]).includes('deprecated')); + expect(deprecations).toHaveLength(1); + expect(String(deprecations[0]![0])).toContain('docs/migration.md'); + expect(String(deprecations[0]![0])).toContain('removed in 2.0'); + }); +}); + +describe('convertLegacyStyle', () => { + it('maps xlsx-style keys to javascript-excel styles', () => { + expect( + convertLegacyStyle({ + font: { sz: '14', bold: true, color: { rgb: 'FFFF0000' } }, + fill: { patternType: 'solid', fgColor: { rgb: 'FFFFFF00' } }, + alignment: { horizontal: 'right', textRotation: 135, readingOrder: 2 }, + border: { top: { style: 'thin', color: { theme: '1', tint: '-0.25' } } }, + numFmt: '0.00%', + }), + ).toMatchObject({ + font: { size: 14, bold: true, color: { rgb: 'FFFF0000' } }, + fill: { pattern: 'solid', fgColor: { rgb: 'FFFFFF00' } }, + alignment: { horizontal: 'right', rotation: -45, readingOrder: 'rtl' }, + border: { top: { style: 'thin', color: { theme: 1, tint: -0.25 } } }, + numFmt: '0.00%', + }); + }); + + it("drops a 'none' fill and maps stacked text and auto colours", () => { + const s = convertLegacyStyle({ fill: { patternType: 'none', fgColor: { rgb: 'FF000000' } }, alignment: { textRotation: 255 }, font: { color: { auto: 1 } } }); + expect(s.fill).toBeUndefined(); + expect(s.alignment?.rotation).toBe('vertical'); + expect(s.font?.color).toEqual({ auto: true }); + }); +}); diff --git a/packages/react-data-export/test/legacy/goldens-0.6.json b/packages/react-data-export/test/legacy/goldens-0.6.json new file mode 100644 index 0000000..f0eec12 --- /dev/null +++ b/packages/react-data-export/test/legacy/goldens-0.6.json @@ -0,0 +1,475 @@ +{ + "generatedFrom": "react-data-export@0.6.0", + "goldens": { + "columns-basic": { + "fileName": "Download.xlsx", + "fileExtension": "xlsx", + "sheets": [ + { + "name": "People", + "ref": "A1:H3", + "cols": null, + "cells": { + "A1": { + "t": "s", + "v": "Name" + }, + "B1": { + "t": "s", + "v": "Age" + }, + "C1": { + "t": "s", + "v": "Joined" + }, + "D1": { + "t": "s", + "v": "Active" + }, + "E1": { + "t": "s", + "v": "Note" + }, + "F1": { + "t": "s", + "v": "Score" + }, + "G1": { + "t": "s", + "v": "Code" + }, + "H1": { + "t": "s", + "v": "Empty" + }, + "A2": { + "t": "s", + "v": "Ada" + }, + "B2": { + "t": "n", + "v": 36 + }, + "C2": { + "t": "n", + "v": 45306, + "z": "m/d/yy" + }, + "D2": { + "t": "b", + "v": true + }, + "E2": { + "t": "s", + "v": "" + }, + "F2": { + "t": "s", + "v": "" + }, + "G2": { + "t": "s", + "v": "007" + }, + "A3": { + "t": "s", + "v": "Alan" + }, + "B3": { + "t": "n", + "v": 41 + }, + "C3": { + "t": "n", + "v": 45414.520833333336, + "z": "m/d/yy" + }, + "D3": { + "t": "b", + "v": false + }, + "E3": { + "t": "s", + "v": "x" + }, + "F3": { + "t": "n", + "v": 0 + }, + "G3": { + "t": "s", + "v": "12" + } + } + } + ] + }, + "columns-functions": { + "fileName": "report.xlsx.xlsx", + "fileExtension": "xlsx", + "sheets": [ + { + "name": "Computed", + "ref": "A1:B3", + "cols": null, + "cells": { + "A1": { + "t": "s", + "v": "Upper" + }, + "B1": { + "t": "s", + "v": "Double" + }, + "A2": { + "t": "s", + "v": "ADA" + }, + "B2": { + "t": "n", + "v": 72 + }, + "A3": { + "t": "s", + "v": "ALAN" + }, + "B3": { + "t": "n", + "v": 82 + } + } + } + ] + }, + "dataset-styles": { + "fileName": "styled.xlsx", + "fileExtension": "xlsx", + "sheets": [ + { + "name": "Styled", + "ref": "A1:D6", + "cols": [ + { + "wpx": 80 + }, + { + "wch": 12 + }, + { + "wpx": 120 + }, + { + "wpx": 80 + } + ], + "cells": { + "A1": { + "t": "s", + "v": "Item", + "s": { + "font": { + "bold": true + } + } + }, + "B1": { + "t": "s", + "v": "Qty", + "s": { + "font": { + "bold": true + } + } + }, + "C1": { + "t": "s", + "v": "Price", + "s": { + "font": { + "color": { + "rgb": "FFFF0000" + } + }, + "fill": { + "patternType": "solid", + "fgColor": { + "rgb": "FFFFFF00" + } + } + } + }, + "D1": { + "t": "s", + "v": "When", + "s": { + "font": { + "bold": true + } + } + }, + "A2": { + "t": "s", + "v": "Pens", + "s": { + "font": { + "sz": "14", + "bold": true, + "name": "Arial" + } + } + }, + "B2": { + "t": "n", + "v": 10 + }, + "C2": { + "t": "n", + "v": 1.5, + "s": { + "numFmt": "0.00" + } + }, + "D2": { + "t": "n", + "v": 45306, + "z": "m/d/yy" + }, + "A3": { + "t": "s", + "v": "Paper" + }, + "B3": { + "t": "n", + "v": 3, + "s": { + "fill": { + "patternType": "solid", + "fgColor": { + "rgb": "FF00FF00" + } + }, + "alignment": { + "horizontal": "right" + } + } + }, + "D3": { + "t": "n", + "v": 45657.75, + "z": "m/d/yy" + }, + "A4": { + "t": "b", + "v": true, + "s": { + "border": { + "top": { + "style": "thin", + "color": { + "rgb": "FF000000" + } + } + } + } + }, + "B4": { + "t": "n", + "v": 0 + }, + "C4": { + "t": "n", + "v": -2.25 + } + } + } + ] + }, + "dataset-blocks": { + "fileName": "blocks.xlsx", + "fileExtension": "xlsx", + "sheets": [ + { + "name": "Blocks", + "ref": "A2:C12", + "cols": [ + { + "wch": 30 + } + ], + "cells": { + "A2": { + "t": "s", + "v": "A", + "s": { + "font": { + "bold": true + } + } + }, + "B2": { + "t": "s", + "v": "B", + "s": { + "font": { + "bold": true + } + } + }, + "A3": { + "t": "n", + "v": 1 + }, + "B3": { + "t": "n", + "v": 2 + }, + "A4": { + "t": "n", + "v": 3 + }, + "B4": { + "t": "n", + "v": 4 + }, + "B7": { + "t": "s", + "v": null, + "s": { + "font": { + "bold": true + } + } + }, + "C7": { + "t": "s", + "v": null, + "s": { + "font": { + "bold": true + } + } + }, + "B8": { + "t": "s", + "v": "Johnson" + }, + "C8": { + "t": "s", + "v": "Finance" + }, + "C9": { + "t": "s", + "v": "Last", + "s": { + "font": { + "bold": true + } + } + }, + "C10": { + "t": "s", + "v": "z" + }, + "A12": { + "t": "s", + "v": "no header" + }, + "B12": { + "t": "n", + "v": 5 + } + } + } + ] + }, + "sheets-mixed": { + "fileName": "book.xlsx", + "fileExtension": "xlsx", + "sheets": [ + { + "name": "First", + "ref": "A1:A3", + "cols": null, + "cells": { + "A1": { + "t": "s", + "v": "Name" + }, + "A2": { + "t": "s", + "v": "Ada" + }, + "A3": { + "t": "s", + "v": "Alan" + } + } + }, + { + "name": "Second", + "ref": "A1:A4", + "cols": [ + { + "wpx": 80 + } + ], + "cells": { + "A1": { + "t": "s", + "v": "X", + "s": { + "font": { + "bold": true + } + } + }, + "A2": { + "t": "n", + "v": 1 + }, + "A3": { + "t": "n", + "v": 2 + } + } + }, + { + "name": "Third", + "ref": "A1:A2", + "cols": null, + "cells": { + "A1": { + "t": "s", + "v": "V" + }, + "A2": { + "t": "s", + "v": "fallback" + } + } + } + ] + }, + "filename-from-name": { + "fileName": "data.xlsx.xlsx", + "fileExtension": "xlsx", + "sheets": [ + { + "name": "S", + "ref": "A1:A2", + "cols": null, + "cells": { + "A1": { + "t": "s", + "v": "A" + }, + "A2": { + "t": "n", + "v": 1 + } + } + } + ] + } + } +} diff --git a/packages/react-data-export/test/legacy/goldens.test.ts b/packages/react-data-export/test/legacy/goldens.test.ts new file mode 100644 index 0000000..52c93ae --- /dev/null +++ b/packages/react-data-export/test/legacy/goldens.test.ts @@ -0,0 +1,130 @@ +// react-data-export/legacy against the real react-data-export@0.6.0. +// goldens-0.6.json is generated by scripts/legacy-goldens.mjs from 0.6.0's own +// sheet-building code; each scenario here is exported by the legacy entry, +// read back with javascript-excel/read, and compared cell by cell. +import { createElement } from 'react'; +import { read } from 'javascript-excel/read'; +import { encodeCell, decodeCell } from 'javascript-excel'; +import { ExcelColumn, ExcelFile, ExcelSheet, convertLegacyStyle, type LegacyStyle } from '../../src/legacy'; +import { exportLegacy } from '../../src/legacy/components'; +import goldensFile from './goldens-0.6.json'; +import { scenarios } from './scenarios.mjs'; + +vi.mock('javascript-excel/dom', async (importOriginal) => ({ + ...(await importOriginal()), + download: vi.fn(), +})); + +interface GoldenCell { + t: 's' | 'n' | 'b'; + v: string | number | boolean | null; + s?: LegacyStyle; + z?: string; +} +interface GoldenSheet { + name: string; + cols: Array<{ wch: number } | { wpx: number }> | null; + cells: Record; +} +const goldens = (goldensFile as { goldens: Record }).goldens; + +/** + * The deliberate differences from 0.6.0's output (see docs/migration.md, + * "Quick path: react-data-export/legacy"). 0.6.0 left headers of string + * `dataSet` columns empty, a regression in its last release (0.5 and the 0.x + * README wrote the text); legacy writes the text. + */ +const DIFFERENCES: Record> = { + 'dataset-blocks': { B7: 'Name', C7: 'Dept' }, +}; + +const rgb = (c: unknown): string | undefined => + c && typeof c === 'object' && 'rgb' in c ? String((c as { rgb: string }).rgb).slice(-6).toUpperCase() : undefined; + +/** The parts of a style that 0.6 could set, in a comparable shape. */ +function styleSummary(style: any): Record { + return { + bold: style?.font?.bold === true, + size: style?.font?.size === 11 ? undefined : style?.font?.size, + fontName: style?.font?.name === 'Calibri' ? undefined : style?.font?.name, + fontColor: rgb(style?.font?.color), + fill: rgb(style?.fill?.fgColor) ?? (typeof style?.fill === 'string' ? String(style.fill).slice(-6).toUpperCase() : undefined), + horizontal: style?.alignment?.horizontal, + borderTop: style?.border?.top?.style, + numFmt: style?.numFmt === 14 ? undefined : style?.numFmt, + }; +} + +/** 0.6 widths in Excel characters, as the reader reports them. */ +const chars = (w: { wch: number } | { wpx: number }): number => ('wch' in w ? w.wch : (w.wpx - 5) / 7); + +const elements = new Map( + scenarios({ createElement }, { ExcelFile, ExcelSheet, ExcelColumn }).map((s) => [s.name, s.element]), +); + +describe('react-data-export/legacy reproduces react-data-export@0.6.0', () => { + it('has a golden for every scenario', () => { + expect([...elements.keys()].sort()).toEqual(Object.keys(goldens).sort()); + }); + + for (const [name, golden] of Object.entries(goldens)) { + it(name, async () => { + const element = elements.get(name)!; + const result = await exportLegacy(element.props as never, { download: false }); + expect(result.filename).toBe(golden.fileName); + + const { workbook } = await read(result.blob as Blob, { dates: 'serial' }); + expect(workbook.sheets.map((s) => s.name)).toEqual(golden.sheets.map((s) => s.name)); + + golden.sheets.forEach((gs, i) => { + const sheet = workbook.sheets[i]!; + const expected = new Map(Object.entries(gs.cells)); + const diff = DIFFERENCES[name] ?? {}; + + // Every 0.6 cell: same place, value, type, date format and style. + for (const [ref, g] of expected) { + const { row, col } = decodeCell(ref); + const cell = sheet.rows[row]?.[col]; + const where = `${name} ${gs.name}!${ref}`; + if (ref in diff) { + expect(cell?.value, where).toBe(diff[ref]); + continue; + } + expect(cell, where).toBeDefined(); + if (g.t === 's') { + expect(cell!.type, where).toBe('string'); + expect(cell!.value, where).toBe(g.v ?? ''); + } else if (g.t === 'b') { + expect(cell!.value, where).toBe(g.v); + } else if (g.z !== undefined) { + // A 0.6 date: the same UTC serial, built-in short date format 14. + expect(cell!.value as number, where).toBeCloseTo(g.v as number, 9); + expect(cell!.style?.numFmt, where).toBe(14); + } else { + expect(cell!.value, where).toBe(g.v); + } + const want = styleSummary(g.s ? convertLegacyStyle(g.s) : undefined); + expect(styleSummary(cell!.style), `${where} style`).toEqual(want); + } + + // And nothing else: cells 0.6 didn't write are absent here too. + sheet.rows.forEach((r, row) => + r?.forEach((cell, col) => { + if (cell === undefined || (cell.value === undefined && !cell.style)) return; + const ref = encodeCell({ row, col }); + expect(expected.has(ref) || ref in diff, `${name} ${gs.name}!${ref} is extra`).toBe(true); + }), + ); + + // Column widths: 0.6's !cols, from column A. + const widths = (sheet.colProps ?? []).map((c) => c?.width); + if (gs.cols === null) { + expect(widths.filter((w) => w !== undefined), `${name} ${gs.name} widths`).toEqual([]); + } else { + expect(widths.length, `${name} ${gs.name} widths`).toBe(gs.cols.length); + gs.cols.forEach((w, c) => expect(widths[c] as number, `${name} ${gs.name} width ${c}`).toBeCloseTo(chars(w), 1)); + } + }); + }); + } +}); diff --git a/packages/react-data-export/test/legacy/scenarios.d.mts b/packages/react-data-export/test/legacy/scenarios.d.mts new file mode 100644 index 0000000..e34b71e --- /dev/null +++ b/packages/react-data-export/test/legacy/scenarios.d.mts @@ -0,0 +1,7 @@ +// Types for scenarios.mjs (plain JS so the 0.6 golden generator can import it too). +export interface Scenario { + name: string; + /** An element built with the components passed in. */ + element: { props: Record }; +} +export function scenarios(React: { createElement: (...args: any[]) => unknown }, components: { ExcelFile: unknown; ExcelSheet: unknown; ExcelColumn: unknown }): Scenario[]; diff --git a/packages/react-data-export/test/legacy/scenarios.mjs b/packages/react-data-export/test/legacy/scenarios.mjs new file mode 100644 index 0000000..f3ddd23 --- /dev/null +++ b/packages/react-data-export/test/legacy/scenarios.mjs @@ -0,0 +1,118 @@ +// Scenarios shared by the 0.6 golden generator (scripts/legacy-goldens.mjs, +// run against the real react-data-export@0.6.0) and the react-data-export/legacy +// tests. Plain JS so both can import it. Dates use Date.UTC, so the goldens +// don't depend on the time zone of the machine that generated them. +// +// scenarios(React, { ExcelFile, ExcelSheet, ExcelColumn }) -> [{ name, element }] + +const d = (y, m, day, h = 0, min = 0) => new Date(Date.UTC(y, m, day, h, min)); + +export function scenarios(React, { ExcelFile, ExcelSheet, ExcelColumn }) { + const h = React.createElement; + const people = [ + { name: 'Ada', age: 36, joined: d(2024, 0, 15), active: true, note: undefined, score: Number.NaN, code: '007', empty: null }, + { name: 'Alan', age: 41, joined: d(2024, 4, 2, 12, 30), active: false, note: 'x', score: 0, code: '12', empty: null }, + ]; + + return [ + { + // path: plain headers, string keys, value types, empty values, dates, default filename. + name: 'columns-basic', + element: h( + ExcelFile, + {}, + h( + ExcelSheet, + { data: people, name: 'People' }, + h(ExcelColumn, { label: 'Name', value: 'name' }), + h(ExcelColumn, { label: 'Age', value: 'age' }), + h(ExcelColumn, { label: 'Joined', value: 'joined' }), + h(ExcelColumn, { label: 'Active', value: 'active' }), + h(ExcelColumn, { label: 'Note', value: 'note' }), + h(ExcelColumn, { label: 'Score', value: 'score' }), + h(ExcelColumn, { label: 'Code', value: 'code' }), + h(ExcelColumn, { label: 'Empty', value: 'empty' }), + ), + ), + }, + { + // Function values, data as a function, filename with the extension already in it. + name: 'columns-functions', + element: h( + ExcelFile, + { filename: 'report.xlsx' }, + h( + ExcelSheet, + { data: () => people, name: 'Computed' }, + h(ExcelColumn, { label: 'Upper', value: (r) => r.name.toUpperCase() }), + h(ExcelColumn, { label: 'Double', value: (r) => r.age * 2 }), + ), + ), + }, + { + // dataSet: object columns (default 80 px, explicit wch/wpx), header style replacing the bold, + // styled cells in xlsx-style keys, number formats, null cells, dates. + name: 'dataset-styles', + element: h( + ExcelFile, + { filename: 'styled', fileExtension: 'xlsx' }, + h(ExcelSheet, { + name: 'Styled', + dataSet: [ + { + columns: [ + { title: 'Item' }, + { title: 'Qty', width: { wch: 12 } }, + { title: 'Price', width: { wpx: 120 }, style: { font: { color: { rgb: 'FFFF0000' } }, fill: { patternType: 'solid', fgColor: { rgb: 'FFFFFF00' } } } }, + { title: 'When' }, + ], + data: [ + [{ value: 'Pens', style: { font: { sz: '14', bold: true, name: 'Arial' } } }, 10, { value: 1.5, style: { numFmt: '0.00' } }, d(2024, 0, 15)], + ['Paper', { value: 3, style: { fill: { patternType: 'solid', fgColor: { rgb: 'FF00FF00' } }, alignment: { horizontal: 'right' } } }, null, d(2024, 11, 31, 18, 0)], + [{ value: true, style: { border: { top: { style: 'thin', color: { rgb: 'FF000000' } } } } }, 0, -2.25, null], + ], + }, + ], + }), + ), + }, + { + // Several blocks: xSteps/ySteps placement, the last block's widths written from column A, + // string columns (0.6.0 left these headers empty; see the legacy docs), empty columns. + name: 'dataset-blocks', + element: h( + ExcelFile, + { filename: 'blocks' }, + h(ExcelSheet, { + name: 'Blocks', + dataSet: [ + { ySteps: 1, columns: [{ title: 'A', width: { wpx: 50 } }, { title: 'B' }], data: [[1, 2], [3, 4]] }, + { xSteps: 1, ySteps: 2, columns: ['Name', 'Dept'], data: [['Johnson', 'Finance']] }, + { xSteps: 2, columns: [{ title: 'Last', width: { wch: 30 } }], data: [['z']] }, + { columns: [], data: [['no header', 5]] }, + ], + }), + ), + }, + { + // Several sheets, mixed shapes; an empty dataSet falls back to data + columns. + name: 'sheets-mixed', + element: h( + ExcelFile, + { filename: 'book' }, + h(ExcelSheet, { name: 'First', data: people }, h(ExcelColumn, { label: 'Name', value: 'name' })), + h(ExcelSheet, { name: 'Second', dataSet: [{ columns: [{ title: 'X' }], data: [[1], [2]] }] }), + h(ExcelSheet, { name: 'Third', dataSet: [], data: [{ v: 'fallback' }] }, h(ExcelColumn, { label: 'V', value: 'v' })), + ), + }, + { + // fileExtension '' takes the extension from the filename (and still appends it). + name: 'filename-from-name', + element: h( + ExcelFile, + { filename: 'data.xlsx', fileExtension: '' }, + h(ExcelSheet, { name: 'S', data: [{ a: 1 }] }, h(ExcelColumn, { label: 'A', value: 'a' })), + ), + }, + ]; +} diff --git a/packages/react-data-export/tsdown.config.ts b/packages/react-data-export/tsdown.config.ts index 84b90e8..e14e66d 100644 --- a/packages/react-data-export/tsdown.config.ts +++ b/packages/react-data-export/tsdown.config.ts @@ -4,7 +4,7 @@ import { defineConfig, type UserConfig } from 'tsdown'; // declaration build does not depend on the TypeScript compiler API (TS 7 has // none). It also means every export needs an explicit type, including this one. const config: UserConfig = defineConfig({ - entry: ['src/index.ts'], + entry: ['src/index.ts', 'src/legacy.ts'], format: ['esm', 'cjs'], platform: 'neutral', target: 'es2020', @@ -15,6 +15,10 @@ const config: UserConfig = defineConfig({ // no shared chunks rolldown keeps it as the first statement of both builds, // but still warns MODULE_LEVEL_DIRECTIVE. Drop only that warning for that // directive; scripts/smoke.mjs fails if a built file stops starting with it. + // The legacy entry has named exports plus the 0.x default export, so CJS + // consumers get { default, ExcelFile, ... } (what bundlers and TypeScript's + // esModuleInterop expect). Say so explicitly instead of a MIXED_EXPORTS warning. + outputOptions: { exports: 'named' }, inputOptions(options) { const next = options.onLog; return { diff --git a/scripts/consumer-ts.mjs b/scripts/consumer-ts.mjs index 7570925..5f40ba0 100644 --- a/scripts/consumer-ts.mjs +++ b/scripts/consumer-ts.mjs @@ -55,6 +55,7 @@ if (values.tarball) { const tsx = `import { useRef, type ReactElement } from 'react'; import { ExcelExport, ExportTableButton, exportDataset, exportTable, isExcelError, sanitizeSheetName, useExcelExport, useTableExport, version } from 'react-data-export'; import type { FromTableOptions, TableRef } from 'react-data-export'; +import ReactExport, { ExcelColumn, ExcelSheet, convertLegacyStyle, type ExcelSheetData, type LegacyStyle } from 'react-data-export/legacy'; import type { CellInput, CsvWriteOptions, Dataset, ExportResult, Style, WriteOptions } from 'react-data-export'; interface Row { name: string; n: number } @@ -118,10 +119,32 @@ export const wrong: Dataset = { columns: [{ title: 'x', value: (r) => r.mis export const notNumber: number = version; // @ts-expect-error not a fromTable option value export const badHeader: FromTableOptions = { header: 'tbody' }; +// The 0.x API through react-data-export/legacy (deprecated, supported in 1.x). +const { ExcelFile } = ReactExport; +const legacySheet: ExcelSheetData = { xSteps: 1, ySteps: 2, columns: ['Name', { title: 'Age', width: { wpx: 80 } }], data: [['Ada', 36], [{ value: 'x', style: { font: { sz: '12' } } }, null]] }; +export function Legacy(): ReactElement { + return ( + Download}> + + + r.name.toUpperCase()} /> + + + + ); +} +export const legacyStyle: LegacyStyle = { fill: { patternType: 'solid', fgColor: { rgb: 'FFFF0000' } } }; +export const converted: Style = convertLegacyStyle(legacyStyle); +// @ts-expect-error ExcelColumn needs a label +export const noLabel: ReactElement = ; // @ts-expect-error tableRef is required export const noRef: ReactElement = ; `; const cts = `import { exportWorkbook, sanitizeSheetName, version } from 'react-data-export'; +import ReactExport, { convertLegacyStyle, type ExcelSheetData } from 'react-data-export/legacy'; +export const legacyFile: unknown = ReactExport.ExcelFile.ExcelSheet; +export const blocks: ExcelSheetData[] = [{ columns: [{ title: 'A' }], data: [[1]] }]; +export const size: number | undefined = convertLegacyStyle({ font: { sz: 12 } }).font?.size; import type { ExportResult, Style, WorkbookSpec } from 'react-data-export'; const spec: WorkbookSpec = { sheets: [{ name: 'A', columns: [{ title: 'A' }], data: [[1]] }, false] }; diff --git a/scripts/legacy-goldens.mjs b/scripts/legacy-goldens.mjs new file mode 100644 index 0000000..71f66be --- /dev/null +++ b/scripts/legacy-goldens.mjs @@ -0,0 +1,57 @@ +// Regenerates packages/react-data-export/test/legacy/goldens-0.6.json from the +// real react-data-export@0.6.0, so the react-data-export/legacy tests compare +// against what 0.6 actually built, not against a reading of its source. +// +// mkdir -p /some/dir && cd /some/dir +// npm install --ignore-scripts react-data-export@0.6.0 react@16.14.0 react-dom@16.14.0 prop-types@15 +// node scripts/legacy-goldens.mjs --pkg /some/dir +// +// For each scenario in test/legacy/scenarios.mjs it runs 0.6's own sheet +// building (ExcelFile#createSheetData + excelSheetFromAoA, or +// excelSheetFromDataSet), exactly as ExcelFile#download did before handing the +// workbook to tempa-xlsx, plus 0.6's file name logic. Nothing is downloaded. +import { createRequire } from 'node:module'; +import { writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; +import { pathToFileURL } from 'node:url'; + +const args = process.argv.slice(2); +const pkgDir = resolve(args[args.indexOf('--pkg') + 1] ?? ''); +const root = resolve(import.meta.dirname, '..'); +const out = join(root, 'packages/react-data-export/test/legacy/goldens-0.6.json'); + +const req = createRequire(join(pkgDir, 'noop.js')); +const React = req('react'); +const version = req('react-data-export/package.json').version; +if (version !== '0.6.0') throw new Error(`expected react-data-export@0.6.0 in ${pkgDir}, found ${version}`); +const ExcelFile = req('react-data-export/dist/ExcelPlugin/components/ExcelFile').default; +const ExcelSheet = req('react-data-export/dist/ExcelPlugin/elements/ExcelSheet').default; +const ExcelColumn = req('react-data-export/dist/ExcelPlugin/elements/ExcelColumn').default; +const { excelSheetFromAoA, excelSheetFromDataSet } = req('react-data-export/dist/ExcelPlugin/utils/DataUtil'); + +const { scenarios } = await import(pathToFileURL(join(root, 'packages/react-data-export/test/legacy/scenarios.mjs')).href); + +function normalizeSheet(ws) { + const cells = {}; + for (const [ref, cell] of Object.entries(ws)) { + if (ref.startsWith('!')) continue; + cells[ref] = { t: cell.t, v: cell.v === undefined ? null : cell.v, ...(cell.s ? { s: cell.s } : {}), ...(cell.z !== undefined ? { z: cell.z } : {}) }; + } + return { ref: ws['!ref'] ?? null, cols: ws['!cols'] ?? null, cells }; +} + +const goldens = {}; +for (const { name, element } of scenarios(React, { ExcelFile, ExcelSheet, ExcelColumn })) { + const props = { ...ExcelFile.defaultProps, ...element.props }; + const file = new ExcelFile(props); // hideElement is false in every scenario: nothing runs here + const sheets = []; + React.Children.forEach(props.children, (sheet) => { + const ds = sheet.props.dataSet; + const ws = typeof ds === 'undefined' || ds.length === 0 ? excelSheetFromAoA(file.createSheetData(sheet)) : excelSheetFromDataSet(ds); + sheets.push({ name: sheet.props.name, ...normalizeSheet(ws) }); + }); + goldens[name] = { fileName: file.getFileName(), fileExtension: file.getFileExtension(), sheets }; +} + +writeFileSync(out, `${JSON.stringify({ generatedFrom: `react-data-export@${version}`, goldens }, null, 2)}\n`); +console.log(`wrote ${Object.keys(goldens).length} scenarios to ${out}`); diff --git a/scripts/smoke.mjs b/scripts/smoke.mjs index 09b162f..16f00bd 100644 --- a/scripts/smoke.mjs +++ b/scripts/smoke.mjs @@ -28,7 +28,7 @@ try { const allowed = (p) => ['package.json', 'README.md', 'LICENSE'].includes(p) || p.startsWith('dist/'); const extra = files.filter((p) => !allowed(p)); if (extra.length) throw new Error(`unexpected files in tarball: ${extra.join(', ')}`); - for (const need of ['package.json', 'README.md', 'LICENSE', 'dist/index.js', 'dist/index.cjs', 'dist/index.d.ts', 'dist/index.d.cts']) { + for (const need of ['package.json', 'README.md', 'LICENSE', 'dist/index.js', 'dist/index.cjs', 'dist/index.d.ts', 'dist/index.d.cts', 'dist/legacy.js', 'dist/legacy.cjs', 'dist/legacy.d.ts', 'dist/legacy.d.cts']) { if (!files.includes(need)) throw new Error(`missing from tarball: ${need}`); } @@ -38,8 +38,8 @@ try { writeFileSync(join(app, 'package.json'), JSON.stringify({ name: 'smoke-app', private: true })); run('npm', ['install', '--no-audit', '--no-fund', '--loglevel=error', join(work, packed.filename), `react@${reactRange}`, `@types/react@${reactRange}`], app); - step('"use client" directive is the first statement of both builds'); - for (const f of ['dist/index.js', 'dist/index.cjs']) { + step('"use client" directive is the first statement of every entry'); + for (const f of ['dist/index.js', 'dist/index.cjs', 'dist/legacy.js', 'dist/legacy.cjs']) { const first = readFileSync(join(app, 'node_modules/react-data-export', f), 'utf8').split('\n', 1)[0].trim(); if (first !== '"use client";' && first !== "'use client';") throw new Error(`${f} starts with ${JSON.stringify(first)}, not "use client"`); } @@ -58,6 +58,39 @@ try { console.log('esm ok', version, r.filename, r.blob.size + ' bytes'); `], app).trim()); + step('main entry is free of the legacy code (tree-shaken: separate entry)'); + { + const pkgRoot = join(app, 'node_modules/react-data-export'); + // The main entry and every chunk it imports, transitively, in both formats. + for (const entry of ['dist/index.js', 'dist/index.cjs']) { + const seen = new Set(); + const queue = [entry]; + while (queue.length) { + const f = queue.shift(); + if (seen.has(f)) continue; + seen.add(f); + const code = readFileSync(join(pkgRoot, f), 'utf8'); + if (/ExcelFile|ExcelSheet|ExcelColumn|xSteps|convertLegacyStyle/.test(code)) throw new Error(`${f} (reached from ${entry}) contains legacy code`); + for (const m of code.matchAll(/(?:from |require\()["'](\.\/[^"']+)["']/g)) queue.push(join(dirname(f), m[1]).replace(/^\.\//, '')); + } + if (seen.has('dist/legacy.js') || seen.has('dist/legacy.cjs')) throw new Error(`${entry} imports the legacy entry`); + console.log(`${entry}: ${seen.size} file(s), no legacy code`); + } + } + + step('legacy entry: 0.x default import (ESM) and require (CJS)'); + console.log(run('node', ['--input-type=module', '-e', ` + import ReactExport, { ExcelFile, ExcelSheet, ExcelColumn, convertLegacyStyle } from 'react-data-export/legacy'; + if (ReactExport.ExcelFile !== ExcelFile || ExcelFile.ExcelSheet !== ExcelSheet || ExcelFile.ExcelColumn !== ExcelColumn) throw new Error('0.x default export shape'); + if (convertLegacyStyle({ font: { sz: '12' } }).font.size !== 12) throw new Error('convertLegacyStyle'); + console.log('legacy esm ok'); + `], app).trim()); + console.log(run('node', ['-e', ` + const legacy = require('react-data-export/legacy'); + if (legacy.default.ExcelFile !== legacy.ExcelFile || typeof legacy.ExcelFile.ExcelSheet !== 'function') throw new Error('0.x export shape (CJS)'); + console.log('legacy cjs ok'); + `], app).trim()); + step('CJS require'); console.log(run('node', ['-e', ` const { version, exportDataset, exportWorkbook, useExcelExport, ExcelExport, exportTable, useTableExport, ExportTableButton, isExcelError, sanitizeSheetName } = require('react-data-export');