From a4bb64d5e35c4ae3f84ca3ddc43eb18194926225 Mon Sep 17 00:00:00 2001 From: Adam Hari Date: Sat, 24 Oct 2026 19:28:11 -0600 Subject: [PATCH 01/25] feat: add hover gesture support (enableHover + chartHoverConfig) - CartesianChart: new optional \enableHover\ prop driving the first chartPressState via \Gesture.Hover()\ from react-native-gesture-handler; activates on pointer enter with live point tracking and deactivates on pointer leave/end/finalize. - New optional \chartHoverConfig\ prop (\{ activeCursor?: string }\) to style the hover cursor. - Composed with \Gesture.Simultaneous\ alongside existing pan/transform gestures so hover coexists with press-drag. - Export \ChartHoverConfig\ type from the package entry point. - Add \Gesture.Hover\ to the RNGH headless test stub so golden renders work. - Add example screen (\/hover-gesture\) with cursor line + live readouts. - Add example metro.config.js pinning web resolver conditions to the library source (avoids a TDZ crash from freshly-built lib/dist on web). - Changeset (minor). --- .changeset/hover-gesture-support.md | 5 + example/app/hover-gesture.tsx | 153 ++++++++++++++++++ example/consts/routes.ts | 6 + example/metro.config.js | 16 ++ lib/src/cartesian/CartesianChart.tsx | 78 +++++++++ lib/src/index.ts | 1 + lib/src/shared/gestureTypes.ts | 1 + lib/src/types.ts | 10 +- .../stubs/react-native-gesture-handler.ts | 2 + 9 files changed, 271 insertions(+), 1 deletion(-) create mode 100644 .changeset/hover-gesture-support.md create mode 100644 example/app/hover-gesture.tsx create mode 100644 example/metro.config.js diff --git a/.changeset/hover-gesture-support.md b/.changeset/hover-gesture-support.md new file mode 100644 index 00000000..705e9c9e --- /dev/null +++ b/.changeset/hover-gesture-support.md @@ -0,0 +1,5 @@ +--- +"victory-native": minor +--- + +Add hover gesture support to `CartesianChart`. Pass `enableHover` (optionally along with `chartHoverConfig={{ activeCursor }}`) together with `chartPressState` to keep the press value updated — and `isActive` true — while the pointer, e.g. a mouse on web or desktop, hovers over the chart. Hover is implemented with the `Gesture.Hover()` API from React Native Gesture Handler and is composed simultaneously with the press and transform gestures. diff --git a/example/app/hover-gesture.tsx b/example/app/hover-gesture.tsx new file mode 100644 index 00000000..a11f1332 --- /dev/null +++ b/example/app/hover-gesture.tsx @@ -0,0 +1,153 @@ +import * as React from "react"; +import { StyleSheet, View } from "react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; +import { CartesianChart, Line, useChartPressState } from "victory-native"; +import { + Circle, + DashPathEffect, + Line as SkiaLine, + useFont, + vec, +} from "react-native-skia"; +import { type SharedValue, useDerivedValue } from "react-native-reanimated"; +import { useDarkMode } from "react-native-dark"; +import { InfoCard } from "example/components/InfoCard"; +import { AnimatedText } from "../components/AnimatedText"; +import { appColors } from "../consts/colors"; +import inter from "../assets/inter-medium.ttf"; + +export default function HoverGestureScreen() { + const font = useFont(inter, 12); + const isDark = useDarkMode(); + const textColor = isDark ? appColors.text.dark : appColors.text.light; + const axisColor = isDark ? "#71717a" : "#d4d4d8"; + + const { state, isActive } = useChartPressState({ x: 0, y: { highTmp: 0 } }); + + const hoveredDay = useDerivedValue(() => + isActive ? `Day ${state.x.value.value}` : "Hover the chart!", + ); + const hoveredValue = useDerivedValue(() => + isActive ? `${state.y.highTmp.value.value.toFixed(1)} °C` : "- °C", + ); + + return ( + + + + + + + + isActive ? ( + + ) : null + } + > + {({ points }) => ( + <> + + {isActive && ( + + )} + + )} + + + + + This page uses the built-in hover gesture (`enableHover` prop, + implemented with Gesture.Hover() from react-native-gesture-handler) to + update the chart press state while the pointer hovers over the chart - + best experienced with a mouse on web or desktop. On touch-only devices + the chart still supports the regular press interaction. + + + + ); +} + +const DATA = Array.from({ length: 31 }, (_, i) => ({ + day: i, + highTmp: 40 + 30 * Math.random(), +})); + +/** + * Dashed vertical line that tracks the pointer while it hovers. + */ +function Cursor({ + xPosition, + top, + bottom, + color, +}: { + xPosition: SharedValue; + top: number; + bottom: number; + color: string; +}) { + const start = useDerivedValue(() => vec(xPosition.value, top)); + const end = useDerivedValue(() => vec(xPosition.value, bottom)); + + return ( + + + + ); +} + +const styles = StyleSheet.create({ + safeView: { + flex: 1, + backgroundColor: appColors.viewBackground.light, + $dark: { + backgroundColor: appColors.viewBackground.dark, + }, + }, + readout: { + fontSize: 20, + fontWeight: "bold", + }, + readoutValue: { + fontSize: 16, + fontWeight: "400", + opacity: 0.75, + }, +}); diff --git a/example/consts/routes.ts b/example/consts/routes.ts index 030ed6c9..a9fa16df 100644 --- a/example/consts/routes.ts +++ b/example/consts/routes.ts @@ -192,6 +192,12 @@ export const ChartRoutes: ChartRoute[] = [ description: "Basic chart example with a custom tap gesture.", path: "/custom-gesture", }, + { + title: "Hover Gesture", + description: + "Basic chart example where hovering with the mouse updates the chart press state.", + path: "/hover-gesture", + }, { title: "Scroll", description: "Show example of scrolling chart data.", diff --git a/example/metro.config.js b/example/metro.config.js new file mode 100644 index 00000000..cbd60b31 --- /dev/null +++ b/example/metro.config.js @@ -0,0 +1,16 @@ +const { getDefaultConfig } = require("expo/metro-config"); + +const config = getDefaultConfig(__dirname); + +// Prefer the `react-native` export condition (e.g. resolve `victory-native` to +// its TypeScript source on web) so the example dev app bundles the library like +// it does on native, instead of the pre-built `dist` output. +config.resolver.unstable_conditionNames = [ + "react-native", + "node", + "require", + "import", + "default", +]; + +module.exports = config; diff --git a/lib/src/cartesian/CartesianChart.tsx b/lib/src/cartesian/CartesianChart.tsx index 1e980cb1..ba836ca2 100644 --- a/lib/src/cartesian/CartesianChart.tsx +++ b/lib/src/cartesian/CartesianChart.tsx @@ -20,6 +20,7 @@ import type { YAxisPropsWithDefaults, FrameInputProps, ChartPressPanConfig, + ChartHoverConfig, Viewport, GestureHandlerConfig, CartesianChartOrientation, @@ -127,6 +128,17 @@ type CartesianChartBaseProps< chartPressConfig?: { pan?: ChartPressPanConfig; }; + /** + * When enabled, a Hover gesture keeps the first provided `chartPressState` + * value updated (and `isActive` true) as the pointer — most commonly a mouse + * on web or desktop — moves over the chart. The values deactivate again when + * the pointer leaves. Requires `chartPressState` to be provided. + */ + enableHover?: boolean; + /** + * Optional configuration for the hover gesture which needs `enableHover` to be useful. + */ + chartHoverConfig?: ChartHoverConfig; gestureHandlerConfig?: GestureHandlerConfig; children: (args: CartesianChartRenderArg) => React.ReactNode; renderOutside?: ( @@ -295,6 +307,8 @@ function CartesianChartContent< domain, chartPressState, chartPressConfig, + enableHover, + chartHoverConfig, gestureHandlerConfig, onChartBoundsChange, onScaleChange, @@ -801,6 +815,65 @@ function CartesianChartContent< gestureLongPressDelay, }); + /** + * Hover gesture handling: + * - Uses Gesture.Hover() to keep the first `chartPressState` value updated (and + * its isActive flag set) as the pointer — e.g. a mouse on web or desktop — + * moves over the chart, without requiring a press. + * - Coordinates are inverted through the active chart transform the same way + * press touches are. + * - On hover start/end (or finalize), the press values are activated or + * deactivated so tooltips / cursors can hide when the pointer leaves. + */ + const hoverGesture = Gesture.Hover() + .onStart((e) => { + const v = activePressSharedValues[0]; + if (!v) return; + + v.isActive.value = true; + + const pointer = getCartesianTouchCoordinates({ + touch: e, + transform: transformState?.matrix.value, + }); + + handleTouch(v, pointer.x, pointer.y); + }) + .onUpdate((e) => { + const v = activePressSharedValues[0]; + if (!v) return; + if (!v.isActive.value) v.isActive.value = true; + + const pointer = getCartesianTouchCoordinates({ + touch: e, + transform: transformState?.matrix.value, + }); + + handleTouch(v, pointer.x, pointer.y); + }) + /** + * While the mouse button is pressed, the hover gesture may stop receiving + * move events (e.g. on web) while the pan gesture takes over the stream. + * Keep the values activated here so a plain click doesn't "flicker" the + * tooltip off before / while the press gesture activates. + */ + .onTouchesDown(() => { + const v = activePressSharedValues[0]; + if (v && !v.isActive.value) v.isActive.value = true; + }) + .onEnd(() => { + const v = activePressSharedValues[0]; + if (v) v.isActive.value = false; + }) + .onFinalize(() => { + const v = activePressSharedValues[0]; + if (v) v.isActive.value = false; + }); + + if (chartHoverConfig?.activeCursor) { + hoverGesture.activeCursor(chartHoverConfig.activeCursor); + } + /** * Allow end-user to request "raw-ish" data for a given yKey. * Generate this on demand using a proxy. @@ -1005,6 +1078,11 @@ function CartesianChartContent< if (chartPressState) { composed = Gesture.Race(composed, panGesture); } + // The hover gesture should never compete with press/transform recognition, + // so it's composed simultaneously with everything else. + if (enableHover && chartPressState) { + composed = Gesture.Simultaneous(composed, hoverGesture); + } gestureOverlay = ( diff --git a/lib/src/index.ts b/lib/src/index.ts index b10f7d7e..e3aa9905 100644 --- a/lib/src/index.ts +++ b/lib/src/index.ts @@ -16,6 +16,7 @@ export { type Viewport, type ChartBounds, type ChartPressPanConfig, + type ChartHoverConfig, type CartesianChartOrientation, type YAxisSide, type XAxisSide, 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..5c9ac69f 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; @@ -391,6 +391,14 @@ export type ChartPressPanConfig = { simultaneousWithExternalGesture?: ExternalGesture | ExternalGesture[]; }; +export type ChartHoverConfig = { + /** + * Web/desktop only. Cursor used while the pointer hovers over the chart. + * Supports all CSS cursor values (e.g. `"pointer"`, `"crosshair"`). + */ + activeCursor?: Parameters[number]; +}; + 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..dca08c62 100644 --- a/lib/test/headless/stubs/react-native-gesture-handler.ts +++ b/lib/test/headless/stubs/react-native-gesture-handler.ts @@ -17,12 +17,14 @@ export const Gesture = { Race: (..._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 }; From 441e1c2dba0e940ba195d3c6c4e423a70c387ee6 Mon Sep 17 00:00:00 2001 From: Adam Hari Date: Sat, 24 Oct 2026 20:15:51 -0600 Subject: [PATCH 02/25] feat: add pie hover support and hover examples across chart varieties - PolarChart: new optional \enableHover\, \hoverState\ (\{ index }\ \: Reanimated shared value) and \chartHoverConfig\ props. A \Gesture.Hover()\ writes the chart-space pointer position (inverted through the active transform) into the polar chart context; \PieChart\ maps it onto slice geometry with a \useAnimatedReaction\ hit test (angle + radius/innerRadius) and writes the hovered slice index (-1 outside any slice / donut hole / off chart). - Export \PieHoverState\ type from the package entry point. - Examples: \enableHover\ + hover readouts wired into the bar chart and scatter examples (representative cartesian varieties) and slice hover readout in the donut chart example. - Update changeset and route descriptions. --- .changeset/hover-gesture-support.md | 5 +- example/app/bar-chart.tsx | 56 +++++++++++++ example/app/donut-chart.tsx | 54 +++++++++++++ example/app/scatter.tsx | 9 +++ example/consts/routes.ts | 6 +- lib/src/index.ts | 1 + lib/src/pie/PieChart.tsx | 56 +++++++++++++ lib/src/polar/PolarChart.tsx | 83 +++++++++++++++++++- lib/src/polar/contexts/PolarChartContext.tsx | 25 +++++- lib/src/types.ts | 9 +++ 10 files changed, 297 insertions(+), 7 deletions(-) diff --git a/.changeset/hover-gesture-support.md b/.changeset/hover-gesture-support.md index 705e9c9e..b55a9d44 100644 --- a/.changeset/hover-gesture-support.md +++ b/.changeset/hover-gesture-support.md @@ -2,4 +2,7 @@ "victory-native": minor --- -Add hover gesture support to `CartesianChart`. Pass `enableHover` (optionally along with `chartHoverConfig={{ activeCursor }}`) together with `chartPressState` to keep the press value updated — and `isActive` true — while the pointer, e.g. a mouse on web or desktop, hovers over the chart. Hover is implemented with the `Gesture.Hover()` API from React Native Gesture Handler and is composed simultaneously with the press and transform gestures. +Add hover gesture support. + +- `CartesianChart`: pass `enableHover` (optionally along with `chartHoverConfig={{ activeCursor }}`) together with `chartPressState` to keep the press value updated — and `isActive` true — while the pointer, e.g. a mouse on web or desktop, hovers over the chart. Hover is implemented with the `Gesture.Hover()` API from React Native Gesture Handler and is composed simultaneously with the press and transform gestures. +- `PolarChart`: pass `enableHover` (and optionally `chartHoverConfig`) together with `hoverState={{ index }}` — a Reanimated shared value — to receive the index of the hovered data point (slice), or `-1` when the pointer is over the donut hole, outside the pie, or off the chart entirely. diff --git a/example/app/bar-chart.tsx b/example/app/bar-chart.tsx index 489e28d3..71d4db37 100644 --- a/example/app/bar-chart.tsx +++ b/example/app/bar-chart.tsx @@ -14,11 +14,13 @@ import { getTransformComponents, setScale, setTranslate, + useChartPressState, useChartTransformState, } from "victory-native"; import { useDarkMode } from "react-native-dark"; import { useAnimatedReaction, + useDerivedValue, useSharedValue, withTiming, } from "react-native-reanimated"; @@ -31,6 +33,7 @@ import { InfoCard } from "../components/InfoCard"; import { descriptionForRoute } from "../consts/routes"; import { InputSegment } from "../components/InputSegment"; import { InputColor } from "../components/InputColor"; +import { AnimatedText } from "../components/AnimatedText"; const DATA = (length: number = 10) => 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 ( <> + + + + export default function DonutChart(props: { segment: string }) { const description = descriptionForRoute(props.segment); const [data, setData] = useState(DATA(5)); + /** + * `enableHover` on PolarChart tracks the pointer and writes the hovered + * slice index into this shared value (-1 when not over any slice). + */ + const hoverIndex = useSharedValue(-1); + const isDark = useDarkMode(); + const hoveredLabel = useDerivedValue(() => { + const i = hoverIndex.value; + const d = i >= 0 && i < data.length ? data[i] : undefined; + return d ? d.label : "Hover the chart!"; + }); + const hoveredValue = useDerivedValue(() => { + const i = hoverIndex.value; + const d = i >= 0 && i < data.length ? data[i] : undefined; + return d ? `${d.value} (label ${i + 1})` : ""; + }); return ( + + {({ slice }) => { @@ -133,4 +180,11 @@ const styles = StyleSheet.create({ height: 400, padding: 25, }, + readout: { + fontWeight: "bold", + paddingTop: 10, + }, + readoutValue: { + opacity: 0.75, + }, }); diff --git a/example/app/scatter.tsx b/example/app/scatter.tsx index eb5cdd67..0df7bb60 100644 --- a/example/app/scatter.tsx +++ b/example/app/scatter.tsx @@ -48,6 +48,15 @@ export default function ScatterPage(props: { segment: string }) { domainPadding={{ left: 50, right: 50, top: 30 }} domain={{ y: [0, 100] }} chartPressState={state} + /** + * `enableHover` wires the Gesture.Hover() to the chart press + * state: moving the pointer over the chart updates the state and + * its `isActive` flag, and leaving the chart deactivates it again. + */ + enableHover + chartHoverConfig={{ + activeCursor: "crosshair", + }} axisOptions={{ font, tickCount: 5, diff --git a/example/consts/routes.ts b/example/consts/routes.ts index a9fa16df..cec47dbe 100644 --- a/example/consts/routes.ts +++ b/example/consts/routes.ts @@ -25,7 +25,7 @@ export const ChartRoutes: ChartRoute[] = [ { title: "Bar Chart", description: - "This is a single Bar chart in Victory that supports customized spacing between each bar as well as pan/zoom.", + "This is a single Bar chart in Victory that supports customized spacing between each bar as well as pan/zoom. Hovering with the mouse (enableHover) shows the hovered bar's label and value.", path: "/bar-chart", }, { @@ -88,7 +88,7 @@ export const ChartRoutes: ChartRoute[] = [ { title: "Scatter Plot", description: - "This is a Scatter plot in Victory Native that supports custom shapes and sizes.", + "This is a Scatter plot in Victory Native that supports custom shapes and sizes. Hovering with the mouse (enableHover) shows the hovered point's label.", path: "/scatter", }, { @@ -158,7 +158,7 @@ export const ChartRoutes: ChartRoute[] = [ { title: "Donut Chart", description: - "This is how to make a Donut chart in Victory. It is built off of the Pie chart using the `innerRadius` prop.", + "This is how to make a Donut chart in Victory. It is built off of the Pie chart using the `innerRadius` prop. Hovering with the mouse (enableHover + hoverState) reports the hovered slice.", path: "/donut-chart", }, { diff --git a/lib/src/index.ts b/lib/src/index.ts index e3aa9905..18a39236 100644 --- a/lib/src/index.ts +++ b/lib/src/index.ts @@ -17,6 +17,7 @@ export { type ChartBounds, type ChartPressPanConfig, type ChartHoverConfig, + type PieHoverState, type CartesianChartOrientation, type YAxisSide, type XAxisSide, diff --git a/lib/src/pie/PieChart.tsx b/lib/src/pie/PieChart.tsx index 2e219060..dc52b0e0 100644 --- a/lib/src/pie/PieChart.tsx +++ b/lib/src/pie/PieChart.tsx @@ -1,5 +1,6 @@ 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 { getPieLayout } from "./utils/pieLayout"; @@ -82,6 +83,61 @@ export const PieChart = (props: PieChartProps) => { _startAngle, ]); + /** + * Hover support (see `enableHover` on `PolarChart`): + * The polar chart exposes the raw pointer position while the pointer is over + * the chart; here we map that position onto the slice geometry above to + * determine the hovered slice index (or -1 when the pointer is outside the + * pie / donut, in the hole, or off the chart entirely). + */ + const { hoverPointer, hoverState } = usePolarChartContext(); + useAnimatedReaction( + () => hoverPointer?.value ?? null, + (pointer) => { + "worklet"; + if (!hoverState) return; + + if (!pointer) { + hoverState.index.value = -1; + return; + } + + const dx = pointer.x - center.x; + const dy = pointer.y - center.y; + const dist = Math.sqrt(dx * dx + dy * dy); + + if (dist > radius) { + hoverState.index.value = -1; + return; + } + + 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) { + hoverState.index.value = -1; + return; + } + + let hoveredIndex = -1; + for (let i = 0; i < data.length; i++) { + const slice = data[i]; + if (!slice) continue; + if (dist < slice.innerRadius || dist > slice.radius) continue; + const sliceStart = slice.startAngle - _startAngle; + if (rel >= sliceStart && rel <= sliceStart + slice.sweepAngle) { + hoveredIndex = i; + break; + } + } + + hoverState.index.value = hoveredIndex; + }, + ); + return ( <> {data.map((slice, index) => { diff --git a/lib/src/polar/PolarChart.tsx b/lib/src/polar/PolarChart.tsx index 12b90d4b..c8beb26f 100644 --- a/lib/src/polar/PolarChart.tsx +++ b/lib/src/polar/PolarChart.tsx @@ -6,19 +6,26 @@ import { 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 { type ChartExplicitSize } from "../shared/ChartExplicitSize"; import { type ChartLayoutModeProps } from "../shared/ChartLayoutModeProps"; @@ -34,6 +41,9 @@ type PolarChartBaseProps = { transformState?: ChartTransformState; isHeadless: boolean; explicitSize?: ChartExplicitSize; + enableHover?: boolean; + hoverPointer: SharedValue; + chartHoverConfig?: ChartHoverConfig; }; const PolarChartBase = ( @@ -49,6 +59,9 @@ const PolarChartBase = ( transformState, isHeadless, explicitSize, + enableHover, + hoverPointer, + chartHoverConfig, } = props; const Bridge: ContextBridge = useContextBridge(); @@ -61,6 +74,44 @@ const PolarChartBase = ( ); } + /** + * Hover gesture handling: + * - Uses Gesture.Hover() to write the raw chart-space pointer position into + * `hoverPointer` while the pointer is over the chart (and `null` when it + * leaves). Pie charts consume this through the polar chart context to + * hit-test the hovered slice against their own geometry. + * - Coordinates are inverted through the active chart transform the same + * way press touches are. + */ + 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; + }); + + if (chartHoverConfig?.activeCursor) { + hoverGesture.activeCursor(chartHoverConfig.activeCursor); + } + + // The hover gesture should never compete with press/transform recognition. + if (enableHover) { + composed = Gesture.Simultaneous(composed, hoverGesture); + } + const chartContent = ( {hasMeasuredLayoutSize && children} @@ -97,10 +148,32 @@ type PolarChartProps< colorKey: ColorKey; labelKey: LabelKey; valueKey: ValueKey; + /** + * Web/desktop only. When enabled, a Hover gesture (see `Gesture.Hover()` + * from react-native-gesture-handler) tracks the pointer over the chart and + * writes the hovered data point (slice) index into the provided + * `hoverState`, or `-1` when the pointer is not over any slice. + */ + enableHover?: boolean; + /** + * A Reanimated shared value object which is populated with the index of the + * data point (slice) currently hovered by the pointer (requires + * `enableHover`). `-1` means no slice is hovered. + */ + hoverState?: PieHoverState; + /** + * Optional configuration for the hover gesture; requires `enableHover` to + * be useful. + */ + chartHoverConfig?: ChartHoverConfig; } & ChartLayoutModeProps & Omit< PolarChartBaseProps, - "canvasSize" | "onLayout" | "hasMeasuredLayoutSize" | "isHeadless" + | "canvasSize" + | "onLayout" + | "hasMeasuredLayoutSize" + | "isHeadless" + | "hoverPointer" >; export const PolarChart = < RawData extends Record, @@ -124,6 +197,9 @@ export const PolarChart = < headless: props.headless, }); + const hoverPointer = useSharedValue(null); + const hoverState = props.hoverState; + return ( diff --git a/lib/src/polar/contexts/PolarChartContext.tsx b/lib/src/polar/contexts/PolarChartContext.tsx index 34fb806d..62002cdb 100644 --- a/lib/src/polar/contexts/PolarChartContext.tsx +++ b/lib/src/polar/contexts/PolarChartContext.tsx @@ -3,6 +3,14 @@ import React, { createContext, type PropsWithChildren, } from "react"; +import type { SharedValue } from "react-native-reanimated"; +import type { PieHoverState } from "../../types"; + +/** + * Chart-space pointer position while the hover gesture is active + * (see `enableHover` on `PolarChart`), or `null` when not hovering. + */ +export type PolarHoverPointer = { x: number; y: number } | null; interface PolarChartContext { data: Record[]; @@ -10,6 +18,8 @@ interface PolarChartContext { labelKey: string; valueKey: string; colorKey: string; + hoverPointer?: SharedValue; + hoverState?: PieHoverState; } const PolarChartContext = createContext( @@ -22,12 +32,23 @@ interface PolarChartProviderProps { labelKey: string; valueKey: string; colorKey: string; + hoverPointer?: SharedValue; + hoverState?: PieHoverState; } export const PolarChartProvider = ( props: PropsWithChildren, ) => { - const { children, data, canvasSize, labelKey, valueKey, colorKey } = props; + const { + children, + data, + canvasSize, + labelKey, + valueKey, + colorKey, + hoverPointer, + hoverState, + } = props; return ( {children} diff --git a/lib/src/types.ts b/lib/src/types.ts index 5c9ac69f..7af1fba3 100644 --- a/lib/src/types.ts +++ b/lib/src/types.ts @@ -399,6 +399,15 @@ export type ChartHoverConfig = { activeCursor?: Parameters[number]; }; +/** + * Hover state for pie charts. + * `index` holds the index of the data point (slice) currently hovered by the + * pointer, or `-1` when the pointer is not over any slice. + */ +export type PieHoverState = { + index: SharedValue; +}; + export type NonEmptyArray = [T, ...T[]]; /** From 451fffd68749135297e48327f5172215db90ef71 Mon Sep 17 00:00:00 2001 From: Adam Hari Date: Sun, 25 Oct 2026 18:10:34 -0600 Subject: [PATCH 03/25] docs: hover gesture documentation + more hover examples - website: document \enableHover\ / \chartHoverConfig\ (CartesianChart), \enableHover\ / \hoverState\ / \chartHoverConfig\ (PolarChart), add a hover section with a full cartesian example to the Chart Gestures guide, and cross-link hover from the \chartPressState\ and Pie.Chart docs. - examples: enable hover with slice readout in the pie chart example, and turn on \enableHover\ in candlestick, bar-with-tooltip and ordinal-data examples so their existing press tooltips respond to the mouse too. --- example/app/bar-with-tooltip.tsx | 5 ++ example/app/candlestick.tsx | 5 ++ example/app/ordinal-data.tsx | 5 ++ example/app/pie-chart.tsx | 55 ++++++++++++++ website/docs/cartesian/cartesian-chart.md | 42 +++++++++++ website/docs/cartesian/chart-gestures.mdx | 92 +++++++++++++++++++++++ website/docs/polar/pie/pie-charts.md | 6 ++ website/docs/polar/polar-chart.md | 62 +++++++++++++++ 8 files changed, 272 insertions(+) diff --git a/example/app/bar-with-tooltip.tsx b/example/app/bar-with-tooltip.tsx index 7a250727..0b347f72 100644 --- a/example/app/bar-with-tooltip.tsx +++ b/example/app/bar-with-tooltip.tsx @@ -107,6 +107,11 @@ export default function BarGroupWithTooltipPage(props: { segment: string }) { labelColor: isDark ? appColors.text.dark : appColors.text.light, }} chartPressState={state} + /** + * `enableHover` drives the existing press state with the mouse: + * hovering the chart shows the same tooltip press does. + */ + enableHover onChartBoundsChange={({ bottom, left }) => { setChartBottom(bottom); setChartLeft(left); diff --git a/example/app/candlestick.tsx b/example/app/candlestick.tsx index bb710fa0..cefa4300 100644 --- a/example/app/candlestick.tsx +++ b/example/app/candlestick.tsx @@ -123,6 +123,11 @@ 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` drives the existing press state with the mouse: + * hovering the chart scrubs the same tooltip press does. + */ + enableHover xAxis={{ font, tickValues: MAIN_TICK_VALUES, diff --git a/example/app/ordinal-data.tsx b/example/app/ordinal-data.tsx index 42f819c2..f8832372 100644 --- a/example/app/ordinal-data.tsx +++ b/example/app/ordinal-data.tsx @@ -46,6 +46,11 @@ export default function OrdinalDataScreen(props: { segment: string }) { labelColor: isDark ? appColors.text.dark : appColors.text.light, }} chartPressState={state} + /** + * `enableHover` drives the existing press state with the mouse: + * hovering the chart moves the highlighted dot just like pressing. + */ + enableHover > {({ chartBounds, points, yScale }) => { return ( diff --git a/example/app/pie-chart.tsx b/example/app/pie-chart.tsx index 99e9158e..5a74f747 100644 --- a/example/app/pie-chart.tsx +++ b/example/app/pie-chart.tsx @@ -15,8 +15,10 @@ import { useChartTransformState, } from "victory-native"; import { useFont } from "react-native-skia"; +import { useDarkMode } from "react-native-dark"; import { useAnimatedReaction, + useDerivedValue, useSharedValue, withTiming, } from "react-native-reanimated"; @@ -25,6 +27,7 @@ import { Button } from "example/components/Button"; import { InputSlider } from "example/components/InputSlider"; import { InputColor } from "example/components/InputColor"; import { InputSegment } from "example/components/InputSegment"; +import { AnimatedText } from "../components/AnimatedText"; import { appColors } from "../consts/colors"; import { descriptionForRoute } from "../consts/routes"; import inter from "../assets/inter-medium.ttf"; @@ -59,6 +62,23 @@ export default function PieChart(props: { segment: string }) { >("none"); const { state } = useChartTransformState(); + /** + * `enableHover` on PolarChart tracks the pointer and writes the hovered + * slice index into this shared value (-1 when not over any slice). + */ + const hoverIndex = useSharedValue(-1); + const isDark = useDarkMode(); + const hoveredLabel = useDerivedValue(() => { + const i = hoverIndex.value; + const d = i >= 0 && i < data.length ? data[i] : undefined; + return d ? d.label : "Hover the chart!"; + }); + const hoveredValue = useDerivedValue(() => { + const i = hoverIndex.value; + const d = i >= 0 && i < data.length ? data[i] : undefined; + return d ? `${d.value} (slice ${i + 1})` : ""; + }); + const k = useSharedValue(1); const tx = useSharedValue(0); const ty = useSharedValue(0); @@ -94,6 +114,29 @@ export default function PieChart(props: { segment: string }) { return ( + + {({ slice }) => { @@ -192,4 +240,11 @@ const styles = StyleSheet.create({ backgroundColor: appColors.viewBackground.dark, }, }, + readout: { + fontWeight: "bold", + paddingTop: 10, + }, + readoutValue: { + opacity: 0.75, + }, }); diff --git a/website/docs/cartesian/cartesian-chart.md b/website/docs/cartesian/cartesian-chart.md index db4dbf3a..0d40df5a 100644 --- a/website/docs/cartesian/cartesian-chart.md +++ b/website/docs/cartesian/cartesian-chart.md @@ -242,6 +242,8 @@ 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 — 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 @@ -285,6 +287,46 @@ 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 drives the first `chartPressState` value: 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. + +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 a single optional property: + +- `activeCursor`: the cursor to use while the pointer is over the chart. Supports all CSS cursor values (e.g. `"pointer"`, `"crosshair"`). Web/desktop only. + +```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: diff --git a/website/docs/cartesian/chart-gestures.mdx b/website/docs/cartesian/chart-gestures.mdx index 0d747346..defc949e 100644 --- a/website/docs/cartesian/chart-gestures.mdx +++ b/website/docs/cartesian/chart-gestures.mdx @@ -91,6 +91,98 @@ 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. Touch-only behavior is unchanged. + +### Hovering cartesian charts + +Pass `enableHover` along with a `chartPressState` value: while the pointer is over the chart, the first press state is updated (and its `isActive` flag is set) exactly as if the user was pressing; when the pointer leaves the chart, the state is deactivated again. + +```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 + +A full version of this example is in the example app under [`example/app/hover-gesture.tsx`](https://github.com/FormidableLabs/victory-native-xl/tree/main/example/app/hover-gesture.tsx) (and the "Hover Gesture" route of the example). + +::: + ## 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..6fb88cc9 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 the [`enableHover`](/docs/polar/polar-chart#enablehover) and [`hoverState`](/docs/polar/polar-chart#hoverstate) props, which report the hovered slice index while a mouse hovers over 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..17904bb7 100644 --- a/website/docs/polar/polar-chart.md +++ b/website/docs/polar/polar-chart.md @@ -97,3 +97,65 @@ 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 [`hoverState`](#hoverstate) prop below. This enables hover interactions for `Pie` and `Donut` charts without any extra gesture code. + +The hover gesture is composed simultaneously with the transform gestures, so it does not compete with (or break) existing interactions. + +### `hoverState` + +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. Requires `enableHover`. + +```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 `hoverState` to style or animate the hovered slice. + +::: + +### `chartHoverConfig` + +Optional configuration for the hover gesture created by `enableHover`. It accepts an object with a single optional property: + +- `activeCursor`: the cursor to use while the pointer is over the chart. Supports all CSS cursor values (e.g. `"pointer"`, `"crosshair"`). Web/desktop only. From 0d471fd12c5678593135372f0e0ee914afe6229e Mon Sep 17 00:00:00 2001 From: Adam Hari Date: Sun, 25 Oct 2026 18:12:43 -0600 Subject: [PATCH 04/25] example: remove dedicated hover-gesture page Hover coverage for cartesian charts is now spread across the regular chart examples (bar, bar-with-tooltip, scatter, ordinal-data, candlestick), so the dedicated line-chart hover page is redundant. Update the website guide to point at those examples instead. --- example/app/hover-gesture.tsx | 153 ---------------------------------- 1 file changed, 153 deletions(-) delete mode 100644 example/app/hover-gesture.tsx diff --git a/example/app/hover-gesture.tsx b/example/app/hover-gesture.tsx deleted file mode 100644 index a11f1332..00000000 --- a/example/app/hover-gesture.tsx +++ /dev/null @@ -1,153 +0,0 @@ -import * as React from "react"; -import { StyleSheet, View } from "react-native"; -import { SafeAreaView } from "react-native-safe-area-context"; -import { CartesianChart, Line, useChartPressState } from "victory-native"; -import { - Circle, - DashPathEffect, - Line as SkiaLine, - useFont, - vec, -} from "react-native-skia"; -import { type SharedValue, useDerivedValue } from "react-native-reanimated"; -import { useDarkMode } from "react-native-dark"; -import { InfoCard } from "example/components/InfoCard"; -import { AnimatedText } from "../components/AnimatedText"; -import { appColors } from "../consts/colors"; -import inter from "../assets/inter-medium.ttf"; - -export default function HoverGestureScreen() { - const font = useFont(inter, 12); - const isDark = useDarkMode(); - const textColor = isDark ? appColors.text.dark : appColors.text.light; - const axisColor = isDark ? "#71717a" : "#d4d4d8"; - - const { state, isActive } = useChartPressState({ x: 0, y: { highTmp: 0 } }); - - const hoveredDay = useDerivedValue(() => - isActive ? `Day ${state.x.value.value}` : "Hover the chart!", - ); - const hoveredValue = useDerivedValue(() => - isActive ? `${state.y.highTmp.value.value.toFixed(1)} °C` : "- °C", - ); - - return ( - - - - - - - - isActive ? ( - - ) : null - } - > - {({ points }) => ( - <> - - {isActive && ( - - )} - - )} - - - - - This page uses the built-in hover gesture (`enableHover` prop, - implemented with Gesture.Hover() from react-native-gesture-handler) to - update the chart press state while the pointer hovers over the chart - - best experienced with a mouse on web or desktop. On touch-only devices - the chart still supports the regular press interaction. - - - - ); -} - -const DATA = Array.from({ length: 31 }, (_, i) => ({ - day: i, - highTmp: 40 + 30 * Math.random(), -})); - -/** - * Dashed vertical line that tracks the pointer while it hovers. - */ -function Cursor({ - xPosition, - top, - bottom, - color, -}: { - xPosition: SharedValue; - top: number; - bottom: number; - color: string; -}) { - const start = useDerivedValue(() => vec(xPosition.value, top)); - const end = useDerivedValue(() => vec(xPosition.value, bottom)); - - return ( - - - - ); -} - -const styles = StyleSheet.create({ - safeView: { - flex: 1, - backgroundColor: appColors.viewBackground.light, - $dark: { - backgroundColor: appColors.viewBackground.dark, - }, - }, - readout: { - fontSize: 20, - fontWeight: "bold", - }, - readoutValue: { - fontSize: 16, - fontWeight: "400", - opacity: 0.75, - }, -}); From 9ebf07c698292a56ae091ea9665cd9b43c08a8b8 Mon Sep 17 00:00:00 2001 From: Adam Hari Date: Sun, 25 Oct 2026 18:12:50 -0600 Subject: [PATCH 05/25] example: remove hover-gesture route and docs reference --- example/consts/routes.ts | 6 ------ website/docs/cartesian/chart-gestures.mdx | 2 +- 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/example/consts/routes.ts b/example/consts/routes.ts index cec47dbe..a81c8802 100644 --- a/example/consts/routes.ts +++ b/example/consts/routes.ts @@ -192,12 +192,6 @@ export const ChartRoutes: ChartRoute[] = [ description: "Basic chart example with a custom tap gesture.", path: "/custom-gesture", }, - { - title: "Hover Gesture", - description: - "Basic chart example where hovering with the mouse updates the chart press state.", - path: "/hover-gesture", - }, { title: "Scroll", description: "Show example of scrolling chart data.", diff --git a/website/docs/cartesian/chart-gestures.mdx b/website/docs/cartesian/chart-gestures.mdx index defc949e..5f5829ee 100644 --- a/website/docs/cartesian/chart-gestures.mdx +++ b/website/docs/cartesian/chart-gestures.mdx @@ -179,7 +179,7 @@ function Cursor({ :::info -A full version of this example is in the example app under [`example/app/hover-gesture.tsx`](https://github.com/FormidableLabs/victory-native-xl/tree/main/example/app/hover-gesture.tsx) (and the "Hover Gesture" route of the example). +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. ::: From 7002bf9248079b26091faffc189b5db9c1f35c4e Mon Sep 17 00:00:00 2001 From: Adam Hari Date: Sun, 25 Oct 2026 18:44:16 -0600 Subject: [PATCH 06/25] fix: press/click no longer resets hover-driven chart press state A plain mouse click (press + release without movement) finalized the pan gesture, whose end/finalize handlers unconditionally deactivated the first chartPressState - resetting a tooltip that was driven by the (still active) hover gesture. The press gesture's cleanup now consults \isPointerHovering\ (a shared value maintained by the hover gesture's active lifecycle) and defers deactivation while the pointer keeps hovering; the hover gesture deactivates the state when the pointer actually leaves the chart. Touch behavior (hover never active) is unchanged, verified by the test suite. --- lib/src/cartesian/CartesianChart.tsx | 36 +++++++++++++++++++---- website/docs/cartesian/chart-gestures.mdx | 2 ++ 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/lib/src/cartesian/CartesianChart.tsx b/lib/src/cartesian/CartesianChart.tsx index ba836ca2..576b9873 100644 --- a/lib/src/cartesian/CartesianChart.tsx +++ b/lib/src/cartesian/CartesianChart.tsx @@ -654,6 +654,16 @@ function CartesianChartContent< TouchData >[], }); + /** + * Whether the pointer is currently hovering over the chart (see the hover + * gesture below). The pan gesture consults this so that a plain click or a + * press-drag doesn't wipe out a hover-driven (mouse driven) activation of + * the first chartPressState: while the pointer keeps hovering, releasing the + * mouse button simply hands control back to the ongoing hover gesture. + * On touch devices the hover gesture never activates, so press behavior is + * unchanged. + */ + const isPointerHovering = useSharedValue(false); React.useEffect(() => { const vals = chartPressStateRef.current; @@ -735,9 +745,14 @@ function CartesianChartContent< */ .onFinalize(() => { const vals = activePressSharedValues || []; - for (const val of vals) { - if (val) { - val.isActive.value = false; + // Only deactivate while the pointer is not hovering, so releasing the + // mouse button inside the chart keeps a hover-driven tooltip alive. + // See the hover gesture below for how `isPointerHovering` is maintained. + if (!isPointerHovering.value) { + for (const val of vals) { + if (val) { + val.isActive.value = false; + } } } @@ -784,11 +799,13 @@ function CartesianChartContent< for (const touch of e.changedTouches) { const vals = activePressSharedValues || []; - // Set active state to false + // Deactivate the touched value. When the pointer is also hovering + // (mouse on web/desktop), leave the value active so releasing the + // button hands the tooltip back to the ongoing hover gesture. const touchId = touch?.id; const idx = typeof touchId === "number" && touchMap.value[touchId]; const val = typeof idx === "number" && vals[idx]; - if (val) { + if (val && !isPointerHovering.value) { val.isActive.value = false; } @@ -803,7 +820,7 @@ function CartesianChartContent< const vals = activePressSharedValues || []; // Set active state to false for all vals for (const val of vals) { - if (val) { + if (val && !isPointerHovering.value) { val.isActive.value = false; } } @@ -824,9 +841,13 @@ function CartesianChartContent< * press touches are. * - On hover start/end (or finalize), the press values are activated or * deactivated so tooltips / cursors can hide when the pointer leaves. + * - `isPointerHovering` lets the pan gesture's cleanup hooks (below) know + * that a mouse is still over the chart, so pressing/clicking doesn't + * reset a hover-driven tooltip. */ const hoverGesture = Gesture.Hover() .onStart((e) => { + isPointerHovering.value = true; const v = activePressSharedValues[0]; if (!v) return; @@ -858,14 +879,17 @@ function CartesianChartContent< * tooltip off before / while the press gesture activates. */ .onTouchesDown(() => { + isPointerHovering.value = true; const v = activePressSharedValues[0]; if (v && !v.isActive.value) v.isActive.value = true; }) .onEnd(() => { + isPointerHovering.value = false; const v = activePressSharedValues[0]; if (v) v.isActive.value = false; }) .onFinalize(() => { + isPointerHovering.value = false; const v = activePressSharedValues[0]; if (v) v.isActive.value = false; }); diff --git a/website/docs/cartesian/chart-gestures.mdx b/website/docs/cartesian/chart-gestures.mdx index 5f5829ee..82e48bf0 100644 --- a/website/docs/cartesian/chart-gestures.mdx +++ b/website/docs/cartesian/chart-gestures.mdx @@ -95,6 +95,8 @@ function ScrollableChart() { 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. Touch-only behavior is unchanged. +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 `enableHover`. + ### Hovering cartesian charts Pass `enableHover` along with a `chartPressState` value: while the pointer is over the chart, the first press state is updated (and its `isActive` flag is set) exactly as if the user was pressing; when the pointer leaves the chart, the state is deactivated again. From d8b884aa5f747f31a5746c409f5b1c01c9837e05 Mon Sep 17 00:00:00 2001 From: Adam Hari Date: Sun, 25 Oct 2026 18:48:03 -0600 Subject: [PATCH 07/25] example: drive ordinal-data active dot from the shared value The highlighted dot's radius was read from \state.x.position.value\ during render, but shared-value updates happen on the UI thread without a re-render - so the dot lagged/desynced behind hover (and press) movement. Compute the radius reactively with \useAnimatedReaction\ so it follows both gestures accurately. --- example/app/ordinal-data.tsx | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/example/app/ordinal-data.tsx b/example/app/ordinal-data.tsx index f8832372..74962019 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"; @@ -74,7 +75,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)!], @@ -104,18 +105,28 @@ 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]); + /** + * React to the active x position on the UI thread (rather than reading the + * shared value during render, which wouldn't update without a re-render) so + * the highlighted dot follows both press and hover gestures accurately. + */ + useAnimatedReaction( + () => activeXPosition.value === x, + (isActive, wasActive) => { + if (isActive === wasActive) return; + animatedRadius.value = withSpring(isActive ? 12 : 0); + }, + [x], + ); return ; }; From 7f5d72e99d4a0d97c5cf5d83c8f37d76e4313f00 Mon Sep 17 00:00:00 2001 From: Adam Hari Date: Sun, 25 Oct 2026 19:01:07 -0600 Subject: [PATCH 08/25] example: drive horizontal-bands-line dot from the shared value Same fix as ordinal-data: the highlighted dot's radius was read from the press state shared value during render (and driven from render state via useEffect), so it lagged/desynced behind hover and press movement since shared-value updates happen on the UI thread without a re-render. Compute the radius with useAnimatedReaction instead, and enable hover on the example so the pointer tracks the line just like pressing. --- example/app/horizontal-bands-line.tsx | 30 ++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/example/app/horizontal-bands-line.tsx b/example/app/horizontal-bands-line.tsx index b04d3b7d..99ebfa2f 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,11 @@ export default function OrdinalDataScreen(props: { segment: string }) { labelColor: isDark ? appColors.text.dark : appColors.text.light, }} chartPressState={state} + /** + * `enableHover` drives the existing press state with the mouse: + * hovering the chart moves the highlighted dot just like pressing. + */ + enableHover > {({ points, yScale }) => { return ( @@ -124,7 +130,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 +156,28 @@ 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]); + /** + * React to the active x position on the UI thread (rather than reading the + * shared value during render, which wouldn't update without a re-render) so + * the highlighted dot follows both press and hover gestures accurately. + */ + useAnimatedReaction( + () => activeXPosition.value === x, + (isActive, wasActive) => { + if (isActive === wasActive) return; + animatedRadius.value = withSpring(isActive ? 12 : 0); + }, + [x], + ); return ; }; From b3531cf57575db66a41926c7820fd747ad12f591 Mon Sep 17 00:00:00 2001 From: Adam Hari Date: Tue, 27 Oct 2026 13:26:27 -0600 Subject: [PATCH 09/25] example: enable hover on user-facing chart examples --- example/app/bar-charts-custom-bars.tsx | 5 +++++ example/app/chart-refs.tsx | 5 +++++ example/app/guides/getting-started.tsx | 5 +++++ example/app/missing-data.tsx | 5 +++++ example/app/scroll-scrub.tsx | 5 +++++ example/app/scrollview-charts.tsx | 5 +++++ example/app/stacked-bar-charts-complex.tsx | 10 ++++++++++ example/app/stock-price.tsx | 6 ++++++ 8 files changed, 46 insertions(+) diff --git a/example/app/bar-charts-custom-bars.tsx b/example/app/bar-charts-custom-bars.tsx index e9b0ec58..c106a090 100644 --- a/example/app/bar-charts-custom-bars.tsx +++ b/example/app/bar-charts-custom-bars.tsx @@ -88,6 +88,11 @@ export default function BarChartCustomBarsPage() { {({ points }) => ( <> diff --git a/example/app/guides/getting-started.tsx b/example/app/guides/getting-started.tsx index 206d557d..0f153997 100644 --- a/example/app/guides/getting-started.tsx +++ b/example/app/guides/getting-started.tsx @@ -32,6 +32,11 @@ export default function GettingStartedScreen(props: { segment: string }) { font, }} chartPressState={state} + /** + * `enableHover` drives the existing press state with the mouse: + * hovering the chart shows the tooltip just like pressing. + */ + enableHover > {({ points }) => ( <> diff --git a/example/app/missing-data.tsx b/example/app/missing-data.tsx index ff9206d0..7462e36f 100644 --- a/example/app/missing-data.tsx +++ b/example/app/missing-data.tsx @@ -32,6 +32,11 @@ export default function MissingDataScreen() { domain={{ y: [0, 100] }} axisOptions={{ font }} chartPressState={state} + /** + * `enableHover` drives the existing press state with the mouse: + * hovering the chart shows the tooltip just like pressing. + */ + enableHover > {({ points, chartBounds }) => ( <> diff --git a/example/app/scroll-scrub.tsx b/example/app/scroll-scrub.tsx index 9cab0901..8c9805a4 100644 --- a/example/app/scroll-scrub.tsx +++ b/example/app/scroll-scrub.tsx @@ -35,6 +35,11 @@ export default function ScrollAndScrub() { y: [40, 85], }} chartPressState={state} + /** + * `enableHover` drives the existing press state with the mouse: + * hovering the chart shows the tooltip just like pressing. + */ + enableHover transformState={transformState} > {({ points }) => ( diff --git a/example/app/scrollview-charts.tsx b/example/app/scrollview-charts.tsx index c55e870c..d73d29aa 100644 --- a/example/app/scrollview-charts.tsx +++ b/example/app/scrollview-charts.tsx @@ -40,6 +40,11 @@ const LineChart = ({ font, }} chartPressState={state} + /** + * `enableHover` drives the existing press state with the mouse: + * hovering the chart shows the tooltip just like pressing. + */ + 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..2446adeb 100644 --- a/example/app/stacked-bar-charts-complex.tsx +++ b/example/app/stacked-bar-charts-complex.tsx @@ -32,6 +32,11 @@ const IndividualTouchableBarChart = () => { { Date: Tue, 27 Oct 2026 13:26:27 -0600 Subject: [PATCH 10/25] example: fix web renderer freeze from font-passing chart wrappers --- example/app/axis-label-renderers.tsx | 29 ++++++++-------- example/app/axis-title-layout.tsx | 22 +++++------- example/app/horizontal-bar-group.tsx | 46 ++++++++++++-------------- example/app/horizontal-bar.tsx | 14 +++----- example/app/horizontal-stacked-bar.tsx | 43 ++++++++++-------------- 5 files changed, 66 insertions(+), 88 deletions(-) diff --git a/example/app/axis-label-renderers.tsx b/example/app/axis-label-renderers.tsx index 58834e16..bbf160f6 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,11 @@ function ChartSection({ ); } -function MultilingualHorizontalChart({ font }: { font: SkFont | null }) { +function MultilingualHorizontalChart() { + // Load the font here rather than receiving it as a prop: under the React + // Compiler, an SkFont passed as a prop into a chart wrapper triggers an + // infinite render loop on web that crashes the renderer. + 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,11 @@ function ChartSection({ ); } -function NumericYAxisTitleChart({ - font, -}: { - font: ReturnType; -}) { +function NumericYAxisTitleChart() { + // Load the font here rather than receiving it as a prop: under the React + // Compiler, an SkFont passed as a prop into a chart wrapper triggers an + // infinite render loop on web that crashes the renderer. + const font = useFont(inter, 12); return ( ; -}) { +function CategoryYAxisTitleChart() { + const font = useFont(inter, 12); return ( {({ points, chartBounds }) => ( @@ -299,7 +304,7 @@ export default function HorizontalBarGroupPage(props: { segment: string }) { description="A horizontal version of the grouped bar tooltip example." > - + @@ -308,7 +313,7 @@ export default function HorizontalBarGroupPage(props: { segment: string }) { description="Two grouped series with fixed bar thickness and plain colors." > - + @@ -317,7 +322,7 @@ export default function HorizontalBarGroupPage(props: { segment: string }) { description="Many categories with three narrow bars per group." > - + @@ -341,13 +346,11 @@ function ChartSection({ ); } -function TooltipPairChart({ - font, - axisLabelColor, -}: { - font: ReturnType; - axisLabelColor: string; -}) { +function TooltipPairChart({ axisLabelColor }: { axisLabelColor: string }) { + // Load the font here rather than receiving it as a prop: under the React + // Compiler, an SkFont passed as a prop into a chart wrapper triggers an + // infinite render loop on web that crashes the renderer. + const font = useFont(inter, 12); const [barSize, setBarSize] = React.useState({ barWidth: 0, groupWidth: 0, @@ -406,6 +409,11 @@ function TooltipPairChart({ ]} frame={{ lineWidth: 0 }} chartPressState={state} + /** + * `enableHover` drives the existing press state with the mouse: + * hovering a series highlights it just like pressing. + */ + enableHover chartPressConfig={{ pan: { activateAfterLongPress: 0 } }} > {({ points, chartBounds }) => ( @@ -479,13 +487,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,21 @@ function ChartSection({ function HorizontalStackedChart({ data, - font, axisLabelColor, innerPadding, roundedCorner, domain, }: { data: ChannelDatum[]; - font: ReturnType; axisLabelColor: string; innerPadding: number; roundedCorner: number; domain: [number, number]; }) { + // Load the font here rather than receiving it as a prop: under the React + // Compiler, an SkFont passed as a prop into a chart wrapper triggers an + // infinite render loop on web that crashes the renderer. + 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 +311,11 @@ 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 ( Date: Tue, 27 Oct 2026 18:57:05 -0600 Subject: [PATCH 11/25] chore: trim verbose comments from the hover additions --- example/app/axis-label-renderers.tsx | 3 --- example/app/axis-title-layout.tsx | 3 --- example/app/bar-chart.tsx | 5 ----- example/app/bar-charts-custom-bars.tsx | 4 ---- example/app/bar-with-tooltip.tsx | 4 ---- example/app/candlestick.tsx | 4 ---- example/app/chart-refs.tsx | 4 ---- example/app/guides/getting-started.tsx | 4 ---- example/app/horizontal-bands-line.tsx | 4 ---- example/app/horizontal-bar-group.tsx | 11 ----------- example/app/horizontal-stacked-bar.tsx | 7 ------- example/app/missing-data.tsx | 4 ---- example/app/ordinal-data.tsx | 4 ---- example/app/scatter.tsx | 5 ----- example/app/scroll-scrub.tsx | 4 ---- example/app/scrollview-charts.tsx | 4 ---- example/app/stacked-bar-charts-complex.tsx | 8 -------- lib/src/cartesian/CartesianChart.tsx | 15 ++++----------- lib/src/pie/PieChart.tsx | 7 ------- lib/src/polar/PolarChart.tsx | 10 +++------- 20 files changed, 7 insertions(+), 107 deletions(-) diff --git a/example/app/axis-label-renderers.tsx b/example/app/axis-label-renderers.tsx index bbf160f6..0f620737 100644 --- a/example/app/axis-label-renderers.tsx +++ b/example/app/axis-label-renderers.tsx @@ -165,9 +165,6 @@ function ChartSection({ } function MultilingualHorizontalChart() { - // Load the font here rather than receiving it as a prop: under the React - // Compiler, an SkFont passed as a prop into a chart wrapper triggers an - // infinite render loop on web that crashes the renderer. const font = useFont(inter, 12); return ( { setChartBottom(bottom); diff --git a/example/app/candlestick.tsx b/example/app/candlestick.tsx index cefa4300..80ea9c44 100644 --- a/example/app/candlestick.tsx +++ b/example/app/candlestick.tsx @@ -123,10 +123,6 @@ 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` drives the existing press state with the mouse: - * hovering the chart scrubs the same tooltip press does. - */ enableHover xAxis={{ font, diff --git a/example/app/chart-refs.tsx b/example/app/chart-refs.tsx index 9956c83f..f6670a10 100644 --- a/example/app/chart-refs.tsx +++ b/example/app/chart-refs.tsx @@ -176,10 +176,6 @@ export default function ChartRefsExample() { }, }} chartPressState={state} - /** - * `enableHover` drives the existing press state with the mouse: - * hovering the chart displays the tooltip just like pressing. - */ enableHover > {({ points }) => ( diff --git a/example/app/guides/getting-started.tsx b/example/app/guides/getting-started.tsx index 0f153997..54dc829c 100644 --- a/example/app/guides/getting-started.tsx +++ b/example/app/guides/getting-started.tsx @@ -32,10 +32,6 @@ export default function GettingStartedScreen(props: { segment: string }) { font, }} chartPressState={state} - /** - * `enableHover` drives the existing press state with the mouse: - * hovering the chart shows the tooltip just like pressing. - */ enableHover > {({ points }) => ( diff --git a/example/app/horizontal-bands-line.tsx b/example/app/horizontal-bands-line.tsx index 99ebfa2f..365d57a1 100644 --- a/example/app/horizontal-bands-line.tsx +++ b/example/app/horizontal-bands-line.tsx @@ -97,10 +97,6 @@ export default function OrdinalDataScreen(props: { segment: string }) { labelColor: isDark ? appColors.text.dark : appColors.text.light, }} chartPressState={state} - /** - * `enableHover` drives the existing press state with the mouse: - * hovering the chart moves the highlighted dot just like pressing. - */ enableHover > {({ points, yScale }) => { diff --git a/example/app/horizontal-bar-group.tsx b/example/app/horizontal-bar-group.tsx index f83a035e..76045973 100644 --- a/example/app/horizontal-bar-group.tsx +++ b/example/app/horizontal-bar-group.tsx @@ -173,10 +173,6 @@ export default function HorizontalBarGroupPage(props: { segment: string }) { ]} frame={{ lineWidth: 0 }} chartPressState={press.state} - /** - * `enableHover` drives the existing press state with the mouse: - * hovering a row highlights it just like pressing. - */ enableHover chartPressConfig={{ pan: { activateAfterLongPress: 0 } }} > @@ -347,9 +343,6 @@ function ChartSection({ } function TooltipPairChart({ axisLabelColor }: { axisLabelColor: string }) { - // Load the font here rather than receiving it as a prop: under the React - // Compiler, an SkFont passed as a prop into a chart wrapper triggers an - // infinite render loop on web that crashes the renderer. const font = useFont(inter, 12); const [barSize, setBarSize] = React.useState({ barWidth: 0, @@ -409,10 +402,6 @@ function TooltipPairChart({ axisLabelColor }: { axisLabelColor: string }) { ]} frame={{ lineWidth: 0 }} chartPressState={state} - /** - * `enableHover` drives the existing press state with the mouse: - * hovering a series highlights it just like pressing. - */ enableHover chartPressConfig={{ pan: { activateAfterLongPress: 0 } }} > diff --git a/example/app/horizontal-stacked-bar.tsx b/example/app/horizontal-stacked-bar.tsx index c22e5278..55a1c72b 100644 --- a/example/app/horizontal-stacked-bar.tsx +++ b/example/app/horizontal-stacked-bar.tsx @@ -209,9 +209,6 @@ function HorizontalStackedChart({ roundedCorner: number; domain: [number, number]; }) { - // Load the font here rather than receiving it as a prop: under the React - // Compiler, an SkFont passed as a prop into a chart wrapper triggers an - // infinite render loop on web that crashes the renderer. const font = useFont(inter, 12); return ( {({ points, chartBounds }) => ( diff --git a/example/app/ordinal-data.tsx b/example/app/ordinal-data.tsx index 74962019..0293ee3c 100644 --- a/example/app/ordinal-data.tsx +++ b/example/app/ordinal-data.tsx @@ -47,10 +47,6 @@ export default function OrdinalDataScreen(props: { segment: string }) { labelColor: isDark ? appColors.text.dark : appColors.text.light, }} chartPressState={state} - /** - * `enableHover` drives the existing press state with the mouse: - * hovering the chart moves the highlighted dot just like pressing. - */ enableHover > {({ chartBounds, points, yScale }) => { diff --git a/example/app/scatter.tsx b/example/app/scatter.tsx index 0df7bb60..4602dc68 100644 --- a/example/app/scatter.tsx +++ b/example/app/scatter.tsx @@ -48,11 +48,6 @@ export default function ScatterPage(props: { segment: string }) { domainPadding={{ left: 50, right: 50, top: 30 }} domain={{ y: [0, 100] }} chartPressState={state} - /** - * `enableHover` wires the Gesture.Hover() to the chart press - * state: moving the pointer over the chart updates the state and - * its `isActive` flag, and leaving the chart deactivates it again. - */ enableHover chartHoverConfig={{ activeCursor: "crosshair", diff --git a/example/app/scroll-scrub.tsx b/example/app/scroll-scrub.tsx index 8c9805a4..f800f13d 100644 --- a/example/app/scroll-scrub.tsx +++ b/example/app/scroll-scrub.tsx @@ -35,10 +35,6 @@ export default function ScrollAndScrub() { y: [40, 85], }} chartPressState={state} - /** - * `enableHover` drives the existing press state with the mouse: - * hovering the chart shows the tooltip just like pressing. - */ enableHover transformState={transformState} > diff --git a/example/app/scrollview-charts.tsx b/example/app/scrollview-charts.tsx index d73d29aa..cdb36fed 100644 --- a/example/app/scrollview-charts.tsx +++ b/example/app/scrollview-charts.tsx @@ -40,10 +40,6 @@ const LineChart = ({ font, }} chartPressState={state} - /** - * `enableHover` drives the existing press state with the mouse: - * hovering the chart shows the tooltip just like pressing. - */ enableHover chartPressConfig={{ pan: { diff --git a/example/app/stacked-bar-charts-complex.tsx b/example/app/stacked-bar-charts-complex.tsx index 2446adeb..8146c410 100644 --- a/example/app/stacked-bar-charts-complex.tsx +++ b/example/app/stacked-bar-charts-complex.tsx @@ -32,10 +32,6 @@ const IndividualTouchableBarChart = () => { { { diff --git a/lib/src/pie/PieChart.tsx b/lib/src/pie/PieChart.tsx index dc52b0e0..ff5c8a70 100644 --- a/lib/src/pie/PieChart.tsx +++ b/lib/src/pie/PieChart.tsx @@ -83,13 +83,6 @@ export const PieChart = (props: PieChartProps) => { _startAngle, ]); - /** - * Hover support (see `enableHover` on `PolarChart`): - * The polar chart exposes the raw pointer position while the pointer is over - * the chart; here we map that position onto the slice geometry above to - * determine the hovered slice index (or -1 when the pointer is outside the - * pie / donut, in the hole, or off the chart entirely). - */ const { hoverPointer, hoverState } = usePolarChartContext(); useAnimatedReaction( () => hoverPointer?.value ?? null, diff --git a/lib/src/polar/PolarChart.tsx b/lib/src/polar/PolarChart.tsx index c8beb26f..3817713a 100644 --- a/lib/src/polar/PolarChart.tsx +++ b/lib/src/polar/PolarChart.tsx @@ -75,13 +75,9 @@ const PolarChartBase = ( } /** - * Hover gesture handling: - * - Uses Gesture.Hover() to write the raw chart-space pointer position into - * `hoverPointer` while the pointer is over the chart (and `null` when it - * leaves). Pie charts consume this through the polar chart context to - * hit-test the hovered slice against their own geometry. - * - Coordinates are inverted through the active chart transform the same - * way press touches are. + * Hover writes the raw (transform-inverted) chart-space pointer position + * into `hoverPointer` — `null` on leave — which PieChart consumes via the + * polar context to hit-test the hovered slice. */ const hoverGesture = Gesture.Hover() .onStart((e) => { From 505156af67038547d70f20f11023a105dca0128e Mon Sep 17 00:00:00 2001 From: Adam Hari Date: Tue, 27 Oct 2026 19:05:53 -0600 Subject: [PATCH 12/25] chore: prune remaining inline comments to exceptional cases only --- .eslintrc.js | 10 +++++ example/app/donut-chart.tsx | 4 -- example/app/horizontal-bands-line.tsx | 5 --- example/app/ordinal-data.tsx | 5 --- example/app/pie-chart.tsx | 4 -- example/app/stock-price.tsx | 5 --- lib/src/cartesian/CartesianChart.tsx | 42 ++------------------ lib/src/polar/PolarChart.tsx | 21 ---------- lib/src/polar/contexts/PolarChartContext.tsx | 5 +-- lib/src/types.ts | 11 +---- 10 files changed, 17 insertions(+), 95 deletions(-) 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/donut-chart.tsx b/example/app/donut-chart.tsx index a10f40f8..4eb63b0b 100644 --- a/example/app/donut-chart.tsx +++ b/example/app/donut-chart.tsx @@ -54,10 +54,6 @@ const DATA = (numberPoints = 5) => export default function DonutChart(props: { segment: string }) { const description = descriptionForRoute(props.segment); const [data, setData] = useState(DATA(5)); - /** - * `enableHover` on PolarChart tracks the pointer and writes the hovered - * slice index into this shared value (-1 when not over any slice). - */ const hoverIndex = useSharedValue(-1); const isDark = useDarkMode(); const hoveredLabel = useDerivedValue(() => { diff --git a/example/app/horizontal-bands-line.tsx b/example/app/horizontal-bands-line.tsx index 365d57a1..d9100273 100644 --- a/example/app/horizontal-bands-line.tsx +++ b/example/app/horizontal-bands-line.tsx @@ -161,11 +161,6 @@ const AnimatedCircle = ({ color: string; }) => { const animatedRadius = useSharedValue(0); - /** - * React to the active x position on the UI thread (rather than reading the - * shared value during render, which wouldn't update without a re-render) so - * the highlighted dot follows both press and hover gestures accurately. - */ useAnimatedReaction( () => activeXPosition.value === x, (isActive, wasActive) => { diff --git a/example/app/ordinal-data.tsx b/example/app/ordinal-data.tsx index 0293ee3c..c94835a3 100644 --- a/example/app/ordinal-data.tsx +++ b/example/app/ordinal-data.tsx @@ -110,11 +110,6 @@ const AnimatedCircle = ({ color: string; }) => { const animatedRadius = useSharedValue(0); - /** - * React to the active x position on the UI thread (rather than reading the - * shared value during render, which wouldn't update without a re-render) so - * the highlighted dot follows both press and hover gestures accurately. - */ useAnimatedReaction( () => activeXPosition.value === x, (isActive, wasActive) => { diff --git a/example/app/pie-chart.tsx b/example/app/pie-chart.tsx index 5a74f747..d30f759e 100644 --- a/example/app/pie-chart.tsx +++ b/example/app/pie-chart.tsx @@ -62,10 +62,6 @@ export default function PieChart(props: { segment: string }) { >("none"); const { state } = useChartTransformState(); - /** - * `enableHover` on PolarChart tracks the pointer and writes the hovered - * slice index into this shared value (-1 when not over any slice). - */ const hoverIndex = useSharedValue(-1); const isDark = useDarkMode(); const hoveredLabel = useDerivedValue(() => { diff --git a/example/app/stock-price.tsx b/example/app/stock-price.tsx index cdf24a3d..a135bc26 100644 --- a/example/app/stock-price.tsx +++ b/example/app/stock-price.tsx @@ -135,11 +135,6 @@ export default function StockPriceScreen(props: { segment: string }) { xKey="date" yKeys={["high"]} chartPressState={[firstTouch, secondTouch]} - /** - * Hover drives the FIRST press state only: hovering acts like a - * single touch; the range (two-touch) indicators still require - * pressing with a second finger. - */ enableHover axisOptions={{ font, diff --git a/lib/src/cartesian/CartesianChart.tsx b/lib/src/cartesian/CartesianChart.tsx index c20bfa6e..f4b65694 100644 --- a/lib/src/cartesian/CartesianChart.tsx +++ b/lib/src/cartesian/CartesianChart.tsx @@ -128,16 +128,7 @@ type CartesianChartBaseProps< chartPressConfig?: { pan?: ChartPressPanConfig; }; - /** - * When enabled, a Hover gesture keeps the first provided `chartPressState` - * value updated (and `isActive` true) as the pointer — most commonly a mouse - * on web or desktop — moves over the chart. The values deactivate again when - * the pointer leaves. Requires `chartPressState` to be provided. - */ enableHover?: boolean; - /** - * Optional configuration for the hover gesture which needs `enableHover` to be useful. - */ chartHoverConfig?: ChartHoverConfig; gestureHandlerConfig?: GestureHandlerConfig; children: (args: CartesianChartRenderArg) => React.ReactNode; @@ -654,15 +645,8 @@ function CartesianChartContent< TouchData >[], }); - /** - * Whether the pointer is currently hovering over the chart (see the hover - * gesture below). The pan gesture consults this so that a plain click or a - * press-drag doesn't wipe out a hover-driven (mouse driven) activation of - * the first chartPressState: while the pointer keeps hovering, releasing the - * mouse button simply hands control back to the ongoing hover gesture. - * On touch devices the hover gesture never activates, so press behavior is - * unchanged. - */ + /** Pan-press cleanup defers deactivation while this is true, + * so a press/click doesn't reset a hover-driven state. */ const isPointerHovering = useSharedValue(false); React.useEffect(() => { @@ -745,9 +729,6 @@ function CartesianChartContent< */ .onFinalize(() => { const vals = activePressSharedValues || []; - // Only deactivate while the pointer is not hovering, so releasing the - // mouse button inside the chart keeps a hover-driven tooltip alive. - // See the hover gesture below for how `isPointerHovering` is maintained. if (!isPointerHovering.value) { for (const val of vals) { if (val) { @@ -799,9 +780,6 @@ function CartesianChartContent< for (const touch of e.changedTouches) { const vals = activePressSharedValues || []; - // Deactivate the touched value. When the pointer is also hovering - // (mouse on web/desktop), leave the value active so releasing the - // button hands the tooltip back to the ongoing hover gesture. const touchId = touch?.id; const idx = typeof touchId === "number" && touchMap.value[touchId]; const val = typeof idx === "number" && vals[idx]; @@ -832,12 +810,6 @@ function CartesianChartContent< gestureLongPressDelay, }); - /** - * Hover mirrors press onto the first `chartPressState` value. The - * `isPointerHovering` flag lets the pan gesture's cleanup hooks (below) know - * a mouse is still over the chart, so a press/click doesn't reset a - * hover-driven tooltip. - */ const hoverGesture = Gesture.Hover() .onStart((e) => { isPointerHovering.value = true; @@ -865,12 +837,8 @@ function CartesianChartContent< handleTouch(v, pointer.x, pointer.y); }) - /** - * While the mouse button is pressed, the hover gesture may stop receiving - * move events (e.g. on web) while the pan gesture takes over the stream. - * Keep the values activated here so a plain click doesn't "flicker" the - * tooltip off before / while the press gesture activates. - */ + /** 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; const v = activePressSharedValues[0]; @@ -1095,8 +1063,6 @@ function CartesianChartContent< if (chartPressState) { composed = Gesture.Race(composed, panGesture); } - // The hover gesture should never compete with press/transform recognition, - // so it's composed simultaneously with everything else. if (enableHover && chartPressState) { composed = Gesture.Simultaneous(composed, hoverGesture); } diff --git a/lib/src/polar/PolarChart.tsx b/lib/src/polar/PolarChart.tsx index 3817713a..2e8afdc4 100644 --- a/lib/src/polar/PolarChart.tsx +++ b/lib/src/polar/PolarChart.tsx @@ -74,11 +74,6 @@ const PolarChartBase = ( ); } - /** - * Hover writes the raw (transform-inverted) chart-space pointer position - * into `hoverPointer` — `null` on leave — which PieChart consumes via the - * polar context to hit-test the hovered slice. - */ const hoverGesture = Gesture.Hover() .onStart((e) => { hoverPointer.value = getCartesianTouchCoordinates({ @@ -103,7 +98,6 @@ const PolarChartBase = ( hoverGesture.activeCursor(chartHoverConfig.activeCursor); } - // The hover gesture should never compete with press/transform recognition. if (enableHover) { composed = Gesture.Simultaneous(composed, hoverGesture); } @@ -144,23 +138,8 @@ type PolarChartProps< colorKey: ColorKey; labelKey: LabelKey; valueKey: ValueKey; - /** - * Web/desktop only. When enabled, a Hover gesture (see `Gesture.Hover()` - * from react-native-gesture-handler) tracks the pointer over the chart and - * writes the hovered data point (slice) index into the provided - * `hoverState`, or `-1` when the pointer is not over any slice. - */ enableHover?: boolean; - /** - * A Reanimated shared value object which is populated with the index of the - * data point (slice) currently hovered by the pointer (requires - * `enableHover`). `-1` means no slice is hovered. - */ hoverState?: PieHoverState; - /** - * Optional configuration for the hover gesture; requires `enableHover` to - * be useful. - */ chartHoverConfig?: ChartHoverConfig; } & ChartLayoutModeProps & Omit< diff --git a/lib/src/polar/contexts/PolarChartContext.tsx b/lib/src/polar/contexts/PolarChartContext.tsx index 62002cdb..27c9255f 100644 --- a/lib/src/polar/contexts/PolarChartContext.tsx +++ b/lib/src/polar/contexts/PolarChartContext.tsx @@ -6,10 +6,7 @@ import React, { import type { SharedValue } from "react-native-reanimated"; import type { PieHoverState } from "../../types"; -/** - * Chart-space pointer position while the hover gesture is active - * (see `enableHover` on `PolarChart`), or `null` when not hovering. - */ +/** Chart-space pointer position while hovering (`null` otherwise). */ export type PolarHoverPointer = { x: number; y: number } | null; interface PolarChartContext { diff --git a/lib/src/types.ts b/lib/src/types.ts index 7af1fba3..36ddbfce 100644 --- a/lib/src/types.ts +++ b/lib/src/types.ts @@ -392,18 +392,11 @@ export type ChartPressPanConfig = { }; export type ChartHoverConfig = { - /** - * Web/desktop only. Cursor used while the pointer hovers over the chart. - * Supports all CSS cursor values (e.g. `"pointer"`, `"crosshair"`). - */ + /** Cursor shown while the pointer hovers over the chart. */ activeCursor?: Parameters[number]; }; -/** - * Hover state for pie charts. - * `index` holds the index of the data point (slice) currently hovered by the - * pointer, or `-1` when the pointer is not over any slice. - */ +/** Hover state for pie charts; `index` is the hovered slice, or `-1`. */ export type PieHoverState = { index: SharedValue; }; From 9648ccfef2471448382bf06926ba5add7e6c1734 Mon Sep 17 00:00:00 2001 From: Adam Hari Date: Thu, 29 Oct 2026 18:10:42 -0600 Subject: [PATCH 13/25] refactor: extract pie hover hit-test into a pure, unit-tested helper --- lib/src/pie/PieChart.tsx | 47 +--- .../pie/utils/getHoveredPieSliceIndex.test.ts | 236 ++++++++++++++++++ lib/src/pie/utils/getHoveredPieSliceIndex.ts | 47 ++++ 3 files changed, 292 insertions(+), 38 deletions(-) create mode 100644 lib/src/pie/utils/getHoveredPieSliceIndex.test.ts create mode 100644 lib/src/pie/utils/getHoveredPieSliceIndex.ts diff --git a/lib/src/pie/PieChart.tsx b/lib/src/pie/PieChart.tsx index ff5c8a70..f591c550 100644 --- a/lib/src/pie/PieChart.tsx +++ b/lib/src/pie/PieChart.tsx @@ -3,6 +3,7 @@ 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"; @@ -90,44 +91,14 @@ export const PieChart = (props: PieChartProps) => { "worklet"; if (!hoverState) return; - if (!pointer) { - hoverState.index.value = -1; - return; - } - - const dx = pointer.x - center.x; - const dy = pointer.y - center.y; - const dist = Math.sqrt(dx * dx + dy * dy); - - if (dist > radius) { - hoverState.index.value = -1; - return; - } - - 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) { - hoverState.index.value = -1; - return; - } - - let hoveredIndex = -1; - for (let i = 0; i < data.length; i++) { - const slice = data[i]; - if (!slice) continue; - if (dist < slice.innerRadius || dist > slice.radius) continue; - const sliceStart = slice.startAngle - _startAngle; - if (rel >= sliceStart && rel <= sliceStart + slice.sweepAngle) { - hoveredIndex = i; - break; - } - } - - hoverState.index.value = hoveredIndex; + hoverState.index.value = getHoveredPieSliceIndex({ + pointer, + center, + radius, + circleSweepDegrees, + startAngle: _startAngle, + slices: data, + }); }, ); 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; +}; From cc9e6829f59acb011cef13c23ecdb7b1d048e237 Mon Sep 17 00:00:00 2001 From: Adam Hari Date: Thu, 29 Oct 2026 18:11:11 -0600 Subject: [PATCH 14/25] fix: clear pie hover state when the chart data changes --- lib/src/pie/PieChart.tsx | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/lib/src/pie/PieChart.tsx b/lib/src/pie/PieChart.tsx index f591c550..f916725d 100644 --- a/lib/src/pie/PieChart.tsx +++ b/lib/src/pie/PieChart.tsx @@ -85,6 +85,16 @@ export const PieChart = (props: PieChartProps) => { ]); const { hoverPointer, hoverState } = usePolarChartContext(); + // The pointer may stay stationary over a stale geometry while data changes; + // clear the hover index so it doesn't point at outdated slices. + React.useEffect(() => { + if (hoverState) { + hoverState.index.value = -1; + } + // Intentionally keyed only on data: `hoverState` is commonly passed inline + // (`{{ index }}`), so keying on it would reset hover on every render. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [_data]); useAnimatedReaction( () => hoverPointer?.value ?? null, (pointer) => { From 38aa34c5fdbef9edf1187cc8511547c8ab3fcdc7 Mon Sep 17 00:00:00 2001 From: Adam Hari Date: Thu, 29 Oct 2026 18:12:15 -0600 Subject: [PATCH 15/25] feat: warn in development when enableHover is set without chartPressState --- lib/src/cartesian/CartesianChart.tsx | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/lib/src/cartesian/CartesianChart.tsx b/lib/src/cartesian/CartesianChart.tsx index f4b65694..e44a2bbc 100644 --- a/lib/src/cartesian/CartesianChart.tsx +++ b/lib/src/cartesian/CartesianChart.tsx @@ -329,6 +329,19 @@ function CartesianChartContent< const canvasRef = React.useRef(null); const chartPressStateRef = React.useRef(chartPressState); chartPressStateRef.current = chartPressState; + // Hover mirrors into the first `chartPressState`, so without one it has + // nothing to write to and silently does nothing. + React.useEffect(() => { + if ( + enableHover && + !chartPressState && + process.env.NODE_ENV !== "production" + ) { + console.warn( + "CartesianChart: `enableHover` has no effect without `chartPressState`.", + ); + } + }, [enableHover, chartPressState]); const yKeysKey = yKeys.join("\u0000"); const normalizedAxisProps = useBuildChartAxis({ xAxis: xAxis as XAxisInputProps | undefined, From 008aa452e7d211ff69193a4a29df607ec6bd03f1 Mon Sep 17 00:00:00 2001 From: Adam Hari Date: Thu, 29 Oct 2026 21:47:55 -0600 Subject: [PATCH 16/25] feat: add hoverState prop so hover and press interactions are distinct --- lib/src/cartesian/CartesianChart.tsx | 88 ++++++++++++++++++---------- 1 file changed, 58 insertions(+), 30 deletions(-) diff --git a/lib/src/cartesian/CartesianChart.tsx b/lib/src/cartesian/CartesianChart.tsx index e44a2bbc..66f14739 100644 --- a/lib/src/cartesian/CartesianChart.tsx +++ b/lib/src/cartesian/CartesianChart.tsx @@ -125,6 +125,9 @@ type CartesianChartBaseProps< chartPressState?: | ChartPressState<{ x: InputFields[XK]; y: Record }> | ChartPressState<{ x: InputFields[XK]; y: Record }>[]; + hoverState?: + | ChartPressState<{ x: InputFields[XK]; y: Record }> + | ChartPressState<{ x: InputFields[XK]; y: Record }>[]; chartPressConfig?: { pan?: ChartPressPanConfig; }; @@ -297,6 +300,7 @@ function CartesianChartContent< axisOptions, domain, chartPressState, + hoverState, chartPressConfig, enableHover, chartHoverConfig, @@ -329,19 +333,23 @@ function CartesianChartContent< const canvasRef = React.useRef(null); const chartPressStateRef = React.useRef(chartPressState); chartPressStateRef.current = chartPressState; - // Hover mirrors into the first `chartPressState`, so without one it has - // nothing to write to and silently does nothing. + const hoverStateRef = React.useRef(hoverState); + hoverStateRef.current = hoverState; + // `enableHover` drives either an explicit `hoverState` or the given + // `chartPressState` (so hover matches press without extra setup); with + // neither it has nothing to write to and silently does nothing. React.useEffect(() => { if ( enableHover && !chartPressState && + !hoverState && process.env.NODE_ENV !== "production" ) { console.warn( - "CartesianChart: `enableHover` has no effect without `chartPressState`.", + "CartesianChart: `enableHover` has no effect without `chartPressState` or `hoverState`.", ); } - }, [enableHover, chartPressState]); + }, [enableHover, chartPressState, hoverState]); const yKeysKey = yKeys.join("\u0000"); const normalizedAxisProps = useBuildChartAxis({ xAxis: xAxis as XAxisInputProps | undefined, @@ -651,6 +659,21 @@ function CartesianChartContent< const activePressSharedValues = Array.isArray(chartPressState) ? chartPressState : [chartPressState]; + /** Values the hover gesture drives: the explicit `hoverState` when given + * (keeping hover and press interactions distinct), otherwise the press + * states so hover matches press with no extra setup. */ + const activeHoverSharedValues = + hoverState === undefined + ? activePressSharedValues + : Array.isArray(hoverState) + ? hoverState + : [hoverState]; + /** True when the hover gesture writes to the press states directly — + * either because there is no explicit `hoverState` (hover mirrors press) + * or because the caller passed the same state object to both props. */ + const hoverDrivesPressValues = activePressSharedValues.some( + (state) => state && activeHoverSharedValues.includes(state), + ); const gestureState = useSharedValue({ isGestureActive: false, bootstrap: [] as ChartPressBootstrapEntry< @@ -658,15 +681,18 @@ function CartesianChartContent< TouchData >[], }); - /** Pan-press cleanup defers deactivation while this is true, - * so a press/click doesn't reset a hover-driven state. */ + /** Pan-press cleanup defers deactivation while the pointer hovers over + * values the hover gesture drives, 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 = hoverStateRef.current; + const hoverStates = Array.isArray(hoverVals) ? hoverVals : [hoverVals]; - for (const state of states) { + for (const state of [...pressStates, ...hoverStates]) { if (state) resetChartPressState(state); } @@ -742,7 +768,7 @@ function CartesianChartContent< */ .onFinalize(() => { const vals = activePressSharedValues || []; - if (!isPointerHovering.value) { + if (!(hoverDrivesPressValues && isPointerHovering.value)) { for (const val of vals) { if (val) { val.isActive.value = false; @@ -796,7 +822,7 @@ function CartesianChartContent< const touchId = touch?.id; const idx = typeof touchId === "number" && touchMap.value[touchId]; const val = typeof idx === "number" && vals[idx]; - if (val && !isPointerHovering.value) { + if (val && !(hoverDrivesPressValues && isPointerHovering.value)) { val.isActive.value = false; } @@ -811,7 +837,7 @@ function CartesianChartContent< const vals = activePressSharedValues || []; // Set active state to false for all vals for (const val of vals) { - if (val && !isPointerHovering.value) { + if (val && !(hoverDrivesPressValues && isPointerHovering.value)) { val.isActive.value = false; } } @@ -826,46 +852,48 @@ function CartesianChartContent< const hoverGesture = Gesture.Hover() .onStart((e) => { isPointerHovering.value = true; - const v = activePressSharedValues[0]; - if (!v) return; - - v.isActive.value = true; - const pointer = getCartesianTouchCoordinates({ touch: e, transform: transformState?.matrix.value, }); - handleTouch(v, pointer.x, pointer.y); + for (const v of activeHoverSharedValues) { + if (!v) continue; + v.isActive.value = true; + handleTouch(v, pointer.x, pointer.y); + } }) .onUpdate((e) => { - const v = activePressSharedValues[0]; - if (!v) return; - if (!v.isActive.value) v.isActive.value = true; - const pointer = getCartesianTouchCoordinates({ touch: e, transform: transformState?.matrix.value, }); - handleTouch(v, pointer.x, pointer.y); + 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; - const v = activePressSharedValues[0]; - if (v && !v.isActive.value) v.isActive.value = true; + for (const v of activeHoverSharedValues) { + if (v && !v.isActive.value) v.isActive.value = true; + } }) .onEnd(() => { isPointerHovering.value = false; - const v = activePressSharedValues[0]; - if (v) v.isActive.value = false; + for (const v of activeHoverSharedValues) { + if (v) v.isActive.value = false; + } }) .onFinalize(() => { isPointerHovering.value = false; - const v = activePressSharedValues[0]; - if (v) v.isActive.value = false; + for (const v of activeHoverSharedValues) { + if (v) v.isActive.value = false; + } }); if (chartHoverConfig?.activeCursor) { @@ -1076,7 +1104,7 @@ function CartesianChartContent< if (chartPressState) { composed = Gesture.Race(composed, panGesture); } - if (enableHover && chartPressState) { + if (enableHover && (chartPressState || hoverState)) { composed = Gesture.Simultaneous(composed, hoverGesture); } From d9e20a9a6dce44af163dbbedd1a25fdc1e1a45f9 Mon Sep 17 00:00:00 2001 From: Adam Hari Date: Thu, 29 Oct 2026 21:51:04 -0600 Subject: [PATCH 17/25] docs: document cartesian hoverState for distinct hover and press --- .changeset/hover-gesture-support.md | 2 +- website/docs/cartesian/cartesian-chart.md | 34 +++++++++++++++++++++-- website/docs/cartesian/chart-gestures.mdx | 20 ++++++++++++- 3 files changed, 52 insertions(+), 4 deletions(-) diff --git a/.changeset/hover-gesture-support.md b/.changeset/hover-gesture-support.md index b55a9d44..a128f047 100644 --- a/.changeset/hover-gesture-support.md +++ b/.changeset/hover-gesture-support.md @@ -4,5 +4,5 @@ Add hover gesture support. -- `CartesianChart`: pass `enableHover` (optionally along with `chartHoverConfig={{ activeCursor }}`) together with `chartPressState` to keep the press value updated — and `isActive` true — while the pointer, e.g. a mouse on web or desktop, hovers over the chart. Hover is implemented with the `Gesture.Hover()` API from React Native Gesture Handler and is composed simultaneously with the press and transform gestures. +- `CartesianChart`: pass `enableHover` (optionally along with `chartHoverConfig={{ activeCursor }}`) together with `chartPressState` to keep the pressed values updated — and `isActive` true — while the pointer, e.g. a mouse on web or desktop, hovers over the chart. Hover drives the `chartPressState` values exactly like a press, or a separate `hoverState` prop (`ChartPressState | ChartPressState[]`) to track hover and press independently. Hover is implemented with the `Gesture.Hover()` API from React Native Gesture Handler and is composed simultaneously with the press and transform gestures. - `PolarChart`: pass `enableHover` (and optionally `chartHoverConfig`) together with `hoverState={{ index }}` — a Reanimated shared value — to receive the index of the hovered data point (slice), or `-1` when the pointer is over the donut hole, outside the pie, or off the chart entirely. diff --git a/website/docs/cartesian/cartesian-chart.md b/website/docs/cartesian/cartesian-chart.md index 0d40df5a..610e998c 100644 --- a/website/docs/cartesian/cartesian-chart.md +++ b/website/docs/cartesian/cartesian-chart.md @@ -242,7 +242,7 @@ 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 — useful on web/desktop where a mouse is available. +It is also driven by mouse hovers when the [`enableHover`](#enablehover) prop is enabled — unless a separate [`hoverState`](#hoverstate) prop is provided, in which case only the `hoverState` 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. @@ -250,6 +250,36 @@ The `chartPressState` prop has a type of `ChartPressState | ChartPressState[]`, 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. +::: + +### `hoverState` + +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). + +Without a `hoverState`, hovering updates the `chartPressState` values themselves, which makes the hover gesture behave exactly like the press gesture with no extra setup. With a `hoverState`, 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 ( + + {/* ... */} + +); +``` + ### `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. @@ -289,7 +319,7 @@ Explicit `0` values are honored for these options. For example, `activateAfterLo ### `enableHover` -When `true`, the chart builds a [`Gesture.Hover()`](https://docs.swmansion.com/react-native-gesture-handler/docs/gestures/hover-gesture) that drives the first `chartPressState` value: 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. +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 [`hoverState`](#hoverstate) when one is provided, otherwise the `chartPressState` values — so hover behaves exactly like a press. 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. 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. diff --git a/website/docs/cartesian/chart-gestures.mdx b/website/docs/cartesian/chart-gestures.mdx index 82e48bf0..2526f339 100644 --- a/website/docs/cartesian/chart-gestures.mdx +++ b/website/docs/cartesian/chart-gestures.mdx @@ -99,7 +99,7 @@ Press/click and hover interoperate: while the pointer is over the chart, pressin ### Hovering cartesian charts -Pass `enableHover` along with a `chartPressState` value: while the pointer is over the chart, the first press state is updated (and its `isActive` flag is set) exactly as if the user was pressing; when the pointer leaves the chart, the state is deactivated again. +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"; @@ -185,6 +185,24 @@ The example app uses this API in several places — [`example/app/candlestick.ts ::: +### 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 `hoverState` (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`) use the same `hoverState` prop. + ## 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. From a9f2001f50a82b7815550ae04344008c9ee63035 Mon Sep 17 00:00:00 2001 From: Adam Hari Date: Thu, 29 Oct 2026 22:00:58 -0600 Subject: [PATCH 18/25] example: demonstrate distinct hover and press states --- example/app/hover-press.tsx | 179 ++++++++++++++++++++++++++++++++++++ example/consts/routes.ts | 6 ++ 2 files changed, 185 insertions(+) create mode 100644 example/app/hover-press.tsx diff --git a/example/app/hover-press.tsx b/example/app/hover-press.tsx new file mode 100644 index 00000000..bb3d969e --- /dev/null +++ b/example/app/hover-press.tsx @@ -0,0 +1,179 @@ +import React from "react"; +import { ScrollView, StyleSheet, View } from "react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; +import { CartesianChart, Line, useChartPressState } from "victory-native"; +import { useDarkMode } from "react-native-dark"; +import { useDerivedValue, type SharedValue } from "react-native-reanimated"; +import { + Circle, + DashPathEffect, + Line as SkiaLine, + vec, +} from "react-native-skia"; +import { InfoCard } from "example/components/InfoCard"; +import { AnimatedText } from "../components/AnimatedText"; +import { appColors } from "../consts/colors"; +import { descriptionForRoute } from "../consts/routes"; + +const DATA = Array.from({ length: 12 }, (_, i) => ({ + 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(); + + // Two independent states: press drives `chartPressState`, hover drives `hoverState`. + 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/consts/routes.ts b/example/consts/routes.ts index a81c8802..27396c6e 100644 --- a/example/consts/routes.ts +++ b/example/consts/routes.ts @@ -207,6 +207,12 @@ export const ChartRoutes: ChartRoute[] = [ description: "This example demonstrates chart interactions using refs.", path: "/chart-refs", }, + { + title: "Hover and Press", + description: + "This chart tracks hover and press independently: hoverState renders a crosshair readout following the mouse, while chartPressState pins a dot at the clicked point. Hover matches press automatically when you omit hoverState.", + path: "/hover-press", + }, ]; if (__DEV__) { From 101b15404cda2fe06e17c9cef0065d6b8acc6f8d Mon Sep 17 00:00:00 2001 From: Adam Hari Date: Thu, 29 Oct 2026 22:20:18 -0600 Subject: [PATCH 19/25] fix: restore default press activation in the hover-press example --- example/app/hover-press.tsx | 1 - example/consts/routes.ts | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/example/app/hover-press.tsx b/example/app/hover-press.tsx index bb3d969e..989f975f 100644 --- a/example/app/hover-press.tsx +++ b/example/app/hover-press.tsx @@ -93,7 +93,6 @@ export default function HoverPress(props: { segment: string }) { chartHoverConfig={{ activeCursor: "crosshair", }} - chartPressConfig={{ pan: { activateAfterLongPress: 0 } }} renderOutside={({ chartBounds }) => hoverIsActive ? ( Date: Sat, 31 Oct 2026 13:35:26 -0600 Subject: [PATCH 20/25] feat: add simultaneousWithExternalGesture to chartHoverConfig --- lib/src/cartesian/CartesianChart.tsx | 8 ++- lib/src/polar/PolarChart.tsx | 8 ++- lib/src/shared/applyChartHoverConfig.test.ts | 61 ++++++++++++++++++++ lib/src/shared/applyChartHoverConfig.ts | 36 ++++++++++++ lib/src/types.ts | 2 + 5 files changed, 109 insertions(+), 6 deletions(-) create mode 100644 lib/src/shared/applyChartHoverConfig.test.ts create mode 100644 lib/src/shared/applyChartHoverConfig.ts diff --git a/lib/src/cartesian/CartesianChart.tsx b/lib/src/cartesian/CartesianChart.tsx index 66f14739..5eb09f82 100644 --- a/lib/src/cartesian/CartesianChart.tsx +++ b/lib/src/cartesian/CartesianChart.tsx @@ -55,6 +55,7 @@ import { } from "./contexts/CartesianTransformContext"; import { downsampleTicks } from "../utils/tickHelpers"; import { GestureHandler } from "../shared/GestureHandler"; +import { applyChartHoverConfig } from "../shared/applyChartHoverConfig"; import type { ComposedGesture } from "../shared/gestureTypes"; import { type ChartLayoutModeProps } from "../shared/ChartLayoutModeProps"; import { ChartWrapper } from "../shared/ChartWrapper"; @@ -896,9 +897,10 @@ function CartesianChartContent< } }); - if (chartHoverConfig?.activeCursor) { - hoverGesture.activeCursor(chartHoverConfig.activeCursor); - } + applyChartHoverConfig({ + gesture: hoverGesture, + hoverConfig: chartHoverConfig, + }); /** * Allow end-user to request "raw-ish" data for a given yKey. diff --git a/lib/src/polar/PolarChart.tsx b/lib/src/polar/PolarChart.tsx index 2e8afdc4..16f2d244 100644 --- a/lib/src/polar/PolarChart.tsx +++ b/lib/src/polar/PolarChart.tsx @@ -27,6 +27,7 @@ import { } 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"; @@ -94,9 +95,10 @@ const PolarChartBase = ( hoverPointer.value = null; }); - if (chartHoverConfig?.activeCursor) { - hoverGesture.activeCursor(chartHoverConfig.activeCursor); - } + applyChartHoverConfig({ + gesture: hoverGesture, + hoverConfig: chartHoverConfig, + }); if (enableHover) { composed = Gesture.Simultaneous(composed, hoverGesture); 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/types.ts b/lib/src/types.ts index 36ddbfce..06fa5bd7 100644 --- a/lib/src/types.ts +++ b/lib/src/types.ts @@ -394,6 +394,8 @@ export type ChartPressPanConfig = { 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`. */ From 33a48d05eb4933702100774f7bfb89b2e29dc87d Mon Sep 17 00:00:00 2001 From: Adam Hari Date: Sat, 31 Oct 2026 13:37:45 -0600 Subject: [PATCH 21/25] refactor: rename hoverState prop to chartHoverState for API consistency --- .changeset/hover-gesture-support.md | 5 +-- example/app/donut-chart.tsx | 2 +- example/app/hover-press.tsx | 4 +-- example/app/pie-chart.tsx | 2 +- example/consts/routes.ts | 4 +-- lib/src/cartesian/CartesianChart.tsx | 32 ++++++++++---------- lib/src/pie/PieChart.tsx | 12 ++++---- lib/src/polar/PolarChart.tsx | 6 ++-- lib/src/polar/contexts/PolarChartContext.tsx | 8 ++--- website/docs/cartesian/cartesian-chart.md | 10 +++--- website/docs/cartesian/chart-gestures.mdx | 6 ++-- website/docs/polar/pie/pie-charts.md | 2 +- website/docs/polar/polar-chart.md | 8 ++--- 13 files changed, 51 insertions(+), 50 deletions(-) diff --git a/.changeset/hover-gesture-support.md b/.changeset/hover-gesture-support.md index a128f047..f5efe93a 100644 --- a/.changeset/hover-gesture-support.md +++ b/.changeset/hover-gesture-support.md @@ -4,5 +4,6 @@ Add hover gesture support. -- `CartesianChart`: pass `enableHover` (optionally along with `chartHoverConfig={{ activeCursor }}`) together with `chartPressState` to keep the pressed values updated — and `isActive` true — while the pointer, e.g. a mouse on web or desktop, hovers over the chart. Hover drives the `chartPressState` values exactly like a press, or a separate `hoverState` prop (`ChartPressState | ChartPressState[]`) to track hover and press independently. Hover is implemented with the `Gesture.Hover()` API from React Native Gesture Handler and is composed simultaneously with the press and transform gestures. -- `PolarChart`: pass `enableHover` (and optionally `chartHoverConfig`) together with `hoverState={{ index }}` — a Reanimated shared value — to receive the index of the hovered data point (slice), or `-1` when the pointer is over the donut hole, outside the pie, or off the chart entirely. +- `CartesianChart`: pass `enableHover` (optionally along with `chartHoverConfig`) together with `chartPressState` to keep the pressed values updated — and `isActive` true — while the pointer, e.g. a mouse on web or desktop, hovers over the chart. Hover drives the `chartPressState` values exactly like a press, or a separate `chartHoverState` prop (`ChartPressState | ChartPressState[]`) to track hover and press independently. Hover is implemented with the `Gesture.Hover()` API from React Native Gesture Handler and is composed simultaneously with the press and transform gestures. +- `PolarChart`: pass `enableHover` (and optionally `chartHoverConfig`) together with `chartHoverState={{ index }}` — a Reanimated shared value — to receive the index of the hovered data point (slice), or `-1` when the pointer is over the donut hole, outside the pie, or off the chart entirely. +- `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/example/app/donut-chart.tsx b/example/app/donut-chart.tsx index 4eb63b0b..8ede8782 100644 --- a/example/app/donut-chart.tsx +++ b/example/app/donut-chart.tsx @@ -100,7 +100,7 @@ export default function DonutChart(props: { segment: string }) { valueKey={"value"} labelKey={"label"} enableHover - hoverState={{ index: hoverIndex }} + chartHoverState={{ index: hoverIndex }} chartHoverConfig={{ activeCursor: "pointer", }} diff --git a/example/app/hover-press.tsx b/example/app/hover-press.tsx index 989f975f..74f994e4 100644 --- a/example/app/hover-press.tsx +++ b/example/app/hover-press.tsx @@ -42,7 +42,7 @@ export default function HoverPress(props: { segment: string }) { const description = descriptionForRoute(props.segment); const isDark = useDarkMode(); - // Two independent states: press drives `chartPressState`, hover drives `hoverState`. + // Two independent states: press drives `chartPressState`, hover drives `chartHoverState`. const { state: press, isActive: pressIsActive } = useChartPressState({ x: 0, y: { highTmp: 0 }, @@ -88,7 +88,7 @@ export default function HoverPress(props: { segment: string }) { xKey="day" yKeys={["highTmp"]} chartPressState={press} - hoverState={hover} + chartHoverState={hover} enableHover chartHoverConfig={{ activeCursor: "crosshair", diff --git a/example/app/pie-chart.tsx b/example/app/pie-chart.tsx index d30f759e..11dcd84b 100644 --- a/example/app/pie-chart.tsx +++ b/example/app/pie-chart.tsx @@ -145,7 +145,7 @@ export default function PieChart(props: { segment: string }) { valueKey={"value"} labelKey={"label"} enableHover - hoverState={{ index: hoverIndex }} + chartHoverState={{ index: hoverIndex }} chartHoverConfig={{ activeCursor: "pointer", }} diff --git a/example/consts/routes.ts b/example/consts/routes.ts index 658c1104..fb0fc554 100644 --- a/example/consts/routes.ts +++ b/example/consts/routes.ts @@ -158,7 +158,7 @@ export const ChartRoutes: ChartRoute[] = [ { title: "Donut Chart", description: - "This is how to make a Donut chart in Victory. It is built off of the Pie chart using the `innerRadius` prop. Hovering with the mouse (enableHover + hoverState) reports the hovered slice.", + "This is how to make a Donut chart in Victory. It is built off of the Pie chart using the `innerRadius` prop. Hovering with the mouse (enableHover + chartHoverState) reports the hovered slice.", path: "/donut-chart", }, { @@ -210,7 +210,7 @@ export const ChartRoutes: ChartRoute[] = [ { title: "Hover and Press", description: - "This chart tracks hover and press independently: hoverState renders a crosshair readout following the mouse, while chartPressState pins a dot where you press and hold (or press-drag). Omitting hoverState makes hover match press automatically.", + "This chart tracks hover and press independently: chartHoverState renders a crosshair readout following the mouse, while chartPressState pins a dot where you press and hold (or press-drag). Omitting chartHoverState makes hover match press automatically.", path: "/hover-press", }, ]; diff --git a/lib/src/cartesian/CartesianChart.tsx b/lib/src/cartesian/CartesianChart.tsx index 5eb09f82..c26d4607 100644 --- a/lib/src/cartesian/CartesianChart.tsx +++ b/lib/src/cartesian/CartesianChart.tsx @@ -126,7 +126,7 @@ type CartesianChartBaseProps< chartPressState?: | ChartPressState<{ x: InputFields[XK]; y: Record }> | ChartPressState<{ x: InputFields[XK]; y: Record }>[]; - hoverState?: + chartHoverState?: | ChartPressState<{ x: InputFields[XK]; y: Record }> | ChartPressState<{ x: InputFields[XK]; y: Record }>[]; chartPressConfig?: { @@ -301,7 +301,7 @@ function CartesianChartContent< axisOptions, domain, chartPressState, - hoverState, + chartHoverState, chartPressConfig, enableHover, chartHoverConfig, @@ -334,23 +334,23 @@ function CartesianChartContent< const canvasRef = React.useRef(null); const chartPressStateRef = React.useRef(chartPressState); chartPressStateRef.current = chartPressState; - const hoverStateRef = React.useRef(hoverState); - hoverStateRef.current = hoverState; - // `enableHover` drives either an explicit `hoverState` or the given + const chartHoverStateRef = React.useRef(chartHoverState); + chartHoverStateRef.current = chartHoverState; + // `enableHover` drives either an explicit `chartHoverState` or the given // `chartPressState` (so hover matches press without extra setup); with // neither it has nothing to write to and silently does nothing. React.useEffect(() => { if ( enableHover && !chartPressState && - !hoverState && + !chartHoverState && process.env.NODE_ENV !== "production" ) { console.warn( - "CartesianChart: `enableHover` has no effect without `chartPressState` or `hoverState`.", + "CartesianChart: `enableHover` has no effect without `chartPressState` or `chartHoverState`.", ); } - }, [enableHover, chartPressState, hoverState]); + }, [enableHover, chartPressState, chartHoverState]); const yKeysKey = yKeys.join("\u0000"); const normalizedAxisProps = useBuildChartAxis({ xAxis: xAxis as XAxisInputProps | undefined, @@ -660,17 +660,17 @@ function CartesianChartContent< const activePressSharedValues = Array.isArray(chartPressState) ? chartPressState : [chartPressState]; - /** Values the hover gesture drives: the explicit `hoverState` when given + /** Values the hover gesture drives: the explicit `chartHoverState` when given * (keeping hover and press interactions distinct), otherwise the press * states so hover matches press with no extra setup. */ const activeHoverSharedValues = - hoverState === undefined + chartHoverState === undefined ? activePressSharedValues - : Array.isArray(hoverState) - ? hoverState - : [hoverState]; + : Array.isArray(chartHoverState) + ? chartHoverState + : [chartHoverState]; /** True when the hover gesture writes to the press states directly — - * either because there is no explicit `hoverState` (hover mirrors press) + * either because there is no explicit `chartHoverState` (hover mirrors press) * or because the caller passed the same state object to both props. */ const hoverDrivesPressValues = activePressSharedValues.some( (state) => state && activeHoverSharedValues.includes(state), @@ -690,7 +690,7 @@ function CartesianChartContent< React.useEffect(() => { const pressVals = chartPressStateRef.current; const pressStates = Array.isArray(pressVals) ? pressVals : [pressVals]; - const hoverVals = hoverStateRef.current; + const hoverVals = chartHoverStateRef.current; const hoverStates = Array.isArray(hoverVals) ? hoverVals : [hoverVals]; for (const state of [...pressStates, ...hoverStates]) { @@ -1106,7 +1106,7 @@ function CartesianChartContent< if (chartPressState) { composed = Gesture.Race(composed, panGesture); } - if (enableHover && (chartPressState || hoverState)) { + if (enableHover && (chartPressState || chartHoverState)) { composed = Gesture.Simultaneous(composed, hoverGesture); } diff --git a/lib/src/pie/PieChart.tsx b/lib/src/pie/PieChart.tsx index f916725d..8f570b07 100644 --- a/lib/src/pie/PieChart.tsx +++ b/lib/src/pie/PieChart.tsx @@ -84,14 +84,14 @@ export const PieChart = (props: PieChartProps) => { _startAngle, ]); - const { hoverPointer, hoverState } = usePolarChartContext(); + const { hoverPointer, chartHoverState } = usePolarChartContext(); // The pointer may stay stationary over a stale geometry while data changes; // clear the hover index so it doesn't point at outdated slices. React.useEffect(() => { - if (hoverState) { - hoverState.index.value = -1; + if (chartHoverState) { + chartHoverState.index.value = -1; } - // Intentionally keyed only on data: `hoverState` is commonly passed inline + // Intentionally keyed only on data: `chartHoverState` is commonly passed inline // (`{{ index }}`), so keying on it would reset hover on every render. // eslint-disable-next-line react-hooks/exhaustive-deps }, [_data]); @@ -99,9 +99,9 @@ export const PieChart = (props: PieChartProps) => { () => hoverPointer?.value ?? null, (pointer) => { "worklet"; - if (!hoverState) return; + if (!chartHoverState) return; - hoverState.index.value = getHoveredPieSliceIndex({ + chartHoverState.index.value = getHoveredPieSliceIndex({ pointer, center, radius, diff --git a/lib/src/polar/PolarChart.tsx b/lib/src/polar/PolarChart.tsx index 16f2d244..d284a6a0 100644 --- a/lib/src/polar/PolarChart.tsx +++ b/lib/src/polar/PolarChart.tsx @@ -141,7 +141,7 @@ type PolarChartProps< labelKey: LabelKey; valueKey: ValueKey; enableHover?: boolean; - hoverState?: PieHoverState; + chartHoverState?: PieHoverState; chartHoverConfig?: ChartHoverConfig; } & ChartLayoutModeProps & Omit< @@ -175,7 +175,7 @@ export const PolarChart = < }); const hoverPointer = useSharedValue(null); - const hoverState = props.hoverState; + const chartHoverState = props.chartHoverState; return ( @@ -186,7 +186,7 @@ export const PolarChart = < valueKey={valueKey.toString()} canvasSize={canvasSize} hoverPointer={hoverPointer} - hoverState={hoverState} + chartHoverState={chartHoverState} > ; - hoverState?: PieHoverState; + chartHoverState?: PieHoverState; } const PolarChartContext = createContext( @@ -30,7 +30,7 @@ interface PolarChartProviderProps { valueKey: string; colorKey: string; hoverPointer?: SharedValue; - hoverState?: PieHoverState; + chartHoverState?: PieHoverState; } export const PolarChartProvider = ( @@ -44,7 +44,7 @@ export const PolarChartProvider = ( valueKey, colorKey, hoverPointer, - hoverState, + chartHoverState, } = props; return ( @@ -56,7 +56,7 @@ export const PolarChartProvider = ( valueKey, colorKey, hoverPointer, - hoverState, + chartHoverState, }} > {children} diff --git a/website/docs/cartesian/cartesian-chart.md b/website/docs/cartesian/cartesian-chart.md index 610e998c..accd728a 100644 --- a/website/docs/cartesian/cartesian-chart.md +++ b/website/docs/cartesian/cartesian-chart.md @@ -242,7 +242,7 @@ 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 [`hoverState`](#hoverstate) prop is provided, in which case only the `hoverState` receives hover updates. This is useful on web/desktop where a mouse is available. +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. @@ -254,11 +254,11 @@ If you have a data point whose y-value is `null` or `undefined`, when that point 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. ::: -### `hoverState` +### `chartHoverState` 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). -Without a `hoverState`, hovering updates the `chartPressState` values themselves, which makes the hover gesture behave exactly like the press gesture with no extra setup. With a `hoverState`, hover and press are tracked independently — e.g. a hover tooltip that follows the mouse while a pressed tooltip stays pinned. +Without a `chartHoverState`, hovering updates the `chartPressState` values themselves, which makes the hover gesture behave exactly like the press gesture with no extra setup. With a `chartHoverState`, 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"; @@ -272,7 +272,7 @@ return ( xKey="day" yKeys={["highTmp"]} chartPressState={press.state} - hoverState={hover.state} // 👈 hover and press tracked independently + chartHoverState={hover.state} // 👈 hover and press tracked independently enableHover={true} > {/* ... */} @@ -319,7 +319,7 @@ Explicit `0` values are honored for these options. For example, `activateAfterLo ### `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 [`hoverState`](#hoverstate) when one is provided, otherwise the `chartPressState` values — so hover behaves exactly like a press. 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. +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. 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. 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. diff --git a/website/docs/cartesian/chart-gestures.mdx b/website/docs/cartesian/chart-gestures.mdx index 2526f339..72aec4f4 100644 --- a/website/docs/cartesian/chart-gestures.mdx +++ b/website/docs/cartesian/chart-gestures.mdx @@ -187,7 +187,7 @@ The example app uses this API in several places — [`example/app/candlestick.ts ### 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 `hoverState` (a `ChartPressState` value created with `useChartPressState`, just like `chartPressState`) and the hover gesture will drive it instead of the 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 } }); @@ -196,12 +196,12 @@ 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`) use the same `hoverState` prop. +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`) use the same `chartHoverState` prop. ## Multi-press support diff --git a/website/docs/polar/pie/pie-charts.md b/website/docs/polar/pie/pie-charts.md index 6fb88cc9..cfa72904 100644 --- a/website/docs/polar/pie/pie-charts.md +++ b/website/docs/polar/pie/pie-charts.md @@ -11,7 +11,7 @@ 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 the [`enableHover`](/docs/polar/polar-chart#enablehover) and [`hoverState`](/docs/polar/polar-chart#hoverstate) props, which report the hovered slice index while a mouse hovers over the chart. +Hover interactions for `Pie` and `Donut` charts are configured on the `PolarChart` component — see the [`enableHover`](/docs/polar/polar-chart#enablehover) and [`chartHoverState`](/docs/polar/polar-chart#hoverstate) props, which report the hovered slice index while a mouse hovers over the chart. ::: diff --git a/website/docs/polar/polar-chart.md b/website/docs/polar/polar-chart.md index 17904bb7..ba7de9cb 100644 --- a/website/docs/polar/polar-chart.md +++ b/website/docs/polar/polar-chart.md @@ -100,11 +100,11 @@ When `true` (and `explicitSize` is set), renders a Skia-only subtree with no `Vi ### `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 [`hoverState`](#hoverstate) prop below. This enables hover interactions for `Pie` and `Donut` charts without any extra gesture code. +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) prop below. This enables hover interactions for `Pie` and `Donut` charts without any extra gesture code. The hover gesture is composed simultaneously with the transform gestures, so it does not compete with (or break) existing interactions. -### `hoverState` +### `chartHoverState` 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. Requires `enableHover`. @@ -139,7 +139,7 @@ function HoveredPie() { labelKey={"label"} colorKey={"color"} enableHover // 👈 track mouse hovers - hoverState={{ index: hoverIndex }} + chartHoverState={{ index: hoverIndex }} > @@ -150,7 +150,7 @@ function HoveredPie() { :::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 `hoverState` to style or animate the hovered slice. +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. ::: From ab2f1f5ce47a70ee3720c5646cb0435ddaa946e3 Mon Sep 17 00:00:00 2001 From: Adam Hari Date: Sat, 31 Oct 2026 13:38:43 -0600 Subject: [PATCH 22/25] docs: fix polar chart chartHoverState anchor in pie docs cross-link --- website/docs/polar/pie/pie-charts.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/docs/polar/pie/pie-charts.md b/website/docs/polar/pie/pie-charts.md index cfa72904..12607edf 100644 --- a/website/docs/polar/pie/pie-charts.md +++ b/website/docs/polar/pie/pie-charts.md @@ -11,7 +11,7 @@ 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 the [`enableHover`](/docs/polar/polar-chart#enablehover) and [`chartHoverState`](/docs/polar/polar-chart#hoverstate) props, which report the hovered slice index while a mouse hovers over the chart. +Hover interactions for `Pie` and `Donut` charts are configured on the `PolarChart` component — see the [`enableHover`](/docs/polar/polar-chart#enablehover) and [`chartHoverState`](/docs/polar/polar-chart#charthoverstate) props, which report the hovered slice index while a mouse hovers over the chart. ::: From 3807bf697975260b9a9bb5d1996bda096f6b5600 Mon Sep 17 00:00:00 2001 From: Adam Hari Date: Sun, 1 Nov 2026 14:29:40 -0700 Subject: [PATCH 23/25] feat: built-in pie hover state and enable hover by default on web --- .changeset/hover-gesture-support.md | 6 +- example/app/donut-chart.tsx | 88 +++++++++---------- example/app/pie-chart.tsx | 80 +++++++---------- example/consts/routes.ts | 2 +- lib/src/cartesian/CartesianChart.tsx | 15 +++- lib/src/index.ts | 1 + lib/src/pie/PieChart.tsx | 10 +-- lib/src/polar/PolarChart.tsx | 16 +++- lib/src/polar/contexts/PolarChartContext.tsx | 16 +++- .../stubs/react-native-gesture-handler.ts | 1 + website/docs/cartesian/cartesian-chart.md | 5 +- website/docs/cartesian/chart-gestures.mdx | 10 ++- website/docs/polar/pie/pie-charts.md | 2 +- website/docs/polar/polar-chart.md | 46 ++++++++-- 14 files changed, 177 insertions(+), 121 deletions(-) diff --git a/.changeset/hover-gesture-support.md b/.changeset/hover-gesture-support.md index f5efe93a..81094086 100644 --- a/.changeset/hover-gesture-support.md +++ b/.changeset/hover-gesture-support.md @@ -4,6 +4,8 @@ Add hover gesture support. -- `CartesianChart`: pass `enableHover` (optionally along with `chartHoverConfig`) together with `chartPressState` to keep the pressed values updated — and `isActive` true — while the pointer, e.g. a mouse on web or desktop, hovers over the chart. Hover drives the `chartPressState` values exactly like a press, or a separate `chartHoverState` prop (`ChartPressState | ChartPressState[]`) to track hover and press independently. Hover is implemented with the `Gesture.Hover()` API from React Native Gesture Handler and is composed simultaneously with the press and transform gestures. -- `PolarChart`: pass `enableHover` (and optionally `chartHoverConfig`) together with `chartHoverState={{ index }}` — a Reanimated shared value — to receive the index of the hovered data point (slice), or `-1` when the pointer is over the donut hole, outside the pie, or off the chart entirely. +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. +- `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/example/app/donut-chart.tsx b/example/app/donut-chart.tsx index 8ede8782..35fabdad 100644 --- a/example/app/donut-chart.tsx +++ b/example/app/donut-chart.tsx @@ -1,15 +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, useSharedValue } from "react-native-reanimated"; +import { useDerivedValue } from "react-native-reanimated"; import { InfoCard } from "example/components/InfoCard"; import { Button } from "example/components/Button"; -import { AnimatedText } from "../components/AnimatedText"; import { appColors } from "../consts/colors"; import { descriptionForRoute } from "../consts/routes"; +import inter from "../assets/inter-medium.ttf"; function calculateGradientPoints( radius: number, @@ -51,48 +56,44 @@ const DATA = (numberPoints = 5) => label: `Label ${index + 1}`, })); -export default function DonutChart(props: { segment: string }) { - const description = descriptionForRoute(props.segment); - const [data, setData] = useState(DATA(5)); - const hoverIndex = useSharedValue(-1); +/** + * Reads the hover index that `PolarChart` maintains internally — no + * `chartHoverState` prop needed — via the `usePieHoverState` hook. + */ +function HoverReadout({ + data, +}: { + data: { label: string; value: number; color: string }[]; +}) { const isDark = useDarkMode(); - const hoveredLabel = useDerivedValue(() => { - const i = hoverIndex.value; - const d = i >= 0 && i < data.length ? data[i] : undefined; - return d ? d.label : "Hover the chart!"; - }); - const hoveredValue = useDerivedValue(() => { - const i = hoverIndex.value; + 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 ? `${d.value} (label ${i + 1})` : ""; + 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)); + return ( - - + {({ slice }) => { const { startX, startY, endX, endY } = calculateGradientPoints( @@ -176,11 +177,4 @@ const styles = StyleSheet.create({ height: 400, padding: 25, }, - readout: { - fontWeight: "bold", - paddingTop: 10, - }, - readoutValue: { - opacity: 0.75, - }, }); diff --git a/example/app/pie-chart.tsx b/example/app/pie-chart.tsx index 11dcd84b..22d66272 100644 --- a/example/app/pie-chart.tsx +++ b/example/app/pie-chart.tsx @@ -13,8 +13,9 @@ 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, @@ -27,7 +28,6 @@ import { Button } from "example/components/Button"; import { InputSlider } from "example/components/InputSlider"; import { InputColor } from "example/components/InputColor"; import { InputSegment } from "example/components/InputSegment"; -import { AnimatedText } from "../components/AnimatedText"; import { appColors } from "../consts/colors"; import { descriptionForRoute } from "../consts/routes"; import inter from "../assets/inter-medium.ttf"; @@ -48,6 +48,37 @@ const DATA = (numberPoints = 5) => label: `Label ${index + 1}`, })); +/** + * Reads the hover index that `PolarChart` maintains internally — no + * `chartHoverState` prop needed — via the `usePieHoverState` hook. + */ +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(); @@ -62,19 +93,6 @@ export default function PieChart(props: { segment: string }) { >("none"); const { state } = useChartTransformState(); - const hoverIndex = useSharedValue(-1); - const isDark = useDarkMode(); - const hoveredLabel = useDerivedValue(() => { - const i = hoverIndex.value; - const d = i >= 0 && i < data.length ? data[i] : undefined; - return d ? d.label : "Hover the chart!"; - }); - const hoveredValue = useDerivedValue(() => { - const i = hoverIndex.value; - const d = i >= 0 && i < data.length ? data[i] : undefined; - return d ? `${d.value} (slice ${i + 1})` : ""; - }); - const k = useSharedValue(1); const tx = useSharedValue(0); const ty = useSharedValue(0); @@ -110,29 +128,6 @@ export default function PieChart(props: { segment: string }) { return ( - - + {({ slice }) => { return ( @@ -236,11 +231,4 @@ const styles = StyleSheet.create({ backgroundColor: appColors.viewBackground.dark, }, }, - readout: { - fontWeight: "bold", - paddingTop: 10, - }, - readoutValue: { - opacity: 0.75, - }, }); diff --git a/example/consts/routes.ts b/example/consts/routes.ts index fb0fc554..4deae9b3 100644 --- a/example/consts/routes.ts +++ b/example/consts/routes.ts @@ -158,7 +158,7 @@ export const ChartRoutes: ChartRoute[] = [ { title: "Donut Chart", description: - "This is how to make a Donut chart in Victory. It is built off of the Pie chart using the `innerRadius` prop. Hovering with the mouse (enableHover + chartHoverState) reports the hovered slice.", + "This is how to make a Donut chart in Victory. It is built off of the Pie chart using the `innerRadius` prop. Hovering with the mouse reports the hovered slice — `PolarChart` tracks it for you, read out inside the chart via `usePieHoverState()`.", path: "/donut-chart", }, { diff --git a/lib/src/cartesian/CartesianChart.tsx b/lib/src/cartesian/CartesianChart.tsx index c26d4607..f762be66 100644 --- a/lib/src/cartesian/CartesianChart.tsx +++ b/lib/src/cartesian/CartesianChart.tsx @@ -1,4 +1,5 @@ import * as React from "react"; +import { Platform } from "react-native"; import { Group, type CanvasRef } from "react-native-skia"; import { type SharedValue, useSharedValue } from "react-native-reanimated"; import { type ContextBridge, FiberProvider, useContextBridge } from "its-fine"; @@ -303,7 +304,7 @@ function CartesianChartContent< chartPressState, chartHoverState, chartPressConfig, - enableHover, + enableHover: enableHoverProp, chartHoverConfig, gestureHandlerConfig, onChartBoundsChange, @@ -321,6 +322,10 @@ function CartesianChartContent< explicitSize, headless, }: CartesianChartProps) { + // Hover is aimed at pointer devices; it's enabled by default on web, where a + // mouse or trackpad is the norm. Elsewhere (and when explicitly set to + // `false` on web) it stays opt-in. + const enableHover = enableHoverProp ?? Platform.OS === "web"; const { size, hasMeasuredLayoutSize, onLayout, isHeadless } = useChartCanvasSize({ explicitSize, headless }); const chartBoundsRef = React.useRef(undefined); @@ -338,10 +343,12 @@ function CartesianChartContent< chartHoverStateRef.current = chartHoverState; // `enableHover` drives either an explicit `chartHoverState` or the given // `chartPressState` (so hover matches press without extra setup); with - // neither it has nothing to write to and silently does nothing. + // neither it has nothing to write to and silently does nothing. Only warn + // about that when `enableHover` was passed explicitly — on web it resolves + // to `true` by default and plain charts are common. React.useEffect(() => { if ( - enableHover && + enableHoverProp === true && !chartPressState && !chartHoverState && process.env.NODE_ENV !== "production" @@ -350,7 +357,7 @@ function CartesianChartContent< "CartesianChart: `enableHover` has no effect without `chartPressState` or `chartHoverState`.", ); } - }, [enableHover, chartPressState, chartHoverState]); + }, [enableHoverProp, chartPressState, chartHoverState]); const yKeysKey = yKeys.join("\u0000"); const normalizedAxisProps = useBuildChartAxis({ xAxis: xAxis as XAxisInputProps | undefined, diff --git a/lib/src/index.ts b/lib/src/index.ts index 18a39236..0c7c9967 100644 --- a/lib/src/index.ts +++ b/lib/src/index.ts @@ -159,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 8f570b07..abfb4ca6 100644 --- a/lib/src/pie/PieChart.tsx +++ b/lib/src/pie/PieChart.tsx @@ -88,19 +88,15 @@ export const PieChart = (props: PieChartProps) => { // The pointer may stay stationary over a stale geometry while data changes; // clear the hover index so it doesn't point at outdated slices. React.useEffect(() => { - if (chartHoverState) { - chartHoverState.index.value = -1; - } - // Intentionally keyed only on data: `chartHoverState` is commonly passed inline - // (`{{ index }}`), so keying on it would reset hover on every render. + chartHoverState.index.value = -1; + // Intentionally keyed only on data: `chartHoverState` is commonly passed + // inline (`{{ index }}`), so keying on it would reset hover on every render. // eslint-disable-next-line react-hooks/exhaustive-deps }, [_data]); useAnimatedReaction( () => hoverPointer?.value ?? null, (pointer) => { "worklet"; - if (!chartHoverState) return; - chartHoverState.index.value = getHoveredPieSliceIndex({ pointer, center, diff --git a/lib/src/polar/PolarChart.tsx b/lib/src/polar/PolarChart.tsx index d284a6a0..6601c77c 100644 --- a/lib/src/polar/PolarChart.tsx +++ b/lib/src/polar/PolarChart.tsx @@ -1,6 +1,7 @@ import * as React from "react"; import { Group } from "react-native-skia"; import { + Platform, type ViewStyle, type StyleProp, type LayoutChangeEvent, @@ -60,10 +61,14 @@ const PolarChartBase = ( transformState, isHeadless, explicitSize, - enableHover, + enableHover: enableHoverProp, hoverPointer, chartHoverConfig, } = props; + // Hover is aimed at pointer devices; it's enabled by default on web, where + // a mouse or trackpad is the norm. Elsewhere (and when explicitly set to + // `false` on web) it stays opt-in. + const enableHover = enableHoverProp ?? Platform.OS === "web"; const Bridge: ContextBridge = useContextBridge(); let composed = Gesture.Race(); @@ -175,7 +180,14 @@ export const PolarChart = < }); const hoverPointer = useSharedValue(null); - const chartHoverState = props.chartHoverState; + // Pie/donut charts always have a hover state to drive; the `chartHoverState` + // prop only overrides it for consumers that need the value off-thread, e.g. + // readouts rendered outside the chart. Other consumers read the default + // through `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 7b4696a8..e62b964a 100644 --- a/lib/src/polar/contexts/PolarChartContext.tsx +++ b/lib/src/polar/contexts/PolarChartContext.tsx @@ -16,7 +16,7 @@ interface PolarChartContext { valueKey: string; colorKey: string; hoverPointer?: SharedValue; - chartHoverState?: PieHoverState; + chartHoverState: PieHoverState; } const PolarChartContext = createContext( @@ -30,7 +30,7 @@ interface PolarChartProviderProps { valueKey: string; colorKey: string; hoverPointer?: SharedValue; - chartHoverState?: PieHoverState; + chartHoverState: PieHoverState; } export const PolarChartProvider = ( @@ -75,3 +75,15 @@ export const usePolarChartContext = () => { return context; }; + +/** + * Hover state for pie and donut charts: `index` is the hovered slice, or `-1` + * while the pointer is over the donut hole, outside the pie, or off the chart. + * `PolarChart` maintains this value; the `chartHoverState` prop only overrides + * it, so this hook works even without passing the prop. + */ +export const usePieHoverState = (): PieHoverState => { + const { chartHoverState } = usePolarChartContext(); + + return chartHoverState; +}; diff --git a/lib/test/headless/stubs/react-native-gesture-handler.ts b/lib/test/headless/stubs/react-native-gesture-handler.ts index dca08c62..a0236ce0 100644 --- a/lib/test/headless/stubs/react-native-gesture-handler.ts +++ b/lib/test/headless/stubs/react-native-gesture-handler.ts @@ -15,6 +15,7 @@ const chainableGesture = (): ChainableGesture => { export const Gesture = { Race: (..._gestures: unknown[]) => chainableGesture(), + Simultaneous: (..._gestures: unknown[]) => chainableGesture(), Pinch: () => chainableGesture(), Pan: () => chainableGesture(), Hover: () => chainableGesture(), diff --git a/website/docs/cartesian/cartesian-chart.md b/website/docs/cartesian/cartesian-chart.md index accd728a..7e067fda 100644 --- a/website/docs/cartesian/cartesian-chart.md +++ b/website/docs/cartesian/cartesian-chart.md @@ -321,6 +321,8 @@ Explicit `0` values are honored for these options. For example, `activateAfterLo 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. 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 @@ -345,9 +347,10 @@ function HoveredChart() { ### `chartHoverConfig` -Optional configuration for the hover gesture created by `enableHover`. It accepts an object with a single optional property: +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 ``` -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`) use the same `chartHoverState` prop. +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 differently: 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 diff --git a/website/docs/polar/pie/pie-charts.md b/website/docs/polar/pie/pie-charts.md index 12607edf..78a53de3 100644 --- a/website/docs/polar/pie/pie-charts.md +++ b/website/docs/polar/pie/pie-charts.md @@ -11,7 +11,7 @@ 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 the [`enableHover`](/docs/polar/polar-chart#enablehover) and [`chartHoverState`](/docs/polar/polar-chart#charthoverstate) props, which report the hovered slice index while a mouse hovers over the chart. +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. ::: diff --git a/website/docs/polar/polar-chart.md b/website/docs/polar/polar-chart.md index ba7de9cb..df17c837 100644 --- a/website/docs/polar/polar-chart.md +++ b/website/docs/polar/polar-chart.md @@ -100,13 +100,49 @@ When `true` (and `explicitSize` is set), renders a Skia-only subtree with no `Vi ### `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) prop below. This enables hover interactions for `Pie` and `Donut` charts without any extra gesture code. +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` -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. Requires `enableHover`. +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"; @@ -138,8 +174,7 @@ function HoveredPie() { valueKey={"value"} labelKey={"label"} colorKey={"color"} - enableHover // 👈 track mouse hovers - chartHoverState={{ index: hoverIndex }} + chartHoverState={{ index: hoverIndex }} // 👈 your own hover state > @@ -156,6 +191,7 @@ The slice geometry (including each slice's `innerRadius`, start/end angles, valu ### `chartHoverConfig` -Optional configuration for the hover gesture created by `enableHover`. It accepts an object with a single optional property: +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. From 5649b9516d2a997ad73f861c88bd76115abb45b9 Mon Sep 17 00:00:00 2001 From: Adam Hari Date: Sun, 1 Nov 2026 17:47:35 -0700 Subject: [PATCH 24/25] feat: CartesianChart built-in hover state for full pie API parity --- .changeset/hover-gesture-support.md | 2 +- lib/src/cartesian/CartesianChart.tsx | 67 ++++++++++++------ .../hooks/useChartPressState.test.ts | 69 +++++++++++++++++++ lib/src/cartesian/hooks/useChartPressState.ts | 45 +++++++----- lib/src/types.ts | 18 +++++ website/docs/cartesian/cartesian-chart.md | 51 ++++++++++++-- website/docs/cartesian/chart-gestures.mdx | 26 ++++++- 7 files changed, 231 insertions(+), 47 deletions(-) create mode 100644 lib/src/cartesian/hooks/useChartPressState.test.ts diff --git a/.changeset/hover-gesture-support.md b/.changeset/hover-gesture-support.md index 81094086..1c0f1883 100644 --- a/.changeset/hover-gesture-support.md +++ b/.changeset/hover-gesture-support.md @@ -6,6 +6,6 @@ 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. +- `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/lib/src/cartesian/CartesianChart.tsx b/lib/src/cartesian/CartesianChart.tsx index f762be66..a68a1e93 100644 --- a/lib/src/cartesian/CartesianChart.tsx +++ b/lib/src/cartesian/CartesianChart.tsx @@ -8,6 +8,7 @@ import { type MutableRefObject } from "react"; import type { ScaleLinear, ScaleLogarithmic } from "d3-scale"; import isEqual from "react-fast-compare"; import type { + ChartBuiltInHoverState, AxisProps, CartesianChartRenderArg, InputFields, @@ -35,6 +36,7 @@ import type { ChartPressState, ChartPressStateInit, } from "./hooks/useChartPressState"; +import { makeChartPressState } from "./hooks/useChartPressState"; import { useFunctionRef } from "../hooks/useFunctionRef"; import { CartesianChartProvider } from "./contexts/CartesianChartContext"; import { XAxis } from "./components/XAxis"; @@ -341,23 +343,6 @@ function CartesianChartContent< chartPressStateRef.current = chartPressState; const chartHoverStateRef = React.useRef(chartHoverState); chartHoverStateRef.current = chartHoverState; - // `enableHover` drives either an explicit `chartHoverState` or the given - // `chartPressState` (so hover matches press without extra setup); with - // neither it has nothing to write to and silently does nothing. Only warn - // about that when `enableHover` was passed explicitly — on web it resolves - // to `true` by default and plain charts are common. - React.useEffect(() => { - if ( - enableHoverProp === true && - !chartPressState && - !chartHoverState && - process.env.NODE_ENV !== "production" - ) { - console.warn( - "CartesianChart: `enableHover` has no effect without `chartPressState` or `chartHoverState`.", - ); - } - }, [enableHoverProp, chartPressState, chartHoverState]); const yKeysKey = yKeys.join("\u0000"); const normalizedAxisProps = useBuildChartAxis({ xAxis: xAxis as XAxisInputProps | undefined, @@ -667,12 +652,31 @@ function CartesianChartContent< const activePressSharedValues = Array.isArray(chartPressState) ? chartPressState : [chartPressState]; + /** True when neither `chartPressState` nor `chartHoverState` was passed: + * hover then drives a chart-owned built-in state (mirroring `PolarChart`), + * exposed to chart content through the render arg. */ + 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], + ); /** Values the hover gesture drives: the explicit `chartHoverState` when given - * (keeping hover and press interactions distinct), otherwise the press - * states so hover matches press with no extra setup. */ + * (keeping hover and press interactions distinct), the press states so hover + * matches press with no extra setup, or the built-in hover state when no + * states exist at all. */ const activeHoverSharedValues = chartHoverState === undefined - ? activePressSharedValues + ? chartPressState + ? activePressSharedValues + : [builtInHoverState] : Array.isArray(chartHoverState) ? chartHoverState : [chartHoverState]; @@ -703,6 +707,7 @@ function CartesianChartContent< for (const state of [...pressStates, ...hoverStates]) { if (state) resetChartPressState(state); } + resetChartPressState(builtInHoverState); touchMap.value = {}; gestureState.value = { @@ -710,7 +715,15 @@ function CartesianChartContent< bootstrap: [], }; lastIdx.value = null; - }, [data, gestureState, lastIdx, touchMap, xKey, yKeysKey]); + }, [ + builtInHoverState, + data, + gestureState, + lastIdx, + touchMap, + xKey, + yKeysKey, + ]); const panGesture = Gesture.Pan() /** @@ -976,6 +989,14 @@ function CartesianChartContent< chartBounds, canvasSize: size, points, + // Cast is a type-variance workaround: the built-in state IS a + // `ChartPressState` keyed by this chart's y keys, but `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); @@ -1113,7 +1134,9 @@ function CartesianChartContent< if (chartPressState) { composed = Gesture.Race(composed, panGesture); } - if (enableHover && (chartPressState || chartHoverState)) { + // The hover gesture always has a state to drive (an explicit + // `chartHoverState`, the press states, or the built-in one). + if (enableHover) { composed = Gesture.Simultaneous(composed, hoverGesture); } diff --git a/lib/src/cartesian/hooks/useChartPressState.test.ts b/lib/src/cartesian/hooks/useChartPressState.test.ts new file mode 100644 index 00000000..7999096f --- /dev/null +++ b/lib/src/cartesian/hooks/useChartPressState.test.ts @@ -0,0 +1,69 @@ +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); + // reset clears positions but keeps the x/y values + 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..3ad2ff70 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,31 @@ export const useChartPressState = ( return { state, isActive }; }; +/** Builds a `ChartPressState`-shaped object with fully independent shared + * values — usable outside of hooks (e.g. for the chart's built-in hover + * state) as long as it is memoized by the caller. */ +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/types.ts b/lib/src/types.ts index 06fa5bd7..103ec4a0 100644 --- a/lib/src/types.ts +++ b/lib/src/types.ts @@ -133,6 +133,10 @@ export type CartesianChartRenderArg< points: { [K in YK]: PointsArray; }; + /** The built-in hover state the chart maintains when neither + * `chartPressState` nor `chartHoverState` is provided; `undefined` + * otherwise (explicit-state users read their own state objects). */ + hoverState?: ChartBuiltInHoverState>; }; export type Scale = ScaleLinear; @@ -403,6 +407,20 @@ export type PieHoverState = { index: SharedValue; }; +/** + * Built-in hover state `CartesianChart` maintains when neither + * `chartPressState` nor `chartHoverState` is provided — hover-only (press + * stays opt-in), mirroring `PolarChart`'s built-in pie hover state. Exposed + * through the render arg's `hoverState` field. + */ +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/website/docs/cartesian/cartesian-chart.md b/website/docs/cartesian/cartesian-chart.md index 7e067fda..d4a25031 100644 --- a/website/docs/cartesian/cartesian-chart.md +++ b/website/docs/cartesian/cartesian-chart.md @@ -256,9 +256,11 @@ When no point is "active" (no press/hover), the gesture state will return `NaN` ### `chartHoverState` -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). +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). -Without a `chartHoverState`, hovering updates the `chartPressState` values themselves, which makes the hover gesture behave exactly like the press gesture with no extra setup. With a `chartHoverState`, hover and press are tracked independently — e.g. a hover tooltip that follows the mouse while a pressed tooltip stays pinned. +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"; @@ -273,13 +275,43 @@ return ( yKeys={["highTmp"]} chartPressState={press.state} chartHoverState={hover.state} // 👈 hover and press tracked independently - enableHover={true} > {/* ... */} ); ``` +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. @@ -319,7 +351,7 @@ Explicit `0` values are honored for these options. For example, `activateAfterLo ### `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. 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. +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. @@ -690,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 f6a4a6ac..479d694f 100644 --- a/website/docs/cartesian/chart-gestures.mdx +++ b/website/docs/cartesian/chart-gestures.mdx @@ -187,6 +187,30 @@ The example app uses this API in several places — [`example/app/candlestick.ts ::: +### 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: @@ -205,7 +229,7 @@ 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 differently: 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. +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 From 653133388cb64d971589475270276dc831a02401 Mon Sep 17 00:00:00 2001 From: Adam Hari Date: Sun, 1 Nov 2026 20:55:11 -0700 Subject: [PATCH 25/25] chore: trim inline comments across hover PR code --- example/app/donut-chart.tsx | 5 +--- example/app/hover-press.tsx | 1 - example/app/pie-chart.tsx | 5 +--- lib/src/cartesian/CartesianChart.tsx | 26 ++++--------------- .../hooks/useChartPressState.test.ts | 1 - lib/src/cartesian/hooks/useChartPressState.ts | 4 +-- lib/src/pie/PieChart.tsx | 7 +++-- lib/src/polar/PolarChart.tsx | 10 +++---- lib/src/polar/contexts/PolarChartContext.tsx | 7 +++-- lib/src/types.ts | 10 +++---- 10 files changed, 20 insertions(+), 56 deletions(-) diff --git a/example/app/donut-chart.tsx b/example/app/donut-chart.tsx index 35fabdad..c0081689 100644 --- a/example/app/donut-chart.tsx +++ b/example/app/donut-chart.tsx @@ -56,10 +56,7 @@ const DATA = (numberPoints = 5) => label: `Label ${index + 1}`, })); -/** - * Reads the hover index that `PolarChart` maintains internally — no - * `chartHoverState` prop needed — via the `usePieHoverState` hook. - */ +/** Reads the hovered-slice index `PolarChart` maintains internally; no `chartHoverState` prop needed. */ function HoverReadout({ data, }: { diff --git a/example/app/hover-press.tsx b/example/app/hover-press.tsx index 74f994e4..418dbab2 100644 --- a/example/app/hover-press.tsx +++ b/example/app/hover-press.tsx @@ -42,7 +42,6 @@ export default function HoverPress(props: { segment: string }) { const description = descriptionForRoute(props.segment); const isDark = useDarkMode(); - // Two independent states: press drives `chartPressState`, hover drives `chartHoverState`. const { state: press, isActive: pressIsActive } = useChartPressState({ x: 0, y: { highTmp: 0 }, diff --git a/example/app/pie-chart.tsx b/example/app/pie-chart.tsx index 22d66272..e57c5a9d 100644 --- a/example/app/pie-chart.tsx +++ b/example/app/pie-chart.tsx @@ -48,10 +48,7 @@ const DATA = (numberPoints = 5) => label: `Label ${index + 1}`, })); -/** - * Reads the hover index that `PolarChart` maintains internally — no - * `chartHoverState` prop needed — via the `usePieHoverState` hook. - */ +/** Reads the hovered-slice index `PolarChart` maintains internally; no `chartHoverState` prop needed. */ function HoverReadout({ data, }: { diff --git a/lib/src/cartesian/CartesianChart.tsx b/lib/src/cartesian/CartesianChart.tsx index a68a1e93..d90b74c4 100644 --- a/lib/src/cartesian/CartesianChart.tsx +++ b/lib/src/cartesian/CartesianChart.tsx @@ -324,9 +324,7 @@ function CartesianChartContent< explicitSize, headless, }: CartesianChartProps) { - // Hover is aimed at pointer devices; it's enabled by default on web, where a - // mouse or trackpad is the norm. Elsewhere (and when explicitly set to - // `false` on web) it stays opt-in. + // 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 }); @@ -652,9 +650,6 @@ function CartesianChartContent< const activePressSharedValues = Array.isArray(chartPressState) ? chartPressState : [chartPressState]; - /** True when neither `chartPressState` nor `chartHoverState` was passed: - * hover then drives a chart-owned built-in state (mirroring `PolarChart`), - * exposed to chart content through the render arg. */ const usesBuiltInHoverState = !chartPressState && !chartHoverState; const builtInHoverState = React.useMemo( () => @@ -668,10 +663,7 @@ function CartesianChartContent< // eslint-disable-next-line react-hooks/exhaustive-deps [yKeysKey], ); - /** Values the hover gesture drives: the explicit `chartHoverState` when given - * (keeping hover and press interactions distinct), the press states so hover - * matches press with no extra setup, or the built-in hover state when no - * states exist at all. */ + /** Hover drives `chartHoverState` if given, else the press states, else the built-in state. */ const activeHoverSharedValues = chartHoverState === undefined ? chartPressState @@ -680,9 +672,7 @@ function CartesianChartContent< : Array.isArray(chartHoverState) ? chartHoverState : [chartHoverState]; - /** True when the hover gesture writes to the press states directly — - * either because there is no explicit `chartHoverState` (hover mirrors press) - * or because the caller passed the same state object to both props. */ + /** 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), ); @@ -693,9 +683,7 @@ function CartesianChartContent< TouchData >[], }); - /** Pan-press cleanup defers deactivation while the pointer hovers over - * values the hover gesture drives, so a press/click doesn't reset a - * hover-driven state. */ + /** 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(() => { @@ -989,9 +977,7 @@ function CartesianChartContent< chartBounds, canvasSize: size, points, - // Cast is a type-variance workaround: the built-in state IS a - // `ChartPressState` keyed by this chart's y keys, but `SharedValue`'s - // contravariant setter blocks direct assignment to the render-arg type. + // `SharedValue`'s contravariant setter blocks direct assignment to the render-arg type. hoverState: usesBuiltInHoverState ? (builtInHoverState as unknown as ChartBuiltInHoverState< Extract @@ -1134,8 +1120,6 @@ function CartesianChartContent< if (chartPressState) { composed = Gesture.Race(composed, panGesture); } - // The hover gesture always has a state to drive (an explicit - // `chartHoverState`, the press states, or the built-in one). if (enableHover) { composed = Gesture.Simultaneous(composed, hoverGesture); } diff --git a/lib/src/cartesian/hooks/useChartPressState.test.ts b/lib/src/cartesian/hooks/useChartPressState.test.ts index 7999096f..bfc16d6d 100644 --- a/lib/src/cartesian/hooks/useChartPressState.test.ts +++ b/lib/src/cartesian/hooks/useChartPressState.test.ts @@ -60,7 +60,6 @@ describe("makeChartPressState", () => { expect(state.isActive.value).toBe(false); expect(state.matchedIndex.value).toBe(-1); expect(state.yIndex.value).toBe(-1); - // reset clears positions but keeps the x/y values expect(state.x.position.value).toBe(0); expect(state.x.value.value).toBe(5); expect(state.y.high.position.value).toBe(0); diff --git a/lib/src/cartesian/hooks/useChartPressState.ts b/lib/src/cartesian/hooks/useChartPressState.ts index 3ad2ff70..6c046ccd 100644 --- a/lib/src/cartesian/hooks/useChartPressState.ts +++ b/lib/src/cartesian/hooks/useChartPressState.ts @@ -22,9 +22,7 @@ export const useChartPressState = ( return { state, isActive }; }; -/** Builds a `ChartPressState`-shaped object with fully independent shared - * values — usable outside of hooks (e.g. for the chart's built-in hover - * state) as long as it is memoized by the caller. */ +/** Builds a `ChartPressState` outside of hooks (e.g. the chart's built-in hover state); memoize the result. */ export const makeChartPressState = ( initialValues: Init, ): ChartPressState => ({ diff --git a/lib/src/pie/PieChart.tsx b/lib/src/pie/PieChart.tsx index abfb4ca6..68b1d211 100644 --- a/lib/src/pie/PieChart.tsx +++ b/lib/src/pie/PieChart.tsx @@ -85,12 +85,11 @@ export const PieChart = (props: PieChartProps) => { ]); const { hoverPointer, chartHoverState } = usePolarChartContext(); - // The pointer may stay stationary over a stale geometry while data changes; - // clear the hover index so it doesn't point at outdated slices. + // The pointer may sit over stale geometry after a data change; reset the hover index. React.useEffect(() => { chartHoverState.index.value = -1; - // Intentionally keyed only on data: `chartHoverState` is commonly passed - // inline (`{{ index }}`), so keying on it would reset hover on every render. + // 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( diff --git a/lib/src/polar/PolarChart.tsx b/lib/src/polar/PolarChart.tsx index 6601c77c..633c459a 100644 --- a/lib/src/polar/PolarChart.tsx +++ b/lib/src/polar/PolarChart.tsx @@ -65,9 +65,7 @@ const PolarChartBase = ( hoverPointer, chartHoverConfig, } = props; - // Hover is aimed at pointer devices; it's enabled by default on web, where - // a mouse or trackpad is the norm. Elsewhere (and when explicitly set to - // `false` on web) it stays opt-in. + // Hover is aimed at pointer devices, so it's on by default on web. const enableHover = enableHoverProp ?? Platform.OS === "web"; const Bridge: ContextBridge = useContextBridge(); @@ -180,10 +178,8 @@ export const PolarChart = < }); const hoverPointer = useSharedValue(null); - // Pie/donut charts always have a hover state to drive; the `chartHoverState` - // prop only overrides it for consumers that need the value off-thread, e.g. - // readouts rendered outside the chart. Other consumers read the default - // through `usePieHoverState()`. + // 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, diff --git a/lib/src/polar/contexts/PolarChartContext.tsx b/lib/src/polar/contexts/PolarChartContext.tsx index e62b964a..d2dd4c05 100644 --- a/lib/src/polar/contexts/PolarChartContext.tsx +++ b/lib/src/polar/contexts/PolarChartContext.tsx @@ -77,10 +77,9 @@ export const usePolarChartContext = () => { }; /** - * Hover state for pie and donut charts: `index` is the hovered slice, or `-1` - * while the pointer is over the donut hole, outside the pie, or off the chart. - * `PolarChart` maintains this value; the `chartHoverState` prop only overrides - * it, so this hook works even without passing the prop. + * 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(); diff --git a/lib/src/types.ts b/lib/src/types.ts index 103ec4a0..5f8692cf 100644 --- a/lib/src/types.ts +++ b/lib/src/types.ts @@ -133,9 +133,7 @@ export type CartesianChartRenderArg< points: { [K in YK]: PointsArray; }; - /** The built-in hover state the chart maintains when neither - * `chartPressState` nor `chartHoverState` is provided; `undefined` - * otherwise (explicit-state users read their own state objects). */ + /** The chart's built-in hover state; only present when neither `chartPressState` nor `chartHoverState` was passed. */ hoverState?: ChartBuiltInHoverState>; }; @@ -408,10 +406,8 @@ export type PieHoverState = { }; /** - * Built-in hover state `CartesianChart` maintains when neither - * `chartPressState` nor `chartHoverState` is provided — hover-only (press - * stays opt-in), mirroring `PolarChart`'s built-in pie hover state. Exposed - * through the render arg's `hoverState` field. + * 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;