Skip to content

Commit

Permalink
[Table Visualization]restore export csv feature to table vis
Browse files Browse the repository at this point in the history
* add addtional action in toolbar to allow export data to csv.
there are two types of csv, raw and formatted. raw is the original
data and formatted is to show formatted Date and percentage data
when needed.
* when table is not saved, export csv file will be named as
unsaved-raw.csv if choose raw. when table is saved with a filename,
it will be saved as [filename]-[raw/formatted].csv

Partically resolved:
opensearch-project#2379

Signed-off-by: Anan Zhuang <ananzh@amazon.com>
  • Loading branch information
ananzh committed Oct 13, 2022
1 parent 7e969bc commit 91caca9
Show file tree
Hide file tree
Showing 6 changed files with 166 additions and 3 deletions.
1 change: 1 addition & 0 deletions src/plugins/vis_type_table/opensearch_dashboards.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"opensearchDashboardsUtils",
"opensearchDashboardsReact",
"charts",
"share",
"visDefaultEditor"
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,21 @@ import { TableVisConfig, ColumnWidth, SortColumn } from '../types';
import { getDataGridColumns } from './table_vis_grid_columns';
import { usePagination } from '../utils';
import { convertToFormattedData } from '../utils/convert_to_formatted_data';
import { TableVisControl } from './table_vis_control';

interface TableVisComponentProps {
title?: string;
table: Table;
visConfig: TableVisConfig;
handlers: IInterpreterRenderHandlers;
}

