Skip to content

Commit f6acf9e

Browse files
committed
radar utils
1 parent 4f0f807 commit f6acf9e

File tree

1 file changed

+321
-0
lines changed

1 file changed

+321
-0
lines changed
Lines changed: 321 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,321 @@
1+
import {
2+
CharOptionCompType,
3+
ChartCompPropsType,
4+
ChartSize,
5+
noDataAxisConfig,
6+
noDataPieChartConfig,
7+
} from "comps/chartComp/chartConstants";
8+
import { getPieRadiusAndCenter } from "comps/chartComp/chartConfigs/pieChartConfig";
9+
import { EChartsOptionWithMap } from "../chartComp/reactEcharts/types";
10+
import _ from "lodash";
11+
import { chartColorPalette, isNumeric, JSONObject, loadScript } from "lowcoder-sdk";
12+
import { calcXYConfig } from "comps/chartComp/chartConfigs/cartesianAxisConfig";
13+
import Big from "big.js";
14+
import { googleMapsApiUrl } from "../chartComp/chartConfigs/chartUrls";
15+
16+
export function transformData(
17+
originData: JSONObject[],
18+
xAxis: string,
19+
seriesColumnNames: string[]
20+
) {
21+
// aggregate data by x-axis
22+
const transformedData: JSONObject[] = [];
23+
originData.reduce((prev, cur) => {
24+
if (cur === null || cur === undefined) {
25+
return prev;
26+
}
27+
const groupValue = cur[xAxis] as string;
28+
if (!prev[groupValue]) {
29+
// init as 0
30+
const initValue: any = {};
31+
seriesColumnNames.forEach((name) => {
32+
initValue[name] = 0;
33+
});
34+
prev[groupValue] = initValue;
35+
transformedData.push(prev[groupValue]);
36+
}
37+
// remain the x-axis data
38+
prev[groupValue][xAxis] = groupValue;
39+
seriesColumnNames.forEach((key) => {
40+
if (key === xAxis) {
41+
return;
42+
} else if (isNumeric(cur[key])) {
43+
const bigNum = Big(cur[key]);
44+
prev[groupValue][key] = bigNum.add(prev[groupValue][key]).toNumber();
45+
} else {
46+
prev[groupValue][key] += 1;
47+
}
48+
});
49+
return prev;
50+
}, {} as any);
51+
return transformedData;
52+
}
53+
54+
const notAxisChartSet: Set<CharOptionCompType> = new Set(["pie"] as const);
55+
export const echartsConfigOmitChildren = [
56+
"hidden",
57+
"selectedPoints",
58+
"onUIEvent",
59+
"mapInstance"
60+
] as const;
61+
type EchartsConfigProps = Omit<ChartCompPropsType, typeof echartsConfigOmitChildren[number]>;
62+
63+
export function isAxisChart(type: CharOptionCompType) {
64+
return !notAxisChartSet.has(type);
65+
}
66+
67+
export function getSeriesConfig(props: EchartsConfigProps) {
68+
const visibleSeries = props.series.filter((s) => !s.getView().hide);
69+
const seriesLength = visibleSeries.length;
70+
return visibleSeries.map((s, index) => {
71+
if (isAxisChart(props.chartConfig.type)) {
72+
let encodeX: string, encodeY: string;
73+
const horizontalX = props.xAxisDirection === "horizontal";
74+
let itemStyle = props.chartConfig.itemStyle;
75+
// FIXME: need refactor... chartConfig returns a function with paramters
76+
if (props.chartConfig.type === "bar") {
77+
// barChart's border radius, depend on x-axis direction and stack state
78+
const borderRadius = horizontalX ? [2, 2, 0, 0] : [0, 2, 2, 0];
79+
if (props.chartConfig.stack && index === visibleSeries.length - 1) {
80+
itemStyle = { ...itemStyle, borderRadius: borderRadius };
81+
} else if (!props.chartConfig.stack) {
82+
itemStyle = { ...itemStyle, borderRadius: borderRadius };
83+
}
84+
}
85+
if (horizontalX) {
86+
encodeX = props.xAxisKey;
87+
encodeY = s.getView().columnName;
88+
} else {
89+
encodeX = s.getView().columnName;
90+
encodeY = props.xAxisKey;
91+
}
92+
return {
93+
name: s.getView().seriesName,
94+
selectedMode: "single",
95+
select: {
96+
itemStyle: {
97+
borderColor: "#000",
98+
},
99+
},
100+
encode: {
101+
x: encodeX,
102+
y: encodeY,
103+
},
104+
// each type of chart's config
105+
...props.chartConfig,
106+
itemStyle: itemStyle,
107+
label: {
108+
...props.chartConfig.label,
109+
...(!horizontalX && { position: "outside" }),
110+
},
111+
};
112+
} else {
113+
// pie
114+
const radiusAndCenter = getPieRadiusAndCenter(seriesLength, index, props.chartConfig);
115+
return {
116+
...props.chartConfig,
117+
radius: radiusAndCenter.radius,
118+
center: radiusAndCenter.center,
119+
name: s.getView().seriesName,
120+
selectedMode: "single",
121+
encode: {
122+
itemName: props.xAxisKey,
123+
value: s.getView().columnName,
124+
},
125+
};
126+
}
127+
});
128+
}
129+
130+
// https://echarts.apache.org/en/option.html
131+
export function getEchartsConfig(props: EchartsConfigProps, chartSize?: ChartSize): EChartsOptionWithMap {
132+
console.log("🚀 ~ getEchartsConfig ~ props:", props)
133+
if (props.mode === "json") {
134+
let opt={
135+
"title": {
136+
"text": props.echartsTitle,
137+
'top': props.echartsLegendConfig.top === 'bottom' ?'top':'bottom',
138+
"left":"center"
139+
},
140+
"backgroundColor": props?.style?.background,
141+
"color": props.echartsOption.data?.map(data => data.color),
142+
"tooltip": {
143+
"trigger": "axis",
144+
"formatter": function(params) {
145+
let tooltipText = params[0].name + '<br/>';
146+
params.forEach(function(item) {
147+
tooltipText += item.seriesName + ': ' + item.value + '<br/>';
148+
});
149+
return tooltipText;
150+
}
151+
},
152+
"radar": [
153+
{
154+
"indicator": props.echartsOption.indicator,
155+
"center": ["50%", "50%"],
156+
"radius": "60%"
157+
}
158+
],
159+
"series": props.echartsOption.series.map(option=>{return {...option,type:'radar'}})
160+
}
161+
return props.echartsOption ? opt : {};
162+
163+
}
164+
165+
if(props.mode === "map") {
166+
const {
167+
mapZoomLevel,
168+
mapCenterLat,
169+
mapCenterLng,
170+
mapOptions,
171+
showCharts,
172+
} = props;
173+
174+
const echartsOption = mapOptions && showCharts ? mapOptions : {};
175+
return {
176+
gmap: {
177+
center: [mapCenterLng, mapCenterLat],
178+
zoom: mapZoomLevel,
179+
renderOnMoving: true,
180+
echartsLayerZIndex: showCharts ? 2019 : 0,
181+
roam: true
182+
},
183+
...echartsOption,
184+
}
185+
}
186+
// axisChart
187+
const axisChart = isAxisChart(props.chartConfig.type);
188+
const gridPos = {
189+
left: 20,
190+
right: props.legendConfig.left === "right" ? "10%" : 20,
191+
top: 50,
192+
bottom: 35,
193+
};
194+
let config: EChartsOptionWithMap = {
195+
title: { text: props.title, left: "center" },
196+
tooltip: {
197+
confine: true,
198+
trigger: axisChart ? "axis" : "item",
199+
},
200+
legend: props.legendConfig,
201+
grid: {
202+
...gridPos,
203+
containLabel: true,
204+
},
205+
};
206+
if (props.data.length <= 0) {
207+
// no data
208+
return {
209+
...config,
210+
...(axisChart ? noDataAxisConfig : noDataPieChartConfig),
211+
};
212+
}
213+
const yAxisConfig = props.yConfig();
214+
const seriesColumnNames = props.series
215+
.filter((s) => !s.getView().hide)
216+
.map((s) => s.getView().columnName);
217+
// y-axis is category and time, data doesn't need to aggregate
218+
const transformedData =
219+
yAxisConfig.type === "category" || yAxisConfig.type === "time"
220+
? props.data
221+
: transformData(props.data, props.xAxisKey, seriesColumnNames);
222+
config = {
223+
...config,
224+
dataset: [
225+
{
226+
source: transformedData,
227+
sourceHeader: false,
228+
},
229+
],
230+
series: getSeriesConfig(props),
231+
};
232+
if (axisChart) {
233+
// pure chart's size except the margin around
234+
let chartRealSize;
235+
if (chartSize) {
236+
const rightSize =
237+
typeof gridPos.right === "number"
238+
? gridPos.right
239+
: (chartSize.w * parseFloat(gridPos.right)) / 100.0;
240+
chartRealSize = {
241+
// actually it's self-adaptive with the x-axis label on the left, not that accurate but work
242+
w: chartSize.w - gridPos.left - rightSize,
243+
// also self-adaptive on the bottom
244+
h: chartSize.h - gridPos.top - gridPos.bottom,
245+
right: rightSize,
246+
};
247+
}
248+
const finalXyConfig = calcXYConfig(
249+
props.xConfig,
250+
yAxisConfig,
251+
props.xAxisDirection,
252+
transformedData.map((d) => d[props.xAxisKey]),
253+
chartRealSize
254+
);
255+
config = {
256+
...config,
257+
// @ts-ignore
258+
xAxis: finalXyConfig.xConfig,
259+
// @ts-ignore
260+
yAxis: finalXyConfig.yConfig,
261+
};
262+
}
263+
// log.log("Echarts transformedData and config", transformedData, config);
264+
return config;
265+
}
266+
267+
export function getSelectedPoints(param: any, option: any) {
268+
const series = option.series;
269+
const dataSource = _.isArray(option.dataset) && option.dataset[0]?.source;
270+
if (series && dataSource) {
271+
return param.selected.flatMap((selectInfo: any) => {
272+
const seriesInfo = series[selectInfo.seriesIndex];
273+
if (!seriesInfo || !seriesInfo.encode) {
274+
return [];
275+
}
276+
return selectInfo.dataIndex.map((index: any) => {
277+
const commonResult = {
278+
seriesName: seriesInfo.name,
279+
};
280+
if (seriesInfo.encode.itemName && seriesInfo.encode.value) {
281+
return {
282+
...commonResult,
283+
itemName: dataSource[index][seriesInfo.encode.itemName],
284+
value: dataSource[index][seriesInfo.encode.value],
285+
};
286+
} else {
287+
return {
288+
...commonResult,
289+
x: dataSource[index][seriesInfo.encode.x],
290+
y: dataSource[index][seriesInfo.encode.y],
291+
};
292+
}
293+
});
294+
});
295+
}
296+
return [];
297+
}
298+
299+
export function loadGoogleMapsScript(apiKey: string) {
300+
const mapsUrl = `${googleMapsApiUrl}?key=${apiKey}`;
301+
const scripts = document.getElementsByTagName('script');
302+
// is script already loaded
303+
let scriptIndex = _.findIndex(scripts, (script) => script.src.endsWith(mapsUrl));
304+
if(scriptIndex > -1) {
305+
return scripts[scriptIndex];
306+
}
307+
// is script loaded with diff api_key, remove the script and load again
308+
scriptIndex = _.findIndex(scripts, (script) => script.src.startsWith(googleMapsApiUrl));
309+
if(scriptIndex > -1) {
310+
scripts[scriptIndex].remove();
311+
}
312+
313+
const script = document.createElement("script");
314+
script.type = "text/javascript";
315+
script.src = mapsUrl;
316+
script.async = true;
317+
script.defer = true;
318+
window.document.body.appendChild(script);
319+
320+
return script;
321+
}

0 commit comments

Comments
 (0)