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

[DataGrid] Add support for getRowsToExport option to print export #10084

Merged
Merged
Show file tree
Hide file tree
Changes from 8 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
14 changes: 12 additions & 2 deletions docs/data/data-grid/export/export.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ With `pageStyle` option, you can override the main content color with a [more sp

### Customize grid display

By default, the print export display all the DataGrid. It is possible to remove the footer and the toolbar by setting respectively `hideFooter` and `hideToolbar` to `true`.
By default, the print export displays all the DataGrid. It is possible to remove the footer and the toolbar by setting respectively `hideFooter` and `hideToolbar` to `true`.

```jsx
<GridToolbarExport
Expand All @@ -197,7 +197,17 @@ By default, the print export display all the DataGrid. It is possible to remove
/>
```

For more option to customize the print export, please visit the [`printOptions` API page](/x/api/data-grid/grid-print-export-options/).
If rows are selected when exporting, the checkboxes will not be included in the printed page. To export the checkboxes you can set `includeCheckboxes` to `true`.

```jsx
<GridToolbarExport
printOptions={{
includeCheckboxes: true,
}}
/>
```

For more options to customize the print export, please visit the [`printOptions` API page](/x/api/data-grid/grid-print-export-options/).

## Custom export format

Expand Down
22 changes: 12 additions & 10 deletions docs/pages/x/api/data-grid/grid-print-export-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,15 @@ import { GridPrintExportOptions } from '@mui/x-data-grid';

## Properties

| Name | Type | Default | Description |
| :---------------------------------------------------------------------------------------------- | :------------------------------------------------ | :------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------- |
| <span class="prop-name optional">allColumns<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">boolean</span> | <span class="prop-default">false</span> | If `true`, the hidden columns will also be exported. |
| <span class="prop-name optional">bodyClassName<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">string</span> | | One or more classes passed to the print window. |
| <span class="prop-name optional">copyStyles<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">boolean</span> | <span class="prop-default">true</span> | If `false`, all &lt;style&gt; and &lt;link type="stylesheet" /&gt; tags from the &lt;head&gt; will not be copied<br />to the print window. |
| <span class="prop-name optional">fields<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">string[]</span> | | The columns exported.<br />This should only be used if you want to restrict the columns exports. |
| <span class="prop-name optional">fileName<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">string</span> | <span class="prop-default">The title of the page.</span> | The value to be used as the print window title. |
| <span class="prop-name optional">hideFooter<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">boolean</span> | <span class="prop-default">false</span> | If `true`, the footer is removed for when printing. |
| <span class="prop-name optional">hideToolbar<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">boolean</span> | <span class="prop-default">false</span> | If `true`, the toolbar is removed for when printing. |
| <span class="prop-name optional">pageStyle<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">string \| Function</span> | | Provide Print specific styles to the print window. |
| Name | Type | Default | Description |
| :-------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------- | :------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------- |
| <span class="prop-name optional">allColumns<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">boolean</span> | <span class="prop-default">false</span> | If `true`, the hidden columns will also be exported. |
| <span class="prop-name optional">bodyClassName<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">string</span> | | One or more classes passed to the print window. |
| <span class="prop-name optional">copyStyles<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">boolean</span> | <span class="prop-default">true</span> | If `false`, all &lt;style&gt; and &lt;link type="stylesheet" /&gt; tags from the &lt;head&gt; will not be copied<br />to the print window. |
| <span class="prop-name optional">fields<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">string[]</span> | | The columns exported.<br />This should only be used if you want to restrict the columns exports. |
| <span class="prop-name optional">fileName<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">string</span> | <span class="prop-default">The title of the page.</span> | The value to be used as the print window title. |
| <span class="prop-name optional">getRowsToExport<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">(params: GridPrintGetRowsToExportParams) =&gt; GridRowId[]</span> | | Function that returns the id of the rows to export in the order they should be exported. |
| <span class="prop-name optional">hideFooter<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">boolean</span> | <span class="prop-default">false</span> | If `true`, the footer is removed for when printing. |
| <span class="prop-name optional">hideToolbar<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">boolean</span> | <span class="prop-default">false</span> | If `true`, the toolbar is removed for when printing. |
| <span class="prop-name optional">includeCheckboxes<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">boolean</span> | <span class="prop-default">false</span> | If `true`, the selection checkboxes will be included when printing. |
| <span class="prop-name optional">pageStyle<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">string \| Function</span> | | Provide Print specific styles to the print window. |
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import * as React from 'react';
import { unstable_ownerDocument as ownerDocument } from '@mui/utils';
import { GridPrivateApiCommunity } from '../../../models/api/gridApiCommunity';
import { GridApiCommunity, GridPrivateApiCommunity } from '../../../models/api/gridApiCommunity';
import { GridPrintExportApi } from '../../../models/api/gridPrintExportApi';
import { useGridLogger } from '../../utils/useGridLogger';
import { gridExpandedRowCountSelector } from '../filter/gridFilterSelector';
import { DataGridProcessedProps } from '../../../models/props/DataGridProps';
import { GridPrintExportOptions } from '../../../models/gridExport';
import { GridPrintExportOptions, GridPrintGetRowsToExportParams } from '../../../models/gridExport';
import { GridRowId, GridValidRowModel } from '../../../models/gridRows';
import { GridInitialStateCommunity } from '../../../models/gridStateCommunity';
import {
gridColumnDefinitionsSelector,
Expand All @@ -14,14 +15,15 @@ import {
import { gridClasses } from '../../../constants/gridClasses';
import { useGridApiMethod } from '../../utils/useGridApiMethod';
import { gridRowsMetaSelector } from '../rows/gridRowsMetaSelector';
import { getColumnsToExport } from './utils';
import { getColumnsToExport, defaultGetRowsToExport } from './utils';
import { mergeStateWithPaginationModel } from '../pagination/useGridPagination';
import { GridPipeProcessor, useGridRegisterPipeProcessor } from '../../core/pipeProcessing';
import {
GridExportDisplayOptions,
GridPrintExportMenuItem,
} from '../../../components/toolbar/GridToolbarExport';
import { getTotalHeaderHeight } from '../columns/gridColumnsUtils';
import { GRID_CHECKBOX_SELECTION_COL_DEF } from '../../../colDef/gridCheckboxSelectionColDef';

function raf() {
return new Promise<void>((resolve) => {
Expand All @@ -35,8 +37,14 @@ type PrintWindowOnLoad = (
printWindow: HTMLIFrameElement,
options?: Pick<
GridPrintExportOptions,
'copyStyles' | 'bodyClassName' | 'pageStyle' | 'hideToolbar' | 'hideFooter'
| 'copyStyles'
| 'bodyClassName'
| 'pageStyle'
| 'hideToolbar'
| 'hideFooter'
| 'includeCheckboxes'
>,
hasRowsSelected?: boolean,
) => void;

function buildPrintWindow(title?: string): HTMLIFrameElement {
Expand All @@ -62,6 +70,7 @@ export const useGridPrintExport = (
const doc = React.useRef<Document | null>(null);
const previousGridState = React.useRef<GridInitialStateCommunity | null>(null);
const previousColumnVisibility = React.useRef<{ [key: string]: boolean }>({});
const previousRows = React.useRef<GridValidRowModel[]>([]);

React.useEffect(() => {
doc.current = ownerDocument(apiRef.current.rootElementRef!.current!);
Expand All @@ -70,7 +79,7 @@ export const useGridPrintExport = (
// Returns a promise because updateColumns triggers state update and
// the new state needs to be in place before the grid can be sized correctly
const updateGridColumnsForPrint = React.useCallback(
(fields?: string[], allColumns?: boolean) =>
(fields?: string[], allColumns?: boolean, includeCheckboxes?: boolean) =>
new Promise<void>((resolve) => {
const exportedColumnFields = getColumnsToExport({
apiRef,
Expand All @@ -84,18 +93,37 @@ export const useGridPrintExport = (
newColumnVisibilityModel[column.field] = exportedColumnFields.includes(column.field);
});

if (includeCheckboxes) {
newColumnVisibilityModel[GRID_CHECKBOX_SELECTION_COL_DEF.field] = true;
}

apiRef.current.setColumnVisibilityModel(newColumnVisibilityModel);
resolve();
}),
[apiRef],
);

const updateGridRowsForPrint = React.useCallback(
(rowsToExport?: (params: GridPrintGetRowsToExportParams<GridApiCommunity>) => GridRowId[]) =>
new Promise<void>((resolve) => {
zreecespieces marked this conversation as resolved.
Show resolved Hide resolved
const getRowsToExport = rowsToExport ?? defaultGetRowsToExport;
const rowsToExportIds = getRowsToExport({ apiRef });

const newRows = rowsToExportIds.map((id) => apiRef.current.getRow(id));

apiRef.current.setRows(newRows);
resolve();
}),
[apiRef],
);

const handlePrintWindowLoad: PrintWindowOnLoad = React.useCallback(
(printWindow, options): void => {
(printWindow, options, hasRowsSelected): void => {
const normalizeOptions = {
copyStyles: true,
hideToolbar: false,
hideFooter: false,
includeCheckboxes: false,
...options,
};

Expand Down Expand Up @@ -141,15 +169,26 @@ export const useGridPrintExport = (
}

// Expand container height to accommodate all rows
gridClone.style.height = `${
const computedTotalHeight =
rowsMeta.currentPageTotalHeight +
getTotalHeaderHeight(apiRef, props.columnHeaderHeight) +
gridToolbarElementHeight +
gridFooterElementHeight
}px`;
gridFooterElementHeight;
gridClone.style.height = `${computedTotalHeight}px`;
// The height above does not include grid border width, so we need to exclude it
gridClone.style.boxSizing = 'content-box';

// the footer is always being placed at the bottom of the page as if all rows are exported
// so if there are rows selected it needs to be moved up to the correct position
if (hasRowsSelected) {
const gridFooterElement: HTMLElement | null = gridClone.querySelector(
`.${gridClasses.footerContainer}`,
);
gridFooterElement!.style.position = 'absolute';
gridFooterElement!.style.width = '100%';
gridFooterElement!.style.top = `${computedTotalHeight - gridFooterElementHeight}px`;
}

// printDoc.body.appendChild(gridClone); should be enough but a clone isolation bug in Safari
// prevents us to do it
const container = document.createElement('div');
Expand Down Expand Up @@ -245,10 +284,12 @@ export const useGridPrintExport = (
}

apiRef.current.unstable_enableVirtualization();
apiRef.current.setRows(previousRows.current);

// Clear local state
previousGridState.current = null;
previousColumnVisibility.current = {};
previousRows.current = [];
},
[apiRef],
);
Expand All @@ -264,6 +305,7 @@ export const useGridPrintExport = (
previousGridState.current = apiRef.current.exportState();
// It appends that the visibility model is not exported, especially if columnVisibility is not controlled
previousColumnVisibility.current = gridColumnVisibilityModelSelector(apiRef);
previousRows.current = apiRef.current.getSortedRows();

if (props.pagination) {
const visibleRowCount = gridExpandedRowCountSelector(apiRef);
Expand All @@ -279,18 +321,28 @@ export const useGridPrintExport = (
apiRef.current.forceUpdate();
}

await updateGridColumnsForPrint(options?.fields, options?.allColumns);
await updateGridColumnsForPrint(
options?.fields,
options?.allColumns,
options?.includeCheckboxes,
);

const hasSelectedRows = apiRef.current.getSelectedRows().size > 0;
if (hasSelectedRows) {
zreecespieces marked this conversation as resolved.
Show resolved Hide resolved
await updateGridRowsForPrint(options?.getRowsToExport);
}

apiRef.current.unstable_disableVirtualization();
await raf(); // wait for the state changes to take action
const printWindow = buildPrintWindow(options?.fileName);
if (process.env.NODE_ENV === 'test') {
doc.current!.body.appendChild(printWindow);
// In test env, run the all pipeline without waiting for loading
handlePrintWindowLoad(printWindow, options);
handlePrintWindowLoad(printWindow, options, hasSelectedRows);
handlePrintWindowAfterPrint(printWindow);
} else {
printWindow.onload = () => {
handlePrintWindowLoad(printWindow, options);
handlePrintWindowLoad(printWindow, options, hasSelectedRows);

const mediaQueryList = printWindow.contentWindow!.matchMedia('print');
mediaQueryList.addEventListener('change', (mql) => {
Expand All @@ -310,6 +362,7 @@ export const useGridPrintExport = (
handlePrintWindowLoad,
handlePrintWindowAfterPrint,
updateGridColumnsForPrint,
updateGridRowsForPrint,
],
);

Expand Down
14 changes: 14 additions & 0 deletions packages/grid/x-data-grid/src/models/gridExport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ export interface GridGetRowsToExportParams<Api extends GridApiCommon = GridApiCo
export interface GridCsvGetRowsToExportParams<Api extends GridApiCommon = GridApiCommunity>
extends GridGetRowsToExportParams<Api> {}

export interface GridPrintGetRowsToExportParams<Api extends GridApiCommon = GridApiCommunity>
extends GridGetRowsToExportParams<Api> {}

/**
* The options to apply on the CSV export.
* @demos
Expand Down Expand Up @@ -115,6 +118,11 @@ export interface GridPrintExportOptions extends GridExportOptions {
* @default false
*/
hideFooter?: boolean;
/**
* If `true`, the selection checkboxes will be included when printing.
* @default false
*/
includeCheckboxes?: boolean;
/**
* If `false`, all <style> and <link type="stylesheet" /> tags from the <head> will not be copied
* to the print window.
Expand All @@ -129,6 +137,12 @@ export interface GridPrintExportOptions extends GridExportOptions {
* Provide Print specific styles to the print window.
*/
pageStyle?: string | Function;
/**
* Function that returns the id of the rows to export in the order they should be exported.
* @param {GridPrintGetRowsToExportParams} params With all properties from [[GridPrintGetRowsToExportParams]].
* @returns {GridRowId[]} The id of the rows to export.
*/
getRowsToExport?: (params: GridPrintGetRowsToExportParams) => GridRowId[];
}

/**
Expand Down