-
Notifications
You must be signed in to change notification settings - Fork 241
/
Copy pathlineChartComp.tsx
314 lines (294 loc) · 9.06 KB
/
lineChartComp.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
import {
changeChildAction,
changeValueAction,
CompAction,
CompActionTypes,
wrapChildAction,
} from "lowcoder-core";
import { AxisFormatterComp, EchartsAxisType } from "../basicChartComp/chartConfigs/cartesianAxisConfig";
import { lineChartChildrenMap, ChartSize, getDataKeys } from "./lineChartConstants";
import { lineChartPropertyView } from "./lineChartPropertyView";
import _ from "lodash";
import { useContext, useEffect, useMemo, useRef, useState } from "react";
import ReactResizeDetector from "react-resize-detector";
import ReactECharts from "../basicChartComp/reactEcharts";
import {
childrenToProps,
depsConfig,
genRandomKey,
NameConfig,
UICompBuilder,
withDefault,
withExposingConfigs,
withViewFn,
ThemeContext,
chartColorPalette,
getPromiseAfterDispatch,
dropdownControl,
} from "lowcoder-sdk";
import { getEchartsLocale, trans } from "i18n/comps";
import { ItemColorComp } from "comps/basicChartComp/chartConfigs/lineChartConfig";
import {
echartsConfigOmitChildren,
getEchartsConfig,
getSelectedPoints,
} from "./lineChartUtils";
import 'echarts-extension-gmap';
import log from "loglevel";
let clickEventCallback = () => {};
const chartModeOptions = [
{
label: "ECharts JSON",
value: "json",
}
] as const;
let LineChartTmpComp = (function () {
return new UICompBuilder({mode:dropdownControl(chartModeOptions,'ui'),...lineChartChildrenMap}, () => null)
.setPropertyViewFn(lineChartPropertyView)
.build();
})();
LineChartTmpComp = withViewFn(LineChartTmpComp, (comp) => {
const mode = comp.children.mode.getView();
const onUIEvent = comp.children.onUIEvent.getView();
const onEvent = comp.children.onEvent.getView();
const echartsCompRef = useRef<ReactECharts | null>();
const [chartSize, setChartSize] = useState<ChartSize>();
const firstResize = useRef(true);
const theme = useContext(ThemeContext);
const defaultChartTheme = {
color: chartColorPalette,
backgroundColor: "#fff",
};
let themeConfig = defaultChartTheme;
try {
themeConfig = theme?.theme.chart ? JSON.parse(theme?.theme.chart) : defaultChartTheme;
} catch (error) {
log.error('theme chart error: ', error);
}
const triggerClickEvent = async (dispatch: any, action: CompAction<JSONValue>) => {
await getPromiseAfterDispatch(
dispatch,
action,
{ autoHandleAfterReduce: true }
);
onEvent('click');
}
useEffect(() => {
const echartsCompInstance = echartsCompRef?.current?.getEchartsInstance();
if (!echartsCompInstance) {
return _.noop;
}
echartsCompInstance?.on("click", (param: any) => {
document.dispatchEvent(new CustomEvent("clickEvent", {
bubbles: true,
detail: {
action: 'click',
data: param.data,
}
}));
triggerClickEvent(
comp.dispatch,
changeChildAction("lastInteractionData", param.data, false)
);
});
return () => {
echartsCompInstance?.off("click");
document.removeEventListener('clickEvent', clickEventCallback)
};
}, []);
useEffect(() => {
// bind events
const echartsCompInstance = echartsCompRef?.current?.getEchartsInstance();
if (!echartsCompInstance) {
return _.noop;
}
echartsCompInstance?.on("selectchanged", (param: any) => {
const option: any = echartsCompInstance?.getOption();
document.dispatchEvent(new CustomEvent("clickEvent", {
bubbles: true,
detail: {
action: param.fromAction,
data: getSelectedPoints(param, option)
}
}));
if (param.fromAction === "select") {
comp.dispatch(changeChildAction("selectedPoints", getSelectedPoints(param, option), false));
onUIEvent("select");
} else if (param.fromAction === "unselect") {
comp.dispatch(changeChildAction("selectedPoints", getSelectedPoints(param, option), false));
onUIEvent("unselect");
}
triggerClickEvent(
comp.dispatch,
changeChildAction("lastInteractionData", getSelectedPoints(param, option), false)
);
});
// unbind
return () => {
echartsCompInstance?.off("selectchanged");
document.removeEventListener('clickEvent', clickEventCallback)
};
}, [onUIEvent]);
const echartsConfigChildren = _.omit(comp.children, echartsConfigOmitChildren);
const childrenProps = childrenToProps(echartsConfigChildren);
const option = useMemo(() => {
return getEchartsConfig(
childrenProps as ToViewReturn<typeof echartsConfigChildren>,
chartSize,
themeConfig
);
}, [theme, childrenProps, chartSize, ...Object.values(echartsConfigChildren)]);
return (
<ReactResizeDetector
onResize={(w, h) => {
if (w && h) {
setChartSize({ w: w, h: h });
}
if (!firstResize.current) {
// ignore the first resize, which will impact the loading animation
echartsCompRef.current?.getEchartsInstance().resize();
} else {
firstResize.current = false;
}
}}
>
<ReactECharts
ref={(e) => (echartsCompRef.current = e)}
style={{ height: "100%" }}
notMerge
lazyUpdate
opts={{ locale: getEchartsLocale() }}
option={option}
mode={mode}
/>
</ReactResizeDetector>
);
});
function getYAxisFormatContextValue(
data: Array<JSONObject>,
yAxisType: EchartsAxisType,
yAxisName?: string
) {
const dataSample = yAxisName && data.length > 0 && data[0][yAxisName];
let contextValue = dataSample;
if (yAxisType === "time") {
// to timestamp
const time =
typeof dataSample === "number" || typeof dataSample === "string"
? new Date(dataSample).getTime()
: null;
if (time) contextValue = time;
}
return contextValue;
}
LineChartTmpComp = class extends LineChartTmpComp {
private lastYAxisFormatContextVal?: JSONValue;
private lastColorContext?: JSONObject;
updateContext(comp: this) {
// the context value of axis format
let resultComp = comp;
const data = comp.children.data.getView();
const sampleSeries = comp.children.series.getView().find((s) => !s.getView().hide);
const yAxisContextValue = getYAxisFormatContextValue(
data,
comp.children.yConfig.children.yAxisType.getView(),
sampleSeries?.children.columnName.getView()
);
if (yAxisContextValue !== comp.lastYAxisFormatContextVal) {
comp.lastYAxisFormatContextVal = yAxisContextValue;
resultComp = comp.setChild(
"yConfig",
comp.children.yConfig.reduce(
wrapChildAction(
"formatter",
AxisFormatterComp.changeContextDataAction({ value: yAxisContextValue })
)
)
);
}
// item color context
const colorContextVal = {
seriesName: sampleSeries?.children.seriesName.getView(),
value: yAxisContextValue,
};
if (
comp.children.chartConfig.children.comp.children.hasOwnProperty("itemColor") &&
!_.isEqual(colorContextVal, comp.lastColorContext)
) {
comp.lastColorContext = colorContextVal;
resultComp = resultComp.setChild(
"chartConfig",
comp.children.chartConfig.reduce(
wrapChildAction(
"comp",
wrapChildAction("itemColor", ItemColorComp.changeContextDataAction(colorContextVal))
)
)
);
}
return resultComp;
}
override reduce(action: CompAction): this {
const comp = super.reduce(action);
if (action.type === CompActionTypes.UPDATE_NODES_V2) {
const newData = comp.children.data.getView();
// data changes
if (comp.children.data !== this.children.data) {
setTimeout(() => {
// update x-axis value
const keys = getDataKeys(newData);
if (keys.length > 0 && !keys.includes(comp.children.xAxisKey.getView())) {
comp.children.xAxisKey.dispatch(changeValueAction(keys[0] || ""));
}
// pass to child series comp
comp.children.series.dispatchDataChanged(newData);
}, 0);
}
return this.updateContext(comp);
}
return comp;
}
override autoHeight(): boolean {
return false;
}
};
let LineChartComp = withExposingConfigs(LineChartTmpComp, [
depsConfig({
name: "selectedPoints",
desc: trans("chart.selectedPointsDesc"),
depKeys: ["selectedPoints"],
func: (input) => {
return input.selectedPoints;
},
}),
depsConfig({
name: "lastInteractionData",
desc: trans("chart.lastInteractionDataDesc"),
depKeys: ["lastInteractionData"],
func: (input) => {
return input.lastInteractionData;
},
}),
depsConfig({
name: "data",
desc: trans("chart.dataDesc"),
depKeys: ["data", "mode"],
func: (input) =>[] ,
}),
new NameConfig("title", trans("chart.titleDesc")),
]);
export const LineChartCompWithDefault = withDefault(LineChartComp, {
xAxisKey: "date",
series: [
{
dataIndex: genRandomKey(),
seriesName: "Sales",
columnName: "sales",
},
{
dataIndex: genRandomKey(),
seriesName: "Growth",
columnName: "growth",
},
],
});