import {
BubbleChartPropsType,
BubbleDefaults,
defaultBubbleColors,
useBubbleChart,
withinMinMaxRange,
} from 'gifted-charts-core';
import BarAndLineChartsWrapper from '../Components/BarAndLineChartsWrapper';
import {
Fragment,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import {
Animated,
Easing,
I18nManager,
Text,
View,
ViewStyle,
} from 'react-native';
import {
Circle,
ForeignObject,
Rect,
Svg,
Line,
RadialGradient,
Stop,
Defs,
} from 'react-native-svg';
import {isAndroid, isWebApp, screenWidth} from '../utils';
import {bubbleDataItem} from 'gifted-charts-core';
const AnimatedCircle = Animated.createAnimatedComponent(Circle);
const AnimatedRect = Animated.createAnimatedComponent(Rect);
const AnimatedLine = Animated.createAnimatedComponent(Line);
export const BubbleChart = (props: BubbleChartPropsType) => {
const opacityValue = useMemo(() => new Animated.Value(0), []);
const pointsOpacityValue = useMemo(() => new Animated.Value(0), []);
const {
secondaryXAxis,
xAxisLabelTextStyle,
formatBubbleLabel,
regressionLinesBehindBubbles,
} = props;
const {
data,
barAndLineChartsWrapperProps,
totalWidth,
animationDuration,
containerHeightIncludingBelowXAxis = 0,
getY,
getX,
maxValue,
selectedIndex,
setSelectedIndex,
showTextOnFocus,
focusEnabled,
focusTogether,
selectedLineNumber,
lastLineNumber,
initialSpacing,
spacing,
containerHeight,
handleFocus,
handleUnFocus,
isAnimated,
showBubbleOnFocus,
showBubbleLabelOnFocus,
bubblesShape,
bubblesWidth,
bubblesHeight,
bubblesColor,
bubblesRadius,
labelFontSize,
labelMaxLength,
labelTextStyle,
startIndex,
endIndex,
showValuesAsBubbleLabels,
hideBubbles,
xAxisLabelsVerticalShift,
labelsExtraHeight,
xAxisThickness,
xAxisTextNumberOfLines,
rotateLabel,
allowFontScaling,
borderColor,
borderWidth,
opacity,
borderOpacity,
xAxisLabelTexts,
showRegressionLine,
regressionLineX1,
regressionLineY1,
regressionLineX2,
regressionLineY2,
regressionLineCoordinates,
regressionLineConfig,
regressionLineConfigs,
scatterChart,
maxRadius,
minRadius,
extraWidthDueToBubble,
showGradient,
centerColorForGradient,
disableForeignObject,
} = useBubbleChart({
...props,
parentWidth: props.parentWidth ?? screenWidth,
});
const progress = useRef(new Animated.Value(0)).current;
const AnimatedRegressionLineX = useRef(new Animated.Value(0)).current;
const AnimatedRegressionLineY = useRef(new Animated.Value(0)).current;
const animatedRegressionLineXValues = useMemo(
() => regressionLineConfigs.map(() => new Animated.Value(0)),
[regressionLineConfigs.length],
);
const animatedRegressionLineYValues = useMemo(
() => regressionLineConfigs.map(() => new Animated.Value(0)),
[regressionLineConfigs.length],
);
const scrollRef = props.scrollRef ?? useRef(null);
const widthValue = useMemo(() => new Animated.Value(0), []);
const appearingOpacity = opacityValue.interpolate({
inputRange: [0, 1],
outputRange: [0, 1],
});
// const appearRegressionLine = RegressionLine.interpolate({
// inputRange:[0,1],
// outputRange:[regressionLineX1,regressionLineX2]
// })
const growingRadii = useMemo(
() =>
(data ?? []).map(item =>
progress.interpolate({
inputRange: [0, 1],
outputRange: [
0,
withinMinMaxRange(item.r ?? bubblesRadius, maxRadius, minRadius),
],
}),
),
[data, progress],
);
const growingHeight = (data ?? []).map((_, i) =>
progress.interpolate({
inputRange: [0, 1],
outputRange: [0, data?.[i].bubbleHeight ?? bubblesHeight],
}),
);
const growingWidth = (data ?? []).map((_, i) =>
progress.interpolate({
inputRange: [0, 1],
outputRange: [0, data?.[i].bubbleWidth ?? bubblesWidth],
}),
);
const appearingDataPoints = pointsOpacityValue.interpolate({
inputRange: [0, 1],
outputRange: [0, opacity],
});
const appearingDataPointsAndroid = pointsOpacityValue.interpolate({
inputRange: [0, 1],
outputRange: [0, opacity / 2], // hack to show slightly transparent bubbles while animating, as gradient on Android can't be animated
});
const appearingBorder = pointsOpacityValue.interpolate({
inputRange: [0, 1],
outputRange: [0, borderOpacity],
});
const drawRegressionLine = useCallback(() => {
const hasMultipleRegressionLines = regressionLineConfigs.length > 0;
if (hasMultipleRegressionLines) {
const animations: Animated.CompositeAnimation[] = [];
regressionLineConfigs.forEach((config, index) => {
if (!config.isAnimated) {
return;
}
const coordinates = regressionLineCoordinates[index];
if (!coordinates) {
return;
}
const {
regressionLineX1: x1,
regressionLineX2: x2,
regressionLineY1: y1,
regressionLineY2: y2,
} = coordinates;
const animatedX = animatedRegressionLineXValues[index];
const animatedY = animatedRegressionLineYValues[index];
if (!animatedX || !animatedY) {
return;
}
animatedX.setValue(x1);
animatedY.setValue(y1);
animations.push(
Animated.timing(animatedX, {
toValue: x2,
duration: config.animationDuration,
easing: Easing.linear,
useNativeDriver: false, // SVG props
}),
);
animations.push(
Animated.timing(animatedY, {
toValue: y2,
duration: config.animationDuration,
easing: Easing.linear,
useNativeDriver: false, // SVG props
}),
);
});
if (animations.length) {
Animated.parallel(animations).start();
}
return;
}
if (!regressionLineConfig.isAnimated) {
return;
}
AnimatedRegressionLineX.setValue(regressionLineX1);
AnimatedRegressionLineY.setValue(regressionLineY1);
Animated.parallel([
Animated.timing(AnimatedRegressionLineX, {
toValue: regressionLineX2,
duration: regressionLineConfig.animationDuration,
easing: Easing.linear,
useNativeDriver: false, // SVG props
}),
Animated.timing(AnimatedRegressionLineY, {
toValue: regressionLineY2,
duration: regressionLineConfig.animationDuration,
easing: Easing.linear,
useNativeDriver: false, // SVG props
}),
]).start();
}, [
regressionLineConfig,
regressionLineX1,
regressionLineX2,
regressionLineY1,
regressionLineY2,
// regressionLineConfigs,
regressionLineCoordinates,
animatedRegressionLineXValues,
animatedRegressionLineYValues,
]);
const decreaseWidth = useCallback(() => {
widthValue.setValue(0);
Animated.timing(widthValue, {
toValue: totalWidth,
duration: animationDuration,
easing: Easing.linear,
useNativeDriver: false,
}).start();
}, [animationDuration, widthValue]);
const labelsAppear = useCallback(() => {
opacityValue.setValue(0);
Animated.timing(opacityValue, {
toValue: 1,
duration: 500,
easing: Easing.ease,
useNativeDriver: false,
}).start();
}, [opacityValue]);
const radiiGrow = useCallback(() => {
if (bubblesShape === 'rectangular') return;
progress.setValue(0);
Animated.timing(progress, {
toValue: 1,
duration: animationDuration,
easing: Easing.out(Easing.cubic),
useNativeDriver: false,
}).start();
}, [progress, animationDuration]);
const bubblesHeightsWidthsGrow = useCallback(() => {
if (bubblesShape !== 'rectangular') return;
progress.setValue(0);
Animated.timing(progress, {
toValue: 1,
duration: animationDuration,
easing: Easing.out(Easing.cubic),
useNativeDriver: false,
}).start();
}, [progress, animationDuration]);
const dataPointsAppear = useCallback(() => {
pointsOpacityValue.setValue(0);
Animated.timing(pointsOpacityValue, {
toValue: 1,
duration: animationDuration,
easing: Easing.ease,
useNativeDriver: false,
}).start();
}, [pointsOpacityValue]);
const [isAnimationOver, setIsAnimationOver] = useState(false);
useEffect(() => {
if (isAnimated) {
decreaseWidth();
labelsAppear();
dataPointsAppear();
if (bubblesShape === 'rectangular') {
bubblesHeightsWidthsGrow();
} else {
radiiGrow();
}
if (isAndroid) {
setTimeout(() => {
setIsAnimationOver(true);
}, animationDuration + 20);
}
}
const hasAnimatedRegressionLine =
regressionLineConfig.isAnimated ||
regressionLineConfigs.some(config => config.isAnimated);
if (hasAnimatedRegressionLine) {
drawRegressionLine();
}
}, [
isAnimated,
bubblesShape,
regressionLineConfig.isAnimated,
// regressionLineConfigs,
// drawRegressionLine,
]);
const svgHeight =
containerHeightIncludingBelowXAxis + (props.overflowBottom ?? 0);
// const onStripPress = (item: any, index: number) => {
// if (props.focusedBubbleIndex === undefined || !props.onFocus) {
// setSelectedIndex(index);
// }
// if (props.onFocus) {
// props.onFocus(item, index);
// }
// };
const renderLabel = (top: boolean, index: number, label: string) => {
const left = index
? initialSpacing + spacing * index - spacing / 2
: initialSpacing / 2;
return (
{label}
);
};
const renderAnimatedLabel = (top: boolean, index: number, label: string) => {
const left = index
? initialSpacing + spacing * index - spacing / 2
: initialSpacing / 2;
return (
{label}
);
};
const renderBubbles = (
hideBubbles: any,
dataForRender: any,
originalDataFromProps: any,
bubsShape: any,
bubsWidth: any,
bubsHeight: any,
bubsColor: any,
bubsRadius: any,
labelFontSize: any,
startIndex: any,
endIndex: any,
isSecondary: any,
showValuesAsDataPointsText: any,
key: number,
) => {
const getYOrSecondaryY = getY; //isSecondary ? getSecondaryY : getY;
return dataForRender.map((item: bubbleDataItem, index: number) => {
// if (index < startIndex || index > endIndex) return null;
if (item.hideBubble) {
return null;
}
let bubblesShape,
bubblesWidth,
bubblesHeight,
dataPointsColor,
bubblesRadius,
text,
customBubble,
labelComponent;
if (
index === selectedIndex &&
(focusTogether || key === selectedLineNumber)
) {
bubblesShape =
item.focusedBubbleShape ||
props.focusedBubbleShape ||
item.bubbleShape ||
bubsShape;
bubblesWidth =
item.focusedBubbleWidth ||
props.focusedBubbleWidth ||
item.bubbleWidth ||
bubsWidth;
bubblesHeight =
item.focusedBubbleHeight ||
props.focusedBubbleHeight ||
item.bubbleHeight ||
bubsHeight;
dataPointsColor =
item.focusedBubbleColor ||
props.focusedBubbleColor ||
BubbleDefaults.focusedBubbleColor;
bubblesRadius = withinMinMaxRange(
item.focusedBubbleRadius ??
props.focusedBubbleRadius ??
item.r ??
bubsRadius,
maxRadius,
minRadius,
);
if (showTextOnFocus) {
text = item.label;
}
customBubble =
item.focusedCustomBubble ||
props.focusedCustomBubble ||
item.customBubble ||
props.customBubble;
labelComponent =
item.focusedLabelComponent ||
item.labelComponent ||
props.focusedLabelComponent ||
props.labelComponent;
} else {
bubblesShape = item.bubbleShape || bubsShape;
bubblesWidth = item.bubbleWidth || bubsWidth;
bubblesHeight = item.bubbleHeight || bubsHeight;
dataPointsColor =
item.bubbleColor ||
bubsColor ||
defaultBubbleColors[index % defaultBubbleColors.length];
bubblesRadius = withinMinMaxRange(
item.r ?? bubsRadius,
maxRadius,
minRadius,
);
if (showTextOnFocus) {
text = '';
}
customBubble = item.customBubble || props.customBubble;
labelComponent = item.labelComponent || props.labelComponent;
}
if (showValuesAsDataPointsText) {
text = originalDataFromProps[index].y;
}
const labelWidth = item.labelWidth
? item.labelWidth
: props.labelWidth
? props.labelWidth
: 30;
const textLabel =
!showTextOnFocus && !showValuesAsDataPointsText
? item.label
: text.toString();
let formattedTextLabel = textLabel
? (formatBubbleLabel?.(textLabel) ?? textLabel)
: '';
if (formattedTextLabel.length > labelMaxLength) {
formattedTextLabel =
formattedTextLabel.slice(0, labelMaxLength - 3) + '...';
}
const textStyle = (item.labelTextStyle ?? labelTextStyle ?? {}) as any;
const fontSize =
textStyle.fontSize || item.labelFontSize || labelFontSize;
const defaultFontSize = 14;
const fillColorForAnimatedGradientOnAndroid = isAnimationOver
? `url(#radial${index})`
: dataPointsColor;
const localBorderColor =
item.borderColor ??
borderColor ??
defaultBubbleColors[index % defaultBubbleColors.length];
const bubbleKey = `${key}-${item.indexUsedInDevForDataSet ?? ''}-${
item.label ?? ''
}-${index}`;
return (
{focusEnabled ? (
<>
{key === lastLineNumber - 1 ? (
{
const locationY = evt.nativeEvent.locationY; // Note that we have another property named pageY which can be useful
handleFocus(
index,
// item,
// locationY,
// onStripPress,
);
}}
onPressOut={handleUnFocus}
/>
) : null}
{/* {unFocusOnPressOut ? ( // remove strip on onFocus
{
const locationY = evt.nativeEvent.locationY
onStripPress(item, index)
}}
onPressOut={() =>
setTimeout(() => setSelectedIndex(-1), delayBeforeUnFocus)
}
x={initialSpacing + (spacing * index - spacing / 2)}
y={8}
width={spacing}
height={containerHeight - 0}
fill={'none'}
/>
) : (
onStripPress(item, index)}
x={initialSpacing + (spacing * index - spacing / 2)}
y={8}
width={spacing}
height={containerHeight}
fill={'none'}
/>
)} */}
>
) : null}
{/* {renderStrips(item, index, key)} // handled with strips coming from geifted-charts-core */}
{hideBubbles ? null : (
<>
{customBubble ? (
isWebApp && !disableForeignObject ? (
{customBubble(item, index)}
) : (
{customBubble(item, index)}
)
) : null}
{bubblesShape === 'rectangular' ? (
{customBubble ? null : (
{
item.onPress
? item.onPress(item, index)
: props.onPress
? props.onPress(item, index)
: focusEnabled
? handleFocus(
index,
// item,
// 0,
// onStripPress,
)
: null;
}}
onPressOut={() => {
if (!item.onPress && !props.onPress && focusEnabled) {
handleUnFocus();
}
}}
/>
)}
) : (
{customBubble ? null : (
{
item.onPress
? item.onPress(item, index)
: props.onPress
? props.onPress(item, index)
: focusEnabled
? handleFocus(
index,
// item,
// 0,
// onStripPress,
)
: null;
}}
onPressOut={() => {
if (!item.onPress && !props.onPress && focusEnabled) {
handleUnFocus();
}
}}
/>
)}
)}
{labelComponent ? (
!showTextOnFocus || index === selectedIndex ? (
isWebApp && !disableForeignObject ? (
{showBubbleLabelOnFocus
? index === selectedIndex &&
(focusTogether || key == selectedLineNumber)
? labelComponent(item, index) // not pushed in latest release
: null
: labelComponent(item, index)}
) : (
{showBubbleLabelOnFocus
? index === selectedIndex &&
(focusTogether || key == selectedLineNumber)
? labelComponent(item, index) // not pushed in latest release
: null
: labelComponent(item, index)}
)
) : null
) : formattedTextLabel ? (
!showTextOnFocus || index === selectedIndex ? (
isWebApp && !disableForeignObject ? (
{formattedTextLabel}
) : (
{formattedTextLabel}
)
) : null
) : null}
{/* Workaround to fix the issue - focusedCustomBubble not rendering for focused data, (when both customBubble and focusedCustomBubble are used together)*/}
{index === selectedIndex ? {''} : null}
>
)}
);
});
};
const svgWrapperViewStyle = {
position: 'absolute',
top: xAxisLabelsVerticalShift, // 281 + xAxisLabelsVerticalShift + labelsExtraHeight - xAxisThickness,
left: 0,
zIndex: 1,
transform: [{scaleX: I18nManager.isRTL ? -1 : 1}],
};
const renderChartContent = () => {
return (
{xAxisLabelTexts?.map((label: string, index: number) => {
const labelKey = `${label}-${index}`;
return (
{isAnimated
? renderAnimatedLabel(false, index, label)
: renderLabel(false, index, label)}
{/* {secondaryXAxis
? isAnimated
? renderAnimatedLabel(
true,
index,
label
)
: renderLabel(
true,
index,
label
)
: null} */}
);
})}
);
};
const remainingScrollViewProps = {
onScroll: (ev: any) => {
props.onScroll?.(ev);
},
bounces: props.bounces,
overScrollMode: props.overScrollMode ?? 'auto',
};
return (
);
};