Skip to content

Commit

Permalink
feat: code strongness improvement (#27)
Browse files Browse the repository at this point in the history
* chore: update to 1.2.8

* Update widget.config.json

* fix: add file

fix: add file

* fix: fix error

* fix: add
  • Loading branch information
ranglang committed Nov 23, 2023
1 parent 370c05d commit 52641af
Show file tree
Hide file tree
Showing 8 changed files with 61 additions and 43 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"version": "1.2.8",
"version": "1.2.9",
"description": "my apitable widget chart",
"engines": {
"node": ">=8.x"
Expand Down
13 changes: 7 additions & 6 deletions src/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { IDimensionMetricsMap, StackType } from './model/interface';
import { Strings, t } from './i18n';
import { sortBy } from './sortBy';
import { IOutputChartData, IOutputRecordData } from '../interface';
import {safeParseNumberOrText} from "./utils";

dayjs.extend(advancedFormat);
dayjs.extend(weekOfYear);
Expand Down Expand Up @@ -278,11 +279,11 @@ export const getFormatter = (field?: Field, times = 1) => {
// Currency/percentage needs to be signed.
if (field.formatType?.type === 'currency') {
const formatting = field.formatType.formatting as ICurrencyFormat;
return (val) => `${formatting.symbol} ${parseFloat(val).toFixed(formatting.precision)}`;
return (val) => `${formatting.symbol} ${safeParseNumberOrText(val, formatting.precision)}`;
}
if (field.formatType?.type === 'percent') {
const formatting = field.formatType.formatting as IPercentFormat;
return (val) => `${(parseFloat(val) * times).toFixed(formatting.precision)}%`;
return (val) => `${ safeParseNumberOrText((parseFloat(val) * times), formatting.precision)} %`;
}
// val is converted to a space when it contains '\n'.
return defaultFormatter;
Expand Down Expand Up @@ -315,7 +316,7 @@ export const formatterValue = (field, value, notFormatter = true): string | numb
const precision = property?.precision ?? property?.format?.format?.precision ?? 1;
if (isCurrency) {
try {
const textValue = isNumber(value) ? value.toFixed(precision) : parseFloat(value).toFixed(precision);
const textValue = isNumber(value) ? safeParseNumberOrText(value, precision) : safeParseNumberOrText(value, precision);
return `${fieldSymbol} ${textValue}`;
}catch (e) {
console.error('parse currency' , e);
Expand All @@ -326,7 +327,7 @@ export const formatterValue = (field, value, notFormatter = true): string | numb
// Percentages, numbers with units.
if (isPercent || isNumberType) {
const suffixSymbol = isPercent ? '%' : fieldSymbol;
return `${Number(value).toFixed(precision)} ${suffixSymbol}`;
return `${safeParseNumberOrText(value, precision)} ${suffixSymbol}`;
}

// Smart Formula Date, value is timestamp.
Expand Down Expand Up @@ -791,7 +792,7 @@ export const sortSeries = (props: {
const sortList = newData[i];
for (let j = 0; j < sortList.length; j++) {
const val = sortList[j][yKey];
sortList[j][yKey] = (val / sums[i] * 100).toFixed(2);
sortList[j][yKey] = safeParseNumberOrText(val / sums[i] * 100, 2);
}
}
}
Expand Down Expand Up @@ -840,7 +841,7 @@ export const sortSeries = (props: {
const valueIndex = isColumn ? 1 : 0;
const isEqualPrev = coordinate[coordinateIndex] === lastItem[coordinateIndex];
if (isEqualPrev) {
lastItem[valueIndex] = parseFloat((lastItem[valueIndex] + coordinate[valueIndex]).toFixed(metricsFieldPrecision));
lastItem[valueIndex] = parseFloat(safeParseNumberOrText(lastItem[valueIndex] + coordinate[valueIndex], metricsFieldPrecision));
} else {
seriesItem.series.push(coordinate);
}
Expand Down
7 changes: 4 additions & 3 deletions src/model/column.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ import { transformAnnotation } from '../helper';
import { Chart } from './base';
import { ChartType, StackType } from './interface';
import { Strings } from '../i18n';
import {safeParseNumberOrText} from "../utils";

/**
* The bar chart is equivalent to the base class of Cartesian coordinate system graphs.
* The bar chart is equivalent to the base class of Cartesian coordinate system graphs.
* Subsequent bar graphs \ line graphs \ scatter are based on this graph.
*/
export class ColumnChart extends Chart {
Expand Down Expand Up @@ -84,7 +85,7 @@ export class ColumnChart extends Chart {
};
if (this.stackType === StackType.Percent) {
styleOptions.label.content = (item) => {
return `${(100 * item[dimensionMetricsMap.metrics.key])?.toFixed(2)}%`;
return `${safeParseNumberOrText((100 * item[dimensionMetricsMap.metrics.key]), 2) }%`;
};
}
}
Expand Down Expand Up @@ -116,4 +117,4 @@ export class ColumnChart extends Chart {
};
return res;
}
}
}
30 changes: 15 additions & 15 deletions src/model/echarts_pie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { ChartType, StackType } from './interface';
import { Strings, t } from '../i18n';
import { sortBy } from '../sortBy';
import { getNumberBaseFieldPrecision, maxRenderNum, processChartData, processRecords } from '../helper';
import { safeParseNumberOrText } from '../utils';

export class EchartsPie extends EchartsBase {
type = ChartType.EchartsPie;
Expand All @@ -15,29 +16,29 @@ export class EchartsPie extends EchartsBase {
add(arg1, arg2) {
let len1, len2, expand, subLen;
try {
len1 = arg1.toString().split(".")[1].length;
len1 = arg1.toString().split('.')[1].length;
} catch (e) {
len1 = 0;
}
try {
len2 = arg2.toString().split(".")[1].length;
len2 = arg2.toString().split('.')[1].length;
} catch (e) {
len2 = 0;
}
subLen = Math.abs(len1 - len2);
expand = Math.pow(10, Math.max(len1, len2));
if (subLen > 0) {
let scale = Math.pow(10, subLen);
const scale = Math.pow(10, subLen);
if (len1 > len2) {
arg1 = Number(arg1.toString().replace(".", ""));
arg2 = Number(arg2.toString().replace(".", "")) * scale;
arg1 = Number(arg1.toString().replace('.', ''));
arg2 = Number(arg2.toString().replace('.', '')) * scale;
} else {
arg1 = Number(arg1.toString().replace(".", "")) * scale;
arg2 = Number(arg2.toString().replace(".", ""));
arg1 = Number(arg1.toString().replace('.', '')) * scale;
arg2 = Number(arg2.toString().replace('.', ''));
}
} else {
arg1 = Number(arg1.toString().replace(".", ""));
arg2 = Number(arg2.toString().replace(".", ""));
arg1 = Number(arg1.toString().replace('.', ''));
arg2 = Number(arg2.toString().replace('.', ''));
}
return (arg1 + arg2) / expand;
}
Expand Down Expand Up @@ -86,8 +87,7 @@ export class EchartsPie extends EchartsBase {
label: {
...color,
show: showDataTips,
formatter: (params) => `${params.name}: ${params.percent.toFixed(1)} %`
// formatter: (params) => `${params.name}: ${Number(params.value / dataSum * 100).toFixed(2)}%`
formatter: (params) => `${params.name}: ${safeParseNumberOrText(params.percent, 1)} %`
},
},
};
Expand All @@ -108,7 +108,7 @@ export class EchartsPie extends EchartsBase {
// const totalContent = Math.round(params.value / (params.percent / 100));
// console.log(totalContent, params.value / (params.percent / 100));
// return `{a|${t(Strings.total)}}\n{b|${totalContent}}`;
return `{a|${t(Strings.total)}}\n{b|${dataSum.toFixed(fieldPrecision)}}`;
return `{a|${t(Strings.total)}}\n{b|${safeParseNumberOrText(dataSum, fieldPrecision)}}`;
},
// formatter: () => {
// const precision = guessNumberFieldPrecision(data.map(item => item.value).filter(Boolean));
Expand All @@ -117,7 +117,7 @@ export class EchartsPie extends EchartsBase {
// return `{a|${t(Strings.total)}}\n{b|${totalContent}}`;
// },
rich: {
a: { fontSize: 18, height: 24, },
a: { fontSize: 18, height: 24 },
b: { fontSize: 24, fontWeight: 'bolder' }
}
},
Expand All @@ -132,7 +132,7 @@ export class EchartsPie extends EchartsBase {
label: {
...styleOption.series.label,
formatter: (params) => {
return `${params.name}: ${params.percent.toFixed(1)}%`
return `${params.name}: ${safeParseNumberOrText(params.percent, 1)}%`;
}
}
};
Expand Down Expand Up @@ -203,7 +203,7 @@ export class EchartsPie extends EchartsBase {
return {
...options,
series: [
{ ...styleOption.series, data},
{ ...styleOption.series, data },
{ ...styleOption.stackSeries, data }
]
};
Expand Down
7 changes: 4 additions & 3 deletions src/model/echarts_scatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Strings, t } from "../i18n";
import { METRICS_TYPES } from '../const';
import { ChartType, StackType } from "./interface";
import { EchartsBase } from './echarts_base';
import {safeParseNumberOrText} from "../utils";

export class EchartsScatter extends EchartsBase {
type = ChartType.EchartsScatter;
Expand Down Expand Up @@ -124,7 +125,7 @@ export class EchartsScatter extends EchartsBase {
const shouldFormatDatetime = isFormatDatetime && dimensionField?.formatType?.type === 'datetime';

const countTotalRecords = metricsType === 'COUNT_RECORDS';

// Whether the y-axis text field needs to be formatted.
const noFormatMetric = metricsType === 'COUNT_RECORDS' || this.stackType === StackType.Percent;

Expand Down Expand Up @@ -171,7 +172,7 @@ export class EchartsScatter extends EchartsBase {
data = rows.map(row => {
let metricsValue = row.metrics;
if (!isNumber(metricsValue)) {
// Switching field types can cause this result. With a value of 0,
// Switching field types can cause this result. With a value of 0,
// the chart does not crash, the form form will give a prompt.
metricsValue = 0;
}
Expand All @@ -183,7 +184,7 @@ export class EchartsScatter extends EchartsBase {
const precision = metricsField?.property?.precision ?? metricsField?.fieldData?.property?.formatting?.precision
return {
[dimensionMetricsMap.dimension.key]: dimensionValue,
[dimensionMetricsMap.metrics.key]: parseFloat(metricsValue?.toFixed(precision)),
[dimensionMetricsMap.metrics.key]: parseFloat(safeParseNumberOrText(metricsValue, precision)),
};
}).filter(item => item != null);
}
Expand Down
11 changes: 7 additions & 4 deletions src/model/pie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import sum from 'lodash/sum';
import { processChartData, processRecords, guessNumberFieldPrecision } from '../helper';
import { Chart } from './base';
import { ChartType, StackType } from './interface';
import { safeParseNumberOrText } from '../utils';

export class PieChart extends Chart {
type = ChartType.Pie;
Expand Down Expand Up @@ -49,7 +50,8 @@ export class PieChart extends Chart {
style: { display: 'unset' },
customHtml: (container: HTMLElement, view, datum: object, data: object[]) => {
const precision = guessNumberFieldPrecision(data.map(item => (item as any).angleField).filter(Boolean));
const totalValue = sum(data.map(item => (item as any).angleField)).toFixed(precision);
const totalValue = safeParseNumberOrText(sum(data.map(item => (item as any).angleField)), precision);
// .toFixed(precision);
const totalContent = totalValue + '';
// const containerWidth = parseInt(container.style.width);
// const fontSize = containerWidth / totalContent.length * 0.7;
Expand Down Expand Up @@ -144,7 +146,7 @@ export class PieChart extends Chart {
return angleValue;
});
/**
* Sorting from smallest to largest will cause the labels to squeeze on the top border of
* Sorting from smallest to largest will cause the labels to squeeze on the top border of
* the chart because the smaller categories are displayed centrally in the 12-point direction.
* The largest category needs to be rotated to 12 o'clock. Achieve a better visual display.
* [0,1,2,20,30,100] => [100,0,1,2,20,30]
Expand All @@ -167,7 +169,8 @@ export class PieChart extends Chart {
[dimensionMetricsMap.metrics.key]: {
alias: metricsName,
formatter: v => {
return v?.toFixed(isCountRecords ? 0 : getNumberBaseFieldPrecision(metricsField))
return safeParseNumberOrText(v, isCountRecords ? 0 : getNumberBaseFieldPrecision(metricsField));
// v?.toFixed()
},
},
COUNT_RECORDS: {
Expand All @@ -191,4 +194,4 @@ export class PieChart extends Chart {
return options;
}

}
}
10 changes: 5 additions & 5 deletions src/model/scatter.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { Strings } from '../i18n';
import { Field, Record, t } from '@apitable/widget-sdk';
import { themesMap } from '../theme';
import groupBy from 'lodash/groupBy';
import groupBy from 'lodash/groupBy';
import isNumber from 'lodash/isNumber';
import { METRICS_TYPES } from '../const';
import { formatDatetime, getAggregationValue, getFormatter, getNumberBaseFieldPrecision, processChartDataSort, processRecords } from '../helper';
import { ColumnChart } from './column';
import { ChartType, StackType } from './interface';
import {safeParseNumberOrText} from "../utils";

export class ScatterChart extends ColumnChart {
type = ChartType.Scatter;
Expand Down Expand Up @@ -147,7 +148,7 @@ export class ScatterChart extends ColumnChart {
data = rows.map(row => {
let metricsValue = row.metrics;
if (!isNumber(metricsValue)) {
// Switching field types can cause this result. With a value of 0, the chart does not crash,
// Switching field types can cause this result. With a value of 0, the chart does not crash,
// the form form will give a prompt.
metricsValue = 0;
}
Expand All @@ -157,8 +158,7 @@ export class ScatterChart extends ColumnChart {
if (!isCountNullValue && dimensionValue === t(Strings.null)) return null;
return {
[dimensionMetricsMap.dimension.key]: dimensionValue,
[dimensionMetricsMap.metrics.key]: parseFloat(metricsValue?.toFixed(metricsField?.property?.precision)),
// [seriesField]: seriesFieldInstance?.convertCellValueToString(row.series) || t(Strings.null),
[dimensionMetricsMap.metrics.key]: parseFloat(safeParseNumberOrText(metricsValue, metricsField?.property?.precision)),
};
}).filter(item => item != null);
}
Expand Down Expand Up @@ -210,4 +210,4 @@ export class ScatterChart extends ColumnChart {
};
return options;
}
}
}
24 changes: 18 additions & 6 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ export function listenDOMSize(dom: React.RefObject<HTMLElement>) {
}
}
handle = requestAnimationFrame(() => listen(callback));
};
}

function addListen(callback) {
handle = requestAnimationFrame(() => listen(callback));
}
Expand All @@ -26,7 +26,7 @@ export function listenDOMSize(dom: React.RefObject<HTMLElement>) {
cancelAnimationFrame(handle);
}

return { addListen, removeListen }
return { addListen, removeListen };
}

const MIN_CHAR_SIZE = 12;
Expand All @@ -46,7 +46,7 @@ class CanvasUtils {
setCanvasSize = (width, height) => {
this.canvas.width = width;
this.canvas.height = height;
}
};

calcSize = (texts: string[], isColumn: boolean, axisItemWidth: number) => {
const { canvas, ctx } = this;
Expand Down Expand Up @@ -75,7 +75,19 @@ class CanvasUtils {
perSize: maxWidth ? axisItemWidth : perSize, // If you need to rotate, take the set width directly.
interval
};
}
};
}

export const canvasUtilsIns = new CanvasUtils();
export const canvasUtilsIns = new CanvasUtils();

export const safeParseNumberOrText = (num : number | string | undefined, precision: number) => {
if(!num) {
return '';
}

const a = Number(num);
if(isNaN(a)) {
return '';
}
return a.toFixed(precision);
};

0 comments on commit 52641af

Please sign in to comment.