Skip to content

Commit

Permalink
Fix #3059: ChartJS allow loading by script tag
Browse files Browse the repository at this point in the history
  • Loading branch information
melloware committed Jul 14, 2022
1 parent 2718dae commit 369331a
Showing 1 changed file with 35 additions and 23 deletions.
58 changes: 35 additions & 23 deletions components/lib/chart/Chart.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,42 @@ import * as React from 'react';
import { useUnmountEffect } from '../hooks/Hooks';
import { classNames, ObjectUtils } from '../utils/Utils';

export const Chart = React.memo(React.forwardRef((props, ref) => {
// GitHub #3059 wrapper if loaded by script tag
const ChartJS = function() {try {return Chart;} catch {return null;}}();

const PrimeReactChart = React.memo(React.forwardRef((props, ref) => {
const chartRef = React.useRef(null);
const canvasRef = React.useRef(null);

const initChart = () => {
import('chart.js/auto').then((module) => {
if (chartRef.current) {
chartRef.current.destroy();
chartRef.current = null;
}

const configuration = {
type: props.type,
data: props.data,
options: props.options,
plugins: props.plugins
};
if (chartRef.current) {
chartRef.current.destroy();
chartRef.current = null;
}

if (module) {
if (module.default) {
chartRef.current = new module.default(canvasRef.current, configuration);
} else {
chartRef.current = new module(canvasRef.current, configuration);
const configuration = {
type: props.type,
data: props.data,
options: props.options,
plugins: props.plugins
};
if (ChartJS) {
// GitHub #3059 loaded by script only
chartRef.current = new ChartJS(canvasRef.current, configuration);
}
else {
import('chart.js/auto').then((module) => {
if (module) {
if (module.default) {
// WebPack
chartRef.current = new module.default(canvasRef.current, configuration);
} else {
// ParcelJS
chartRef.current = new module(canvasRef.current, configuration);
}
}
}
});
});
}
}

React.useImperativeHandle(ref, () => ({
Expand All @@ -50,7 +60,7 @@ export const Chart = React.memo(React.forwardRef((props, ref) => {
}
});

const otherProps = ObjectUtils.findDiffKeys(props, Chart.defaultProps);
const otherProps = ObjectUtils.findDiffKeys(props, PrimeReactChart.defaultProps);
const className = classNames('p-chart', props.className);
const style = Object.assign({ width: props.width, height: props.height }, props.style);

Expand All @@ -61,8 +71,8 @@ export const Chart = React.memo(React.forwardRef((props, ref) => {
);
}), (prevProps, nextProps) => prevProps.data === nextProps.data && prevProps.options === nextProps.options && prevProps.type === nextProps.type);

Chart.displayName = 'Chart';
Chart.defaultProps = {
PrimeReactChart .displayName = 'Chart';
PrimeReactChart .defaultProps = {
__TYPE: 'Chart',
id: null,
type: null,
Expand All @@ -74,3 +84,5 @@ Chart.defaultProps = {
style: null,
className: null
}

export { PrimeReactChart as Chart };

0 comments on commit 369331a

Please sign in to comment.