react-native-chart-kit
Version:
Beautiful React Native charts for dashboards, reports, and data-rich mobile apps.
95 lines (94 loc) • 3.34 kB
JavaScript
export const normalizeLineChartSelectedIndex = (selectedIndex) => {
return typeof selectedIndex === "number" && Number.isFinite(selectedIndex)
? Math.round(selectedIndex)
: undefined;
};
export const getLineChartInteractionConfig = (interaction) => {
if (!interaction) {
return {
mode: "none",
selectionPersistence: "persist",
deselectOnOutsidePress: false
};
}
if (typeof interaction === "string") {
return {
mode: interaction,
selectionPersistence: "persist",
deselectOnOutsidePress: true
};
}
const mode = interaction.mode ?? "tap";
return {
mode,
selectionPersistence: interaction.selectionPersistence ?? "persist",
deselectOnOutsidePress: interaction.deselectOnOutsidePress ?? true,
...(interaction.onSelect ? { onSelect: interaction.onSelect } : {}),
...(interaction.onDeselect ? { onDeselect: interaction.onDeselect } : {}),
...(interaction.onGestureStart
? { onGestureStart: interaction.onGestureStart }
: {}),
...(interaction.onGestureEnd
? { onGestureEnd: interaction.onGestureEnd }
: {})
};
};
export const isLineChartInteractionEnabled = (config) => config.mode !== "none";
export const isLineChartInteractionInBounds = ({ bounds, locationX, locationY, touchSlop = 16 }) => {
return (locationX >= bounds.x - touchSlop &&
locationX <= bounds.x + bounds.width + touchSlop &&
locationY >= bounds.y - touchSlop &&
locationY <= bounds.y + bounds.height + touchSlop);
};
export const getLineChartVisibleInteractionBounds = ({ bounds, scrollable, viewportWidth }) => {
if (!scrollable) {
return bounds;
}
return {
...bounds,
width: Math.max(0, viewportWidth - bounds.x)
};
};
export const getNearestLineChartInteractionIndex = ({ locationX, points }) => {
let nearest;
points.forEach((point) => {
if (!Number.isFinite(point.x)) {
return;
}
const distance = Math.abs(point.x - locationX);
if (!nearest || distance < nearest.distance) {
nearest = {
dataIndex: point.dataIndex,
distance
};
}
});
return nearest?.dataIndex;
};
export const buildLineChartSelectEvent = ({ interactionPoints, selectedDataIndex, selectedSeries }) => {
const interactionPoint = interactionPoints.find((point) => point.dataIndex === selectedDataIndex);
if (!interactionPoint || selectedSeries.length === 0) {
return undefined;
}
const y = Math.min(...selectedSeries.map((item) => item.point.y));
const event = {
index: selectedDataIndex,
x: interactionPoint.xValue,
xLabel: interactionPoint.xLabel,
position: {
x: interactionPoint.x,
y
},
series: selectedSeries.map((item) => ({
key: item.key,
label: item.label,
color: item.color,
value: item.value,
formattedValue: item.formattedValue,
point: item.point
}))
};
return interactionPoint.raw !== undefined
? { ...event, raw: interactionPoint.raw }
: event;
};