export const TableVisComponent = ({ table, visConfig, handlers }: TableVisComponentProps) => {
export const TableVisComponent = ({
title,
table,
visConfig,
handlers,
}: TableVisComponentProps) => {
const { formattedRows: rows, formattedColumns: columns } = convertToFormattedData(
table,
visConfig
Expand All @@ -32,7 +39,7 @@ export const TableVisComponent = ({ table, visConfig, handlers }: TableVisCompon
const currentColState = useRef<{
columnsWidth: ColumnWidth[];
}>({
columnsWidth: handlers.uiState.get('vis.columnsWidth'),
columnsWidth: handlers.uiState.get('vis.columnsWidth') || [],
});

const sortedRows = useMemo(() => {
Expand Down Expand Up @@ -97,9 +104,11 @@ export const TableVisComponent = ({ table, visConfig, handlers }: TableVisCompon
[columns, currentColState, handlers.uiState]
);

const ariaLabel = title || visConfig.title || 'tableVis';

return (
<EuiDataGrid
aria-label="tableVis"
aria-label={ariaLabel}
columns={dataGridColumns}
columnVisibility={{
visibleColumns: columns.map(({ id }) => id),
Expand All @@ -110,6 +119,15 @@ export const TableVisComponent = ({ table, visConfig, handlers }: TableVisCompon
sorting={{ columns: sortedColumns, onSort }}
onColumnResize={onColumnResize}
pagination={pagination}
toolbarVisibility={{
showColumnSelector: false,
showSortSelector: false,
showFullScreenSelector: false,
showStyleSelector: false,
additionalControls: (
<TableVisControl filename={visConfig.title} rows={sortedRows} columns={columns} />
),
}}
/>
);
};
57 changes: 57 additions & 0 deletions src/plugins/vis_type_table/public/components/table_vis_control.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/

import React, { useState } from 'react';
import { EuiPopover, EuiButtonEmpty, EuiContextMenuPanel, EuiContextMenuItem } from '@elastic/eui';
import { OpenSearchDashboardsDatatableRow } from 'src/plugins/expressions';
import { CoreStart } from 'opensearch-dashboards/public';
import { exportAsCsv } from '../utils/convert_to_csv_data';
import { FormattedColumn } from '../types';
import { useOpenSearchDashboards } from '../../../../../src/plugins/opensearch_dashboards_react/public';

interface TableVisControlProps {
filename?: string;
rows: OpenSearchDashboardsDatatableRow[];
columns: FormattedColumn[];
}

export const TableVisControl = (props: TableVisControlProps) => {
const {
services: { uiSettings },
} = useOpenSearchDashboards<CoreStart>();
const [isPopoverOpen, setPopover] = useState(false);

return (
<EuiPopover
id="dataTableExportData"
button={
<EuiButtonEmpty size="xs" iconType="download" onClick={() => setPopover((open) => !open)}>
Export
</EuiButtonEmpty>
}
isOpen={isPopoverOpen}
closePopover={() => setPopover(false)}
panelPaddingSize="none"
>
<EuiContextMenuPanel
size="s"
items={[
<EuiContextMenuItem
key="rawCsv"
onClick={() => exportAsCsv(false, { ...props, uiSettings })}
>
Raw
</EuiContextMenuItem>,
<EuiContextMenuItem
key="formattedCsv"
onClick={() => exportAsCsv(true, { ...props, uiSettings })}
>
Formatted
</EuiContextMenuItem>,
]}
/>
</EuiPopover>
);
};
1 change: 1 addition & 0 deletions src/plugins/vis_type_table/public/to_ast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export const toExpressionAst = (vis: Vis, params: any) => {
const schemas = getVisSchemas(vis, params);

const tableData = {
title: vis.title,
metrics: schemas.metric,
buckets: schemas.bucket || [],
splitRow: schemas.split_row,
Expand Down
1 change: 1 addition & 0 deletions src/plugins/vis_type_table/public/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export enum AggTypes {
}

export interface TableVisConfig extends TableVisParams {
title: string;
metrics: SchemaConfig[];
buckets: SchemaConfig[];
splitRow?: SchemaConfig[];
Expand Down
85 changes: 85 additions & 0 deletions src/plugins/vis_type_table/public/utils/convert_to_csv_data.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Any modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/

/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import { isObject } from 'lodash';
// @ts-ignore
import { saveAs } from '@elastic/filesaver';
import { CoreStart } from 'opensearch-dashboards/public';
import { CSV_SEPARATOR_SETTING, CSV_QUOTE_VALUES_SETTING } from '../../../share/public';
import { OpenSearchDashboardsDatatable } from '../../../expressions/public';
import { FormattedColumn } from '../types';

const nonAlphaNumRE = /[^a-zA-Z0-9]/;
const allDoubleQuoteRE = /"/g;

interface CSVDataProps {
filename?: string;
rows: OpenSearchDashboardsDatatable['rows'];
columns: FormattedColumn[];
uiSettings: CoreStart['uiSettings'];
}

const toCsv = function (formatted: boolean, { rows, columns, uiSettings }: CSVDataProps) {
const separator = uiSettings.get(CSV_SEPARATOR_SETTING);
const quoteValues = uiSettings.get(CSV_QUOTE_VALUES_SETTING);

function escape(val: any) {
if (!formatted && isObject(val)) val = val.valueOf();
val = String(val);
if (quoteValues && nonAlphaNumRE.test(val)) {
val = '"' + val.replace(allDoubleQuoteRE, '""') + '"';
}
return val;
}

let csvRows: string[][] = [];
for (const row of rows) {
const rowArray = [];
for (const col of columns) {
const value = row[col.id];
const formattedValue =
formatted && col.formatter ? escape(col.formatter.convert(value)) : escape(value);
rowArray.push(formattedValue);
}
csvRows = [...csvRows, rowArray];
}

// add the columns to the rows
csvRows.unshift(columns.map((col) => escape(col.title)));

return csvRows.map((row) => row.join(separator) + '\r\n').join('');
};

export const exportAsCsv = function (formatted: boolean, csvData: CSVDataProps) {
const csv = new Blob([toCsv(formatted, csvData)], { type: 'text/csv;charset=utf-8' });
const type = formatted ? 'formatted' : 'raw';
if (csvData.filename) saveAs(csv, `${csvData.filename}-${type}.csv`);
else saveAs(csv, `unsaved-${type}.csv`);
};

0 comments on commit 91caca9

Please sign in to comment.