Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement download without react-dom/server #3613

Merged
merged 6 commits into from
Oct 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 8 additions & 27 deletions website/exportUtils.tsx
Original file line number Diff line number Diff line change
@@ -1,28 +1,17 @@
import { cloneElement } from 'react';
import type { ReactElement } from 'react';

import type { DataGridProps } from '../src';

export async function exportToCsv<R, SR>(
gridElement: ReactElement<DataGridProps<R, SR>>,
fileName: string
) {
const { head, body, foot } = await getGridContent(gridElement);
export function exportToCsv(gridEl: HTMLDivElement, fileName: string) {
const { head, body, foot } = getGridContent(gridEl);
const content = [...head, ...body, ...foot]
.map((cells) => cells.map(serialiseCellValue).join(','))
.join('\n');

downloadFile(fileName, new Blob([content], { type: 'text/csv;charset=utf-8;' }));
}

export async function exportToPdf<R, SR>(
gridElement: ReactElement<DataGridProps<R, SR>>,
fileName: string
) {
const [{ jsPDF }, autoTable, { head, body, foot }] = await Promise.all([
export async function exportToPdf(gridEl: HTMLDivElement, fileName: string) {
const { head, body, foot } = getGridContent(gridEl);
const [{ jsPDF }, { default: autoTable }] = await Promise.all([
import('jspdf'),
(await import('jspdf-autotable')).default,
await getGridContent(gridElement)
import('jspdf-autotable')
]);
const doc = new jsPDF({
orientation: 'l',
Expand All @@ -40,23 +29,15 @@ export async function exportToPdf<R, SR>(
doc.save(fileName);
}

async function getGridContent<R, SR>(gridElement: ReactElement<DataGridProps<R, SR>>) {
const { renderToStaticMarkup } = await import('react-dom/server');
const grid = document.createElement('div');
grid.innerHTML = renderToStaticMarkup(
cloneElement(gridElement, {
enableVirtualization: false
})
);

function getGridContent(gridEl: HTMLDivElement) {
return {
head: getRows('.rdg-header-row'),
body: getRows('.rdg-row:not(.rdg-summary-row)'),
foot: getRows('.rdg-summary-row')
};

function getRows(selector: string) {
return Array.from(grid.querySelectorAll<HTMLDivElement>(selector)).map((gridRow) => {
return Array.from(gridEl.querySelectorAll<HTMLDivElement>(selector)).map((gridRow) => {
return Array.from(gridRow.querySelectorAll<HTMLDivElement>('.rdg-cell')).map(
(gridCell) => gridCell.innerText
);
Expand Down
102 changes: 52 additions & 50 deletions website/routes/CommonFeatures.lazy.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useMemo, useState } from 'react';
import { createPortal } from 'react-dom';
import { useMemo, useRef, useState } from 'react';
import { createPortal, flushSync } from 'react-dom';
import { faker } from '@faker-js/faker';
import { createLazyFileRoute } from '@tanstack/react-router';
import { css } from '@linaria/core';
Expand All @@ -9,6 +9,7 @@ import DataGrid, {
SelectColumn,
textEditor,
type Column,
type DataGridHandle,
type SortColumn
} from '../../src';
import { textEditorClassname } from '../../src/editors/textEditor';
Expand Down Expand Up @@ -310,6 +311,8 @@ function CommonFeatures() {
const [rows, setRows] = useState(createRows);
const [sortColumns, setSortColumns] = useState<readonly SortColumn[]>([]);
const [selectedRows, setSelectedRows] = useState((): ReadonlySet<number> => new Set());
const [isExporting, setIsExporting] = useState(false);
const gridRef = useRef<DataGridHandle>(null);

const countries = useMemo((): readonly string[] => {
return [...new Set(rows.map((r) => r.country))].sort(new Intl.Collator().compare);
Expand Down Expand Up @@ -342,61 +345,60 @@ function CommonFeatures() {
});
}, [rows, sortColumns]);

const gridElement = (
<DataGrid
rowKeyGetter={rowKeyGetter}
columns={columns}
rows={sortedRows}
defaultColumnOptions={{
sortable: true,
resizable: true
}}
selectedRows={selectedRows}
onSelectedRowsChange={setSelectedRows}
onRowsChange={setRows}
sortColumns={sortColumns}
onSortColumnsChange={setSortColumns}
topSummaryRows={summaryRows}
bottomSummaryRows={summaryRows}
className="fill-grid"
direction={direction}
/>
);
function handleExportToCsv() {
flushSync(() => {
setIsExporting(true);
});

exportToCsv(gridRef.current!.element!, 'CommonFeatures.csv');

flushSync(() => {
setIsExporting(false);
});
}

async function handleExportToPdf() {
flushSync(() => {
setIsExporting(true);
});

await exportToPdf(gridRef.current!.element!, 'CommonFeatures.pdf');

flushSync(() => {
setIsExporting(false);
});
}

return (
<>
<div className={toolbarClassname}>
<ExportButton onExport={() => exportToCsv(gridElement, 'CommonFeatures.csv')}>
<button type="button" onClick={handleExportToCsv}>
Export to CSV
</ExportButton>
<ExportButton onExport={() => exportToPdf(gridElement, 'CommonFeatures.pdf')}>
</button>
<button type="button" onClick={handleExportToPdf}>
Export to PDF
</ExportButton>
</button>
</div>
{gridElement}
<DataGrid
ref={gridRef}
rowKeyGetter={rowKeyGetter}
columns={columns}
rows={sortedRows}
defaultColumnOptions={{
sortable: true,
resizable: true
}}
selectedRows={selectedRows}
onSelectedRowsChange={setSelectedRows}
onRowsChange={setRows}
sortColumns={sortColumns}
onSortColumnsChange={setSortColumns}
topSummaryRows={summaryRows}
bottomSummaryRows={summaryRows}
className="fill-grid"
direction={direction}
enableVirtualization={!isExporting}
/>
</>
);
}

function ExportButton({
onExport,
children
}: {
onExport: () => Promise<unknown>;
children: React.ReactNode;
}) {
const [exporting, setExporting] = useState(false);
return (
<button
type="button"
disabled={exporting}
onClick={async () => {
setExporting(true);
await onExport();
setExporting(false);
}}
>
{exporting ? 'Exporting' : children}
</button>
);
}