@carbon/ibm-security
Version:
Carbon for Cloud & Cognitive IBM Security UI components
95 lines (93 loc) • 3.09 kB
JavaScript
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _iconsReact = require("@carbon/icons-react");
var _exportToCsv = require("export-to-csv");
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = _interopRequireDefault(require("react"));
var _IconButton = _interopRequireDefault(require("../IconButton"));
/**
* @file Table toolbar button for downloading table data as CSV
* @copyright IBM Security 2019 - 2021
*/
var options = {
fieldSeparator: ',',
quoteStrings: '"',
decimalSeparator: '.',
showLabels: true,
useTextFile: false,
useBom: true
};
var TableToolbarDownload = function TableToolbarDownload(_ref) {
var headers = _ref.headers,
rows = _ref.rows,
title = _ref.title,
filename = _ref.filename,
label = _ref.label;
var csvRows = rows.map(function (row) {
var newRow = {};
headers.forEach(function (_ref2) {
var key = _ref2.key;
newRow[key] = row[key] ? row[key] : '';
});
return newRow;
});
if (title) {
options.showTitle = true;
options.title = title;
}
options.filename = filename;
options.headers = headers.map(function (_ref3) {
var header = _ref3.header;
return header;
});
var csvExporter = new _exportToCsv.ExportToCsv(options);
return /*#__PURE__*/_react.default.createElement(_IconButton.default, {
size: "lg",
renderIcon: _iconsReact.Download16,
label: label,
onClick: function onClick() {
if (rows.length > 0 && headers.length > 0) {
csvExporter.generateCsv(csvRows);
}
}
});
};
TableToolbarDownload.propTypes = {
/** @type {string} the filename used for the generated CSV file */
filename: _propTypes.default.string,
/**
* @type {Record<string, any>}
* The `headers` prop represents the order in which the headers should
* appear in the table. We expect an array of objects to be passed in, where
* `key` is the name of the key in a row object, and `header` is the name of
* the header.
*/
headers: _propTypes.default.arrayOf(_propTypes.default.shape({
key: _propTypes.default.string.isRequired,
header: _propTypes.default.string.isRequired
})).isRequired,
/** @type {string} the aria-label for the button */
label: _propTypes.default.string,
/**
* @type {Record<string, any>}
* The `rows` prop is where you provide us with a list of all the rows that
* you want to render in the table. The only hard requirement is that this
* is an array of objects, and that each object has a unique `id` field
* available on it.
*/
rows: _propTypes.default.arrayOf(_propTypes.default.shape({
id: _propTypes.default.string.isRequired
})).isRequired,
/** @type {string} the title used for the generated CSV table */
title: _propTypes.default.string
};
TableToolbarDownload.defaultProps = {
title: '',
filename: 'DataTable',
label: 'Download'
};
var _default = exports.default = TableToolbarDownload;