From 5acb5ba20cd500df58ce5fae29f3605464866014 Mon Sep 17 00:00:00 2001 From: Amir Fefer Date: Wed, 6 Sep 2023 11:45:48 +0300 Subject: [PATCH] feat(HMS-1897): add export to csv btn to instances table --- src/Components/InstancesTable/helpers.js | 26 +++++++++++++++ src/Components/InstancesTable/index.js | 41 +++++++++++++++--------- 2 files changed, 52 insertions(+), 15 deletions(-) diff --git a/src/Components/InstancesTable/helpers.js b/src/Components/InstancesTable/helpers.js index b4896d6a..c9def358 100644 --- a/src/Components/InstancesTable/helpers.js +++ b/src/Components/InstancesTable/helpers.js @@ -12,3 +12,29 @@ export const SSHUsername = (provider) => { ''; } }; + +const flattenInstances = (instances) => { + return instances.map(({ instance_id, detail }) => ({ id: instance_id, ...detail })); +}; +const convertToCSV = (objArray) => { + const flatten = flattenInstances(objArray); + const header = Object.keys(flatten[0]); + const csv = flatten.map((row) => header.map((fieldName) => JSON.stringify(row[fieldName])).join(',')); + csv.unshift(header.join(',')); + return csv.join('\r\n'); +}; + +export const exportToCSV = (data) => { + const csv = convertToCSV(data); + const blob = new Blob([csv], { type: 'text/csv' }); + const url = window.URL.createObjectURL(blob); + const a = document.createElement('a'); + a.style.display = 'none'; + a.href = url; + a.download = 'instances.csv'; + document.body.appendChild(a); + a.click(); + + window.URL.revokeObjectURL(url); + document.body.removeChild(a); +}; diff --git a/src/Components/InstancesTable/index.js b/src/Components/InstancesTable/index.js index a46a123e..4426ed43 100644 --- a/src/Components/InstancesTable/index.js +++ b/src/Components/InstancesTable/index.js @@ -1,11 +1,11 @@ import PropTypes from 'prop-types'; import React from 'react'; import { TableComposable, Thead, Tr, Th, Tbody, Td } from '@patternfly/react-table'; -import { ExternalLinkAltIcon } from '@patternfly/react-icons'; -import { Button, ClipboardCopy, Card, Pagination, Spinner, Bullseye } from '@patternfly/react-core'; +import { ExternalLinkAltIcon, DownloadIcon } from '@patternfly/react-icons'; +import { Toolbar, ToolbarItem, ToolbarContent, Button, ClipboardCopy, Pagination, Spinner, Bullseye } from '@patternfly/react-core'; import { useQuery } from '@tanstack/react-query'; -import { SSHUsername } from './helpers'; +import { SSHUsername, exportToCSV } from './helpers'; import { instanceLink, humanizeInstanceID } from '../Common/instanceHelpers'; import { fetchReservationByProvider } from '../../API'; @@ -39,17 +39,28 @@ const InstancesTable = ({ reservationID, provider, region }) => { ); return ( - - + <> + + + + + + + + + + @@ -99,7 +110,7 @@ const InstancesTable = ({ reservationID, provider, region }) => { ))} - + ); };