Skip to content

Commit 073c8c8

Browse files
auto: apply newest APITable commit
1 parent 39da187 commit 073c8c8

7 files changed

Lines changed: 60 additions & 42 deletions

File tree

src/helper.ts

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import { IDimensionMetricsMap, StackType } from './model/interface';
2121
import { Strings, t } from './i18n';
2222
import { sortBy } from './sortBy';
2323
import { IOutputChartData, IOutputRecordData } from '../interface';
24+
import {safeParseNumberOrText} from "./utils";
2425

2526
dayjs.extend(advancedFormat);
2627
dayjs.extend(weekOfYear);
@@ -278,11 +279,11 @@ export const getFormatter = (field?: Field, times = 1) => {
278279
// Currency/percentage needs to be signed.
279280
if (field.formatType?.type === 'currency') {
280281
const formatting = field.formatType.formatting as ICurrencyFormat;
281-
return (val) => `${formatting.symbol} ${parseFloat(val).toFixed(formatting.precision)}`;
282+
return (val) => `${formatting.symbol} ${safeParseNumberOrText(val, formatting.precision)}`;
282283
}
283284
if (field.formatType?.type === 'percent') {
284285
const formatting = field.formatType.formatting as IPercentFormat;
285-
return (val) => `${(parseFloat(val) * times).toFixed(formatting.precision)}%`;
286+
return (val) => `${ safeParseNumberOrText((parseFloat(val) * times), formatting.precision)} %`;
286287
}
287288
// val is converted to a space when it contains '\n'.
288289
return defaultFormatter;
@@ -315,7 +316,7 @@ export const formatterValue = (field, value, notFormatter = true): string | numb
315316
const precision = property?.precision ?? property?.format?.format?.precision ?? 1;
316317
if (isCurrency) {
317318
try {
318-
const textValue = isNumber(value) ? value.toFixed(precision) : parseFloat(value).toFixed(precision);
319+
const textValue = isNumber(value) ? safeParseNumberOrText(value, precision) : safeParseNumberOrText(value, precision);
319320
return `${fieldSymbol} ${textValue}`;
320321
}catch (e) {
321322
console.error('parse currency' , e);
@@ -326,7 +327,7 @@ export const formatterValue = (field, value, notFormatter = true): string | numb
326327
// Percentages, numbers with units.
327328
if (isPercent || isNumberType) {
328329
const suffixSymbol = isPercent ? '%' : fieldSymbol;
329-
return `${Number(value).toFixed(precision)} ${suffixSymbol}`;
330+
return `${safeParseNumberOrText(value, precision)} ${suffixSymbol}`;
330331
}
331332

332333
// Smart Formula Date, value is timestamp.
@@ -791,7 +792,7 @@ export const sortSeries = (props: {
791792
const sortList = newData[i];
792793
for (let j = 0; j < sortList.length; j++) {
793794
const val = sortList[j][yKey];
794-
sortList[j][yKey] = (val / sums[i] * 100).toFixed(2);
795+
sortList[j][yKey] = safeParseNumberOrText(val / sums[i] * 100, 2);
795796
}
796797
}
797798
}
@@ -840,7 +841,7 @@ export const sortSeries = (props: {
840841
const valueIndex = isColumn ? 1 : 0;
841842
const isEqualPrev = coordinate[coordinateIndex] === lastItem[coordinateIndex];
842843
if (isEqualPrev) {
843-
lastItem[valueIndex] = parseFloat((lastItem[valueIndex] + coordinate[valueIndex]).toFixed(metricsFieldPrecision));
844+
lastItem[valueIndex] = parseFloat(safeParseNumberOrText(lastItem[valueIndex] + coordinate[valueIndex], metricsFieldPrecision));
844845
} else {
845846
seriesItem.series.push(coordinate);
846847
}

src/model/column.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@ import { transformAnnotation } from '../helper';
33
import { Chart } from './base';
44
import { ChartType, StackType } from './interface';
55
import { Strings } from '../i18n';
6+
import {safeParseNumberOrText} from "../utils";
67

78
/**
8-
* The bar chart is equivalent to the base class of Cartesian coordinate system graphs.
9+
* The bar chart is equivalent to the base class of Cartesian coordinate system graphs.
910
* Subsequent bar graphs \ line graphs \ scatter are based on this graph.
1011
*/
1112
export class ColumnChart extends Chart {
@@ -84,7 +85,7 @@ export class ColumnChart extends Chart {
8485
};
8586
if (this.stackType === StackType.Percent) {
8687
styleOptions.label.content = (item) => {
87-
return `${(100 * item[dimensionMetricsMap.metrics.key])?.toFixed(2)}%`;
88+
return `${safeParseNumberOrText((100 * item[dimensionMetricsMap.metrics.key]), 2) }%`;
8889
};
8990
}
9091
}
@@ -116,4 +117,4 @@ export class ColumnChart extends Chart {
116117
};
117118
return res;
118119
}
119-
}
120+
}

src/model/echarts_pie.ts

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { ChartType, StackType } from './interface';
44
import { Strings, t } from '../i18n';
55
import { sortBy } from '../sortBy';
66
import { getNumberBaseFieldPrecision, maxRenderNum, processChartData, processRecords } from '../helper';
7+
import { safeParseNumberOrText } from '../utils';
78

89
export class EchartsPie extends EchartsBase {
910
type = ChartType.EchartsPie;
@@ -15,29 +16,29 @@ export class EchartsPie extends EchartsBase {
1516
add(arg1, arg2) {
1617
let len1, len2, expand, subLen;
1718
try {
18-
len1 = arg1.toString().split(".")[1].length;
19+
len1 = arg1.toString().split('.')[1].length;
1920
} catch (e) {
2021
len1 = 0;
2122
}
2223
try {
23-
len2 = arg2.toString().split(".")[1].length;
24+
len2 = arg2.toString().split('.')[1].length;
2425
} catch (e) {
2526
len2 = 0;
2627
}
2728
subLen = Math.abs(len1 - len2);
2829
expand = Math.pow(10, Math.max(len1, len2));
2930
if (subLen > 0) {
30-
let scale = Math.pow(10, subLen);
31+
const scale = Math.pow(10, subLen);
3132
if (len1 > len2) {
32-
arg1 = Number(arg1.toString().replace(".", ""));
33-
arg2 = Number(arg2.toString().replace(".", "")) * scale;
33+
arg1 = Number(arg1.toString().replace('.', ''));
34+
arg2 = Number(arg2.toString().replace('.', '')) * scale;
3435
} else {
35-
arg1 = Number(arg1.toString().replace(".", "")) * scale;
36-
arg2 = Number(arg2.toString().replace(".", ""));
36+
arg1 = Number(arg1.toString().replace('.', '')) * scale;
37+
arg2 = Number(arg2.toString().replace('.', ''));
3738
}
3839
} else {
39-
arg1 = Number(arg1.toString().replace(".", ""));
40-
arg2 = Number(arg2.toString().replace(".", ""));
40+
arg1 = Number(arg1.toString().replace('.', ''));
41+
arg2 = Number(arg2.toString().replace('.', ''));
4142
}
4243
return (arg1 + arg2) / expand;
4344
}
@@ -86,8 +87,7 @@ export class EchartsPie extends EchartsBase {
8687
label: {
8788
...color,
8889
show: showDataTips,
89-
formatter: (params) => `${params.name}: ${params.percent.toFixed(1)} %`
90-
// formatter: (params) => `${params.name}: ${Number(params.value / dataSum * 100).toFixed(2)}%`
90+
formatter: (params) => `${params.name}: ${safeParseNumberOrText(params.percent, 1)} %`
9191
},
9292
},
9393
};
@@ -108,7 +108,7 @@ export class EchartsPie extends EchartsBase {
108108
// const totalContent = Math.round(params.value / (params.percent / 100));
109109
// console.log(totalContent, params.value / (params.percent / 100));
110110
// return `{a|${t(Strings.total)}}\n{b|${totalContent}}`;
111-
return `{a|${t(Strings.total)}}\n{b|${dataSum.toFixed(fieldPrecision)}}`;
111+
return `{a|${t(Strings.total)}}\n{b|${safeParseNumberOrText(dataSum, fieldPrecision)}}`;
112112
},
113113
// formatter: () => {
114114
// const precision = guessNumberFieldPrecision(data.map(item => item.value).filter(Boolean));
@@ -117,7 +117,7 @@ export class EchartsPie extends EchartsBase {
117117
// return `{a|${t(Strings.total)}}\n{b|${totalContent}}`;
118118
// },
119119
rich: {
120-
a: { fontSize: 18, height: 24, },
120+
a: { fontSize: 18, height: 24 },
121121
b: { fontSize: 24, fontWeight: 'bolder' }
122122
}
123123
},
@@ -132,7 +132,7 @@ export class EchartsPie extends EchartsBase {
132132
label: {
133133
...styleOption.series.label,
134134
formatter: (params) => {
135-
return `${params.name}: ${params.percent.toFixed(1)}%`
135+
return `${params.name}: ${safeParseNumberOrText(params.percent, 1)}%`;
136136
}
137137
}
138138
};
@@ -203,7 +203,7 @@ export class EchartsPie extends EchartsBase {
203203
return {
204204
...options,
205205
series: [
206-
{ ...styleOption.series, data},
206+
{ ...styleOption.series, data },
207207
{ ...styleOption.stackSeries, data }
208208
]
209209
};

src/model/echarts_scatter.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { Strings, t } from "../i18n";
66
import { METRICS_TYPES } from '../const';
77
import { ChartType, StackType } from "./interface";
88
import { EchartsBase } from './echarts_base';
9+
import {safeParseNumberOrText} from "../utils";
910

1011
export class EchartsScatter extends EchartsBase {
1112
type = ChartType.EchartsScatter;
@@ -124,7 +125,7 @@ export class EchartsScatter extends EchartsBase {
124125
const shouldFormatDatetime = isFormatDatetime && dimensionField?.formatType?.type === 'datetime';
125126

126127
const countTotalRecords = metricsType === 'COUNT_RECORDS';
127-
128+
128129
// Whether the y-axis text field needs to be formatted.
129130
const noFormatMetric = metricsType === 'COUNT_RECORDS' || this.stackType === StackType.Percent;
130131

@@ -171,7 +172,7 @@ export class EchartsScatter extends EchartsBase {
171172
data = rows.map(row => {
172173
let metricsValue = row.metrics;
173174
if (!isNumber(metricsValue)) {
174-
// Switching field types can cause this result. With a value of 0,
175+
// Switching field types can cause this result. With a value of 0,
175176
// the chart does not crash, the form form will give a prompt.
176177
metricsValue = 0;
177178
}
@@ -183,7 +184,7 @@ export class EchartsScatter extends EchartsBase {
183184
const precision = metricsField?.property?.precision ?? metricsField?.fieldData?.property?.formatting?.precision
184185
return {
185186
[dimensionMetricsMap.dimension.key]: dimensionValue,
186-
[dimensionMetricsMap.metrics.key]: parseFloat(metricsValue?.toFixed(precision)),
187+
[dimensionMetricsMap.metrics.key]: parseFloat(safeParseNumberOrText(metricsValue, precision)),
187188
};
188189
}).filter(item => item != null);
189190
}

src/model/pie.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import sum from 'lodash/sum';
66
import { processChartData, processRecords, guessNumberFieldPrecision } from '../helper';
77
import { Chart } from './base';
88
import { ChartType, StackType } from './interface';
9+
import { safeParseNumberOrText } from '../utils';
910

1011
export class PieChart extends Chart {
1112
type = ChartType.Pie;
@@ -49,7 +50,8 @@ export class PieChart extends Chart {
4950
style: { display: 'unset' },
5051
customHtml: (container: HTMLElement, view, datum: object, data: object[]) => {
5152
const precision = guessNumberFieldPrecision(data.map(item => (item as any).angleField).filter(Boolean));
52-
const totalValue = sum(data.map(item => (item as any).angleField)).toFixed(precision);
53+
const totalValue = safeParseNumberOrText(sum(data.map(item => (item as any).angleField)), precision);
54+
// .toFixed(precision);
5355
const totalContent = totalValue + '';
5456
// const containerWidth = parseInt(container.style.width);
5557
// const fontSize = containerWidth / totalContent.length * 0.7;
@@ -144,7 +146,7 @@ export class PieChart extends Chart {
144146
return angleValue;
145147
});
146148
/**
147-
* Sorting from smallest to largest will cause the labels to squeeze on the top border of
149+
* Sorting from smallest to largest will cause the labels to squeeze on the top border of
148150
* the chart because the smaller categories are displayed centrally in the 12-point direction.
149151
* The largest category needs to be rotated to 12 o'clock. Achieve a better visual display.
150152
* [0,1,2,20,30,100] => [100,0,1,2,20,30]
@@ -167,7 +169,8 @@ export class PieChart extends Chart {
167169
[dimensionMetricsMap.metrics.key]: {
168170
alias: metricsName,
169171
formatter: v => {
170-
return v?.toFixed(isCountRecords ? 0 : getNumberBaseFieldPrecision(metricsField))
172+
return safeParseNumberOrText(v, isCountRecords ? 0 : getNumberBaseFieldPrecision(metricsField));
173+
// v?.toFixed()
171174
},
172175
},
173176
COUNT_RECORDS: {
@@ -191,4 +194,4 @@ export class PieChart extends Chart {
191194
return options;
192195
}
193196

194-
}
197+
}

src/model/scatter.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
import { Strings } from '../i18n';
22
import { Field, Record, t } from '@apitable/widget-sdk';
33
import { themesMap } from '../theme';
4-
import groupBy from 'lodash/groupBy';
4+
import groupBy from 'lodash/groupBy';
55
import isNumber from 'lodash/isNumber';
66
import { METRICS_TYPES } from '../const';
77
import { formatDatetime, getAggregationValue, getFormatter, getNumberBaseFieldPrecision, processChartDataSort, processRecords } from '../helper';
88
import { ColumnChart } from './column';
99
import { ChartType, StackType } from './interface';
10+
import {safeParseNumberOrText} from "../utils";
1011

1112
export class ScatterChart extends ColumnChart {
1213
type = ChartType.Scatter;
@@ -147,7 +148,7 @@ export class ScatterChart extends ColumnChart {
147148
data = rows.map(row => {
148149
let metricsValue = row.metrics;
149150
if (!isNumber(metricsValue)) {
150-
// Switching field types can cause this result. With a value of 0, the chart does not crash,
151+
// Switching field types can cause this result. With a value of 0, the chart does not crash,
151152
// the form form will give a prompt.
152153
metricsValue = 0;
153154
}
@@ -157,8 +158,7 @@ export class ScatterChart extends ColumnChart {
157158
if (!isCountNullValue && dimensionValue === t(Strings.null)) return null;
158159
return {
159160
[dimensionMetricsMap.dimension.key]: dimensionValue,
160-
[dimensionMetricsMap.metrics.key]: parseFloat(metricsValue?.toFixed(metricsField?.property?.precision)),
161-
// [seriesField]: seriesFieldInstance?.convertCellValueToString(row.series) || t(Strings.null),
161+
[dimensionMetricsMap.metrics.key]: parseFloat(safeParseNumberOrText(metricsValue, metricsField?.property?.precision)),
162162
};
163163
}).filter(item => item != null);
164164
}
@@ -210,4 +210,4 @@ export class ScatterChart extends ColumnChart {
210210
};
211211
return options;
212212
}
213-
}
213+
}

src/utils.ts

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@ export function listenDOMSize(dom: React.RefObject<HTMLElement>) {
1616
}
1717
}
1818
handle = requestAnimationFrame(() => listen(callback));
19-
};
20-
19+
}
20+
2121
function addListen(callback) {
2222
handle = requestAnimationFrame(() => listen(callback));
2323
}
@@ -26,7 +26,7 @@ export function listenDOMSize(dom: React.RefObject<HTMLElement>) {
2626
cancelAnimationFrame(handle);
2727
}
2828

29-
return { addListen, removeListen }
29+
return { addListen, removeListen };
3030
}
3131

3232
const MIN_CHAR_SIZE = 12;
@@ -46,7 +46,7 @@ class CanvasUtils {
4646
setCanvasSize = (width, height) => {
4747
this.canvas.width = width;
4848
this.canvas.height = height;
49-
}
49+
};
5050

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

81-
export const canvasUtilsIns = new CanvasUtils();
81+
export const canvasUtilsIns = new CanvasUtils();
82+
83+
export const safeParseNumberOrText = (num : number | string | undefined, precision: number) => {
84+
if(!num) {
85+
return '';
86+
}
87+
88+
const a = Number(num);
89+
if(isNaN(a)) {
90+
return '';
91+
}
92+
return a.toFixed(precision);
93+
};

0 commit comments

Comments
 (0)