diff --git a/.changeset/hover-gesture-support.md b/.changeset/hover-gesture-support.md new file mode 100644 index 00000000..1c0f1883 --- /dev/null +++ b/.changeset/hover-gesture-support.md @@ -0,0 +1,11 @@ +--- +"victory-native": minor +--- + +Add hover gesture support. + +Hover is aimed at pointer devices (mouse/trackpad on web or desktop) and is **enabled by default on web**; `enableHover` opts in on other platforms and `enableHover={false}` opts out on web. The hover gesture is composed simultaneously with the press and transform gestures, so touch-only behavior is unchanged. + +- `CartesianChart`: hover drives the `chartPressState` values exactly like a press (values and `isActive`), or a separate `chartHoverState` prop (`ChartPressState | ChartPressState[]`) to track hover and press independently. With no states passed at all, the chart maintains a built-in hover state exposed through the render functions' `hoverState` field (`isActive`, `x.value`/`x.position`, `y..value`/`position`), so hover readouts need zero setup — mirroring `PolarChart`. +- `PolarChart`: the hovered-slice index is tracked for you — read it in chart content with the new `usePieHoverState()` hook (`index` is the hovered slice, or `-1` over the donut hole, outside the pie, or off the chart). Pass `chartHoverState={{ index }}` — a Reanimated shared value — only to consume the index outside the chart. +- `chartHoverConfig` (both charts): supports `activeCursor` for cursor styling and `simultaneousWithExternalGesture` to compose the hover gesture with custom gestures built outside the chart. diff --git a/.eslintrc.js b/.eslintrc.js index 3a189db0..addf49cc 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -28,6 +28,16 @@ module.exports = { sourceType: "script", }, }, + { + env: { + node: true, + browser: false, + }, + files: ["**/metro.config.js"], + parserOptions: { + sourceType: "script", + }, + }, ], parser: "@typescript-eslint/parser", parserOptions: { diff --git a/example/app/axis-label-renderers.tsx b/example/app/axis-label-renderers.tsx index 58834e16..0f620737 100644 --- a/example/app/axis-label-renderers.tsx +++ b/example/app/axis-label-renderers.tsx @@ -103,8 +103,6 @@ const createBadgeLabelRenderer = ( export default function AxisLabelRenderersPage(props: { segment: string }) { const description = descriptionForRoute(props.segment); - const font = useFont(inter, 12); - const badgeLabelRenderer = createBadgeLabelRenderer(font); return ( @@ -120,7 +118,7 @@ export default function AxisLabelRenderersPage(props: { segment: string }) { description="Paragraph labels reserve space for mixed scripts and explicit line breaks on a horizontal category axis." > - + @@ -129,7 +127,7 @@ export default function AxisLabelRenderersPage(props: { segment: string }) { description="Paragraph labels can constrain width while newline labels keep the numeric axis compact." > - + @@ -138,7 +136,7 @@ export default function AxisLabelRenderersPage(props: { segment: string }) { description="Custom renderers measure their own label boxes before the chart reserves axis space." > - + @@ -166,7 +164,8 @@ function ChartSection({ ); } -function MultilingualHorizontalChart({ font }: { font: SkFont | null }) { +function MultilingualHorizontalChart() { + const font = useFont(inter, 12); return ( ; -}) { +function BadgeAxisChart() { + const font = useFont(inter, 12); + const badgeLabelRenderer = createBadgeLabelRenderer(font); return ( @@ -45,13 +44,13 @@ export default function AxisTitleLayoutPage(props: { segment: string }) { - + - + @@ -73,11 +72,8 @@ function ChartSection({ ); } -function NumericYAxisTitleChart({ - font, -}: { - font: ReturnType; -}) { +function NumericYAxisTitleChart() { + const font = useFont(inter, 12); return ( ; -}) { +function CategoryYAxisTitleChart() { + const font = useFont(inter, 12); return ( Array.from({ length }, (_, index) => ({ @@ -84,9 +87,43 @@ export default function BarChartPage(props: { segment: string }) { }, ); + const { state: pressState, isActive: pressIsActive } = useChartPressState({ + x: 0, + y: { listenCount: 0 }, + }); + + const hoveredLabel = useDerivedValue(() => { + if (!pressIsActive) return "Hover the chart!"; + const month = pressState.x.value.value; + const date = new Date(2023, month - 1); + return date.toLocaleString("default", { month: "short" }); + }); + const hoveredValue = useDerivedValue(() => { + if (!pressIsActive) return ""; + return `${pressState.y.listenCount.value.value} plays`; + }); + return ( <> + + + + { setChartBottom(bottom); setChartLeft(left); diff --git a/example/app/candlestick.tsx b/example/app/candlestick.tsx index bb710fa0..80ea9c44 100644 --- a/example/app/candlestick.tsx +++ b/example/app/candlestick.tsx @@ -123,6 +123,7 @@ export default function CandlestickPage(props: { segment: string }) { padding={{ left: 10, right: 10, top: 20, bottom: 10 }} domainPadding={{ left: 18, right: 18, top: 20, bottom: 12 }} chartPressState={pressState} + enableHover xAxis={{ font, tickValues: MAIN_TICK_VALUES, diff --git a/example/app/chart-refs.tsx b/example/app/chart-refs.tsx index ae2ff4cd..f6670a10 100644 --- a/example/app/chart-refs.tsx +++ b/example/app/chart-refs.tsx @@ -176,6 +176,7 @@ export default function ChartRefsExample() { }, }} chartPressState={state} + enableHover > {({ points }) => ( <> diff --git a/example/app/donut-chart.tsx b/example/app/donut-chart.tsx index 8bfc482d..c0081689 100644 --- a/example/app/donut-chart.tsx +++ b/example/app/donut-chart.tsx @@ -1,12 +1,20 @@ import React, { useState } from "react"; import { ScrollView, StyleSheet, View } from "react-native"; import { SafeAreaView } from "react-native-safe-area-context"; -import { LinearGradient, vec } from "react-native-skia"; -import { Pie, PolarChart } from "victory-native"; +import { + LinearGradient, + Text as SkiaText, + useFont, + vec, +} from "react-native-skia"; +import { Pie, PolarChart, usePieHoverState } from "victory-native"; +import { useDarkMode } from "react-native-dark"; +import { useDerivedValue } from "react-native-reanimated"; import { InfoCard } from "example/components/InfoCard"; import { Button } from "example/components/Button"; import { appColors } from "../consts/colors"; import { descriptionForRoute } from "../consts/routes"; +import inter from "../assets/inter-medium.ttf"; function calculateGradientPoints( radius: number, @@ -48,6 +56,34 @@ const DATA = (numberPoints = 5) => label: `Label ${index + 1}`, })); +/** Reads the hovered-slice index `PolarChart` maintains internally; no `chartHoverState` prop needed. */ +function HoverReadout({ + data, +}: { + data: { label: string; value: number; color: string }[]; +}) { + const isDark = useDarkMode(); + const font = useFont(inter, 14); + const hover = usePieHoverState(); + const text = useDerivedValue(() => { + const i = hover.index.value; + const d = i >= 0 && i < data.length ? data[i] : undefined; + return d + ? `Label ${i + 1}: ${d.label} — value ${d.value}` + : "Hover the donut!"; + }); + + return ( + + ); +} + export default function DonutChart(props: { segment: string }) { const description = descriptionForRoute(props.segment); const [data, setData] = useState(DATA(5)); @@ -61,7 +97,12 @@ export default function DonutChart(props: { segment: string }) { colorKey={"color"} valueKey={"value"} labelKey={"label"} + enableHover + chartHoverConfig={{ + activeCursor: "pointer", + }} > + {({ slice }) => { const { startX, startY, endX, endY } = calculateGradientPoints( diff --git a/example/app/guides/getting-started.tsx b/example/app/guides/getting-started.tsx index 206d557d..54dc829c 100644 --- a/example/app/guides/getting-started.tsx +++ b/example/app/guides/getting-started.tsx @@ -32,6 +32,7 @@ export default function GettingStartedScreen(props: { segment: string }) { font, }} chartPressState={state} + enableHover > {({ points }) => ( <> diff --git a/example/app/horizontal-bands-line.tsx b/example/app/horizontal-bands-line.tsx index b04d3b7d..d9100273 100644 --- a/example/app/horizontal-bands-line.tsx +++ b/example/app/horizontal-bands-line.tsx @@ -9,11 +9,12 @@ import { Circle, Shader, Skia, useFont } from "react-native-skia"; import { ScrollView, StyleSheet, View } from "react-native"; import { SafeAreaView } from "react-native-safe-area-context"; import { + useAnimatedReaction, useDerivedValue, useSharedValue, withSpring, + type SharedValue, } from "react-native-reanimated"; -import { useEffect } from "react"; import { useDarkMode } from "react-native-dark"; import inter from "../assets/inter-medium.ttf"; import { appColors } from "../consts/colors"; @@ -96,6 +97,7 @@ export default function OrdinalDataScreen(props: { segment: string }) { labelColor: isDark ? appColors.text.dark : appColors.text.light, }} chartPressState={state} + enableHover > {({ points, yScale }) => { return ( @@ -124,7 +126,7 @@ export default function OrdinalDataScreen(props: { segment: string }) { key={`circle-${x}-${y}`} x={x} y={y ?? 0} - radius={state.x.position.value === x ? 12 : 0} + activeXPosition={state.x.position} color={"#f00"} /> ))} @@ -150,18 +152,23 @@ export default function OrdinalDataScreen(props: { segment: string }) { const AnimatedCircle = ({ x, y, - radius, + activeXPosition, color, }: { x: number; y: number; - radius: number; + activeXPosition: SharedValue; color: string; }) => { const animatedRadius = useSharedValue(0); - useEffect(() => { - animatedRadius.value = withSpring(radius); - }, [animatedRadius, radius]); + useAnimatedReaction( + () => activeXPosition.value === x, + (isActive, wasActive) => { + if (isActive === wasActive) return; + animatedRadius.value = withSpring(isActive ? 12 : 0); + }, + [x], + ); return ; }; diff --git a/example/app/horizontal-bar-group.tsx b/example/app/horizontal-bar-group.tsx index c2e8425b..76045973 100644 --- a/example/app/horizontal-bar-group.tsx +++ b/example/app/horizontal-bar-group.tsx @@ -173,6 +173,7 @@ export default function HorizontalBarGroupPage(props: { segment: string }) { ]} frame={{ lineWidth: 0 }} chartPressState={press.state} + enableHover chartPressConfig={{ pan: { activateAfterLongPress: 0 } }} > {({ points, chartBounds }) => ( @@ -299,7 +300,7 @@ export default function HorizontalBarGroupPage(props: { segment: string }) { description="A horizontal version of the grouped bar tooltip example." > - + @@ -308,7 +309,7 @@ export default function HorizontalBarGroupPage(props: { segment: string }) { description="Two grouped series with fixed bar thickness and plain colors." > - + @@ -317,7 +318,7 @@ export default function HorizontalBarGroupPage(props: { segment: string }) { description="Many categories with three narrow bars per group." > - + @@ -341,13 +342,8 @@ function ChartSection({ ); } -function TooltipPairChart({ - font, - axisLabelColor, -}: { - font: ReturnType; - axisLabelColor: string; -}) { +function TooltipPairChart({ axisLabelColor }: { axisLabelColor: string }) { + const font = useFont(inter, 12); const [barSize, setBarSize] = React.useState({ barWidth: 0, groupWidth: 0, @@ -406,6 +402,7 @@ function TooltipPairChart({ ]} frame={{ lineWidth: 0 }} chartPressState={state} + enableHover chartPressConfig={{ pan: { activateAfterLongPress: 0 } }} > {({ points, chartBounds }) => ( @@ -479,13 +476,8 @@ function TooltipPairChart({ ); } -function CompactPairChart({ - font, - axisLabelColor, -}: { - font: ReturnType; - axisLabelColor: string; -}) { +function CompactPairChart({ axisLabelColor }: { axisLabelColor: string }) { + const font = useFont(inter, 12); return ( ; - axisLabelColor: string; -}) { +function DenseFixedWidthChart({ axisLabelColor }: { axisLabelColor: string }) { + const font = useFont(inter, 12); return ( - + @@ -164,7 +159,7 @@ export default function HorizontalStackedBarPage(props: { segment: string }) { description="Segments can provide Skia children such as gradients through barOptions." > - + @@ -173,7 +168,7 @@ export default function HorizontalStackedBarPage(props: { segment: string }) { description="Missing values are skipped, zero values stay zero-width, and outer corners remain on visible stack ends." > - + @@ -203,19 +198,18 @@ function ChartSection({ function HorizontalStackedChart({ data, - font, axisLabelColor, innerPadding, roundedCorner, domain, }: { data: ChannelDatum[]; - font: ReturnType; axisLabelColor: string; innerPadding: number; roundedCorner: number; domain: [number, number]; }) { + const font = useFont(inter, 12); return ( ; axisLabelColor: string; }) { + const font = useFont(inter, 12); const { state, isActive } = useChartPressState({ x: "Alpha", y: { product: 0, services: 0, support: 0 }, @@ -315,6 +308,7 @@ function TouchableSegmentsChart({ ; - axisLabelColor: string; -}) { +function CustomChildrenChart({ axisLabelColor }: { axisLabelColor: string }) { + const font = useFont(inter, 12); return ( ; - axisLabelColor: string; -}) { +function NonUniformChart({ axisLabelColor }: { axisLabelColor: string }) { + const font = useFont(inter, 12); return ( ({ + day: i, + highTmp: Math.round(40 + 30 * Math.random()), +})); + +/** Vertical dashed line tracking the pointer while it hovers the chart. */ +function HoverCursor({ + xPosition, + chartBounds, +}: { + xPosition: SharedValue; + chartBounds: { top: number; bottom: number }; +}) { + const start = useDerivedValue(() => vec(xPosition.value, chartBounds.top)); + const end = useDerivedValue(() => vec(xPosition.value, chartBounds.bottom)); + + return ( + + + + ); +} + +export default function HoverPress(props: { segment: string }) { + const description = descriptionForRoute(props.segment); + const isDark = useDarkMode(); + + const { state: press, isActive: pressIsActive } = useChartPressState({ + x: 0, + y: { highTmp: 0 }, + }); + const { state: hover, isActive: hoverIsActive } = useChartPressState({ + x: 0, + y: { highTmp: 0 }, + }); + + const hoverReadout = useDerivedValue(() => { + if (!hoverIsActive) return "Hover the chart!"; + return `Hover day ${hover.x.value.value} / ${( + hover.y.highTmp.value.value ?? 0 + ).toFixed(1)}°C`; + }); + const pressReadout = useDerivedValue(() => { + if (!pressIsActive) return "Nothing pressed."; + return `Pressed day ${press.x.value.value} / ${( + press.y.highTmp.value.value ?? 0 + ).toFixed(1)}°C`; + }); + + return ( + + + + + + + + hoverIsActive ? ( + + ) : null + } + > + {({ points }) => ( + <> + + {pressIsActive && ( + + )} + {hoverIsActive && ( + + )} + + )} + + + + {description} + + + ); +} + +const styles = StyleSheet.create({ + safeView: { + flex: 1, + backgroundColor: appColors.viewBackground.light, + $dark: { + backgroundColor: appColors.viewBackground.dark, + }, + }, + chart: { + flex: 1.5, + }, + readout: { + fontSize: 18, + fontWeight: "bold", + }, + readoutValue: { + fontSize: 16, + fontWeight: "400", + opacity: 0.75, + }, + optionsScrollView: { + flex: 1, + backgroundColor: appColors.cardBackground.light, + $dark: { + backgroundColor: appColors.cardBackground.dark, + }, + }, + options: { + paddingHorizontal: 20, + paddingVertical: 15, + alignItems: "flex-start", + justifyContent: "flex-start", + }, +}); diff --git a/example/app/missing-data.tsx b/example/app/missing-data.tsx index ff9206d0..b89d7d2b 100644 --- a/example/app/missing-data.tsx +++ b/example/app/missing-data.tsx @@ -32,6 +32,7 @@ export default function MissingDataScreen() { domain={{ y: [0, 100] }} axisOptions={{ font }} chartPressState={state} + enableHover > {({ points, chartBounds }) => ( <> diff --git a/example/app/ordinal-data.tsx b/example/app/ordinal-data.tsx index 42f819c2..c94835a3 100644 --- a/example/app/ordinal-data.tsx +++ b/example/app/ordinal-data.tsx @@ -5,11 +5,12 @@ import { ScrollView, StyleSheet, View } from "react-native"; import { SafeAreaView } from "react-native-safe-area-context"; import { interpolateColor, + useAnimatedReaction, useDerivedValue, useSharedValue, withSpring, + type SharedValue, } from "react-native-reanimated"; -import { useEffect } from "react"; import { useDarkMode } from "react-native-dark"; import inter from "../assets/inter-medium.ttf"; import { appColors } from "../consts/colors"; @@ -46,6 +47,7 @@ export default function OrdinalDataScreen(props: { segment: string }) { labelColor: isDark ? appColors.text.dark : appColors.text.light, }} chartPressState={state} + enableHover > {({ chartBounds, points, yScale }) => { return ( @@ -69,7 +71,7 @@ export default function OrdinalDataScreen(props: { segment: string }) { key={`circle-${x}-${y}`} x={x} y={y ?? 0} - radius={state.x.position.value === x ? 12 : 0} + activeXPosition={state.x.position} color={interpolateColor( yValue ?? 0, [yScale.domain().at(0)!, yScale.domain().at(-1)!], @@ -99,18 +101,23 @@ export default function OrdinalDataScreen(props: { segment: string }) { const AnimatedCircle = ({ x, y, - radius, + activeXPosition, color, }: { x: number; y: number; - radius: number; + activeXPosition: SharedValue; color: string; }) => { const animatedRadius = useSharedValue(0); - useEffect(() => { - animatedRadius.value = withSpring(radius); - }, [animatedRadius, radius]); + useAnimatedReaction( + () => activeXPosition.value === x, + (isActive, wasActive) => { + if (isActive === wasActive) return; + animatedRadius.value = withSpring(isActive ? 12 : 0); + }, + [x], + ); return ; }; diff --git a/example/app/pie-chart.tsx b/example/app/pie-chart.tsx index 99e9158e..e57c5a9d 100644 --- a/example/app/pie-chart.tsx +++ b/example/app/pie-chart.tsx @@ -13,10 +13,13 @@ import { setScale, setTranslate, useChartTransformState, + usePieHoverState, } from "victory-native"; -import { useFont } from "react-native-skia"; +import { Text as SkiaText, useFont } from "react-native-skia"; +import { useDarkMode } from "react-native-dark"; import { useAnimatedReaction, + useDerivedValue, useSharedValue, withTiming, } from "react-native-reanimated"; @@ -45,6 +48,34 @@ const DATA = (numberPoints = 5) => label: `Label ${index + 1}`, })); +/** Reads the hovered-slice index `PolarChart` maintains internally; no `chartHoverState` prop needed. */ +function HoverReadout({ + data, +}: { + data: { label: string; value: number; color: string }[]; +}) { + const isDark = useDarkMode(); + const font = useFont(inter, 14); + const hover = usePieHoverState(); + const text = useDerivedValue(() => { + const i = hover.index.value; + const d = i >= 0 && i < data.length ? data[i] : undefined; + return d + ? `Slice ${i + 1}: ${d.label} — value ${d.value}` + : "Hover the pie!"; + }); + + return ( + + ); +} + export default function PieChart(props: { segment: string }) { const description = descriptionForRoute(props.segment); const { width, height } = useWindowDimensions(); @@ -105,7 +136,12 @@ export default function PieChart(props: { segment: string }) { colorKey={"color"} valueKey={"value"} labelKey={"label"} + enableHover + chartHoverConfig={{ + activeCursor: "pointer", + }} > + {({ slice }) => { return ( diff --git a/example/app/scatter.tsx b/example/app/scatter.tsx index eb5cdd67..4602dc68 100644 --- a/example/app/scatter.tsx +++ b/example/app/scatter.tsx @@ -48,6 +48,10 @@ export default function ScatterPage(props: { segment: string }) { domainPadding={{ left: 50, right: 50, top: 30 }} domain={{ y: [0, 100] }} chartPressState={state} + enableHover + chartHoverConfig={{ + activeCursor: "crosshair", + }} axisOptions={{ font, tickCount: 5, diff --git a/example/app/scroll-scrub.tsx b/example/app/scroll-scrub.tsx index 9cab0901..f800f13d 100644 --- a/example/app/scroll-scrub.tsx +++ b/example/app/scroll-scrub.tsx @@ -35,6 +35,7 @@ export default function ScrollAndScrub() { y: [40, 85], }} chartPressState={state} + enableHover transformState={transformState} > {({ points }) => ( diff --git a/example/app/scrollview-charts.tsx b/example/app/scrollview-charts.tsx index c55e870c..cdb36fed 100644 --- a/example/app/scrollview-charts.tsx +++ b/example/app/scrollview-charts.tsx @@ -40,6 +40,7 @@ const LineChart = ({ font, }} chartPressState={state} + enableHover chartPressConfig={{ pan: { activateAfterLongPress: 100, diff --git a/example/app/stacked-bar-charts-complex.tsx b/example/app/stacked-bar-charts-complex.tsx index e60dd720..8146c410 100644 --- a/example/app/stacked-bar-charts-complex.tsx +++ b/example/app/stacked-bar-charts-complex.tsx @@ -32,6 +32,7 @@ const IndividualTouchableBarChart = () => { { [XK]; y: Record }> | ChartPressState<{ x: InputFields[XK]; y: Record }>[]; + chartHoverState?: + | ChartPressState<{ x: InputFields[XK]; y: Record }> + | ChartPressState<{ x: InputFields[XK]; y: Record }>[]; chartPressConfig?: { pan?: ChartPressPanConfig; }; + enableHover?: boolean; + chartHoverConfig?: ChartHoverConfig; gestureHandlerConfig?: GestureHandlerConfig; children: (args: CartesianChartRenderArg) => React.ReactNode; renderOutside?: ( @@ -294,7 +304,10 @@ function CartesianChartContent< axisOptions, domain, chartPressState, + chartHoverState, chartPressConfig, + enableHover: enableHoverProp, + chartHoverConfig, gestureHandlerConfig, onChartBoundsChange, onScaleChange, @@ -311,6 +324,8 @@ function CartesianChartContent< explicitSize, headless, }: CartesianChartProps) { + // Hover is aimed at pointer devices, so it's on by default on web. + const enableHover = enableHoverProp ?? Platform.OS === "web"; const { size, hasMeasuredLayoutSize, onLayout, isHeadless } = useChartCanvasSize({ explicitSize, headless }); const chartBoundsRef = React.useRef(undefined); @@ -324,6 +339,8 @@ function CartesianChartContent< const canvasRef = React.useRef(null); const chartPressStateRef = React.useRef(chartPressState); chartPressStateRef.current = chartPressState; + const chartHoverStateRef = React.useRef(chartHoverState); + chartHoverStateRef.current = chartHoverState; const yKeysKey = yKeys.join("\u0000"); const normalizedAxisProps = useBuildChartAxis({ xAxis: xAxis as XAxisInputProps | undefined, @@ -633,6 +650,32 @@ function CartesianChartContent< const activePressSharedValues = Array.isArray(chartPressState) ? chartPressState : [chartPressState]; + const usesBuiltInHoverState = !chartPressState && !chartHoverState; + const builtInHoverState = React.useMemo( + () => + makeChartPressState({ + x: 0 as InputFields[XK], + y: Object.fromEntries(yKeys.map((key) => [key, 0])) as Record< + YK, + number + >, + }), + // eslint-disable-next-line react-hooks/exhaustive-deps + [yKeysKey], + ); + /** Hover drives `chartHoverState` if given, else the press states, else the built-in state. */ + const activeHoverSharedValues = + chartHoverState === undefined + ? chartPressState + ? activePressSharedValues + : [builtInHoverState] + : Array.isArray(chartHoverState) + ? chartHoverState + : [chartHoverState]; + /** Whether hover writes to the press states directly (no separate hover state, or the same object for both). */ + const hoverDrivesPressValues = activePressSharedValues.some( + (state) => state && activeHoverSharedValues.includes(state), + ); const gestureState = useSharedValue({ isGestureActive: false, bootstrap: [] as ChartPressBootstrapEntry< @@ -640,14 +683,19 @@ function CartesianChartContent< TouchData >[], }); + /** Pan-press cleanup defers deactivation while the pointer hovers, so a press/click doesn't reset a hover-driven state. */ + const isPointerHovering = useSharedValue(false); React.useEffect(() => { - const vals = chartPressStateRef.current; - const states = Array.isArray(vals) ? vals : [vals]; + const pressVals = chartPressStateRef.current; + const pressStates = Array.isArray(pressVals) ? pressVals : [pressVals]; + const hoverVals = chartHoverStateRef.current; + const hoverStates = Array.isArray(hoverVals) ? hoverVals : [hoverVals]; - for (const state of states) { + for (const state of [...pressStates, ...hoverStates]) { if (state) resetChartPressState(state); } + resetChartPressState(builtInHoverState); touchMap.value = {}; gestureState.value = { @@ -655,7 +703,15 @@ function CartesianChartContent< bootstrap: [], }; lastIdx.value = null; - }, [data, gestureState, lastIdx, touchMap, xKey, yKeysKey]); + }, [ + builtInHoverState, + data, + gestureState, + lastIdx, + touchMap, + xKey, + yKeysKey, + ]); const panGesture = Gesture.Pan() /** @@ -721,9 +777,11 @@ function CartesianChartContent< */ .onFinalize(() => { const vals = activePressSharedValues || []; - for (const val of vals) { - if (val) { - val.isActive.value = false; + if (!(hoverDrivesPressValues && isPointerHovering.value)) { + for (const val of vals) { + if (val) { + val.isActive.value = false; + } } } @@ -770,11 +828,10 @@ function CartesianChartContent< for (const touch of e.changedTouches) { const vals = activePressSharedValues || []; - // Set active state to false const touchId = touch?.id; const idx = typeof touchId === "number" && touchMap.value[touchId]; const val = typeof idx === "number" && vals[idx]; - if (val) { + if (val && !(hoverDrivesPressValues && isPointerHovering.value)) { val.isActive.value = false; } @@ -789,7 +846,7 @@ function CartesianChartContent< const vals = activePressSharedValues || []; // Set active state to false for all vals for (const val of vals) { - if (val) { + if (val && !(hoverDrivesPressValues && isPointerHovering.value)) { val.isActive.value = false; } } @@ -801,6 +858,58 @@ function CartesianChartContent< gestureLongPressDelay, }); + const hoverGesture = Gesture.Hover() + .onStart((e) => { + isPointerHovering.value = true; + const pointer = getCartesianTouchCoordinates({ + touch: e, + transform: transformState?.matrix.value, + }); + + for (const v of activeHoverSharedValues) { + if (!v) continue; + v.isActive.value = true; + handleTouch(v, pointer.x, pointer.y); + } + }) + .onUpdate((e) => { + const pointer = getCartesianTouchCoordinates({ + touch: e, + transform: transformState?.matrix.value, + }); + + for (const v of activeHoverSharedValues) { + if (!v) continue; + if (!v.isActive.value) v.isActive.value = true; + handleTouch(v, pointer.x, pointer.y); + } + }) + /** Hover may stop receiving move events while pan owns the stream + * (e.g. web); stay active so a plain click doesn't flicker the tooltip. */ + .onTouchesDown(() => { + isPointerHovering.value = true; + for (const v of activeHoverSharedValues) { + if (v && !v.isActive.value) v.isActive.value = true; + } + }) + .onEnd(() => { + isPointerHovering.value = false; + for (const v of activeHoverSharedValues) { + if (v) v.isActive.value = false; + } + }) + .onFinalize(() => { + isPointerHovering.value = false; + for (const v of activeHoverSharedValues) { + if (v) v.isActive.value = false; + } + }); + + applyChartHoverConfig({ + gesture: hoverGesture, + hoverConfig: chartHoverConfig, + }); + /** * Allow end-user to request "raw-ish" data for a given yKey. * Generate this on demand using a proxy. @@ -868,6 +977,12 @@ function CartesianChartContent< chartBounds, canvasSize: size, points, + // `SharedValue`'s contravariant setter blocks direct assignment to the render-arg type. + hoverState: usesBuiltInHoverState + ? (builtInHoverState as unknown as ChartBuiltInHoverState< + Extract + >) + : undefined, }; const clipRect = boundsToClip(chartBounds); @@ -1005,6 +1120,9 @@ function CartesianChartContent< if (chartPressState) { composed = Gesture.Race(composed, panGesture); } + if (enableHover) { + composed = Gesture.Simultaneous(composed, hoverGesture); + } gestureOverlay = ( diff --git a/lib/src/cartesian/hooks/useChartPressState.test.ts b/lib/src/cartesian/hooks/useChartPressState.test.ts new file mode 100644 index 00000000..bfc16d6d --- /dev/null +++ b/lib/src/cartesian/hooks/useChartPressState.test.ts @@ -0,0 +1,68 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { SharedValue } from "react-native-reanimated"; +import { makeChartPressState } from "./useChartPressState"; +import { resetChartPressState } from "../utils/resetChartPressState"; + +const mutableStores: { value: unknown }[] = []; + +vi.mock("react-native-reanimated", () => ({ + makeMutable: (init: unknown) => { + const sv = { value: init } as SharedValue; + mutableStores.push(sv); + return sv; + }, +})); + +beforeEach(() => { + mutableStores.length = 0; +}); + +describe("makeChartPressState", () => { + it("builds a fully initialized ChartPressState from the initial values", () => { + const state = makeChartPressState({ + x: 3, + y: { high: 40, low: 10 }, + }); + + expect(state.isActive.value).toBe(false); + expect(state.matchedIndex.value).toBe(-1); + expect(state.yIndex.value).toBe(-1); + expect(state.x.value.value).toBe(3); + expect(state.x.position.value).toBe(0); + expect(state.y.high.value.value).toBe(40); + expect(state.y.high.position.value).toBe(0); + expect(state.y.low.value.value).toBe(10); + expect(state.y.low.position.value).toBe(0); + }); + + it("creates independent shared values per call", () => { + const a = makeChartPressState({ x: 1, y: { v: 0 } }); + const b = makeChartPressState({ x: 2, y: { v: 0 } }); + + a.x.value.value = 99; + expect(b.x.value.value).toBe(2); + + a.isActive.value = true; + expect(b.isActive.value).toBe(false); + }); + + it("produces a state that resetChartPressState clears", () => { + const state = makeChartPressState({ x: 5, y: { high: 1 } }); + + state.isActive.value = true; + state.matchedIndex.value = 7; + state.yIndex.value = 3; + state.x.position.value = 120; + state.y.high.position.value = 80; + + resetChartPressState(state); + + expect(state.isActive.value).toBe(false); + expect(state.matchedIndex.value).toBe(-1); + expect(state.yIndex.value).toBe(-1); + expect(state.x.position.value).toBe(0); + expect(state.x.value.value).toBe(5); + expect(state.y.high.position.value).toBe(0); + expect(state.y.high.value.value).toBe(1); + }); +}); diff --git a/lib/src/cartesian/hooks/useChartPressState.ts b/lib/src/cartesian/hooks/useChartPressState.ts index ebc185f0..6c046ccd 100644 --- a/lib/src/cartesian/hooks/useChartPressState.ts +++ b/lib/src/cartesian/hooks/useChartPressState.ts @@ -13,25 +13,7 @@ export const useChartPressState = ( const keys = Object.keys(initialValues.y).join(","); const state = React.useMemo(() => { - return { - isActive: makeMutable(false), - matchedIndex: makeMutable(-1), - x: { value: makeMutable(initialValues.x), position: makeMutable(0) }, - y: Object.entries(initialValues.y).reduce( - (acc, [key, initVal]) => { - acc[key as keyof Init["y"]] = { - value: makeMutable(initVal), - position: makeMutable(0), - }; - return acc; - }, - {} as Record< - keyof Init["y"], - { value: SharedValue; position: SharedValue } - >, - ), - yIndex: makeMutable(-1), // used for stacked bar charts - }; + return makeChartPressState(initialValues); // eslint-disable-next-line react-hooks/exhaustive-deps }, [keys]); @@ -40,6 +22,29 @@ export const useChartPressState = ( return { state, isActive }; }; +/** Builds a `ChartPressState` outside of hooks (e.g. the chart's built-in hover state); memoize the result. */ +export const makeChartPressState = ( + initialValues: Init, +): ChartPressState => ({ + isActive: makeMutable(false), + matchedIndex: makeMutable(-1), + x: { value: makeMutable(initialValues.x), position: makeMutable(0) }, + y: Object.entries(initialValues.y).reduce( + (acc, [key, initVal]) => { + acc[key as keyof Init["y"]] = { + value: makeMutable(initVal), + position: makeMutable(0), + }; + return acc; + }, + {} as Record< + keyof Init["y"], + { value: SharedValue; position: SharedValue } + >, + ), + yIndex: makeMutable(-1), // used for stacked bar charts +}); + export type ChartPressStateInit = { x: InputFieldType; y: Record; diff --git a/lib/src/index.ts b/lib/src/index.ts index b10f7d7e..0c7c9967 100644 --- a/lib/src/index.ts +++ b/lib/src/index.ts @@ -16,6 +16,8 @@ export { type Viewport, type ChartBounds, type ChartPressPanConfig, + type ChartHoverConfig, + type PieHoverState, type CartesianChartOrientation, type YAxisSide, type XAxisSide, @@ -157,3 +159,4 @@ export { Pie, type PieSliceData } from "./pie"; export { useSlicePath } from "./pie/hooks/useSlicePath"; export { useSliceAngularInsetPath } from "./pie/hooks/useSliceAngularInsetPath"; +export { usePieHoverState } from "./polar/contexts/PolarChartContext"; diff --git a/lib/src/pie/PieChart.tsx b/lib/src/pie/PieChart.tsx index 2e219060..68b1d211 100644 --- a/lib/src/pie/PieChart.tsx +++ b/lib/src/pie/PieChart.tsx @@ -1,7 +1,9 @@ import * as React from "react"; import { type Color } from "react-native-skia"; +import { useAnimatedReaction } from "react-native-reanimated"; import { PieSlice, type PieSliceData } from "./PieSlice"; import { handleTranslateInnerRadius } from "./utils/innerRadius"; +import { getHoveredPieSliceIndex } from "./utils/getHoveredPieSliceIndex"; import { getPieLayout } from "./utils/pieLayout"; import { PieSliceProvider } from "./contexts/PieSliceContext"; import { usePolarChartContext } from "../polar/contexts/PolarChartContext"; @@ -82,6 +84,29 @@ export const PieChart = (props: PieChartProps) => { _startAngle, ]); + const { hoverPointer, chartHoverState } = usePolarChartContext(); + // The pointer may sit over stale geometry after a data change; reset the hover index. + React.useEffect(() => { + chartHoverState.index.value = -1; + // Keyed only on data: `chartHoverState` is commonly inline (`{{ index }}`) + // and would reset hover on every render. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [_data]); + useAnimatedReaction( + () => hoverPointer?.value ?? null, + (pointer) => { + "worklet"; + chartHoverState.index.value = getHoveredPieSliceIndex({ + pointer, + center, + radius, + circleSweepDegrees, + startAngle: _startAngle, + slices: data, + }); + }, + ); + return ( <> {data.map((slice, index) => { diff --git a/lib/src/pie/utils/getHoveredPieSliceIndex.test.ts b/lib/src/pie/utils/getHoveredPieSliceIndex.test.ts new file mode 100644 index 00000000..edf07109 --- /dev/null +++ b/lib/src/pie/utils/getHoveredPieSliceIndex.test.ts @@ -0,0 +1,236 @@ +import { describe, expect, it } from "vitest"; +import { getHoveredPieSliceIndex } from "./getHoveredPieSliceIndex"; +import type { PieSliceData } from "../PieSlice"; + +const center = { x: 100, y: 100 }; +const radius = 80; + +type SliceInput = { sweepAngle: number }; + +const makeSlices = ( + startAngleIn: number, + inputs: SliceInput[], +): PieSliceData[] => { + let startAngle = startAngleIn; + return inputs.map((input) => { + const slice: PieSliceData = { + value: 1, + label: "slice", + color: "#000", + innerRadius: 0, + startAngle, + endAngle: startAngle + input.sweepAngle, + sweepAngle: input.sweepAngle, + sliceIsEntireCircle: false, + radius, + center, + }; + startAngle += input.sweepAngle; + return slice; + }); +}; + +const pointerAt = (angleDeg: number, dist?: number) => { + const r = dist ?? radius / 2; + return { + x: center.x + r * Math.cos((angleDeg * Math.PI) / 180), + y: center.y + r * Math.sin((angleDeg * Math.PI) / 180), + }; +}; + +describe("getHoveredPieSliceIndex", () => { + it("returns -1 without a pointer", () => { + expect( + getHoveredPieSliceIndex({ + pointer: null, + center, + radius, + circleSweepDegrees: 360, + startAngle: 0, + slices: makeSlices(0, [{ sweepAngle: 180 }, { sweepAngle: 180 }]), + }), + ).toBe(-1); + }); + + it("returns -1 when the pointer is outside the pie radius", () => { + expect( + getHoveredPieSliceIndex({ + pointer: pointerAt(90, radius + 20), + center, + radius, + circleSweepDegrees: 360, + startAngle: 0, + slices: makeSlices(0, [{ sweepAngle: 360 }]), + }), + ).toBe(-1); + }); + + it("matches the slice containing the pointer angle", () => { + const slices = makeSlices(0, [ + { sweepAngle: 120 }, + { sweepAngle: 120 }, + { sweepAngle: 120 }, + ]); + expect( + getHoveredPieSliceIndex({ + pointer: pointerAt(60), + center, + radius, + circleSweepDegrees: 360, + startAngle: 0, + slices, + }), + ).toBe(0); + expect( + getHoveredPieSliceIndex({ + pointer: pointerAt(150), + center, + radius, + circleSweepDegrees: 360, + startAngle: 0, + slices, + }), + ).toBe(1); + expect( + getHoveredPieSliceIndex({ + pointer: pointerAt(300), + center, + radius, + circleSweepDegrees: 360, + startAngle: 0, + slices, + }), + ).toBe(2); + }); + + it("matches slices after a negative start angle offset", () => { + const startAngle = -90; // chart starts at 12 o'clock + const slices = makeSlices(startAngle, [ + { sweepAngle: 180 }, + { sweepAngle: 180 }, + ]); + // atan2 angle 0° (due right) sits 90° into the -90° chart + expect( + getHoveredPieSliceIndex({ + pointer: pointerAt(0), + center, + radius, + circleSweepDegrees: 360, + startAngle, + slices, + }), + ).toBe(0); + // atan2 angle 135° is 225° past the chart start -> second slice + expect( + getHoveredPieSliceIndex({ + pointer: pointerAt(135), + center, + radius, + circleSweepDegrees: 360, + startAngle, + slices, + }), + ).toBe(1); + }); + + it("wraps pointer angles around 360°", () => { + const slices = makeSlices(0, [{ sweepAngle: 90 }, { sweepAngle: 270 }]); + // atan2 angle of 350° sits just before the 90°-start chart boundary, + // rel = (350 - 90) % 360 = 260 -> second slice + expect( + getHoveredPieSliceIndex({ + pointer: pointerAt(350), + center, + radius, + circleSweepDegrees: 360, + startAngle: 90, + slices, + }), + ).toBe(1); + }); + + it("returns -1 when the pointer is outside a partial-pie sweep", () => { + const slices = makeSlices(0, [{ sweepAngle: 180 }]); + // full circle sweep is only 180° deep, pointer at rel ~270° is beyond it + expect( + getHoveredPieSliceIndex({ + pointer: pointerAt(270), + center, + radius, + circleSweepDegrees: 180, + startAngle: 0, + slices, + }), + ).toBe(-1); + }); + + it("returns -1 inside the donut hole", () => { + const slices = makeSlices(0, [{ sweepAngle: 360 }]).map((slice) => ({ + ...slice, + innerRadius: 40, + })); + // dead center of the donut + expect( + getHoveredPieSliceIndex({ + pointer: { x: center.x, y: center.y }, + center, + radius, + circleSweepDegrees: 360, + startAngle: 0, + slices, + }), + ).toBe(-1); + // within the hole but off-center + expect( + getHoveredPieSliceIndex({ + pointer: pointerAt(200, 10), + center, + radius, + circleSweepDegrees: 360, + startAngle: 0, + slices, + }), + ).toBe(-1); + }); + + it("matches slices whose angles are measured relative to the chart start", () => { + const startAngle = 200; + const slices: PieSliceData[] = [ + { + value: 1, + label: "slice", + color: "#000", + innerRadius: 0, + // unwrapped domain continues past 360, like the real PieChart build + startAngle: startAngle, + endAngle: startAngle + 160, + sweepAngle: 160, + sliceIsEntireCircle: false, + radius, + center, + }, + { + value: 1, + label: "slice", + color: "#000", + innerRadius: 0, + startAngle: startAngle + 160, + endAngle: startAngle + 360, + sweepAngle: 200, + sliceIsEntireCircle: false, + radius, + center, + }, + ]; + expect( + getHoveredPieSliceIndex({ + pointer: pointerAt(20), // rel = (20 - 200 + 360) % 360 = 180 -> second + center, + radius, + circleSweepDegrees: 360, + startAngle, + slices, + }), + ).toBe(1); + }); +}); diff --git a/lib/src/pie/utils/getHoveredPieSliceIndex.ts b/lib/src/pie/utils/getHoveredPieSliceIndex.ts new file mode 100644 index 00000000..905a660a --- /dev/null +++ b/lib/src/pie/utils/getHoveredPieSliceIndex.ts @@ -0,0 +1,47 @@ +import type { PieSliceData } from "../PieSlice"; +import type { PolarHoverPointer } from "../../polar/contexts/PolarChartContext"; + +export const getHoveredPieSliceIndex = ({ + pointer, + center, + radius, + circleSweepDegrees, + startAngle, + slices, +}: { + pointer: PolarHoverPointer; + center: { x: number; y: number }; + radius: number; + circleSweepDegrees: number; + startAngle: number; + slices: PieSliceData[]; +}) => { + "worklet"; + if (!pointer) return -1; + + const dx = pointer.x - center.x; + const dy = pointer.y - center.y; + const dist = Math.sqrt(dx * dx + dy * dy); + + if (dist > radius) return -1; + + let angle = (Math.atan2(dy, dx) * 180) / Math.PI; + if (angle < 0) angle += 360; + // Pointer angle relative to the chart's start angle, wrapped into + // [0, 360) so it can be compared against unwrapped slice angles. + let rel = angle - startAngle; + rel = ((rel % 360) + 360) % 360; + if (rel > circleSweepDegrees) return -1; + + for (let i = 0; i < slices.length; i++) { + const slice = slices[i]; + if (!slice) continue; + if (dist < slice.innerRadius || dist > slice.radius) continue; + const sliceStart = slice.startAngle - startAngle; + if (rel >= sliceStart && rel <= sliceStart + slice.sweepAngle) { + return i; + } + } + + return -1; +}; diff --git a/lib/src/polar/PolarChart.tsx b/lib/src/polar/PolarChart.tsx index 12b90d4b..633c459a 100644 --- a/lib/src/polar/PolarChart.tsx +++ b/lib/src/polar/PolarChart.tsx @@ -1,25 +1,34 @@ import * as React from "react"; import { Group } from "react-native-skia"; import { + Platform, type ViewStyle, type StyleProp, type LayoutChangeEvent, } from "react-native"; import { Gesture } from "react-native-gesture-handler"; +import { useSharedValue, type SharedValue } from "react-native-reanimated"; import { type ContextBridge, FiberProvider, useContextBridge } from "its-fine"; -import { PolarChartProvider } from "./contexts/PolarChartContext"; +import { + PolarChartProvider, + type PolarHoverPointer, +} from "./contexts/PolarChartContext"; import type { ColorFields, InputFields, NumericalFields, StringKeyOf, + ChartHoverConfig, + PieHoverState, } from "../types"; import { type ChartTransformState } from "../cartesian/hooks/useChartTransformState"; import { panTransformGesture, pinchTransformGesture, } from "../cartesian/utils/transformGestures"; +import { getCartesianTouchCoordinates } from "../cartesian/utils/getCartesianTouchCoordinates"; import { GestureHandler } from "../shared/GestureHandler"; +import { applyChartHoverConfig } from "../shared/applyChartHoverConfig"; import { type ChartExplicitSize } from "../shared/ChartExplicitSize"; import { type ChartLayoutModeProps } from "../shared/ChartLayoutModeProps"; import { ChartWrapper } from "../shared/ChartWrapper"; @@ -34,6 +43,9 @@ type PolarChartBaseProps = { transformState?: ChartTransformState; isHeadless: boolean; explicitSize?: ChartExplicitSize; + enableHover?: boolean; + hoverPointer: SharedValue; + chartHoverConfig?: ChartHoverConfig; }; const PolarChartBase = ( @@ -49,7 +61,12 @@ const PolarChartBase = ( transformState, isHeadless, explicitSize, + enableHover: enableHoverProp, + hoverPointer, + chartHoverConfig, } = props; + // Hover is aimed at pointer devices, so it's on by default on web. + const enableHover = enableHoverProp ?? Platform.OS === "web"; const Bridge: ContextBridge = useContextBridge(); let composed = Gesture.Race(); @@ -61,6 +78,35 @@ const PolarChartBase = ( ); } + const hoverGesture = Gesture.Hover() + .onStart((e) => { + hoverPointer.value = getCartesianTouchCoordinates({ + touch: e, + transform: transformState?.matrix.value, + }); + }) + .onUpdate((e) => { + hoverPointer.value = getCartesianTouchCoordinates({ + touch: e, + transform: transformState?.matrix.value, + }); + }) + .onEnd(() => { + hoverPointer.value = null; + }) + .onFinalize(() => { + hoverPointer.value = null; + }); + + applyChartHoverConfig({ + gesture: hoverGesture, + hoverConfig: chartHoverConfig, + }); + + if (enableHover) { + composed = Gesture.Simultaneous(composed, hoverGesture); + } + const chartContent = ( {hasMeasuredLayoutSize && children} @@ -97,10 +143,17 @@ type PolarChartProps< colorKey: ColorKey; labelKey: LabelKey; valueKey: ValueKey; + enableHover?: boolean; + chartHoverState?: PieHoverState; + chartHoverConfig?: ChartHoverConfig; } & ChartLayoutModeProps & Omit< PolarChartBaseProps, - "canvasSize" | "onLayout" | "hasMeasuredLayoutSize" | "isHeadless" + | "canvasSize" + | "onLayout" + | "hasMeasuredLayoutSize" + | "isHeadless" + | "hoverPointer" >; export const PolarChart = < RawData extends Record, @@ -124,6 +177,14 @@ export const PolarChart = < headless: props.headless, }); + const hoverPointer = useSharedValue(null); + // The `chartHoverState` prop only overrides this default for consumers that + // need the index outside the chart; other content reads it via `usePieHoverState()`. + const defaultHoverIndex = useSharedValue(-1); + const chartHoverState = props.chartHoverState ?? { + index: defaultHoverIndex, + }; + return ( diff --git a/lib/src/polar/contexts/PolarChartContext.tsx b/lib/src/polar/contexts/PolarChartContext.tsx index 34fb806d..d2dd4c05 100644 --- a/lib/src/polar/contexts/PolarChartContext.tsx +++ b/lib/src/polar/contexts/PolarChartContext.tsx @@ -3,6 +3,11 @@ import React, { createContext, type PropsWithChildren, } from "react"; +import type { SharedValue } from "react-native-reanimated"; +import type { PieHoverState } from "../../types"; + +/** Chart-space pointer position while hovering (`null` otherwise). */ +export type PolarHoverPointer = { x: number; y: number } | null; interface PolarChartContext { data: Record[]; @@ -10,6 +15,8 @@ interface PolarChartContext { labelKey: string; valueKey: string; colorKey: string; + hoverPointer?: SharedValue; + chartHoverState: PieHoverState; } const PolarChartContext = createContext( @@ -22,12 +29,23 @@ interface PolarChartProviderProps { labelKey: string; valueKey: string; colorKey: string; + hoverPointer?: SharedValue; + chartHoverState: PieHoverState; } export const PolarChartProvider = ( props: PropsWithChildren, ) => { - const { children, data, canvasSize, labelKey, valueKey, colorKey } = props; + const { + children, + data, + canvasSize, + labelKey, + valueKey, + colorKey, + hoverPointer, + chartHoverState, + } = props; return ( {children} @@ -55,3 +75,14 @@ export const usePolarChartContext = () => { return context; }; + +/** + * Hover state for pie and donut charts; `index` is the hovered slice, or `-1` + * when none is hovered. `PolarChart` maintains this value (`chartHoverState` + * only overrides it), so this hook works without passing the prop. + */ +export const usePieHoverState = (): PieHoverState => { + const { chartHoverState } = usePolarChartContext(); + + return chartHoverState; +}; diff --git a/lib/src/shared/applyChartHoverConfig.test.ts b/lib/src/shared/applyChartHoverConfig.test.ts new file mode 100644 index 00000000..305a6fd9 --- /dev/null +++ b/lib/src/shared/applyChartHoverConfig.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it, vi } from "vitest"; +import { applyChartHoverConfig } from "./applyChartHoverConfig"; + +const createHoverGesture = () => ({ + activeCursor: vi.fn(), + simultaneousWithExternalGesture: vi.fn(), +}); + +describe("applyChartHoverConfig", () => { + it("leaves the gesture untouched when no hover config is provided", () => { + const hoverGesture = createHoverGesture(); + + applyChartHoverConfig({ gesture: hoverGesture }); + + expect(hoverGesture.activeCursor).not.toHaveBeenCalled(); + expect(hoverGesture.simultaneousWithExternalGesture).not.toHaveBeenCalled(); + }); + + it("wires the activeCursor to the gesture", () => { + const hoverGesture = createHoverGesture(); + + applyChartHoverConfig({ + gesture: hoverGesture, + hoverConfig: { activeCursor: "pointer" }, + }); + + expect(hoverGesture.activeCursor).toHaveBeenCalledWith("pointer"); + expect(hoverGesture.simultaneousWithExternalGesture).not.toHaveBeenCalled(); + }); + + it("wires a single external gesture", () => { + const hoverGesture = createHoverGesture(); + const scrollRef = { current: undefined }; + + applyChartHoverConfig({ + gesture: hoverGesture, + hoverConfig: { simultaneousWithExternalGesture: scrollRef }, + }); + + expect(hoverGesture.simultaneousWithExternalGesture).toHaveBeenCalledWith( + scrollRef, + ); + expect(hoverGesture.activeCursor).not.toHaveBeenCalled(); + }); + + it("wires an array of external gestures", () => { + const hoverGesture = createHoverGesture(); + const first = { current: undefined }; + const second = { current: undefined }; + + applyChartHoverConfig({ + gesture: hoverGesture, + hoverConfig: { simultaneousWithExternalGesture: [first, second] }, + }); + + expect(hoverGesture.simultaneousWithExternalGesture).toHaveBeenCalledWith( + first, + second, + ); + }); +}); diff --git a/lib/src/shared/applyChartHoverConfig.ts b/lib/src/shared/applyChartHoverConfig.ts new file mode 100644 index 00000000..b0a482b1 --- /dev/null +++ b/lib/src/shared/applyChartHoverConfig.ts @@ -0,0 +1,36 @@ +import type { HoverGesture, PanGesture } from "./gestureTypes"; +import type { ChartHoverConfig } from "../types"; + +type ChartHoverExternalGesture = Parameters< + PanGesture["simultaneousWithExternalGesture"] +>[number]; + +type ChartHoverGesture = { + activeCursor: ( + cursor: Parameters[number], + ) => void; + simultaneousWithExternalGesture: ( + ...gestures: ChartHoverExternalGesture[] + ) => void; +}; + +export const applyChartHoverConfig = ({ + gesture, + hoverConfig, +}: { + gesture: ChartHoverGesture; + hoverConfig?: ChartHoverConfig; +}) => { + if (hoverConfig?.activeCursor) { + gesture.activeCursor(hoverConfig.activeCursor); + } + + if (hoverConfig?.simultaneousWithExternalGesture) { + const externalGestures = Array.isArray( + hoverConfig.simultaneousWithExternalGesture, + ) + ? hoverConfig.simultaneousWithExternalGesture + : [hoverConfig.simultaneousWithExternalGesture]; + gesture.simultaneousWithExternalGesture(...externalGestures); + } +}; diff --git a/lib/src/shared/gestureTypes.ts b/lib/src/shared/gestureTypes.ts index b292bd2f..1448cb61 100644 --- a/lib/src/shared/gestureTypes.ts +++ b/lib/src/shared/gestureTypes.ts @@ -4,4 +4,5 @@ import type { Gesture } from "react-native-gesture-handler"; // Gesture API so our declarations work with both RNGH 2 and 3. export type PanGesture = ReturnType; export type PinchGesture = ReturnType; +export type HoverGesture = ReturnType; export type ComposedGesture = ReturnType; diff --git a/lib/src/types.ts b/lib/src/types.ts index 16e8e35e..5f8692cf 100644 --- a/lib/src/types.ts +++ b/lib/src/types.ts @@ -11,7 +11,7 @@ import type { UserSelect, TouchAction, } from "react-native-gesture-handler/lib/typescript/handlers/gestureHandlerCommon"; -import type { PanGesture } from "./shared/gestureTypes"; +import type { PanGesture, HoverGesture } from "./shared/gestureTypes"; export type PrimitiveViewWindow = { xMin: number; @@ -133,6 +133,8 @@ export type CartesianChartRenderArg< points: { [K in YK]: PointsArray; }; + /** The chart's built-in hover state; only present when neither `chartPressState` nor `chartHoverState` was passed. */ + hoverState?: ChartBuiltInHoverState>; }; export type Scale = ScaleLinear; @@ -391,6 +393,30 @@ export type ChartPressPanConfig = { simultaneousWithExternalGesture?: ExternalGesture | ExternalGesture[]; }; +export type ChartHoverConfig = { + /** Cursor shown while the pointer hovers over the chart. */ + activeCursor?: Parameters[number]; + /** Gestures the hover gesture composes with simultaneously, e.g. custom gestures built outside the chart. */ + simultaneousWithExternalGesture?: ExternalGesture | ExternalGesture[]; +}; + +/** Hover state for pie charts; `index` is the hovered slice, or `-1`. */ +export type PieHoverState = { + index: SharedValue; +}; + +/** + * The built-in, hover-only state `CartesianChart` maintains when neither + * `chartPressState` nor `chartHoverState` is passed; exposed via the render arg's `hoverState`. + */ +export type ChartBuiltInHoverState = { + isActive: SharedValue; + matchedIndex: SharedValue; + x: { value: SharedValue; position: SharedValue }; + y: Record; position: SharedValue }>; + yIndex: SharedValue; +}; + export type NonEmptyArray = [T, ...T[]]; /** diff --git a/lib/test/headless/stubs/react-native-gesture-handler.ts b/lib/test/headless/stubs/react-native-gesture-handler.ts index 8d16a272..a0236ce0 100644 --- a/lib/test/headless/stubs/react-native-gesture-handler.ts +++ b/lib/test/headless/stubs/react-native-gesture-handler.ts @@ -15,14 +15,17 @@ const chainableGesture = (): ChainableGesture => { export const Gesture = { Race: (..._gestures: unknown[]) => chainableGesture(), + Simultaneous: (..._gestures: unknown[]) => chainableGesture(), Pinch: () => chainableGesture(), Pan: () => chainableGesture(), + Hover: () => chainableGesture(), LongPress: () => chainableGesture(), Tap: () => chainableGesture(), }; export type PanGesture = ReturnType; export type PinchGesture = ReturnType; +export type HoverGesture = ReturnType; export type ComposedGesture = ReturnType; export type GestureType = PanGesture | PinchGesture | ComposedGesture; export type TouchData = { x: number; y: number }; diff --git a/website/docs/cartesian/cartesian-chart.md b/website/docs/cartesian/cartesian-chart.md index db4dbf3a..d4a25031 100644 --- a/website/docs/cartesian/cartesian-chart.md +++ b/website/docs/cartesian/cartesian-chart.md @@ -242,12 +242,76 @@ The `frame` is an optional prop allows you to configure the frame of the chart. The `chartPressState` prop allows you to pass in Reanimated `SharedValue`s that will be used to track the user's "press" gesture on the chart. This is generally used for creating some sort of tooltip/active value indicator. See the [Chart Gestures page](./chart-gestures.mdx) for more in-depth information on how to use this prop. +It is also driven by mouse hovers when the [`enableHover`](#enablehover) prop is enabled — unless a separate [`chartHoverState`](#charthoverstate) prop is provided, in which case only the `chartHoverState` receives hover updates. This is useful on web/desktop where a mouse is available. + The `chartPressState` prop has a type of `ChartPressState | ChartPressState[]`, where `ChartPressState` is an object generated from the `useChartPressState` hook. :::info If you have a data point whose y-value is `null` or `undefined`, when that point is "active" the gesture state will return `NaN` for the y-value and y-position. ::: +:::info +When no point is "active" (no press/hover), the gesture state will return `NaN` for `x.value` and the y-values. Use the `isActive` flag to determine whether the state is active. +::: + +### `chartHoverState` + +Optional. A `ChartPressState` value (or array of them) generated from the `useChartPressState` hook — same type as `chartPressState` — that the hover gesture writes to instead of the press values. Requires [`enableHover`](#enablehover) on non-web platforms (hover is on by default on web). + +Hover always has some state to write to, in this priority order: + +1. **`chartHoverState`** when provided — hover and press are tracked independently, e.g. a hover tooltip that follows the mouse while a pressed tooltip stays pinned: + +```tsx +import { CartesianChart, useChartPressState } from "victory-native"; + +const press = useChartPressState({ x: 0, y: { highTmp: 0 } }); +const hover = useChartPressState({ x: 0, y: { highTmp: 0 } }); + +return ( + + {/* ... */} + +); +``` + +2. **`chartPressState`** when `chartHoverState` is omitted — hovering updates the press values themselves, so the hover gesture behaves exactly like the press gesture with no extra setup. + +3. **A built-in hover state** (mirroring `PolarChart`) when neither prop is passed. The chart owns this state and exposes it via the render function's [`hoverState`](#hoverstate) field, so simple hover readouts need no state setup at all: + +```tsx +import * as React from "react"; +import { Circle } from "react-native-skia"; +import { CartesianChart, Line } from "victory-native"; + +function Chart({ data }: { data: { day: number; highTmp: number }[] }) { + return ( + + {({ points, hoverState }) => ( + <> + + {/* hoverState is the chart's built-in hover state; undefined when + you pass chartPressState or chartHoverState yourself */} + {hoverState && hoverState.isActive.value && ( + + )} + + )} + + ); +} +``` + ### `renderOutside` The `renderOutside` prop is identical to [the `children` prop](#children-required) in form, but it will render elements at the root of the Skia canvas (not inside of a clipping group). This allows you to render elements outside of the bounds of any axes that you have configured. @@ -285,6 +349,49 @@ These properties correspond directly to the [React Native Gesture Handler's PanG Explicit `0` values are honored for these options. For example, `activateAfterLongPress: 0` is applied rather than treated as an omitted value. +### `enableHover` + +When `true`, the chart builds a [`Gesture.Hover()`](https://docs.swmansion.com/react-native-gesture-handler/docs/gestures/hover-gesture) that updates the values the hover gesture drives: a [`chartHoverState`](#charthoverstate) when one is provided, otherwise the `chartPressState` values — so hover behaves exactly like a press — or the chart's built-in hover state when neither prop is passed (exposed via the render function's [`hoverState`](#hoverstate) field). Moving the pointer — e.g. a mouse on web or desktop — over the chart updates the active x/y values and positions and sets `isActive` to `true`, and leaving the chart deactivates the state again. This makes it easy to show tooltips, cursors, or readouts while the pointer is over the chart, without requiring a press. + +Hover is aimed at pointer devices, so `enableHover` **defaults to `true` on web** (pass `enableHover={false}` there to opt out); on other platforms it stays opt-in. + +The hover gesture is composed simultaneously with the press and transform gestures, so it does not compete with (or break) existing interactions. On touch-only devices the regular press behavior is unaffected. + +```tsx +import { CartesianChart, useChartPressState } from "victory-native"; + +function HoveredChart() { + const { state, isActive } = useChartPressState({ x: 0, y: { highTmp: 0 } }); + + return ( + + {/* ... */} + + ); +} +``` + +### `chartHoverConfig` + +Optional configuration for the hover gesture created by `enableHover`. It accepts an object with the following optional properties: + +- `activeCursor`: the cursor to use while the pointer is over the chart. Supports all CSS cursor values (e.g. `"pointer"`, `"crosshair"`). Web/desktop only. +- `simultaneousWithExternalGesture`: one or more external Gesture Handler gesture refs that the hover gesture composes with simultaneously — useful when custom gestures are built outside the chart. + +```tsx + +``` + ### `transformState` The `transformState` prop allows you to pass in a transform state object that enables pan and zoom interactions with the chart. This object is typically created using the `useChartTransformState` hook. When provided, users can: @@ -615,3 +722,14 @@ a `number[]` which holds the normalized values of the canvas's horizontal axis. ### `yTicks` a `number[]` which holds the normalized values of the canvas's vertical axis. To map into canvas position values, use `yScale` (i.e. `yScale(yTicks[0])`) + +### `hoverState` + +Available **only when neither `chartPressState` nor `chartHoverState` is provided**; `undefined` otherwise (in that case, read your own state objects). This is the built-in hover state `CartesianChart` maintains so that hover works with zero setup — shaped like a `ChartPressState` and driven by the hover gesture only (press stays opt-in via [`chartPressState`](#chartpressstate)): + +- `isActive` — `true` while the pointer is over the chart +- `x.value` / `x.position` — the hovered x data value and its canvas position +- `y..value` / `y..position` — hovered y values and canvas positions for each key in `yKeys` +- `matchedIndex` / `yIndex` — index bookkeeping used by the bundled marks + +See the [`chartHoverState`](#charthoverstate) section for the full list of hover-driven state shapes. diff --git a/website/docs/cartesian/chart-gestures.mdx b/website/docs/cartesian/chart-gestures.mdx index 0d747346..479d694f 100644 --- a/website/docs/cartesian/chart-gestures.mdx +++ b/website/docs/cartesian/chart-gestures.mdx @@ -91,6 +91,146 @@ function ScrollableChart() { } ``` +## Hover gesture support + +The `CartesianChart` component (as well as `PolarChart` for pie/donut charts) supports tracking the user's mouse as it _hovers_ over the chart. On web, or on desktop builds, this lets readers explore a chart — e.g. read out values via a tooltip — without pressing anything. The hover gesture is built with the [`Gesture.Hover()`](https://docs.swmansion.com/react-native-gesture-handler/docs/gestures/hover-gesture) API from React Native Gesture Handler and is composed simultaneously with the press/transform gestures, so it never takes precedence over them. + +Hover is aimed at pointer devices, so it is **enabled by default on web** — `enableHover` opts in on other platforms (and `enableHover={false}` opts out on web). Touch-only behavior is unchanged either way. + +Press/click and hover interoperate: while the pointer is over the chart, pressing or clicking does not deactivate the hover-driven state — releasing the mouse button simply hands the tooltip back to the ongoing hover gesture — and moving the pointer out of the chart deactivates it as usual. On touch devices (where hover never activates), press behavior is exactly the same as it would be without hover. + +### Hovering cartesian charts + +Pass `enableHover` along with a `chartPressState` value: while the pointer is over the chart, the press state values are updated (and their `isActive` flags are set) exactly as if the user was pressing; when the pointer leaves the chart, the states are deactivated again. Because hover drives the press states themselves, no extra setup is needed to make hover match press. + +```tsx +import * as React from "react"; +import { View } from "react-native"; +import { Line, CartesianChart, useChartPressState } from "victory-native"; +import { + Circle, + DashPathEffect, + Line as SkiaLine, + vec, +} from "react-native-skia"; +import { useDerivedValue, type SharedValue } from "react-native-reanimated"; +import { AnimatedText } from "./components/AnimatedText"; + +const DATA = Array.from({ length: 31 }, (_, i) => ({ + day: i, + highTmp: 40 + 30 * Math.random(), +})); + +function HoverGestureScreen() { + const { state, isActive } = useChartPressState({ x: 0, y: { highTmp: 0 } }); + + const hoveredDay = useDerivedValue(() => + isActive ? `Day ${state.x.value.value}` : "Hover the chart!", + ); + + return ( + + + + + isActive ? ( + + ) : null + } + > + {({ points }) => ( + <> + + {isActive && ( + + )} + + )} + + + ); +} + +function Cursor({ + xPosition, + chartBounds, +}: { + xPosition: SharedValue; + chartBounds: { top: number; bottom: number }; +}) { + const start = useDerivedValue(() => vec(xPosition.value, chartBounds.top)); + const end = useDerivedValue(() => vec(xPosition.value, chartBounds.bottom)); + + return ( + + + + ); +} +``` + +:::info + +The example app uses this API in several places — [`example/app/candlestick.tsx`](https://github.com/FormidableLabs/victory-native-xl/tree/main/example/app/candlestick.tsx) scrubs its tooltip on hover, and [`example/app/bar-chart.tsx`](https://github.com/FormidableLabs/victory-native-xl/tree/main/example/app/bar-chart.tsx) additionally shows a hover readout above the chart. Check the "Candlestick Chart" and "Bar Chart" routes of the example. + +::: + +### Zero-setup hover (no state required) + +You don't need any state at all: when neither `chartPressState` nor `chartHoverState` is passed, `CartesianChart` maintains a built-in hover state (mirroring `PolarChart`'s built-in pie state) and hands it to your render functions via `hoverState`: + +```tsx + + {({ points, hoverState }) => ( + <> + + {hoverState?.isActive.value && ( + + )} + + )} + +``` + +This state is hover-only — press interactions stay opt-in via [`chartPressState`](#the-chartpressstate-prop-of-cartesianchart). When you do pass a state, `hoverState` is `undefined` and you read your own object instead. + +### Distinct hover and press states + +Sharing the press state keeps things simple, but hovering and pressing may need to be tracked independently — e.g. a hover tooltip that follows the mouse while a pressed tooltip stays pinned where the mouse last clicked. Pass a separate `chartHoverState` (a `ChartPressState` value created with `useChartPressState`, just like `chartPressState`) and the hover gesture will drive it instead of the press states: + +```tsx +const press = useChartPressState({ x: 0, y: { highTmp: 0 } }); +const hover = useChartPressState({ x: 0, y: { highTmp: 0 } }); + + +``` + +Each state (and its `isActive` shared value) is updated independently, so a "hover is active" readout and a "press is active" indicator can coexist. + +Pie/donut charts (`PolarChart`) work the same way — they always maintain a hovered-slice-index state, consumable inside chart content with the [`usePieHoverState`](/docs/polar/polar-chart#charthoverstate) hook; the [`chartHoverState`](/docs/polar/polar-chart#charthoverstate) prop only overrides it when the index needs to be read outside the chart. + ## Multi-press support The `CartesianChart` component can track as many fingers as you want, but two will likely be the max you'd reasonably want to use. See [the multi-press guide](./guides/multi-press.md) to see an example of multi-press in action. diff --git a/website/docs/polar/pie/pie-charts.md b/website/docs/polar/pie/pie-charts.md index 221e7bce..78a53de3 100644 --- a/website/docs/polar/pie/pie-charts.md +++ b/website/docs/polar/pie/pie-charts.md @@ -9,6 +9,12 @@ The [example app](https://github.com/FormidableLabs/victory-native-xl/tree/main/ ::: +:::info + +Hover interactions for `Pie` and `Donut` charts are configured on the `PolarChart` component — see [`enableHover`](/docs/polar/polar-chart#enablehover) (on by default on web) and [`chartHoverState`](/docs/polar/polar-chart#charthoverstate). `PolarChart` maintains the hovered slice index for you; read it inside your pie content with [`usePieHoverState`](/docs/polar/polar-chart#charthoverstate), and pass `chartHoverState` only to consume the index outside the chart. + +::: + ## Example The example below shows the most basic use of the `Pie.Chart`. diff --git a/website/docs/polar/polar-chart.md b/website/docs/polar/polar-chart.md index 3018fc9b..df17c837 100644 --- a/website/docs/polar/polar-chart.md +++ b/website/docs/polar/polar-chart.md @@ -97,3 +97,101 @@ An object `{ width: number; height: number }` that seeds chart dimensions withou ### `headless` When `true` (and `explicitSize` is set), renders a Skia-only subtree with no `View`, `Canvas`, or gesture handlers—intended for offscreen render hosts. See [Headless rendering](../headless-rendering.md). + +### `enableHover` + +When `true`, the chart builds a [`Gesture.Hover()`](https://docs.swmansion.com/react-native-gesture-handler/docs/gestures/hover-gesture) to track the pointer — e.g. a mouse on web or desktop — as it moves over the chart. The pointer position is written into the chart context (inverted through the active `transformState`, when provided), and consumed through the [`chartHoverState`](#charthoverstate) behavior below. This enables hover interactions for `Pie` and `Donut` charts without any extra gesture code. + +Hover is aimed at pointer devices, so `enableHover` **defaults to `true` on web** (pass `enableHover={false}` there to opt out); on other platforms it stays opt-in. + +The hover gesture is composed simultaneously with the transform gestures, so it does not compete with (or break) existing interactions. + +### `chartHoverState` + +Optional. A Reanimated shared value object which receives the index of the data point (slice) currently under the pointer, or `-1` when the pointer is over the donut hole, outside the pie, or off the chart entirely. + +When omitted, `PolarChart` maintains a built-in hover state, which chart content reads with the [`usePieHoverState`](#charthoverstate) hook — so hover highlighting inside `Pie.Chart` needs no extra setup: + +```tsx +import * as React from "react"; +import { Text } from "react-native-skia"; +import { Pie, PolarChart, usePieHoverState } from "victory-native"; +import { useDerivedValue } from "react-native-reanimated"; + +function HoverReadout() { + // 👈 the built-in hover state; no `chartHoverState` prop needed + const hover = usePieHoverState(); + const text = useDerivedValue(() => + hover.index.value >= 0 ? "Slice hovered!" : "Hover the pie!", + ); + + return ( + + + + {/* 👇 drawn on the chart */} + + + + ); +} +``` + +Pass your own `chartHoverState` only when the hovered index must be consumed *outside* the chart — e.g. a readout rendered above the `Canvas`, where the shared value needs to live in your component: + +```tsx +import * as React from "react"; +import { View } from "react-native"; +import { Pie, PolarChart } from "victory-native"; +import { + useDerivedValue, + useSharedValue, +} from "react-native-reanimated"; +import { AnimatedText } from "./components/AnimatedText"; + +function HoveredPie() { + const [data, setData] = React.useState(DATA(5)); + + // 👇 a shared value receiving the hovered slice index (-1 = none) + const hoverIndex = useSharedValue(-1); + + const hoveredLabel = useDerivedValue(() => { + const i = hoverIndex.value; + return i >= 0 && i < data.length ? data[i].label : "Hover the pie!"; + }); + + return ( + + + + + + + + ); +} +``` + +:::info + +The slice geometry (including each slice's `innerRadius`, start/end angles, values, labels, and colors) is available to `Pie.Chart`'s `children` render prop — combine it with `chartHoverState` to style or animate the hovered slice. + +::: + +### `chartHoverConfig` + +Optional configuration for the hover gesture created by `enableHover`. It accepts an object with the following optional properties: + +- `activeCursor`: the cursor to use while the pointer is over the chart. Supports all CSS cursor values (e.g. `"pointer"`, `"crosshair"`). Web/desktop only. +- `simultaneousWithExternalGesture`: one or more external Gesture Handler gesture refs that the hover gesture composes with simultaneously — useful when custom gestures are built outside the chart.