Skip to content

fix echarts compatiblity with older versions #856

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion client/packages/lowcoder-comps/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "lowcoder-comps",
"version": "2.4.3",
"version": "2.4.4",
"type": "module",
"license": "MIT",
"dependencies": {
Expand Down Expand Up @@ -74,6 +74,14 @@
"h": 40
}
},
"basicChart": {
"name": "Basic Chart",
"icon": "./icons/icon-chart.svg",
"layoutInfo": {
"w": 12,
"h": 40
}
},
"imageEditor": {
"name": "Image Editor",
"icon": "./icons/icon-chart.svg",
Expand Down
295 changes: 295 additions & 0 deletions client/packages/lowcoder-comps/src/comps/basicChartComp/chartComp.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,295 @@
import {
changeChildAction,
changeValueAction,
CompAction,
CompActionTypes,
wrapChildAction,
} from "lowcoder-core";
import { AxisFormatterComp, EchartsAxisType } from "./chartConfigs/cartesianAxisConfig";
import { chartChildrenMap, ChartSize, getDataKeys } from "./chartConstants";
import { chartPropertyView } from "./chartPropertyView";
import _ from "lodash";
import { useContext, useEffect, useMemo, useRef, useState } from "react";
import ReactResizeDetector from "react-resize-detector";
import ReactECharts from "./reactEcharts";
import {
childrenToProps,
depsConfig,
genRandomKey,
NameConfig,
UICompBuilder,
withDefault,
withExposingConfigs,
withMethodExposing,
withViewFn,
ThemeContext,
chartColorPalette,
getPromiseAfterDispatch,
dropdownControl
} from "lowcoder-sdk";
import { getEchartsLocale, trans } from "i18n/comps";
import { ItemColorComp } from "comps/chartComp/chartConfigs/lineChartConfig";
import {
echartsConfigOmitChildren,
getEchartsConfig,
getSelectedPoints,
} from "comps/chartComp/chartUtils";
import 'echarts-extension-gmap';
import log from "loglevel";

let clickEventCallback = () => {};

const chartModeOptions = [
{
label: trans("chart.UIMode"),
value: "ui",
}
] as const;

let BasicChartTmpComp = (function () {
return new UICompBuilder({mode:dropdownControl(chartModeOptions,'ui'),...chartChildrenMap}, () => null)
.setPropertyViewFn(chartPropertyView)
.build();
})();

BasicChartTmpComp = withViewFn(BasicChartTmpComp, (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(() => {
// 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 option = useMemo(() => {
return getEchartsConfig(
childrenToProps(echartsConfigChildren) as ToViewReturn<typeof echartsConfigChildren>,
chartSize
);
}, [chartSize, ...Object.values(echartsConfigChildren)]);

useEffect(() => {
comp.children.mapInstance.dispatch(changeValueAction(null, false))
}, [option])

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}
theme={themeConfig}
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;
}

BasicChartTmpComp = class extends BasicChartTmpComp {
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 BasicChartComp = withExposingConfigs(BasicChartTmpComp, [
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) => input.data,
}),
new NameConfig("title", trans("chart.titleDesc")),
]);

export const BasicChartCompWithDefault = withDefault(BasicChartComp, {
xAxisKey: "date",
series: [
{
dataIndex: genRandomKey(),
seriesName: trans("chart.spending"),
columnName: "spending",
},
{
dataIndex: genRandomKey(),
seriesName: trans("chart.budget"),
columnName: "budget",
},
],
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import {
BoolControl,
dropdownControl,
MultiCompBuilder,
showLabelPropertyView,
} from "lowcoder-sdk";
import { BarSeriesOption } from "echarts";
import { trans } from "i18n/comps";

const BarTypeOptions = [
{
label: trans("chart.basicBar"),
value: "basicBar",
},
{
label: trans("chart.stackedBar"),
value: "stackedBar",
},
] as const;

export const BarChartConfig = (function () {
return new MultiCompBuilder(
{
showLabel: BoolControl,
type: dropdownControl(BarTypeOptions, "basicBar"),
},
(props): BarSeriesOption => {
const config: BarSeriesOption = {
type: "bar",
label: {
show: props.showLabel,
position: "top",
},
};
if (props.type === "stackedBar") {
config.stack = "stackValue";
}
return config;
}
)
.setPropertyViewFn((children) => (
<>
{showLabelPropertyView(children)}
{children.type.propertyView({
label: trans("chart.barType"),
radioButton: true,
})}
</>
))
.build();
})();
Loading
Loading