Skip to content

Commit fe2000b

Browse files
committed
themeriver chart utils
1 parent 6ce567e commit fe2000b

File tree

1 file changed

+345
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)