Skip to content
This repository has been archived by the owner on Jun 25, 2020. It is now read-only.

Commit

Permalink
refactor(clean the code): clean the code
Browse files Browse the repository at this point in the history
  • Loading branch information
Conglei Shi committed Aug 12, 2019
1 parent 861e3db commit 393733e
Show file tree
Hide file tree
Showing 10 changed files with 292 additions and 153 deletions.
2 changes: 1 addition & 1 deletion packages/superset-ui-plugin-chart-table/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"access": "public"
},
"dependencies": {
"@airbnb/lunar": "^1.8.1",
"@airbnb/lunar": "^1.11.0",
"@airbnb/lunar-icons": "^1.1.1"
},
"peerDependencies": {
Expand Down
44 changes: 30 additions & 14 deletions packages/superset-ui-plugin-chart-table/src/Table.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import React from 'react';
import DataTable from '@airbnb/lunar/lib/components/DataTable';
import Text from '@airbnb/lunar/lib/components/Text';
import Input from '@airbnb/lunar/lib/components/Input';
import withStyles, { css, WithStylesProps } from '@airbnb/lunar/lib/composers/withStyles';
import { Renderers, ParentRow } from '@airbnb/lunar/lib/components/DataTable/types';
import { Renderers, ParentRow, ColumnMetadata } from '@airbnb/lunar/lib/components/DataTable/types';
import { getRenderer, ColumnType, heightType, Cell } from './renderer';

type Props = {
Expand Down Expand Up @@ -84,7 +85,6 @@ class TableVis extends React.PureComponent<InternalTableProps, TableState> {
};

handleSearch = (value: string) => {
console.log(value);
const { searchKeyword } = this.state;
const { data } = this.props;
if (searchKeyword !== value) {
Expand All @@ -94,7 +94,6 @@ class TableVis extends React.PureComponent<InternalTableProps, TableState> {
.toLowerCase();
return content.indexOf(value) >= 0;
});
console.log(filteredRows);
this.setState({
searchKeyword: value,
filteredRows,
Expand Down Expand Up @@ -142,8 +141,7 @@ class TableVis extends React.PureComponent<InternalTableProps, TableState> {
const renderers: Renderers = {};

const dataToRender = searchKeyword !== '' ? filteredRows : data;

console.log(dataToRender);
const columnMetadata: ColumnMetadata = {};

columns.forEach(column => {
renderers[column.key] = getRenderer({
Expand All @@ -154,24 +152,35 @@ class TableVis extends React.PureComponent<InternalTableProps, TableState> {
isSelected: this.isSelected,
handleCellSelected: this.handleCellSelected,
});
if (column.type == 'metric') {
columnMetadata[column.key] = {
rightAlign: 1,
};
}
});

return (
<React.Fragment>
{includeSearch && (
<div {...css(styles.searchBar)}>
<Input
name="search"
label=""
placeholder="Search"
onChange={this.handleSearch}
compact
value={searchKeyword}
/>
<div {...css(styles.searchBox)}>
<Input
name="search"
label=""
placeholder="Search"
onChange={this.handleSearch}
compact
value={searchKeyword}
/>
</div>
<Text small>
Showing {dataToRender.length} out of {data.length} rows
</Text>
</div>
)}
<DataTable
data={dataToRender}
columnMetadata={columnMetadata}
zebra
rowHeight={heightType}
renderers={renderers}
Expand All @@ -182,9 +191,16 @@ class TableVis extends React.PureComponent<InternalTableProps, TableState> {
}
}

export default withStyles(() => ({
export default withStyles(({ unit }) => ({
searchBar: {
display: 'flex',
flexGrow: 0,
flexDirection: 'row-reverse',
marginBottom: unit,
alignItems: 'baseline',
},
searchBox: {
width: 25 * unit,
marginLeft: unit,
},
}))(TableVis);
131 changes: 21 additions & 110 deletions packages/superset-ui-plugin-chart-table/src/legacy/transformProps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,10 @@
*/
/* eslint-disable sort-keys */

import { ChartProps, FormDataMetric, Metric } from '@superset-ui/chart';
import { getNumberFormatter, NumberFormats, NumberFormatter } from '@superset-ui/number-format';
import { getTimeFormatter, TimeFormatter } from '@superset-ui/time-format';

const DTTM_ALIAS = '__timestamp';

type PlainObject = {
[key: string]: any;
};
import { ChartProps } from '@superset-ui/chart';
import processColumns from '../processColumns';
import processMetrics from '../processMetrics';
import processData from '../processData';

export default function transformProps(chartProps: ChartProps) {
const { height, datasource, filters, formData, onAddFilter, payload } = chartProps;
Expand All @@ -42,116 +37,32 @@ export default function transformProps(chartProps: ChartProps) {
tableTimestampFormat,
timeseriesLimitMetric,
} = formData;
const { columnFormats, verboseMap } = datasource;
const { records, columns } = payload.data;

const metrics = ((rawMetrics as FormDataMetric[]) || [])
.map(m => (m as Metric).label || (m as string))
// Add percent metrics
.concat(((percentMetrics as string[]) || []).map(m => `%${m}`))
// Removing metrics (aggregates) that are strings
.filter(m => typeof records[0][m as string] === 'number');

const dataArray: {
[key: string]: any[];
} = {};

const sortByKey =
timeseriesLimitMetric &&
((timeseriesLimitMetric as Metric).label || (timeseriesLimitMetric as string));

let formattedData: {
data: PlainObject;
}[] = records.map((row: PlainObject) => ({
data: row,
}));

if (sortByKey) {
formattedData = formattedData.sort((a, b) => {
const delta = a.data[sortByKey] - b.data[sortByKey];
if (orderDesc) {
return -delta;
}
return delta;
});
if (metrics.indexOf(sortByKey) < 0) {
formattedData = formattedData.map(row => {
const data = { ...row.data };
delete data[sortByKey];
return {
data,
};
});
}
}

metrics.forEach(metric => {
const arr = [];
for (let i = 0; i < records.length; i += 1) {
arr.push(records[i][metric]);
}

dataArray[metric] = arr;
const metrics = processMetrics({
metrics: rawMetrics,
percentMetrics,
records,
});

const maxes: {
[key: string]: number;
} = {};
const mins: {
[key: string]: number;
} = {};

for (let i = 0; i < metrics.length; i += 1) {
maxes[metrics[i]] = Math.max(...dataArray[metrics[i]]);
mins[metrics[i]] = Math.min(...dataArray[metrics[i]]);
}

const formatPercent = getNumberFormatter(NumberFormats.PERCENT_3_POINT);
const tsFormatter = getTimeFormatter(tableTimestampFormat);

const processedColumns = columns.map((key: string) => {
let label = verboseMap[key];
let formatString = columnFormats && columnFormats[key];
let formatFunction: NumberFormatter | TimeFormatter | undefined;
let type = 'string';

// Handle verbose names for percents
if (!label) {
if (key[0] === '%') {
const cleanedKey = key.substring(1);
label = `% ${verboseMap[cleanedKey] || cleanedKey}`;
formatFunction = formatPercent;
} else {
label = key;
}
}

if (key === DTTM_ALIAS) {
formatFunction = tsFormatter;
}

const extraField: {
[key: string]: any;
} = {};
const processedData = processData({
timeseriesLimitMetric,
orderDesc,
records,
metrics,
});

if (metrics.indexOf(key) >= 0) {
formatFunction = getNumberFormatter(formatString);
type = 'metric';
extraField['maxValue'] = maxes[key];
extraField['minValue'] = mins[key];
}
return {
key,
label,
format: formatFunction,
type,
...extraField,
};
const processedColumns = processColumns({
columns,
metrics,
records,
tableTimestampFormat,
datasource,
});

return {
height,
data: formattedData,
data: processedData,
alignPositiveNegative: alignPn,
colorPositiveNegative: colorPn,
columns: processedColumns,
Expand Down
92 changes: 92 additions & 0 deletions packages/superset-ui-plugin-chart-table/src/processColumns.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { getNumberFormatter, NumberFormats, NumberFormatter } from '@superset-ui/number-format';
import { getTimeFormatter, TimeFormatter } from '@superset-ui/time-format';
import { PlainObject } from './types';

const DTTM_ALIAS = '__timestamp';

export default function processColumns({
columns,
metrics,
records,
tableTimestampFormat,
datasource,
}: {
columns: string[];
metrics: string[];
records: any[];
tableTimestampFormat: string;
datasource: PlainObject;
}) {
const { columnFormats, verboseMap } = datasource;

const dataArray: {
[key: string]: any[];
} = {};

metrics.forEach(metric => {
const arr = [];
for (let i = 0; i < records.length; i += 1) {
arr.push(records[i][metric]);
}

dataArray[metric] = arr;
});

const maxes: {
[key: string]: number;
} = {};
const mins: {
[key: string]: number;
} = {};

for (let i = 0; i < metrics.length; i += 1) {
maxes[metrics[i]] = Math.max(...dataArray[metrics[i]]);
mins[metrics[i]] = Math.min(...dataArray[metrics[i]]);
}

const formatPercent = getNumberFormatter(NumberFormats.PERCENT_3_POINT);
const tsFormatter = getTimeFormatter(tableTimestampFormat);

const processedColumns = columns.map((key: string) => {
let label = verboseMap[key];
let formatString = columnFormats && columnFormats[key];
let formatFunction: NumberFormatter | TimeFormatter | undefined;
let type = 'string';

if (key === DTTM_ALIAS) {
formatFunction = tsFormatter;
}

const extraField: {
[key: string]: any;
} = {};

if (metrics.indexOf(key) >= 0) {
formatFunction = getNumberFormatter(formatString);
type = 'metric';
extraField['maxValue'] = maxes[key];
extraField['minValue'] = mins[key];
}

// Handle verbose names for percents
if (!label) {
if (key[0] === '%') {
const cleanedKey = key.substring(1);
label = `% ${verboseMap[cleanedKey] || cleanedKey}`;
formatFunction = formatPercent;
} else {
label = key;
}
}

return {
key,
label,
format: formatFunction,
type,
...extraField,
};
});

return processedColumns;
}
Loading

0 comments on commit 393733e

Please sign in to comment.