Skip to content

Commit

Permalink
feat(platform): support 'canvas' chart
Browse files Browse the repository at this point in the history
  • Loading branch information
xiejay97 committed Jul 5, 2023
1 parent 7d36f78 commit 74419de
Showing 1 changed file with 38 additions and 9 deletions.
47 changes: 38 additions & 9 deletions packages/platform/src/app/components/chart/Chart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,20 @@ import * as echarts from 'echarts';
import { cloneDeep, merge } from 'lodash';
import React, { useEffect, useImperativeHandle, useRef, useState } from 'react';

import { useAsync, useResize, useStorage } from '@react-devui/hooks';
import { useAsync, useResize } from '@react-devui/hooks';
import { getClassName } from '@react-devui/utils';

import { STORAGE_KEY } from '../../config/storage';
import chartTheme from './theme.json';

echarts.registerTheme('light', chartTheme.light);
echarts.registerTheme('dark', merge(cloneDeep(chartTheme.light), chartTheme.dark));

export interface AppChartProps<O extends echarts.EChartsOption> extends Omit<React.HTMLAttributes<HTMLDivElement>, 'children'> {
aOption: O | null;
aRenderer?: 'canvas' | 'svg';
}

function Chart<O extends echarts.EChartsOption>(props: AppChartProps<O>, ref: React.ForwardedRef<echarts.ECharts>): JSX.Element | null {
const {
aOption,
aRenderer = 'canvas',

...restProps
} = props;
Expand All @@ -35,17 +33,48 @@ function Chart<O extends echarts.EChartsOption>(props: AppChartProps<O>, ref: Re

const async = useAsync();

const themeStorage = useStorage<AppTheme>(...STORAGE_KEY.theme);

const [instance, setInstance] = useState<echarts.ECharts | null>(null);
const [theme, setTheme] = useState<AppTheme | null>(null);

useEffect(() => {
for (const theme of ['light', 'dark'] as const) {
if (document.body.className.includes(theme)) {
setTheme(theme);
break;
}
}

const observer = new MutationObserver(() => {
setTheme(document.body.className.includes('dark') ? 'dark' : 'light');
});
observer.observe(document.body, { attributeFilter: ['class'] });

return () => {
observer.disconnect();
};
}, []);

useEffect(() => {
const instance = containerRef.current ? echarts.init(containerRef.current, themeStorage.value, { renderer: 'svg' }) : null;
const instance =
containerRef.current && theme
? echarts.init(
containerRef.current,
JSON.parse(
JSON.stringify(theme === 'light' ? chartTheme.light : merge(cloneDeep(chartTheme.light), chartTheme.dark)).replace(
/var\((.+?)\)/g,
(match, p1) => {
return getComputedStyle(document.body).getPropertyValue(p1);
}
)
),
{ renderer: aRenderer }
)
: null;
setInstance(instance);
return () => {
instance?.dispose();
};
}, [themeStorage.value]);
}, [aRenderer, theme]);

useEffect(() => {
if (instance && aOption) {
Expand Down

0 comments on commit 74419de

Please sign in to comment.