|
| 1 | +/** |
| 2 | + * Copyright (c) 2025, RTE (http://www.rte-france.com) |
| 3 | + * This Source Code Form is subject to the terms of the Mozilla Public |
| 4 | + * License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 | + * file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 6 | + */ |
| 7 | + |
| 8 | +import { useCallback } from 'react'; |
| 9 | +import { ProcessCellForExportParams, ProcessHeaderForExportParams } from 'ag-grid-community'; |
| 10 | +import { useIntl, IntlShape } from 'react-intl'; |
| 11 | +import { CsvDownloadProps } from './csv-export.type'; |
| 12 | +import { LANG_FRENCH } from '../../utils'; |
| 13 | + |
| 14 | +const NA_VALUE = 'N/A'; |
| 15 | + |
| 16 | +const formatNAValue = (value: string, intl: IntlShape): string => { |
| 17 | + return value === NA_VALUE ? intl.formatMessage({ id: 'export/undefined' }) : value; |
| 18 | +}; |
| 19 | + |
| 20 | +export const useCsvExport = () => { |
| 21 | + const intl = useIntl(); |
| 22 | + |
| 23 | + const getCSVFilename = useCallback((tableName: string) => { |
| 24 | + return tableName |
| 25 | + .trim() |
| 26 | + .replace(/[\\/:"*?<>|\s]/g, '-') // Removes the filesystem sensible characters |
| 27 | + .substring(0, 27); // Best practice : limits the filename size to 31 characters (27+'.csv') |
| 28 | + }, []); |
| 29 | + |
| 30 | + const downloadCSVData = useCallback( |
| 31 | + (props: CsvDownloadProps) => { |
| 32 | + const hasColId = (colId: string | undefined): colId is string => { |
| 33 | + return colId !== undefined; |
| 34 | + }; |
| 35 | + |
| 36 | + const processCell = (params: ProcessCellForExportParams): string => { |
| 37 | + if (params.column.getColId() === 'limitName') { |
| 38 | + return formatNAValue(params.value, intl); |
| 39 | + } |
| 40 | + |
| 41 | + // If the language is in French, we change the decimal separator |
| 42 | + if (props.language === LANG_FRENCH && typeof params.value === 'number') { |
| 43 | + return params.value.toString().replace('.', ','); |
| 44 | + } |
| 45 | + return params.value; |
| 46 | + }; |
| 47 | + const prefix = props.tableNamePrefix ?? ''; |
| 48 | + |
| 49 | + props.exportDataAsCsv({ |
| 50 | + suppressQuotes: false, |
| 51 | + columnSeparator: props.language === LANG_FRENCH ? ';' : ',', |
| 52 | + columnKeys: props.columns.map((col) => col.colId).filter(hasColId), |
| 53 | + skipColumnHeaders: props.skipColumnHeaders, |
| 54 | + processHeaderCallback: (params: ProcessHeaderForExportParams) => |
| 55 | + params.column.getColDef().headerComponentParams?.displayName ?? |
| 56 | + params.column.getColDef().headerName ?? |
| 57 | + params.column.getColId(), |
| 58 | + fileName: prefix.concat(getCSVFilename(props.tableName)), |
| 59 | + processCellCallback: processCell, |
| 60 | + }); |
| 61 | + }, |
| 62 | + [getCSVFilename, intl] |
| 63 | + ); |
| 64 | + |
| 65 | + return { downloadCSVData }; |
| 66 | +}; |
0 commit comments