Skip to content

Commit 64ec597

Browse files
committed
sunburst chart utils
1 parent 22a139b commit 64ec597

File tree

1 file changed

+318
-0
lines changed

1 file changed

+318
-0
lines changed
Lines changed: 318 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,318 @@
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+
if (props.mode === "json") {
133+
let opt={
134+
"title": {
135+
"text": props.echartsTitle,
136+
'top': props.echartsLegendConfig.top === 'bottom' ?'top':'bottom',
137+
"left":"center"
138+
},
139+
"backgroundColor": props?.style?.background,
140+
"color": props.echartsOption.data?.map(data => data.color),
141+
"tooltip": props.tooltip&&{
142+
"trigger": "item",
143+
"formatter": "{b}: {c}"
144+
},
145+
"series": [
146+
{
147+
"name": props.echartsConfig.type,
148+
"type": props.echartsConfig.type,
149+
"top": "10%",
150+
"left": "10%",
151+
"bottom": "10%",
152+
"right": "10%",
153+
"symbolSize": 7,
154+
'data': props.echartsOption.data,
155+
}
156+
]
157+
}
158+
return props.echartsOption ? opt : {};
159+
160+
}
161+
162+
if(props.mode === "map") {
163+
const {
164+
mapZoomLevel,
165+
mapCenterLat,
166+
mapCenterLng,
167+
mapOptions,
168+
showCharts,
169+
} = props;
170+
171+
const echartsOption = mapOptions && showCharts ? mapOptions : {};
172+
return {
173+
gmap: {
174+
center: [mapCenterLng, mapCenterLat],
175+
zoom: mapZoomLevel,
176+
renderOnMoving: true,
177+
echartsLayerZIndex: showCharts ? 2019 : 0,
178+
roam: true
179+
},
180+
...echartsOption,
181+
}
182+
}
183+
// axisChart
184+
const axisChart = isAxisChart(props.chartConfig.type);
185+
const gridPos = {
186+
left: 20,
187+
right: props.legendConfig.left === "right" ? "10%" : 20,
188+
top: 50,
189+
bottom: 35,
190+
};
191+
let config: EChartsOptionWithMap = {
192+
title: { text: props.title, left: "center" },
193+
tooltip: {
194+
confine: true,
195+
trigger: axisChart ? "axis" : "item",
196+
},
197+
legend: props.legendConfig,
198+
grid: {
199+
...gridPos,
200+
containLabel: true,
201+
},
202+
};
203+
if (props.data.length <= 0) {
204+
// no data
205+
return {
206+
...config,
207+
...(axisChart ? noDataAxisConfig : noDataPieChartConfig),
208+
};
209+
}
210+
const yAxisConfig = props.yConfig();
211+
const seriesColumnNames = props.series
212+
.filter((s) => !s.getView().hide)
213+
.map((s) => s.getView().columnName);
214+
// y-axis is category and time, data doesn't need to aggregate
215+
const transformedData =
216+
yAxisConfig.type === "category" || yAxisConfig.type === "time"
217+
? props.data
218+
: transformData(props.data, props.xAxisKey, seriesColumnNames);
219+
config = {
220+
...config,
221+
dataset: [
222+
{
223+
source: transformedData,
224+
sourceHeader: false,
225+
},
226+
],
227+
series: getSeriesConfig(props),
228+
};
229+
if (axisChart) {
230+
// pure chart's size except the margin around
231+
let chartRealSize;
232+
if (chartSize) {
233+
const rightSize =
234+
typeof gridPos.right === "number"
235+
? gridPos.right
236+
: (chartSize.w * parseFloat(gridPos.right)) / 100.0;
237+
chartRealSize = {
238+
// actually it's self-adaptive with the x-axis label on the left, not that accurate but work
239+
w: chartSize.w - gridPos.left - rightSize,
240+
// also self-adaptive on the bottom
241+
h: chartSize.h - gridPos.top - gridPos.bottom,
242+
right: rightSize,
243+
};
244+
}
245+
const finalXyConfig = calcXYConfig(
246+
props.xConfig,
247+
yAxisConfig,
248+
props.xAxisDirection,
249+
transformedData.map((d) => d[props.xAxisKey]),
250+
chartRealSize
251+
);
252+
config = {
253+
...config,
254+
// @ts-ignore
255+
xAxis: finalXyConfig.xConfig,
256+
// @ts-ignore
257+
yAxis: finalXyConfig.yConfig,
258+
};
259+
}
260+
// log.log("Echarts transformedData and config", transformedData, config);
261+
return config;
262+
}
263+
264+
export function getSelectedPoints(param: any, option: any) {
265+
const series = option.series;
266+
const dataSource = _.isArray(option.dataset) && option.dataset[0]?.source;
267+
if (series && dataSource) {
268+
return param.selected.flatMap((selectInfo: any) => {
269+
const seriesInfo = series[selectInfo.seriesIndex];
270+
if (!seriesInfo || !seriesInfo.encode) {
271+
return [];
272+
}
273+
return selectInfo.dataIndex.map((index: any) => {
274+
const commonResult = {
275+
seriesName: seriesInfo.name,
276+
};
277+
if (seriesInfo.encode.itemName && seriesInfo.encode.value) {
278+
return {
279+
...commonResult,
280+
itemName: dataSource[index][seriesInfo.encode.itemName],
281+
value: dataSource[index][seriesInfo.encode.value],
282+
};
283+
} else {
284+
return {
285+
...commonResult,
286+
x: dataSource[index][seriesInfo.encode.x],
287+
y: dataSource[index][seriesInfo.encode.y],
288+
};
289+
}
290+
});
291+
});
292+
}
293+
return [];
294+
}
295+
296+
export function loadGoogleMapsScript(apiKey: string) {
297+
const mapsUrl = `${googleMapsApiUrl}?key=${apiKey}`;
298+
const scripts = document.getElementsByTagName('script');
299+
// is script already loaded
300+
let scriptIndex = _.findIndex(scripts, (script) => script.src.endsWith(mapsUrl));
301+
if(scriptIndex > -1) {
302+
return scripts[scriptIndex];
303+
}
304+
// is script loaded with diff api_key, remove the script and load again
305+
scriptIndex = _.findIndex(scripts, (script) => script.src.startsWith(googleMapsApiUrl));
306+
if(scriptIndex > -1) {
307+
scripts[scriptIndex].remove();
308+
}
309+
310+
const script = document.createElement("script");
311+
script.type = "text/javascript";
312+
script.src = mapsUrl;
313+
script.async = true;
314+
script.defer = true;
315+
window.document.body.appendChild(script);
316+
317+
return script;
318+
}

0 commit comments

Comments
 (0)