Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(quill-charts): keep pinned tooltip open while selecting text to copy (#71814)

Sam Penningtona8a3483bca15
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index 1315d85a2102..ee05666483a2 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -72,7 +72,7 @@ Charts fill their container and need a parent with real dimensions — a `0`-hei
- Overlays (`ReferenceLine`/`ReferenceLines`, `ValueLabels`, `AxisTitles`, `TrendLineOverlay`, `HighlightedRange`) compose as children.
- `HighlightedRange` draws a translucent box spanning an x-axis range — pass `start`/`end` as data indices or labels (e.g. straight from `onDateRangeZoom`'s `startIndex`/`endIndex`). Use it to mirror an external selection (the rows visible in a paired virtualized list, a picked time window) onto the chart. On band (bar) charts the box covers the endpoints' full bands; on point (line) charts it runs point to point. `color`, `fillOpacity`, and `borderOpacity` tune the look (`borderOpacity: 0` drops the edge border); it clamps to the plot area and renders null when an endpoint doesn't resolve.
-- `DefaultTooltip` (the built-in tooltip, also usable from a custom `tooltip` render prop) takes optional `valueFormatter`, `labelFormatter`, `labelRenderer`, `showHeader`, `showTotal`, `totalLabel`, `totalFormatter`, `sortedByValue`, `hideZeroRows`, `onRowClick`, and `footer`. `valueFormatter` gets `(value, entry)` — the row's `seriesData` entry as a second arg — so each row can format with its own `series.meta` (e.g. per-column currency/duration); it may return a node, not just a string (e.g. a property-formatted value). `labelFormatter` transforms the raw x-axis label shown in the tooltip header (e.g. convert an ISO datetime string to "Jun 24, 10:00"); on time-series charts with `xAxis.timezone` + `interval` set it defaults to an interval-aware date formatter that includes the weekday for single-day buckets ("Sat, Jun 6, 2026", "Sat, Jun 6, 14:00"; week/month buckets span days, so "Jun 1, 2026", "Jun 2026"), so the header matches the auto-formatted axis ticks — an explicit `labelFormatter` still wins. `labelRenderer` overrides how each row's label renders (defaults to the series label) — use for richer labels than a plain string, e.g. breakdown-value pills. `showHeader` (default true) toggles the header label row — pass false for charts without a meaningful header (pie slices, aggregated single-column bars). `showTotal` appends a footer row summing the visible series; it excludes `overlay` series (goal lines) and series with `visibility.total: false` (values that don't sum meaningfully with the rest, e.g. a percentage column alongside counts — the row itself still renders) from the sum, and is suppressed when fewer than two summable series remain. `totalFormatter` formats the total (defaults to `valueFormatter` applied with the first summable row's entry); `totalLabel` defaults to `'Total'`. `sortedByValue` sorts rows by value descending so the highest value appears first. `hideZeroRows` drops rows whose value is exactly `0` (e.g. lifecycle statuses absent for a period), so the tooltip lists only series with data at the hovered point. `onRowClick` makes each series row clickable (firing with the row's `seriesData` entry) — the tooltip must be pinned for clicks to land, since an unpinned tooltip is `pointer-events: none`; use it to open a per-series drill-down (e.g. the persons modal). `footer` renders arbitrary content below all rows (with a divider) — useful for "click to inspect" hints. A formatter taking only `value` stays compatible — the extra arg is ignored.
+- `DefaultTooltip` (the built-in tooltip, also usable from a custom `tooltip` render prop) takes optional `valueFormatter`, `labelFormatter`, `labelRenderer`, `showHeader`, `showTotal`, `totalLabel`, `totalFormatter`, `sortedByValue`, `hideZeroRows`, `onRowClick`, and `footer`. `valueFormatter` gets `(value, entry)` — the row's `seriesData` entry as a second arg — so each row can format with its own `series.meta` (e.g. per-column currency/duration); it may return a node, not just a string (e.g. a property-formatted value). `labelFormatter` transforms the raw x-axis label shown in the tooltip header (e.g. convert an ISO datetime string to "Jun 24, 10:00"); on time-series charts with `xAxis.timezone` + `interval` set it defaults to an interval-aware date formatter that includes the weekday for single-day buckets ("Sat, Jun 6, 2026", "Sat, Jun 6, 14:00"; week/month buckets span days, so "Jun 1, 2026", "Jun 2026"), so the header matches the auto-formatted axis ticks — an explicit `labelFormatter` still wins. `labelRenderer` overrides how each row's label renders (defaults to the series label) — use for richer labels than a plain string, e.g. breakdown-value pills. `showHeader` (default true) toggles the header label row — pass false for charts without a meaningful header (pie slices, aggregated single-column bars). `showTotal` appends a footer row summing the visible series; it excludes `overlay` series (goal lines) and series with `visibility.total: false` (values that don't sum meaningfully with the rest, e.g. a percentage column alongside counts — the row itself still renders) from the sum, and is suppressed when fewer than two summable series remain. `totalFormatter` formats the total (defaults to `valueFormatter` applied with the first summable row's entry); `totalLabel` defaults to `'Total'`. `sortedByValue` sorts rows by value descending so the highest value appears first. `hideZeroRows` drops rows whose value is exactly `0` (e.g. lifecycle statuses absent for a period), so the tooltip lists only series with data at the hovered point. `onRowClick` makes each series row clickable (firing with the row's `seriesData` entry) — the tooltip must be pinned for clicks to land, since an unpinned tooltip is `pointer-events: none`; use it to open a per-series drill-down (e.g. the persons modal). `footer` renders arbitrary content below all rows (with a divider) — useful for "click to inspect" hints. A formatter taking only `value` stays compatible — the extra arg is ignored. Pinned tooltips are copy-friendly: outside-dismissal keys off where the press _started_ (pointer-down outside the tooltip/chart, or Escape), so a text-selection drag that releases outside the tooltip doesn't dismiss it, and a click that completes a text selection inside a row doesn't fire `onRowClick`.
- BarChart sets `TooltipContext.hoveredSeriesKey` — the key of the bar/segment under the cursor (stacked: the visible segment; grouped: the band-slot hit). Stacked `seriesData` keeps every segment in declaration order, so a custom tooltip that describes a single segment (e.g. a funnel breakdown) must select by `hoveredSeriesKey`, not `seriesData[0]`. It may reference a series hidden from `seriesData` via `visibility.tooltip: false` (e.g. a drop-off filler), and is `undefined` on other chart types and pinned rebuilds without a cursor.
- To tune the built-in tooltip **without writing a render prop**, put those same fields on `config.tooltip` (`{ enabled, pinnable, resolveClickToNearestSeries, placement, valueFormatter, labelFormatter, showTotal, totalLabel, totalFormatter, sortedByValue }`). When no `tooltip` render prop is supplied, the chart renders `DefaultTooltip` with them applied; a render prop, if given, owns content entirely and these are ignored. Prefer config for "format each row / add a total" cases (e.g. SQL insights pass per-column formatters this way) and reach for the render prop only for genuinely custom tooltip markup (e.g. adding a `footer` hint). `resolveClickToNearestSeries` (default false) changes what a click on a `pinnable` multi-series chart does: instead of always pinning first (letting the user then click a specific row), it resolves the series nearest the cursor and fires `onPointClick` for it directly — skip pinning only where a click's target series is visually unambiguous by position (e.g. funnel breakdown areas, one per breakdown value); leave it off where series overlap closely and a wrong guess is costly (e.g. trend lines).
- `ReferenceLine` variants: `goal` (dashed grey), `alert` (dashed red), `marker` (solid thin).
diff --git a/packages/quill/packages/charts/src/core/hooks/useChartInteraction.test.ts b/packages/quill/packages/charts/src/core/hooks/useChartInteraction.test.ts
index 5b96feb2ec68..b250d4927e51 100644
--- a/packages/quill/packages/charts/src/core/hooks/useChartInteraction.test.ts
+++ b/packages/quill/packages/charts/src/core/hooks/useChartInteraction.test.ts
@@ -69,6 +69,20 @@ function simulateMouseMove(
handlers.onMouseMove(mockEvent)
}
+function simulateClick(handlers: { onClick: (e: React.MouseEvent<HTMLDivElement>) => void }, target: Element): void {
+ handlers.onClick({ target } as unknown as React.MouseEvent<HTMLDivElement>)
+}
+
+/** An element inside a (simulated) portaled tooltip — carries the marker the guards check. */
+function makeTooltipChild(): { child: Element; cleanup: () => void } {
+ const tooltipEl = document.createElement('div')
+ tooltipEl.setAttribute('data-hog-charts-tooltip', '')
+ const child = document.createElement('span')
+ tooltipEl.appendChild(child)
+ document.body.appendChild(tooltipEl)
+ return { child, cleanup: () => document.body.removeChild(tooltipEl) }
+}
+
describe('useChartInteraction — tooltip pinning', () => {
let refs: ReturnType<typeof makeRefs>
@@ -115,7 +129,7 @@ describe('useChartInteraction — tooltip pinning', () => {
// Click to pin
act(() => {
- result.current.handlers.onClick()
+ simulateClick(result.current.handlers, refs.wrapperRef.current!)
})
expect(result.current.tooltipCtx?.isPinned).toBe(true)
}
@@ -179,10 +193,10 @@ describe('useChartInteraction — tooltip pinning', () => {
},
],
[
- 'click outside',
+ 'pointer-down outside',
() => {
jest.runAllTimers()
- document.body.dispatchEvent(new MouseEvent('click', { bubbles: true }))
+ document.body.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }))
},
],
])('clears pinned tooltip on %s', (_name, trigger) => {
@@ -262,12 +276,71 @@ describe('useChartInteraction — tooltip pinning', () => {
hoverAndPin(result)
act(() => {
- result.current.handlers.onClick()
+ simulateClick(result.current.handlers, refs.wrapperRef.current!)
})
expect(result.current.tooltipCtx).toBeNull()
})
+ it('keeps pinned tooltip when a click originates inside the portaled tooltip', () => {
+ // React portals bubble synthetic events through the React tree, so a click inside
+ // the tooltip reaches the wrapper's onClick — it must not unpin.
+ const { result } = renderInteraction()
+ hoverAndPin(result)
+
+ const { child, cleanup } = makeTooltipChild()
+ act(() => {
+ simulateClick(result.current.handlers, child)
+ })
+
+ expect(result.current.tooltipCtx?.isPinned).toBe(true)
+ cleanup()
+ })
+
+ it('does not start a zoom drag from a press inside the portaled tooltip', () => {
+ const onDateRangeZoom = jest.fn()
+ const { result } = renderHook(() =>
+ useChartInteraction({
+ scales,
+ dimensions,
+ labels,
+ series,
+ canvasRef: refs.canvasRef,
+ wrapperRef: refs.wrapperRef,
+ showTooltip: true,
+ pinnable: true,
+ resolveValue: (s, i) => s.data[i],
+ onDateRangeZoom,
+ })
+ )
+ act(() => {
+ simulateMouseMove(result.current.handlers, refs, 200, 100)
+ })
+ act(() => {
+ simulateClick(result.current.handlers, refs.wrapperRef.current!)
+ })
+ expect(result.current.tooltipCtx?.isPinned).toBe(true)
+
+ // A text-selection drag starting inside the tooltip bubbles mousedown + mousemove to
+ // the wrapper; without the guard the drag activates and clears the pin mid-copy.
+ const { child, cleanup } = makeTooltipChild()
+ act(() => {
+ result.current.handlers.onMouseDown!({
+ target: child,
+ currentTarget: refs.wrapperRef.current!,
+ clientX: 200,
+ clientY: 100,
+ button: 0,
+ } as unknown as React.MouseEvent<HTMLDivElement>)
+ })
+ act(() => {
+ simulateMouseMove(result.current.handlers, refs, 320, 100)
+ })
+
+ expect(result.current.tooltipCtx?.isPinned).toBe(true)
+ cleanup()
+ })
+
it('hover context does not have onUnpin', () => {
const { result } = renderInteraction(true)
@@ -298,7 +371,7 @@ describe('useChartInteraction — tooltip pinning', () => {
simulateMouseMove(result.current.handlers, refs, 200, 100)
})
act(() => {
- result.current.handlers.onClick()
+ simulateClick(result.current.handlers, refs.wrapperRef.current!)
})
expect(onPointClick).not.toHaveBeenCalled()
@@ -319,7 +392,7 @@ describe('useChartInteraction — tooltip pinning', () => {
simulateMouseMove(result.current.handlers, refs, 200, cursorY)
})
act(() => {
- result.current.handlers.onClick()
+ simulateClick(result.current.handlers, refs.wrapperRef.current!)
})
expect(onPointClick).toHaveBeenCalledTimes(1)
@@ -349,7 +422,7 @@ describe('useChartInteraction — tooltip pinning', () => {
simulateMouseMove(result.current.handlers, refs, 200, 100)
})
act(() => {
- result.current.handlers.onClick()
+ simulateClick(result.current.handlers, refs.wrapperRef.current!)
})
expect(result.current.tooltipCtx?.isPinned).toBe(true)
const initialIndex = result.current.tooltipCtx!.dataIndex
@@ -389,7 +462,7 @@ describe('useChartInteraction — tooltip pinning', () => {
simulateMouseMove(result.current.handlers, refs, 200, 100)
})
act(() => {
- result.current.handlers.onClick()
+ simulateClick(result.current.handlers, refs.wrapperRef.current!)
})
expect(result.current.tooltipCtx?.isPinned).toBe(true)
const initialCtx = result.current.tooltipCtx
@@ -424,7 +497,7 @@ describe('useChartInteraction — tooltip pinning', () => {
simulateMouseMove(result.current.handlers, refs, 300, 100)
})
act(() => {
- result.current.handlers.onClick()
+ simulateClick(result.current.handlers, refs.wrapperRef.current!)
})
expect(result.current.tooltipCtx?.isPinned).toBe(true)
diff --git a/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts b/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts
index eb6dddbed254..e6c0d7904d85 100644
--- a/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts
+++ b/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts
@@ -23,6 +23,13 @@ import { useDragToZoom } from './useDragToZoom'
import { useLatest } from './useLatest'
import { useTooltipLifecycle } from './useTooltipLifecycle'
+/** The tooltip is portaled out of the wrapper's DOM tree, but React portals still bubble
+ * synthetic events through the React tree — so a click or drag that starts inside the pinned
+ * tooltip reaches the wrapper's handlers and would dismiss the pin or start a zoom drag. */
+function originatesInTooltip(e: React.SyntheticEvent): boolean {
+ return e.target instanceof Element && !!e.target.closest('[data-hog-charts-tooltip]')
+}
+
interface UseChartInteractionOptions<Meta> {
scales: ChartScales | null
dimensions: ChartDimensions | null
@@ -95,7 +102,7 @@ interface UseChartInteractionResult<Meta> {
onMouseDown: (e: React.MouseEvent<HTMLDivElement>) => void
onMouseMove: (e: React.MouseEvent<HTMLDivElement>) => void
onMouseLeave: () => void
- onClick: () => void
+ onClick: (e: React.MouseEvent<HTMLDivElement>) => void
}
}
@@ -295,74 +302,96 @@ export function useChartInteraction<Meta = unknown>({
clearTooltip()
}, [isPinned, clearTooltip])
- const onClick = useCallback(() => {
- // A click that closes out a drag-to-zoom gesture must not also pin/unpin or fire onPointClick.
- if (shouldSwallowClick()) {
- return
- }
- const currentIndex = hoverIndexRef.current
- if (currentIndex < 0) {
- return
- }
+ const onClick = useCallback(
+ (e: React.MouseEvent<HTMLDivElement>) => {
+ if (originatesInTooltip(e)) {
+ return
+ }
+ // A click that closes out a drag-to-zoom gesture must not also pin/unpin or fire onPointClick.
+ if (shouldSwallowClick()) {
+ return
+ }
+ const currentIndex = hoverIndexRef.current
+ if (currentIndex < 0) {
+ return
+ }
- if (isPinned) {
- clearTooltip()
- return
- }
+ if (isPinned) {
+ clearTooltip()
+ return
+ }
+
+ // Pin the tooltip if pinnable and there are multiple series — first click pins,
+ // a follow-up click on a tooltip row drills into a specific series via the
+ // consumer's own row handler. With a single series there's nothing to pin, so
+ // onPointClick fires immediately instead.
+ if (pinnable && tooltipCtx && tooltipCtx.seriesData.length > 1) {
+ // Opt-in: a click nearer one series than the others is unambiguous, so resolve it
+ // and fire onPointClick directly instead of making the user pin then pick a row.
+ if (resolveClickToNearestSeries && onPointClick && hoverPositionRef.current) {
+ const clickData = resolveNearestSeriesClickData(
+ currentIndex,
+ series,
+ labels,
+ tooltipCtx,
+ interactionAxis,
+ hoverPositionRef.current
+ )
+ if (clickData) {
+ onPointClick(wrapClickData && scales ? wrapClickData(clickData, scales) : clickData)
+ return
+ }
+ }
+ pin()
+ return
+ }
- // Pin the tooltip if pinnable and there are multiple series — first click pins,
- // a follow-up click on a tooltip row drills into a specific series via the
- // consumer's own row handler. With a single series there's nothing to pin, so
- // onPointClick fires immediately instead.
- if (pinnable && tooltipCtx && tooltipCtx.seriesData.length > 1) {
- // Opt-in: a click nearer one series than the others is unambiguous, so resolve it
- // and fire onPointClick directly instead of making the user pin then pick a row.
- if (resolveClickToNearestSeries && onPointClick && hoverPositionRef.current) {
- const clickData = resolveNearestSeriesClickData(
+ if (onPointClick) {
+ const clickData = buildPointClickData(
currentIndex,
series,
labels,
- tooltipCtx,
- interactionAxis,
+ resolveValue,
hoverPositionRef.current
)
if (clickData) {
onPointClick(wrapClickData && scales ? wrapClickData(clickData, scales) : clickData)
- return
}
}
- pin()
- return
- }
+ },
+ [
+ onPointClick,
+ series,
+ labels,
+ resolveValue,
+ pinnable,
+ resolveClickToNearestSeries,
+ interactionAxis,
+ tooltipCtx,
+ isPinned,
+ clearTooltip,
+ pin,
+ shouldSwallowClick,
+ hoverIndexRef,
+ hoverPositionRef,
+ wrapClickData,
+ scales,
+ ]
+ )
- if (onPointClick) {
- const clickData = buildPointClickData(currentIndex, series, labels, resolveValue, hoverPositionRef.current)
- if (clickData) {
- onPointClick(wrapClickData && scales ? wrapClickData(clickData, scales) : clickData)
+ const guardedMouseDown = useCallback(
+ (e: React.MouseEvent<HTMLDivElement>) => {
+ if (originatesInTooltip(e)) {
+ return
}
- }
- }, [
- onPointClick,
- series,
- labels,
- resolveValue,
- pinnable,
- resolveClickToNearestSeries,
- interactionAxis,
- tooltipCtx,
- isPinned,
- clearTooltip,
- pin,
- shouldSwallowClick,
- hoverIndexRef,
- hoverPositionRef,
- wrapClickData,
- scales,
- ])
+ onMouseDown(e)
+ },
+ [onMouseDown]
+ )
const handlers = useMemo(
- () => ({ onMouseDown, onMouseMove, onMouseLeave, onClick }),
- [onMouseDown, onMouseMove, onMouseLeave, onClick]
+ () => ({ onMouseDown: guardedMouseDown, onMouseMove, onMouseLeave, onClick }),
+ [guardedMouseDown, onMouseMove, onMouseLeave, onClick]
)
return { hoverIndex, hoverPosition, tooltipCtx, dragRect, handlers }
diff --git a/packages/quill/packages/charts/src/core/hooks/useTooltipLifecycle.test.ts b/packages/quill/packages/charts/src/core/hooks/useTooltipLifecycle.test.ts
index bcf5043b1706..0f41f865544f 100644
--- a/packages/quill/packages/charts/src/core/hooks/useTooltipLifecycle.test.ts
+++ b/packages/quill/packages/charts/src/core/hooks/useTooltipLifecycle.test.ts
@@ -161,10 +161,10 @@ describe('useTooltipLifecycle', () => {
},
],
[
- 'click outside',
+ 'pointer-down outside',
() => {
jest.runAllTimers()
- document.body.dispatchEvent(new MouseEvent('click', { bubbles: true }))
+ document.body.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }))
},
],
])('clears pinned tooltip on %s', (_name, trigger) => {
@@ -190,7 +190,7 @@ describe('useTooltipLifecycle', () => {
expect(result.current.tooltipCtx!.isPinned).toBe(true)
})
- it('does not clear pinned tooltip on click inside the wrapper', () => {
+ it('does not clear pinned tooltip on pointer-down inside the wrapper', () => {
const { result } = renderLifecycle()
pinFromHover(result)
act(() => {
@@ -198,13 +198,37 @@ describe('useTooltipLifecycle', () => {
})
act(() => {
- refs.wrapperRef.current!.dispatchEvent(new MouseEvent('click', { bubbles: true }))
+ refs.wrapperRef.current!.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }))
})
expect(result.current.tooltipCtx).not.toBeNull()
expect(result.current.tooltipCtx!.isPinned).toBe(true)
})
+ it('survives a text-selection drag that starts inside the tooltip and releases outside', () => {
+ const { result } = renderLifecycle()
+ pinFromHover(result)
+ act(() => {
+ jest.runAllTimers()
+ })
+
+ const tooltipEl = document.createElement('div')
+ tooltipEl.setAttribute('data-hog-charts-tooltip', '')
+ document.body.appendChild(tooltipEl)
+
+ // Selecting text: press starts inside the tooltip, release lands outside — the browser
+ // then fires `click` on the common ancestor (body). Neither event may dismiss the pin,
+ // or the selection is wiped mid-copy.
+ act(() => {
+ tooltipEl.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }))
+ document.body.dispatchEvent(new MouseEvent('click', { bubbles: true }))
+ })
+
+ expect(result.current.tooltipCtx).not.toBeNull()
+ expect(result.current.tooltipCtx!.isPinned).toBe(true)
+ document.body.removeChild(tooltipEl)
+ })
+
it('does not clear pinned tooltip on scroll inside the tooltip element', () => {
const { result } = renderLifecycle()
pinFromHover(result)
diff --git a/packages/quill/packages/charts/src/core/hooks/useTooltipLifecycle.ts b/packages/quill/packages/charts/src/core/hooks/useTooltipLifecycle.ts
index c55581360b77..1e6fbb0aee5d 100644
--- a/packages/quill/packages/charts/src/core/hooks/useTooltipLifecycle.ts
+++ b/packages/quill/packages/charts/src/core/hooks/useTooltipLifecycle.ts
@@ -62,8 +62,8 @@ export interface UseTooltipLifecycleResult<Meta> {
/** Geometry-independent tooltip state and dismiss lifecycle.
*
* Owns: tooltipCtx (and the boolean `isPinned`), hoverIndex/hoverPosition, the three dismiss
- * effects (scroll outside the chart, click outside, Escape), and the pinned-rebuild effect
- * with its value-equivalence bail.
+ * effects (scroll outside the chart, pointer-down outside, Escape), and the pinned-rebuild
+ * effect with its value-equivalence bail.
*
* Does NOT own: cursor → index hit-testing (cartesian or radial), or anchor positioning. Geometry
* hooks compute those and call `setHover` + `setTooltipCtx` to publish results, and pass a
@@ -154,13 +154,17 @@ export function useTooltipLifecycle<Meta = unknown>({
}
}, [tooltipShown, wrapperRef, clearTooltip])
- // Dismiss listeners for pinned tooltip (click outside, Escape).
+ // Dismiss listeners for pinned tooltip (pointer-down outside, Escape). Outside-ness is
+ // decided at pointerdown — where the press *started* — not at click: a text-selection drag
+ // that starts inside the tooltip and releases outside it fires its click on the common
+ // ancestor of the two targets (usually <body>), and dismissing on that would clear the
+ // tooltip and wipe the selection mid-copy.
useEffect(() => {
if (!isPinned) {
return
}
- const handleClickOutside = (e: MouseEvent): void => {
+ const handlePointerDownOutside = (e: PointerEvent): void => {
const target = e.target
if (target instanceof Element && target.closest('[data-hog-charts-tooltip]')) {
return
@@ -177,15 +181,15 @@ export function useTooltipLifecycle<Meta = unknown>({
}
}
- // Delay click listener so the pinning click doesn't immediately unpin.
+ // Defer attaching so the gesture that created the pin can't also dismiss it.
const timer = setTimeout(() => {
- document.addEventListener('click', handleClickOutside, { passive: true })
+ document.addEventListener('pointerdown', handlePointerDownOutside, { passive: true })
}, 0)
document.addEventListener('keydown', handleKeyDown, { passive: true })
return () => {
clearTimeout(timer)
- document.removeEventListener('click', handleClickOutside)
+ document.removeEventListener('pointerdown', handlePointerDownOutside)
document.removeEventListener('keydown', handleKeyDown)
}
}, [isPinned, wrapperRef, clearTooltip])
diff --git a/packages/quill/packages/charts/src/overlays/DefaultTooltip.test.tsx b/packages/quill/packages/charts/src/overlays/DefaultTooltip.test.tsx
index cd84d5bdd393..9caa52d94b9f 100644
--- a/packages/quill/packages/charts/src/overlays/DefaultTooltip.test.tsx
+++ b/packages/quill/packages/charts/src/overlays/DefaultTooltip.test.tsx
@@ -235,6 +235,17 @@ describe('DefaultTooltip', () => {
expect(onRowClick.mock.calls[0][0].series.key).toBe('b')
})
+ it('onRowClick does not fire when the click completes a text selection', () => {
+ const onRowClick = jest.fn()
+ renderTooltip({ onRowClick }, TWO_SERIES)
+ const spy = jest
+ .spyOn(window, 'getSelection')
+ .mockReturnValue({ toString: () => 'copied text' } as Selection)
+ fireEvent.click(document.querySelectorAll<HTMLElement>('[data-attr="hog-chart-tooltip-row"]')[1])
+ expect(onRowClick).not.toHaveBeenCalled()
+ spy.mockRestore()
+ })
+
it('sorts rows by yPixel ascending (visual top-to-bottom) when not sortedByValue', () => {
const withYPixel: TooltipContext['seriesData'] = [
{ series: { key: 'low', label: 'Low', data: [] }, value: 5, color: '#000', yPixel: 300 },
diff --git a/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsx b/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsx
index a9248ab103ce..503ed808117d 100644
--- a/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsx
+++ b/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsx
@@ -72,8 +72,7 @@ export function DefaultTooltip<Meta = unknown>({
? [...visible].sort((a, b) => (a.yPixel ?? Infinity) - (b.yPixel ?? Infinity))
: visible
const summable = rows.filter((s) => !s.series.overlay && s.series.visibility?.total !== false)
- const closestKey =
- hoverPosition != null && rows.length > 1 ? findClosestSeriesKey(rows, hoverPosition.y) : null
+ const closestKey = hoverPosition != null && rows.length > 1 ? findClosestSeriesKey(rows, hoverPosition.y) : null
const renderTotal = showTotal && summable.length > 1
const total = summable.reduce((acc, s) => acc + s.value, 0)
const formatTotal = totalFormatter ?? ((value: number): React.ReactNode => format(value, summable[0]))
@@ -161,7 +160,18 @@ export function DefaultTooltip<Meta = unknown>({
data-attr="hog-chart-tooltip-row"
data-closest={isClosest ? 'true' : undefined}
className={`flex items-center gap-2 min-w-0 py-0.5 px-1.5 rounded transition-colors duration-150${isClosest ? ' font-semibold bg-current/[.1]' : ''}${clickable}`}
- onClick={onRowClick ? () => onRowClick(s) : undefined}
+ onClick={
+ onRowClick
+ ? () => {
+ // A click that completes a text selection is a copy
+ // gesture, not a drill-down.
+ if (window.getSelection()?.toString()) {
+ return
+ }
+ onRowClick(s)
+ }
+ : undefined
+ }
>
<TooltipSwatch color={s.color} />
{/* Grid-stack the label so an invisible semibold ghost always reserves