Skip to content

Commit

Permalink
remove total func and percentage col
Browse files Browse the repository at this point in the history
total func and percentage col are two features that we might
need to remove or re-invent for future table vis. For hookup
purpose, it doesn't make sense to include some features that
we would like to remove.

this PR removes total func and percentage col in both table
vis and vis builder

Signed-off-by: Anan Zhuang <ananzh@amazon.com>
  • Loading branch information
ananzh committed Nov 3, 2022
1 parent a52185d commit 43aa08f
Show file tree
Hide file tree
Showing 6 changed files with 4 additions and 266 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,55 +11,17 @@ import produce from 'immer';
import { Draft } from 'immer';
import { EuiIconTip } from '@elastic/eui';
import { search } from '../../../../../data/public';
import { NumberInputOption, SwitchOption, SelectOption } from '../../../../../charts/public';
import { NumberInputOption, SwitchOption } from '../../../../../charts/public';
import {
useTypedDispatch,
useTypedSelector,
setStyleState,
} from '../../../application/utils/state_management';
import { useAggs } from '../../../../public/application/utils/use';
import { TableOptionsDefaults } from '../table_viz_type';
import { Option } from '../../../application/app';
import { AggTypes } from '../types';

const { tabifyGetColumns } = search;

const totalAggregations = [
{
value: AggTypes.SUM,
text: i18n.translate('visTypeTableNew.totalAggregations.sumText', {
defaultMessage: 'Sum',
}),
},
{
value: AggTypes.AVG,
text: i18n.translate('visTypeTableNew.totalAggregations.averageText', {
defaultMessage: 'Average',
}),
},
{
value: AggTypes.MIN,
text: i18n.translate('visTypeTableNewNew.totalAggregations.minText', {
defaultMessage: 'Min',
}),
},
{
value: AggTypes.MAX,
text: i18n.translate('visTypeTableNewNew.totalAggregations.maxText', {
defaultMessage: 'Max',
}),
},
{
value: AggTypes.COUNT,
text: i18n.translate('visTypeTableNewNew.totalAggregations.countText', {
defaultMessage: 'Count',
}),
},
];

