Skip to content

Commit cbf9973

Browse files
committed
tree chart utils
1 parent b51a34b commit cbf9973

File tree

1 file changed

+330
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)