function TableVizOptions() {
const styleState = useTypedSelector((state) => state.style) as TableOptionsDefaults;
const { aggConfigs } = useAggs();
const dispatch = useTypedDispatch();

const setOption = useCallback(
Expand All @@ -70,35 +32,6 @@ function TableVizOptions() {
[dispatch, styleState]
);

const percentageColumns = useMemo(() => {
const defaultPercentageColText = {
value: '',
text: i18n.translate('visTypeTableNew.params.defaultPercentageCol', {
defaultMessage: 'Don’t show',
}),
};
return aggConfigs
? [
defaultPercentageColText,
...tabifyGetColumns(aggConfigs.getResponseAggs(), true)
.filter((col) => get(col.aggConfig.toSerializedFieldFormat(), 'id') === 'number')
.map(({ name }) => ({ value: name, text: name })),
]
: [defaultPercentageColText];
}, [aggConfigs]);

useEffect(() => {
if (
!percentageColumns.find(({ value }) => value === styleState.percentageCol) &&
percentageColumns[0] &&
percentageColumns[0].value !== styleState.percentageCol
) {
setOption((draft) => {
draft.percentageCol = percentageColumns[0].value;
});
}
}, [percentageColumns, styleState.percentageCol, setOption]);

const isPerPageValid = styleState.perPage === '' || styleState.perPage > 0;

return (
Expand Down Expand Up @@ -168,49 +101,6 @@ function TableVizOptions() {
}
data-test-subj="showPartialRows"
/>

<SwitchOption
label={i18n.translate('visTypeTableNewNew.params.showTotalLabel', {
defaultMessage: 'Show total',
})}
paramName="showTotal"
value={styleState.showTotal}
setValue={(_, value) =>
setOption((draft) => {
draft.showTotal = value;
})
}
/>

<SelectOption
label={i18n.translate('visTypeTableNewNew.params.totalFunctionLabel', {
defaultMessage: 'Total function',
})}
disabled={!styleState.showTotal}
options={totalAggregations}
paramName="totalFunc"
value={styleState.totalFunc}
setValue={(_, value) =>
setOption((draft) => {
draft.totalFunc = value;
})
}
/>

<SelectOption
label={i18n.translate('visTypeTableNewNew.params.PercentageColLabel', {
defaultMessage: 'Percentage column',
})}
options={percentageColumns}
paramName="percentageCol"
value={styleState.percentageCol}
setValue={(_, value) =>
setOption((draft) => {
draft.percentageCol = value;
})
}
id="datatableVisualizationPercentageCol"
/>
</Option>
</>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,11 @@ import { AggGroupNames } from '../../../../data/public';
import { TableVizOptions } from './components/table_viz_options';
import { VisualizationTypeOptions } from '../../services/type_service';
import { toExpression } from './to_expression';
import { AggTypes } from './types';

export interface TableOptionsDefaults {
perPage: number | '';
showPartialRows: boolean;
showMetricsAtAllLevels: boolean;
showTotal: boolean;
totalFunc: AggTypes;
percentageCol: string;
}

export const createTableConfig = (): VisualizationTypeOptions<TableOptionsDefaults> => ({
Expand Down Expand Up @@ -91,9 +87,6 @@ export const createTableConfig = (): VisualizationTypeOptions<TableOptionsDefaul
perPage: 10,
showPartialRows: false,
showMetricsAtAllLevels: false,
showTotal: false,
totalFunc: AggTypes.SUM,
percentageCol: '',
},
render: TableVizOptions,
},
Expand Down
12 changes: 0 additions & 12 deletions src/plugins/vis_builder/public/visualizations/table/types.ts

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -103,13 +103,6 @@ export const TableVisComponent = ({

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

const footerCellValue = visConfig.showTotal
? ({ columnId }: { columnId: any }) => {
const colIndex = columns.findIndex((col) => col.id === columnId);
return columns[colIndex]?.formattedTotal || null;
}
: undefined;

return (
<>
{title && (
Expand All @@ -134,7 +127,6 @@ export const TableVisComponent = ({
header: 'underline',
}}
minSizeForControls={1}
renderFooterCellValue={footerCellValue}
toolbarVisibility={{
showColumnSelector: false,
showSortSelector: false,
Expand Down
14 changes: 0 additions & 14 deletions src/plugins/vis_type_table_new/public/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,6 @@
import { SchemaConfig } from 'src/plugins/visualizations/public';
import { IFieldFormat } from 'src/plugins/data/public';

export enum AggTypes {
SUM = 'sum',
AVG = 'avg',
MIN = 'min',
MAX = 'max',
COUNT = 'count',
}

export interface TableVisConfig extends TableVisParams {
title: string;
metrics: SchemaConfig[];
Expand All @@ -51,19 +43,13 @@ export interface TableVisParams {
perPage: number | '';
showPartialRows: boolean;
showMetricsAtAllLevels: boolean;
showTotal: boolean;
totalFunc: AggTypes;
percentageCol: string;
}

export interface FormattedColumn {
id: string;
title: string;
formatter: IFieldFormat;
filterable: boolean;
formattedTotal?: string | number;
sumTotal?: number;
total?: number;
}

export interface ColumnWidth {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,54 +28,11 @@
* under the License.
*/

import { i18n } from '@osd/i18n';
import { chain } from 'lodash';
import { OpenSearchDashboardsDatatableRow } from 'src/plugins/expressions';
import { Table } from '../table_vis_response_handler';
import { AggTypes, TableVisConfig } from '../types';
import { TableVisConfig } from '../types';
import { getFormatService } from '../services';
import { FormattedColumn } from '../types';

function insert(arr: FormattedColumn[], index: number, col: FormattedColumn) {
const newArray = [...arr];
newArray.splice(index + 1, 0, col);
return newArray;
}

/**
* @param columns - the formatted columns that will be displayed
* @param title - the title of the column to add to
* @param rows - the row data for the columns
* @param insertAtIndex - the index to insert the percentage column at
* @returns cols and rows for the table to render now included percentage column(s)
*/
function addPercentageCol(
columns: FormattedColumn[],
title: string,
rows: Table['rows'],
insertAtIndex: number
) {
const { id, sumTotal } = columns[insertAtIndex];
const newId = `${id}-percents`;
const formatter = getFormatService().deserialize({ id: 'percent' });
const i18nTitle = i18n.translate('visTypeTableNew.params.percentageTableColumnName', {
defaultMessage: '{title} percentages',
values: { title },
});
const newCols = insert(columns, insertAtIndex, {
title: i18nTitle,
id: newId,
formatter,
filterable: false,
});
const newRows = rows.map((row) => ({
[newId]: (row[id] as number) / (sumTotal as number),
...row,
}));

return { cols: newCols, rows: newRows };
}

export interface FormattedDataProps {
formattedRows: OpenSearchDashboardsDatatableRow[];
formattedColumns: FormattedColumn[];
Expand All @@ -86,8 +43,8 @@ export const convertToFormattedData = (
visConfig: TableVisConfig
): FormattedDataProps => {
const { buckets, metrics } = visConfig;
let formattedRows: OpenSearchDashboardsDatatableRow[] = table.rows;
let formattedColumns: FormattedColumn[] = table.columns
const formattedRows: OpenSearchDashboardsDatatableRow[] = table.rows;
const formattedColumns: FormattedColumn[] = table.columns
.map(function (col, i) {
const isBucket = buckets.find((bucket) => bucket.accessor === i);
const dimension = isBucket || metrics.find((metric) => metric.accessor === i);
Expand All @@ -103,77 +60,9 @@ export const convertToFormattedData = (
filterable: !!isBucket,
};

const isDate = dimension?.format?.id === 'date' || dimension?.format?.params?.id === 'date';
const allowsNumericalAggregations = formatter?.allowsNumericalAggregations;

if (allowsNumericalAggregations || isDate || visConfig.totalFunc === AggTypes.COUNT) {
const sum = table.rows.reduce((prev, curr) => {
// some metrics return undefined for some of the values
// derivative is an example of this as it returns undefined in the first row
if (curr[col.id] === undefined) return prev;
return prev + (curr[col.id] as number);
}, 0);

formattedColumn.sumTotal = sum;
switch (visConfig.totalFunc) {
case AggTypes.SUM: {
if (!isDate) {
formattedColumn.formattedTotal = formatter?.convert(sum);
formattedColumn.total = formattedColumn.sumTotal;
}
break;
}
case AggTypes.AVG: {
if (!isDate) {
const total = sum / table.rows.length;
formattedColumn.formattedTotal = formatter?.convert(total);
formattedColumn.total = total;
}
break;
}
case AggTypes.MIN: {
const total = chain(table.rows).map(col.id).min().value() as number;
formattedColumn.formattedTotal = formatter?.convert(total);
formattedColumn.total = total;
break;
}
case AggTypes.MAX: {
const total = chain(table.rows).map(col.id).max().value() as number;
formattedColumn.formattedTotal = formatter?.convert(total);
formattedColumn.total = total;
break;
}
case 'count': {
const total = table.rows.length;
formattedColumn.formattedTotal = total;
formattedColumn.total = total;
break;
}
default:
break;
}
}

return formattedColumn;
})
.filter((column): column is FormattedColumn => !!column);

if (visConfig.percentageCol) {
const insertAtIndex = formattedColumns.findIndex(
(col) => col.title === visConfig.percentageCol
);

// column to show percentage for was removed
if (insertAtIndex < 0) return { formattedRows, formattedColumns };

const { cols, rows } = addPercentageCol(
formattedColumns,
visConfig.percentageCol,
table.rows,
insertAtIndex
);
formattedRows = rows;
formattedColumns = cols;
}
return { formattedRows, formattedColumns };
};

0 comments on commit 43aa08f

Please sign in to comment.