From b7af7bb7430bcedf4c61c71dfd7be1361c070ccf Mon Sep 17 00:00:00 2001 From: Farhan Date: Thu, 3 Dec 2026 19:42:47 +0000 Subject: [PATCH 01/14] Add Plotly-style unified hover (hover_mode="x unified" / "y unified") MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Hover no longer requires landing on a point. With hover_mode="x unified" the cursor snaps to the nearest x anywhere over the plot, a spike line marks that x, and one tooltip lists every series' value there under the x value, each row with a color chip (new tooltip_swatch slot). "y unified" is the transpose; "closest" stays the default. - Two-pass snap mirroring Plotly: the nearest position wins, then every series reports its point there, kept only within 20 px (hoverdistance) so series that end early are not reported at the wrong x. - Sorted columns snap by binary search (O(log n) per pointermove); unsorted, category-filtered, and mid-transition columns scan. - Line/scatter/area/bar series take part; other marks and polar charts fall back to closest-point hover. - Live kernels get one exact pick per row on consecutive seqs; all but the winner are `silent`, so Python on_hover still fires once. - The spike reuses the crosshair line and its slot/token styling. Spec: interaction.md §7.1, wire-protocol (pick `silent`), view-state §7.1 payload, dossier §17, styling slot tables. --- docs/components/tooltips.md | 51 ++ docs/core-concepts/interactions.md | 6 + docs/styling/capabilities.md | 3 +- docs/styling/chrome-slots.md | 1 + js/src/20_theme.ts | 1 + js/src/50_chartview.ts | 17 +- js/src/52_tooltip.ts | 441 +++++++++++++++++- js/src/53_interaction.ts | 6 +- js/src/54_kernel.ts | 14 +- news/+unified-hover.feature.md | 1 + python/xy/_figure.py | 20 + python/xy/channel.py | 5 +- python/xy/components.py | 18 + python/xy/dom.py | 1 + spec/api/capability-matrix.md | 3 +- spec/api/interaction.md | 61 ++- spec/api/styling.md | 1 + spec/design-dossier.md | 3 + spec/design/reflex-shaped-api.md | 1 + spec/design/view-state.md | 3 + spec/design/wire-protocol.md | 5 +- .../css-tailwind-surface-audit-2026-07-30.md | 2 +- tests/test_static_client_security.py | 1 + tests/test_type_surface.py | 1 + tests/test_unified_hover.py | 357 ++++++++++++++ 25 files changed, 998 insertions(+), 25 deletions(-) create mode 100644 news/+unified-hover.feature.md create mode 100644 tests/test_unified_hover.py diff --git a/docs/components/tooltips.md b/docs/components/tooltips.md index 74803b17b..80b746154 100644 --- a/docs/components/tooltips.md +++ b/docs/components/tooltips.md @@ -140,6 +140,51 @@ def tooltip_title_demo(): return reflex_xy.chart(tooltip_title_chart, height="320px") ~~~ +## Show Every Series at One X + +By default the tooltip reports the mark under the cursor, so comparing series +means hovering each point in turn. Set `hover_mode="x unified"` (Plotly's +`hovermode` spelling) and the cursor only has to be somewhere over the plot: +it snaps to the nearest x, a vertical spike line marks it, and one tooltip +lists every series' value there under the x value as its heading. + +~~~python demo exec +import reflex_xy +import xy + +unified_days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] + +unified_hover_chart = xy.line_chart( + xy.line(unified_days, [5, 5, 5, 11, 0, 0, 0], name="Booked"), + xy.line(unified_days, [0, 2, 5, 5, 0, 0, 0], name="Held"), + xy.line(unified_days, [0, 1, 4, 3, 0, 0, 0], name="Qualified held"), + xy.legend(), + title="Weekly momentum", + hover_mode="x unified", +) + + +def unified_hover_demo(): + return reflex_xy.chart(unified_hover_chart, height="320px") +~~~ + +- `"x unified"` snaps along x; `"y unified"` snaps along y and draws a + horizontal spike. `"closest"` is the default. +- Line, scatter, area, and bar/column series take part. A series whose nearest + point is more than 20 px from the snapped x is left out rather than reported + at the wrong x. Charts with no such series, and polar charts, keep + closest-point hover. +- Each row shows a color chip (`tooltip_swatch` slot), the series name + (`tooltip_label`), and its value (`tooltip_value`). `tooltip(format=...)` + and `labels=` keyed by `"x"`/`"y"` apply; `title=` and `fields=` templates + describe one hovered row and are not used by the unified readout. +- The spike line is the crosshair line, so the `crosshair_x`/`crosshair_y` + slots and the `--chart-crosshair` token style it. +- The `xy:hover` event lists every reported series in `points`. Python + `on_hover` still fires once per hover, with the row nearest the cursor. + +The same setting is available as `xy.interaction_config(hover_mode=...)`. + ## Exact and Resident Readout Standalone HTML composes tooltips from the values resident in its payload. @@ -214,6 +259,12 @@ heatmap value) can be used as tooltip fields. Use braced field names in `title=`, e.g. `xy.tooltip(title="Month {month}")` — each placeholder is replaced with the value from the hovered row. +### How do I show all series values at the hovered x, like Plotly's unified hover? + +Pass `hover_mode="x unified"` to the chart, e.g. +`xy.line_chart(..., hover_mode="x unified")`. The cursor snaps to the nearest x +anywhere over the plot and one tooltip lists every series at that x. + ### How do I disable tooltips on a chart? Add `xy.tooltip(show=False)` to the chart. When several tooltip components are diff --git a/docs/core-concepts/interactions.md b/docs/core-concepts/interactions.md index 97dd07126..d411bfa82 100644 --- a/docs/core-concepts/interactions.md +++ b/docs/core-concepts/interactions.md @@ -39,6 +39,12 @@ def browser_behavior_demo(): return reflex_xy.chart(chart, height="360px") ~~~ +`hover_mode` chooses what hover reports. The default, `"closest"`, reads the +mark under the cursor. `"x unified"` snaps to the nearest x anywhere over the +plot and lists every series' value there in one tooltip, with a spike line at +that x; `"y unified"` does the same along y. See +[Show Every Series at One X](/docs/xy/components/tooltips/#show-every-series-at-one-x). + Standalone HTML keeps these local browser behaviors. It cannot invoke Python because no kernel or server is attached. diff --git a/docs/styling/capabilities.md b/docs/styling/capabilities.md index 2c66d0531..0740a45a4 100644 --- a/docs/styling/capabilities.md +++ b/docs/styling/capabilities.md @@ -12,7 +12,7 @@ and *does the change survive where I need it*. This page answers both from the registry the implementation is checked against. - **11** mark style properties across **22** mark kinds, drawn by all three renderers. -- **48** stable chrome slots for CSS and Tailwind in the browser. +- **49** stable chrome slots for CSS and Tailwind in the browser. - **1** way to add a mark kind XY does not ship, without forking it. ## Mark style properties @@ -79,6 +79,7 @@ token bag or in mark and axis `style=`, which every renderer reads. | `tooltip_row` | full | none | none | | `tooltip_label` | full | none | none | | `tooltip_value` | full | none | none | +| `tooltip_swatch` | full | none | none | | `modebar` | full | none | none | | `modebar_drag_handle` | full | none | none | | `modebar_control_group` | full | none | none | diff --git a/docs/styling/chrome-slots.md b/docs/styling/chrome-slots.md index 526d659ee..75dcfd9be 100644 --- a/docs/styling/chrome-slots.md +++ b/docs/styling/chrome-slots.md @@ -38,6 +38,7 @@ primitive or structural descendant is a separate DOM element. | `tooltip_row` | One tooltip field row | | `tooltip_label` | One tooltip field label | | `tooltip_value` | One formatted tooltip value | +| `tooltip_swatch` | Series color chip on a unified-hover row (`--xy-tooltip-swatch-paint`) | | `modebar` | Mode/tool bar container | | `modebar_drag_handle` | Draggable grip revealed beside the toolbar | | `modebar_control_group` | Selection, pan, and export control group | diff --git a/js/src/20_theme.ts b/js/src/20_theme.ts index 4803d1273..59b3dc637 100644 --- a/js/src/20_theme.ts +++ b/js/src/20_theme.ts @@ -125,6 +125,7 @@ export const XY_CHROME_CSS = ` :where(.xy [data-xy-slot="tooltip"]){max-width:calc(100% - 8px);max-height:calc(100% - 8px);box-sizing:border-box;white-space:normal;overflow-wrap:anywhere;overflow:auto;background:var(--chart-tooltip-bg,rgba(20,24,33,.92));color:var(--chart-tooltip-text,#fff);padding:5px 8px;border-radius:4px;font-size:11px;line-height:1.35;box-shadow:0 2px 8px rgba(0,0,0,.3)} :where(.xy [data-xy-slot="tooltip"][data-xy-custom-tooltip]){background:transparent;border:none;padding:0;box-shadow:none} :where(.xy [data-xy-slot="tooltip_label"])::after{content:": "} +:where(.xy [data-xy-slot="tooltip_swatch"]){display:inline-block;width:8px;height:8px;border-radius:50%;margin-right:6px;vertical-align:0;background:var(--xy-tooltip-swatch-paint,currentColor)} :where(.xy [data-xy-slot="legend"]){left:var(--xy-legend-left,auto);right:var(--xy-legend-right,auto);top:var(--xy-legend-top,auto);bottom:var(--xy-legend-bottom,auto);transform:var(--xy-legend-transform,none);max-width:var(--xy-legend-max-width);max-height:var(--xy-legend-max-height);gap:2px;font-size:11px;background:var(--chart-legend-bg,rgba(128,128,128,.08));border-radius:4px;padding:4px 8px;color:var(--chart-text,inherit)} :where(.xy [data-xy-slot="legend_title"]){font-weight:400;text-align:center} :where(.xy [data-xy-slot="legend_swatch"]){display:inline-block;width:var(--xy-legend-swatch-width,12px);height:var(--xy-legend-swatch-height,10px);vertical-align:-1px;background:var(--xy-legend-swatch-paint,transparent);border-radius:2px;margin-right:var(--xy-legend-swatch-margin-right,5px);fill:var(--xy-legend-swatch-fill);stroke:var(--xy-legend-swatch-stroke);stroke-width:var(--xy-legend-swatch-stroke-width);stroke-dasharray:var(--xy-legend-swatch-dasharray)} diff --git a/js/src/50_chartview.ts b/js/src/50_chartview.ts index eea02106e..633b04aed 100644 --- a/js/src/50_chartview.ts +++ b/js/src/50_chartview.ts @@ -7280,7 +7280,12 @@ export class ChartView { } _drawHoverState() { - const hit = this._hoverTarget; + // A unified readout marks every reported point, not only the winner. + const hits = this._unified ? this._unified.hits : [this._hoverTarget]; + for (const hit of hits) this._drawHoverTarget(hit); + } + + _drawHoverTarget(hit) { if (!hit || !hit.g) return; const g = hit.g; if (g.trace.kind !== "scatter" || g.tier === "density" || g._legendHidden) return; @@ -9659,6 +9664,16 @@ export class ChartView { const rect = this.canvas.getBoundingClientRect(); const cssX = e.clientX - rect.left; const cssY = e.clientY - rect.top; + const mode = this._hoverMode(); + if (mode !== "closest" && this._unifiedHover(e, cssX, cssY, mode)) return; + // Nothing answered a unified readout here (or the mode is closest): drop + // any unified state so the closest-point path below starts clean rather + // than treating the old winner as "still hovered". + if (this._unified) { + this._hideTooltip(); + this._hoverId = -1; + this._hoverTarget = null; + } const hit = this._pickAt(cssX, cssY) || this._hoverAt(cssX, cssY); if (!hit) { const hadHover = this._hoverId !== -1; diff --git a/js/src/52_tooltip.ts b/js/src/52_tooltip.ts index 73e26d097..b0b9f2a29 100644 --- a/js/src/52_tooltip.ts +++ b/js/src/52_tooltip.ts @@ -1,6 +1,11 @@ import { fmtCategory, fmtNumberSpec, fmtValue } from "./30_ticks"; import { ChartView } from "./50_chartview"; +// Plotly's default `hoverdistance`: how far (CSS px, along the hover +// dimension) a series' point may sit from the snapped position and still be +// reported in a unified readout. +const UNIFIED_HOVER_DISTANCE_PX = 20; + // ChartView tooltip resolution: map a hovered vertex back to its source // row, denormalize units, and compose the tooltip lines/DOM. Split out of // 50_chartview.js; augments the prototype so `this.*` is unchanged. @@ -479,7 +484,7 @@ Object.assign(ChartView.prototype, { _tooltipLines(items) { return items.map((item) => ( - item.kind === "field" ? `${item.label}: ${item.value}` : item.value + item.kind === "field" || item.kind === "series" ? `${item.label}: ${item.value}` : item.value )); }, @@ -492,7 +497,16 @@ Object.assign(ChartView.prototype, { row.textContent = item.value; } else { this._applySlot(row, "tooltip_row"); - if (item.kind === "field") { + if (item.kind === "series") { + // Unified hover rows identify their series by its paint, like the + // legend does. The color rides a custom property so `tooltip_swatch` + // styles can restyle (or replace) the chip without losing it. + const swatch = document.createElement("span"); + this._applySlot(swatch, "tooltip_swatch"); + if (item.color) swatch.style.setProperty("--xy-tooltip-swatch-paint", item.color); + row.appendChild(swatch); + } + if (item.kind === "field" || item.kind === "series") { const label = document.createElement("span"); this._applySlot(label, "tooltip_label"); label.textContent = item.label; @@ -545,6 +559,10 @@ Object.assign(ChartView.prototype, { _hideTooltip() { this.tooltip.style.display = "none"; this._tooltipAnchor = null; + if (this._unified) { + this._unified = null; + this._hideUnifiedSpike(); + } }, // A hidden retained anchor is off-screen and may return after another draw. @@ -553,19 +571,25 @@ Object.assign(ChartView.prototype, { const pos = this._tooltipAnchorPx(); if (!pos) { this.tooltip.style.display = "none"; + if (this._unified) this._hideUnifiedSpike(); return; } this.tooltip.style.display = "block"; - this._placeTooltip(pos.lx, pos.ly); + this._placeTooltip(pos.lx, pos.ly, !!this._unified); + if (this._unified) this._positionUnifiedSpike(pos); }, - _placeTooltip(lx, ly) { + _placeTooltip(lx, ly, flipX = false) { const tw = this.tooltip.offsetWidth; const th = this.tooltip.offsetHeight; const edge = 4; const gap = 12; const maxLeft = Math.max(edge, this.size.w - tw - edge); - const left = Math.max(edge, Math.min(lx + gap, maxLeft)); + // A unified readout sits beside its hover line; clamping it back over the + // line would cover the very points it describes, so it flips sides. + const left = flipX && lx + gap + tw > this.size.w - edge + ? Math.max(edge, lx - gap - tw) + : Math.max(edge, Math.min(lx + gap, maxLeft)); const below = ly + gap; const above = ly - th - gap; const top = below + th <= this.size.h - edge ? below : Math.max(edge, above); @@ -609,4 +633,411 @@ Object.assign(ChartView.prototype, { this._placeTooltip(clientX - rect.left, clientY - rect.top); } }, + // -- unified hover (interaction spec §7.1: Plotly `hovermode`) ------------- + // + // `hover_mode="x unified"` answers "what does every series read at this x?" + // instead of "which mark is under the cursor?". The cursor only needs to be + // somewhere over the plot: it snaps to the nearest data position along the + // hover dimension, every eligible series contributes its point at that + // position, and one readout lists them under a shared heading, with a spike + // line marking the snapped position. "y unified" is the transpose. + + _hoverMode() { + const mode = this.interaction?.hover_mode; + if (mode !== "x unified" && mode !== "y unified") return "closest"; + // Polar has no single "x" to align on; it keeps closest-point hover. + if (this.spec?.coords === "polar") return "closest"; + return mode; + }, + + // Series that answer a unified readout: plain (x, y) marks with a retained + // CPU column — line, scatter, area, bar/column. Area-shaped geometry with no + // single value per position (rect marks, ribbons, funnels, heatmaps, + // segments), density tiers, legend-hidden series, and error bands (a band is + // its series' uncertainty, not a series) stay out; when nothing answers, the + // caller falls back to closest-point hover so those charts keep a readout. + _unifiedHoverable(g) { + if (!g || !g.trace || g.tier === "density" || g._legendHidden) return false; + if (g._cpuRibbon || g._cpuFunnel || g._cpuHeatmap || g._cpuRect || g._segmentCpu) return false; + if (g.heatmap || g.trace.kind === "error_band") return false; + const cpu = g._cpu; + return !!(cpu && cpu.x && cpu.y && cpu.x.length && cpu.y.length); + }, + + _unifiedCount(g) { + const cpu = g._cpu; + return Math.min(cpu.x.length, cpu.y.length, g.n || cpu.x.length); + }, + + // Decoded data value of row `i` on one channel, following an in-flight + // position transition exactly like the drawn geometry does. + _unifiedValue(g, dim, i) { + const cpu = g._cpu; + const values = cpu[dim]; + const meta = dim === "x" ? (cpu.xMeta || g.xMeta) : (cpu.yMeta || g.yMeta); + const prev = dim === "x" ? g._transitionPrevXValues : g._transitionPrevYValues; + const progress = g._transitionPositionProgress; + const encoded = prev && Number.isFinite(progress) + ? prev[i] + (values[i] - prev[i]) * progress + : values[i]; + return encoded / (meta.scale || 1) + meta.offset; + }, + + // Whether a channel is non-decreasing, cached per column identity and + // length so an append (new arrays or a longer view) re-checks. Sorted + // columns — every line and time series — snap with a binary search, so a + // multi-million-row series costs O(log n) per pointermove instead of O(n). + _unifiedSorted(g, dim, n) { + const values = g._cpu[dim]; + const cache = g._unifiedSortCache || (g._unifiedSortCache = {}); + const hit = cache[dim]; + if (hit && hit.values === values && hit.n === n) return hit.sorted; + let sorted = true; + let prev = -Infinity; + for (let i = 0; i < n; i++) { + const v = values[i]; + if (!(v >= prev)) { sorted = false; break; } + prev = v; + } + cache[dim] = { values, n, sorted }; + return sorted; + }, + + // Row whose `dim` coordinate is nearest `value`, measured in axis-coordinate + // space so log and other monotone scales snap by what the eye sees. + _unifiedNearestIndex(g, dim, value) { + const axis = this._axis(dim === "x" ? g.xAxis : g.yAxis); + const target = this._axisCoord(axis, value); + const n = this._unifiedCount(g); + if (!n || !Number.isFinite(target)) return -1; + const coordAt = (i) => this._axisCoord(axis, this._unifiedValue(g, dim, i)); + const transitioning = Number.isFinite(g._transitionPositionProgress) + && !!(g._transitionPrevXValues || g._transitionPrevYValues); + if (!transitioning && !g._visMap && this._unifiedSorted(g, dim, n)) { + const meta = dim === "x" ? (g._cpu.xMeta || g.xMeta) : (g._cpu.yMeta || g.yMeta); + const encoded = (value - meta.offset) * (meta.scale || 1); + const values = g._cpu[dim]; + let lo = 0; + let hi = n; + while (lo < hi) { + const mid = (lo + hi) >>> 1; + if (values[mid] < encoded) lo = mid + 1; + else hi = mid; + } + let best = -1; + let bestDist = Infinity; + for (const i of [lo - 1, lo]) { + if (i < 0 || i >= n) continue; + const d = Math.abs(coordAt(i) - target); + if (d < bestDist) { bestDist = d; best = i; } + } + return best; + } + // Unsorted or category-filtered rows: a linear scan over what is drawn + // (a filtered category's rows must not answer, interaction spec §10). + let best = -1; + let bestDist = Infinity; + const rows = g._visMap || null; + const count = rows ? rows.length : n; + for (let k = 0; k < count; k++) { + const i = rows ? rows[k] : k; + if (i >= n) continue; + const d = Math.abs(coordAt(i) - target); + if (d < bestDist) { bestDist = d; best = i; } + } + return best; + }, + + // Canvas-relative pixel position of row `i`, or null when it cannot draw. + _unifiedPx(g, i) { + const x = this._unifiedValue(g, "x", i); + const y = this._unifiedValue(g, "y", i); + const [cx, cy] = this._projectDataPoint(g.xAxis || "x", g.yAxis || "y", x, y); + if (!Number.isFinite(cx) || !Number.isFinite(cy)) return null; + return [cx - this.plot.x, cy - this.plot.y]; + }, + + // Two passes, mirroring Plotly: the series position nearest the cursor + // along `dim` wins and fixes the hover position; then every series reports + // its own point nearest that position, kept only within the hover distance + // (so a series that ends early or samples elsewhere does not report a + // far-away point as if it were "at" this x). + _unifiedHits(cssX, cssY, dim) { + const axisOf = (g) => (dim === "x" ? g.xAxis || "x" : g.yAxis || "y"); + const cursorValue = (g, px) => { + const [dx, dy] = this._dataFromCanvas( + dim === "x" ? px : cssX, dim === "y" ? px : cssY, g.xAxis || "x", g.yAxis || "y", + ); + return dim === "x" ? dx : dy; + }; + const along = (p) => (dim === "x" ? p[0] : p[1]); + const cursor = dim === "x" ? cssX : cssY; + const traces = (this.gpuTraces || []).filter((g) => this._unifiedHoverable(g)); + let win = null; + for (const g of traces) { + const value = cursorValue(g, cursor); + if (!Number.isFinite(value)) continue; + const index = this._unifiedNearestIndex(g, dim, value); + if (index < 0) continue; + const p = this._unifiedPx(g, index); + if (!p) continue; + const dist = Math.abs(along(p) - cursor); + if (!win || dist < win.dist) win = { g, index, p, dist }; + } + if (!win) return null; + const position = along(win.p); + const extent = dim === "x" ? this.plot.w : this.plot.h; + if (position < -0.5 || position > extent + 0.5) return null; + const hits = []; + for (const g of traces) { + let index = win.index; + if (g !== win.g) { + const value = cursorValue(g, position); + if (!Number.isFinite(value)) continue; + index = this._unifiedNearestIndex(g, dim, value); + if (index < 0) continue; + } + const p = g === win.g ? win.p : this._unifiedPx(g, index); + if (!p || Math.abs(along(p) - position) > UNIFIED_HOVER_DISTANCE_PX) continue; + // `index` is a shipped row (what _localRow and the kernel pick speak); + // the hover marker addresses the drawn buffer, which a category filter + // compacts. + const drawIndex = g._visMap ? g._visMap.indexOf(index) : index; + hits.push({ trace: g.trace.id, index, drawIndex, g, synthetic: true, axis: axisOf(g) }); + } + const winner = hits.find((h) => h.g === win.g) || null; + return winner ? { dim, position, hits, winner } : null; + }, + + // Returns true when the unified readout handled this pointer position; false + // lets the caller run closest-point hover (nothing answered here). + _unifiedHover(e, cssX, cssY, mode) { + const dim = mode === "y unified" ? "y" : "x"; + const found = this._unifiedHits(cssX, cssY, dim); + if (!found) return false; + const { hits, winner } = found; + const key = hits.map((h) => `${h.trace}:${h.index}`).join(","); + this._lastHoverXY = { clientX: e.clientX, clientY: e.clientY }; + const g = winner.g; + const xAxis = g.xAxis || "x"; + const yAxis = g.yAxis || "y"; + // The readout rides the snapped position along `dim` and follows the + // cursor across it, so it stays beside the hand without covering points. + const [cursorX, cursorY] = this._dataFromCanvas(cssX, cssY, xAxis, yAxis); + const snapped = this._unifiedValue(g, dim, winner.index); + if (this._unified && this._unified.key === key) { + if (this._tooltipAnchor) { + if (dim === "x") this._tooltipAnchor.y = cursorY; + else this._tooltipAnchor.x = cursorX; + this._repositionTooltip(); + } + return true; + } + if (this._unified || this._hoverId !== -1) this._hideTooltip(); + const rows = hits.map((h) => this._localRow(h)); + const winnerAt = hits.indexOf(winner); + this._unified = { dim, key, hits, rows, winnerAt, pending: 0, pickBase: -1 }; + this._hoverId = winner.trace * 1e9 + winner.index; + this._hoverTarget = winner; + this._lastRow = rows[winnerAt]; + this._tooltipAnchor = dim === "x" + ? { xAxis, yAxis, x: snapped, y: cursorY } + : { xAxis, yAxis, x: cursorX, y: snapped }; + if (![this._tooltipAnchor.x, this._tooltipAnchor.y].every(Number.isFinite)) { + this._tooltipAnchor = null; + } + this._renderUnifiedTooltip(); + if (this._interactionFlag("hover")) { + this._dispatchChartEvent("hover", { + row: rows[winnerAt], + trace: winner.trace, + index: winner.index, + view: this._eventView("hover"), + ...this._unifiedHoverPayload(e.clientX, e.clientY, false), + }); + } + if (this.comm) { + // One exact pick per row (§16), on consecutive sequence numbers so each + // reply finds its row. Only the winner's pick reaches `on_hover`; the + // others are `silent`, so a Python callback still fires once per hover. + const base = (this._pickSeq || 0) + 1; + this._pickSeq = base + hits.length - 1; + this._unified.pickBase = base; + this._unified.pending = hits.length; + hits.forEach((hit, k) => { + const req: any = { type: "pick", seq: base + k, trace: hit.trace, index: hit.index }; + if (k !== winnerAt) req.silent = true; + const hg = hit.g; + if (hg && hg.tier === "density" && hg.drill && hg.drill.seq !== undefined) { + req.drill_seq = hg.drill.seq; + } + this.comm.send(req); + }); + } + this._drawKeepPick(); + return true; + }, + + _unifiedItems(state) { + const tooltip = this.spec.tooltip || {}; + const formats = tooltip.format || {}; + const labels = tooltip.labels || {}; + const dim = state.dim; + const other = dim === "x" ? "y" : "x"; + const text = (row, channel) => { + const value = row[channel]; + if (value === undefined || value === null) return null; + if (typeof value === "string") return value; + return this._formatTooltipValue(value, row[`${channel}_kind`], formats[channel]); + }; + const items = []; + const heading = text(state.rows[state.winnerAt], dim); + if (heading) items.push({ kind: "title", value: heading }); + const fallbackLabel = typeof labels[other] === "string" ? labels[other] : other; + const seen = new Set(); + state.rows.forEach((row, k) => { + const value = text(row, other); + if (value === null) return; + const label = this._tooltipSeriesName(row) ?? fallbackLabel; + const color = this._seriesColorCss(state.hits[k].g); + // A composed series can emit more than one mark for the same data + // (a line plus its point markers); one row per visible series. + const id = `${label}\u0000${value}\u0000${color}`; + if (seen.has(id)) return; + seen.add(id); + items.push({ kind: "series", label, value, color }); + }); + return items; + }, + + _renderUnifiedTooltip(options: any = {}) { + const state = this._unified; + if (!state || this.spec.show_tooltip === false) { + this.tooltip.style.display = "none"; + return; + } + const items = this._unifiedItems(state); + if (!this._customTooltip) this._renderBuiltinTooltip(items); + if (this.a11yLive && options.announce !== false) { + const announcement = this._tooltipLines(items).join(", "); + if (this.a11yLive.textContent !== announcement) this.a11yLive.textContent = announcement; + } + this.tooltip.style.display = "block"; + const pos = this._tooltipAnchorPx(); + if (pos) { + this._placeTooltip(pos.lx, pos.ly, true); + this._positionUnifiedSpike(pos); + } else { + this.tooltip.style.display = "none"; + this._hideUnifiedSpike(); + } + }, + + // The spike reuses the crosshair line for the hover dimension, so the + // existing `crosshair_x` / `crosshair_y` slots and `--chart-crosshair` token + // style it. With `crosshair=True` the other line keeps following the cursor. + _positionUnifiedSpike(pos) { + const state = this._unified; + if (!state) return; + const line = state.dim === "x" ? this.crosshairX : this.crosshairY; + if (!line) return; + line.style.display = "block"; + if (state.dim === "x") { + line.style.left = pos.lx + "px"; + line.style.top = this.plot.y + "px"; + line.style.height = this.plot.h + "px"; + } else { + line.style.left = this.plot.x + "px"; + line.style.top = pos.ly + "px"; + line.style.width = this.plot.w + "px"; + } + }, + + _hideUnifiedSpike() { + if (this._interactionFlag("crosshair")) return; // the cursor owns the lines + if (this.crosshairX) this.crosshairX.style.display = "none"; + if (this.crosshairY) this.crosshairY.style.display = "none"; + }, + + _unifiedHoverPayload(clientX, clientY, exact) { + const state = this._unified; + const payload = this._hoverPayload( + state.rows[state.winnerAt], state.hits[state.winnerAt], clientX, clientY, exact, + ); + payload.points = state.rows.map((row, k) => { + const g = state.hits[k].g; + return { + trace: (g && g.trace && g.trace.name) || row.trace, + index: row.index, + row, + x_axis: (g && g.xAxis) || "x", + y_axis: (g && g.yAxis) || "y", + color: this._seriesColorCss(g), + }; + }); + payload.hover_mode = `${state.dim} unified`; + return payload; + }, + + // Whether a `pick_result` sequence belongs to the live unified readout. + _unifiedOwnsPick(seq) { + const state = this._unified; + return !!state && state.pickBase > 0 && Number.isInteger(seq) + && seq >= state.pickBase && seq < state.pickBase + state.hits.length; + }, + + // Exact f64 replacement for one row of the unified readout (§16). A null + // row (a drill swap raced the pick) keeps the instant local value rather + // than collapsing the whole readout. + _applyUnifiedPick(msg) { + const state = this._unified; + const k = msg.seq - state.pickBase; + state.pending = Math.max(0, state.pending - 1); + const local = state.rows[k]; + const exact = msg.row && this._normalizePickRow(msg.row); + if (exact && local && exact.trace === local.trace && exact.index === local.index) { + for (const [key, value] of Object.entries(local)) { + if (exact[key] === undefined) exact[key] = value; + } + this._applySharedTooltipFields(exact); + state.rows[k] = exact; + if (k === state.winnerAt) { + this._lastRow = exact; + const snapped = exact[state.dim]; + if (this._tooltipAnchor && typeof snapped === "number" && Number.isFinite(snapped)) { + this._tooltipAnchor[state.dim] = snapped; + } + } + this._renderUnifiedTooltip({ announce: false }); + } + if (state.pending === 0 && this._interactionFlag("hover") && this._lastHoverXY) { + const xy = this._lastHoverXY; + const winner = state.hits[state.winnerAt]; + this._dispatchChartEvent("hover", { + row: state.rows[state.winnerAt], + trace: winner.trace, + index: winner.index, + exact: true, + view: this._eventView("hover"), + ...this._unifiedHoverPayload(xy.clientX, xy.clientY, true), + }); + } + }, + + // Kernel rows carry raw axis coordinates; a category axis's code becomes its + // label exactly as _localRow did for the instant readout. Returns null for a + // trace the client no longer holds (dropped by a data update in flight). + _normalizePickRow(row) { + const rowG = this.gpuTraces.find((t) => t.trace.id === row.trace); + if (!rowG) return null; + for (const channel of ["x", "y"]) { + if (typeof row[channel] !== "number") continue; + const [value, kind] = this._sourceDisplayValue( + rowG, channel, row[channel], row[`${channel}_kind`], + ); + row[channel] = value; + if (kind === undefined) delete row[`${channel}_kind`]; + } + return row; + }, }); diff --git a/js/src/53_interaction.ts b/js/src/53_interaction.ts index 01c450fa6..a2ee64193 100644 --- a/js/src/53_interaction.ts +++ b/js/src/53_interaction.ts @@ -145,7 +145,9 @@ Object.assign(ChartView.prototype, { }); this._listen(this.selLasso, "pointercancel", cancelLassoHandleDrag); - if (this._interactionFlag("crosshair")) { + // Unified hover (`hover_mode`) draws its spike line with the crosshair's + // line, so it needs the elements even when the cursor crosshair is off. + if (this._interactionFlag("crosshair") || this._hoverMode() !== "closest") { this.crosshairX = document.createElement("div"); this.crosshairX.style.cssText = "position:absolute;display:none;pointer-events:none;z-index:3;width:1px;"; @@ -616,7 +618,7 @@ Object.assign(ChartView.prototype, { }, _updateCrosshair(e) { - if (!this.crosshairX || !this.crosshairY) return; + if (!this.crosshairX || !this.crosshairY || !this._interactionFlag("crosshair")) return; const rect = this.canvas.getBoundingClientRect(); const rootRect = this.root.getBoundingClientRect(); const x = e.clientX - rect.left; diff --git a/js/src/54_kernel.ts b/js/src/54_kernel.ts index 0541c9350..9f7a95dc5 100644 --- a/js/src/54_kernel.ts +++ b/js/src/54_kernel.ts @@ -861,6 +861,9 @@ Object.assign(ChartView.prototype, { } else if (msg.type === "append") { this._applyAppend(msg, buffers); } else if (msg.type === "pick_result") { + // A unified readout issues one pick per row on consecutive sequence + // numbers (52_tooltip.ts); each reply refines its own row. + if (this._unifiedOwnsPick(msg.seq)) { this._applyUnifiedPick(msg); return; } if (msg.seq !== undefined && msg.seq !== this._pickSeq) return; if (!msg.row) { this._hideTooltip(); return; } // The kernel returns exact values for the picked trace only. Rehydrate @@ -877,16 +880,7 @@ Object.assign(ChartView.prototype, { // A reply for a trace no longer in gpuTraces (dropped by a data update // while the pick was in flight) has no mapping source and describes a // mark that no longer exists — a miss. - const rowG = this.gpuTraces.find((t) => t.trace.id === msg.row.trace); - if (!rowG) { this._hideTooltip(); return; } - for (const channel of ["x", "y"]) { - if (typeof msg.row[channel] !== "number") continue; - const [value, kind] = this._sourceDisplayValue( - rowG, channel, msg.row[channel], msg.row[`${channel}_kind`], - ); - msg.row[channel] = value; - if (kind === undefined) delete msg.row[`${channel}_kind`]; - } + if (!this._normalizePickRow(msg.row)) { this._hideTooltip(); return; } const local = this._lastRow; if (local && local.trace === msg.row.trace && local.index === msg.row.index) { for (const [key, value] of Object.entries(local)) { diff --git a/news/+unified-hover.feature.md b/news/+unified-hover.feature.md new file mode 100644 index 000000000..4b4d4b194 --- /dev/null +++ b/news/+unified-hover.feature.md @@ -0,0 +1 @@ +Add `hover_mode="x unified"` and `"y unified"` (Plotly's `hovermode`) to charts and `xy.interaction_config`. The cursor no longer has to sit on a point: it snaps to the nearest x anywhere over the plot, a spike line marks that x, and one tooltip lists every series' value there with a color chip (new `tooltip_swatch` slot). Sorted series snap with a binary search, and live kernels refine every row to exact f64 values while `on_hover` still fires once per hover. diff --git a/python/xy/_figure.py b/python/xy/_figure.py index 3f94bb5e6..4bb6144d6 100644 --- a/python/xy/_figure.py +++ b/python/xy/_figure.py @@ -490,6 +490,7 @@ def set_interaction( select: Optional[bool] = None, brush: Optional[bool] = None, crosshair: Optional[bool] = None, + hover_mode: Optional[str] = None, navigation: Optional[bool] = None, pan: Optional[bool] = None, pan_axes: Optional[tuple[str, ...]] = None, @@ -538,6 +539,8 @@ def set_interaction( updates["zoom_limits"] = zoom_limits if default_drag_action is not None: updates["default_drag_action"] = self._default_drag_action(default_drag_action) + if hover_mode is not None: + updates["hover_mode"] = self._hover_mode(hover_mode) if link_group is not None: group = self._optional_text(link_group, "interaction link_group") if not group: @@ -805,6 +808,21 @@ def _default_drag_action(value: Any) -> str: raise ValueError(f"interaction default_drag_action must be one of {choices}") return value + @staticmethod + def _hover_mode(value: Any) -> str: + """Validate a Plotly-style ``hovermode`` (interaction spec §7.1).""" + allowed = ("closest", "x unified", "y unified") + if isinstance(value, str) and value in allowed: + return value + choices = ", ".join(repr(mode) for mode in allowed) + hint = "" + if value in ("x", "y"): + hint = ( + f"; per-series floating labels (Plotly's {value!r}) are not " + f"supported, use {value + ' unified'!r} for one readout of every series" + ) + raise ValueError(f"interaction hover_mode must be one of {choices}{hint}") + @staticmethod def _zoom_limit_pair(value: Any, label: str) -> list[Optional[float]]: if not isinstance(value, (tuple, list)) or len(value) != 2: @@ -1869,6 +1887,8 @@ def _interaction_spec(self) -> dict[str, Any]: spec["default_drag_action"] = self._default_drag_action( self.interaction["default_drag_action"] ) + if "hover_mode" in self.interaction: + spec["hover_mode"] = self._hover_mode(self.interaction["hover_mode"]) link_group = self.interaction.get("link_group") if link_group is not None: group = self._optional_text(link_group, "interaction link_group") diff --git a/python/xy/channel.py b/python/xy/channel.py index 12639d07b..7248b21c7 100644 --- a/python/xy/channel.py +++ b/python/xy/channel.py @@ -286,7 +286,10 @@ def handle_message( ) except (TypeError, ValueError): return None - if row is not None and callbacks.on_hover is not None: + # A unified readout (hover_mode="x unified") picks every row it shows; + # all but the winner are `silent`, so on_hover fires once per hover. + silent = content.get("silent") is True + if row is not None and callbacks.on_hover is not None and not silent: callbacks.on_hover(row) # Reply ships even when row is None (stale drill_seq): the client # clears its hover state on the empty result. diff --git a/python/xy/components.py b/python/xy/components.py index e9ea46cd1..d70067c6c 100644 --- a/python/xy/components.py +++ b/python/xy/components.py @@ -167,6 +167,7 @@ DefaultDragAction: TypeAlias = Literal[ "auto", "none", "pan", "zoom", "select", "select-x", "select-y", "select-lasso" ] +HoverMode: TypeAlias = Literal["closest", "x unified", "y unified"] ZoomLimit: TypeAlias = tuple[Optional[float], Optional[float]] ZoomLimits: TypeAlias = Union[ZoomLimit, Mapping[str, ZoomLimit]] @@ -355,6 +356,7 @@ class Interaction(Component): select: Optional[bool] = None brush: Optional[bool] = None crosshair: Optional[bool] = None + hover_mode: Optional[HoverMode] = None navigation: Optional[bool] = None pan: Optional[bool] = None pan_axes: Optional[tuple[str, ...]] = None @@ -3489,6 +3491,7 @@ def interaction_config( select: Optional[bool] = None, brush: Optional[bool] = None, crosshair: Optional[bool] = None, + hover_mode: Optional[HoverMode] = None, navigation: Optional[bool] = None, pan: Optional[bool] = None, pan_axes: Optional[tuple[str, ...]] = None, @@ -3513,6 +3516,13 @@ def interaction_config( select: Whether shift-drag box selection is enabled. brush: Whether brush selection is enabled. crosshair: Whether plot-aligned hover guides are shown. + hover_mode: How hover finds what to report, named after Plotly's + ``hovermode``. ``"closest"`` (the default) reports the mark under + the cursor. ``"x unified"`` snaps to the nearest x anywhere over + the plot and lists every series' value at that x in one tooltip, + with a vertical spike line; ``"y unified"`` is the same along y. + Series whose point at that position is more than 20 px away are + left out. Polar charts keep closest-point hover. navigation: Whether pointer drag and wheel gestures pan or zoom the chart. pan: Whether plain-drag pan is enabled. ``False`` ignores plain-drag pan gestures and contains every zoom-enabled axis to its home @@ -3559,6 +3569,7 @@ def interaction_config( select=select, brush=brush, crosshair=crosshair, + hover_mode=hover_mode, navigation=navigation, pan=pan, pan_axes=pan_axes, @@ -3675,6 +3686,7 @@ def __init__( select: Optional[bool] = None, brush: Optional[bool] = None, crosshair: Optional[bool] = None, + hover_mode: Optional[HoverMode] = None, navigation: Optional[bool] = None, pan: Optional[bool] = None, pan_axes: Optional[tuple[str, ...]] = None, @@ -3716,6 +3728,8 @@ def __init__( select: Whether shift-drag box selection is enabled. brush: Whether brush selection is enabled. crosshair: Whether plot-aligned hover guides are shown. + hover_mode: ``"closest"`` (default), ``"x unified"``, or + ``"y unified"``; see :func:`interaction_config`. navigation: Whether browser pan and zoom navigation is enabled. pan: Whether plain-drag panning is enabled. pan_axes: Declared axis IDs translated by pan gestures. @@ -3761,6 +3775,7 @@ def __init__( self._select_switch = select self.brush = brush self.crosshair = crosshair + self.hover_mode = hover_mode self.navigation = navigation self.pan = pan self.pan_axes = pan_axes @@ -3902,6 +3917,7 @@ def figure(self) -> Figure: or self._select_switch is not None or self.brush is not None or self.crosshair is not None + or self.hover_mode is not None or self.navigation is not None or self.pan is not None or self.pan_axes is not None @@ -3922,6 +3938,7 @@ def figure(self) -> Figure: select=self._select_switch, brush=self.brush, crosshair=self.crosshair, + hover_mode=self.hover_mode, navigation=self.navigation, pan=self.pan, pan_axes=self.pan_axes, @@ -3944,6 +3961,7 @@ def figure(self) -> Figure: select=node.select, brush=node.brush, crosshair=node.crosshair, + hover_mode=node.hover_mode, navigation=node.navigation, pan=node.pan, pan_axes=node.pan_axes, diff --git a/python/xy/dom.py b/python/xy/dom.py index 08a513479..080f7966f 100644 --- a/python/xy/dom.py +++ b/python/xy/dom.py @@ -28,6 +28,7 @@ "tooltip_row", "tooltip_label", "tooltip_value", + "tooltip_swatch", "modebar", "modebar_drag_handle", "modebar_control_group", diff --git a/spec/api/capability-matrix.md b/spec/api/capability-matrix.md index 15bbd4301..c2abd62e6 100644 --- a/spec/api/capability-matrix.md +++ b/spec/api/capability-matrix.md @@ -14,7 +14,7 @@ which is sometimes deliberate, and the notes say which. ## In one line - **11** mark style properties across **22** mark kinds, drawn by all three renderers. -- **48** stable chrome slots, CSS- and Tailwind-addressable in the browser; **10** of them reach the native writers — nine through `styles={slot: ...}` itself, and `root` through the chart-level `style=` token bag. +- **49** stable chrome slots, CSS- and Tailwind-addressable in the browser; **10** of them reach the native writers — nine through `styles={slot: ...}` itself, and `root` through the chart-level `style=` token bag. - **1** shipped extension point. - **1** known default divergence between renderers, listed below rather than left to be discovered. @@ -87,6 +87,7 @@ contracted in [export.md](export.md) §9 and pinned by | `tooltip_row` | full | none | none | | `tooltip_label` | full | none | none | | `tooltip_value` | full | none | none | +| `tooltip_swatch` | full | none | none | | `modebar` | full | none | none | | `modebar_drag_handle` | full | none | none | | `modebar_control_group` | full | none | none | diff --git a/spec/api/interaction.md b/spec/api/interaction.md index 33870d820..25e77f5ea 100644 --- a/spec/api/interaction.md +++ b/spec/api/interaction.md @@ -52,7 +52,8 @@ the switch is never set. The non-boolean viewport keys — `default_drag_action` | `click` | off | `_click` returns immediately: no `xy:click` event and no `click` message to the kernel. | | `select` | on | Suppresses the `xy:select` event and the `select_clear` message, removes the modebar Selection menu, and (with `brush`) disables shift-drag. | | `brush` | on | Same conjunction: `canBrush = brush && select` (`53_interaction.ts:115`) gates every selection drag and the modebar Selection menu. | -| `crosshair` | off | The two guide elements are created only when the flag is true, at init (`53_interaction.ts:80`). Not togglable after mount. | +| `crosshair` | off | The two guide elements are created only when the flag is true (or `hover_mode` is unified, which borrows one as its spike line, §7.1), at init (`53_interaction.ts`). Not togglable after mount. | +| `hover_mode` | `"closest"` | Not a boolean: `"closest"`, `"x unified"`, or `"y unified"` (Plotly's `hovermode` spelling). Unified modes are specified in §7.1. Validated at construction; Plotly's per-series `"x"`/`"y"` modes raise with a pointer to the unified spelling. Polar charts resolve to `"closest"` client-side. Not togglable after mount. | | `navigation` | on | Master gate on pointer-drag pan, wheel zoom, box-zoom drags, dblclick reset, and every modebar viewport control. Selection-mode double-click clear is a selection action and is unaffected. | | `pan` | on | Plain-drag pan is ignored, the modebar Pan button is not built, and every zoom-enabled axis is contained (§2.2). Requires `navigation`. Pans `pan_axes` (§2.1). | | `zoom` | on | Master zoom gate: wheel zoom, box zoom, and the zoom actions inside the modebar menu are all ignored. The same dropdown can remain for view history when `history` is on. Requires `navigation`. Zooms `zoom_axes` (§2.1). | @@ -163,7 +164,7 @@ aliases for `ranges.x`/`ranges.y` (`50_chartview.ts`, `_eventView`). | Event | Detail | | --- | --- | -| `xy:hover` | `{row, trace, index, view}` plus the structured payload `{active: true, cursor: {px, data}, points}` (view-state.md §7.1) — genuinely additive; the kernel's exact-value reply re-dispatches with `exact: true` and a refreshed payload. `cursor.px` is chart-root-relative pixels; `cursor.data` is keyed by **exact axis ID** with one entry per declared axis; each `points[]` entry carries `trace` (series name), `index`, `row`, its `x_axis`/`y_axis` bindings, and the series `color`. | +| `xy:hover` | `{row, trace, index, view}` plus the structured payload `{active: true, cursor: {px, data}, points}` (view-state.md §7.1) — genuinely additive; the kernel's exact-value reply re-dispatches with `exact: true` and a refreshed payload. `cursor.px` is chart-root-relative pixels; `cursor.data` is keyed by **exact axis ID** with one entry per declared axis; each `points[]` entry carries `trace` (series name), `index`, `row`, its `x_axis`/`y_axis` bindings, and the series `color`. Under a unified `hover_mode`, `points[]` holds every reported series and the payload adds `hover_mode` (§7.1). | | `xy:leave` | `{view, active: false}` with `source: "leave"`. Dispatched by canvas pointer exit and by a document-level missed-leave backstop: browsers skip boundary events when the element under a stationary cursor changes (page scroll, hit-test churn), so while a pointer-owned readout is live, a `pointerover` whose target left the chart root runs the same exit path (`53_interaction.ts` `_pointerHoverExit`). Keyboard readouts are exempt — they survive mouse movement elsewhere and are dismissed by `Escape`. | | `xy:click` | `{x, y, view, row, trace, index}`; `row`/`trace`/`index` are `null` when the click hit no mark. | | `xy:brush` | `{range: {x0, x1, y0, y1}, view}` for box/axis-range drags, or `{polygon: [[x, y], …], view}` for lasso. | @@ -398,6 +399,62 @@ The hover tooltip is anchored in data space, not at the cursor keeps the edge-clamped placement (the anchor is dropped when its projection starts outside the plot rect). +### 7.1 Unified hover (`hover_mode`) + +`hover_mode="x unified"` mirrors Plotly's `hovermode="x unified"`: the cursor +does not need to touch a mark. Implementation: `js/src/52_tooltip.ts` +(`_unifiedHits`, `_unifiedHover`), wired from `_hover` in `50_chartview.ts`. +`"y unified"` is the same contract with the axes swapped. + +- **Eligible series.** Plain (x, y) marks with a retained CPU column: line, + scatter, area, bar/column. Rect marks (histogram, box), ribbons, funnels, + heatmaps, segments, density tiers, legend-hidden series, and `error_band` + do not answer. When no eligible series answers, the pointer falls through to + closest-point hover, so those charts keep their readout. +- **Snap.** Pass 1: every eligible series finds its row nearest the cursor + along the hover dimension (in axis-coordinate space, so log axes snap by + screen distance); the row nearest in pixels wins and fixes the hover + position. There is no distance cap on the winner — anywhere over the plot + snaps. Pass 2: every series reports its row nearest that position, kept only + within 20 CSS px of it (Plotly's default `hoverdistance`), so a series that + ends early or samples elsewhere is not reported as if it were at that x. + Rows hidden by a legend category filter never answer. +- **Cost.** A non-decreasing column (every line and time series) snaps by + binary search, O(log n) per pointermove; sortedness is checked once per + column identity and length (an append re-checks). Unsorted, category- + filtered, and mid-transition columns use a linear scan, the same cost as + closest-point CPU hover. +- **Readout.** Title: the snapped position's value on the hover axis (a + category label, or the value formatted with `tooltip(format={"x": ...})` + when set). One `series` row per reported series in trace order: a + `tooltip_swatch` chip painted with the series color (via + `--xy-tooltip-swatch-paint`), the series name (or the other axis's tooltip + label, defaulting to `"y"`/`"x"`) in `tooltip_label`, and its value in + `tooltip_value`. Rows with an identical name, value, and color collapse + (one composed series drawn as two marks). +- **Spike and placement.** The hover-dimension crosshair line (`crosshair_x` + for x unified) is the spike: it marks the snapped position across the plot + and is styled by the existing crosshair slot and `--chart-crosshair` token. + With `crosshair=True` the other line keeps following the cursor. The + readout is anchored in data space at (snapped position, cursor) — so it + rides through pans and zooms like §7 — and sits beside the spike, flipping + to the far side instead of clamping over it at the plot edge. Moving along + the spike without changing the reported rows only repositions it. +- **Highlight.** Every reported scatter point gets the hover marker (a line + has none, matching closest mode). +- **Events and picks.** `xy:hover` fires once per change of the reported row + set: `row`/`trace`/`index` describe the winning series, `points[]` lists + every reported series, and `hover_mode` names the mode. With a kernel + attached the client sends one `pick` per row on consecutive `seq` values; + all but the winner's carry `silent: true`, so Python `on_hover` still fires + once per hover. Each `pick_result` refines its own row in place (a `null` + row keeps the local value). When every row has answered, one `exact: true` + `xy:hover` carries all of them. Replies for an abandoned readout are + ignored. +- **Unchanged.** Click picks the mark under the cursor; keyboard traversal + walks points one at a time (§8). Standalone HTML keeps unified hover from + its retained CPU columns. + ## 8. Unconditional behavior Not configurable through any switch: tooltip rendering and the kernel `pick` diff --git a/spec/api/styling.md b/spec/api/styling.md index 453372195..ba8cfa9ac 100644 --- a/spec/api/styling.md +++ b/spec/api/styling.md @@ -893,6 +893,7 @@ raises before it reaches the client. | `tooltip_row` | One tooltip field row | | `tooltip_label` | One tooltip field label | | `tooltip_value` | One formatted tooltip value | +| `tooltip_swatch` | Series color chip on a unified-hover row (`--xy-tooltip-swatch-paint`) | | `modebar` | Mode/tool bar container | | `modebar_drag_handle` | Draggable grip that reveals and moves the modebar | | `modebar_control_group` | Main top-level control group | diff --git a/spec/design-dossier.md b/spec/design-dossier.md index 70e8dddb4..3a51d6ed6 100644 --- a/spec/design-dossier.md +++ b/spec/design-dossier.md @@ -716,6 +716,9 @@ Part I said "60fps" without defining what has to happen inside a frame. The budg **Hover semantics per tier** (the doc previously defined hover only for direct draws): - *Tier 0/1:* GPU pick → point ID → exact source-row readout (f64/i64, via §16). + Unified hover (`hover_mode="x unified"`, interaction spec §7.1) replaces the + pick with a CPU snap along one axis — binary search on sorted columns — and + refines every reported row through the same exact pick. - *Tier 2 (aggregated):* the pick target is a **bin**, not a point. Hover shows bin summary (count, x/y range, aggregate value). Click-to-drill spawns a worker query that returns the top-k underlying rows from the column store — honest about diff --git a/spec/design/reflex-shaped-api.md b/spec/design/reflex-shaped-api.md index 860bf21ac..2346115f7 100644 --- a/spec/design/reflex-shaped-api.md +++ b/spec/design/reflex-shaped-api.md @@ -327,6 +327,7 @@ DOM chrome slots: | `tooltip_row` | One tooltip row | | `tooltip_label` | One tooltip field label | | `tooltip_value` | One tooltip field value | +| `tooltip_swatch` | Series color chip on a unified-hover row | | `modebar` | Modebar container | | `modebar_drag_handle` | Draggable modebar grip | | `modebar_control_group` | Main control group | diff --git a/spec/design/view-state.md b/spec/design/view-state.md index e19de5149..03d97d9ad 100644 --- a/spec/design/view-state.md +++ b/spec/design/view-state.md @@ -310,6 +310,9 @@ existing `xy:hover` two-stage behavior is preserved: the payload re-dispatches with `exact: true` when the kernel's f64 pick reply lands, and on static/standalone charts `points[].row` comes from browser-resident data with no exact upgrade — the same honesty rule the LOD tiers follow. +Under a unified `hover_mode` (interaction spec §7.1) `points` lists every +series reported at the snapped position, the payload adds `"hover_mode"`, +and the `exact: true` re-dispatch waits until every row's pick has answered. **The active flag is trustworthy.** `active: true` is always eventually followed by an `active: false` when the pointer leaves the chart, even when diff --git a/spec/design/wire-protocol.md b/spec/design/wire-protocol.md index 5900984ee..56fe43b39 100644 --- a/spec/design/wire-protocol.md +++ b/spec/design/wire-protocol.md @@ -42,7 +42,7 @@ Every request is a dict with a `type`. Coordinate fields are JSON numbers in | --- | --- | --- | | `view` | `x0`, `x1`, `px?`, `seq?` | `tier_update`, or nothing | | `density_view` | `trace`, `x0`, `x1`, `y0`, `y1`, `w?`, `h?`, `seq?` | `density_update`, or nothing | -| `pick` | `trace`, `index`, `drill_seq?`, `seq?` | `pick_result` | +| `pick` | `trace`, `index`, `drill_seq?`, `seq?`, `silent?` | `pick_result` | | `click` | `trace`, `index`, `drill_seq?` | none (`on_click`) | | `view_change` | `ranges`, `source?`, `axes?`, `phase?`, `interaction_id?` (legacy `x0`/`x1`/`y0`/`y1` accepted) | none (`on_view_change`) | | `select` | `x0`, `x1`, `y0`, `y1` | `selection` | @@ -89,6 +89,9 @@ subset version the client picked against; a non-current seq translates through the kernel's bounded subset history when it is still remembered (the client may be drawing a retired cached point window, LOD doc T13) and resolves to `row: null` otherwise — never to a row in a dead index space. +`silent: true` (exactly `true`) answers the pick but skips `on_hover`: a +unified hover readout (interaction spec §7.1) picks every row it shows and +lets only the winning row reach the callback. **`click`** — same fields and same `fig.pick` resolution as `pick`, minus `seq`; it fires `on_click` and returns nothing. diff --git a/spec/process/css-tailwind-surface-audit-2026-07-30.md b/spec/process/css-tailwind-surface-audit-2026-07-30.md index dc6ec3f39..4a9bf62e8 100644 --- a/spec/process/css-tailwind-surface-audit-2026-07-30.md +++ b/spec/process/css-tailwind-surface-audit-2026-07-30.md @@ -39,7 +39,7 @@ from the same tuple, so documentation and implementation cannot drift. | Marks | Fill, stroke, fill/stroke opacity, stroke width/dash/cap where the renderer supports them, rectangle radius/wedge gap, scatter shape, and mark-specific typed channels/geometry | Root CSS variables may supply any constant CSS color expression; Tailwind can set those variables | Individual marks are WebGL pixels, not DOM. `mark(style={...})` compiles the supported CSS subset identically for WebGL, SVG, and native raster. Unsupported declarations raise. | | Axes | Gesture band, Cartesian spine, major/minor tick marks, tick labels, axis titles | `axis_band`, `axis_line`, `tick_mark`, `tick_label`, `axis_title`; `data-xy-axis`, `data-xy-axis-side`, and `data-xy-tick-kind` refine selectors | Grid lines, polar rings/spokes/frame, and static export use validated axis `style` (`grid_*`, `axis_*`, `tick_*`, label paint/type). | | Legends | Container, title, row, swatch, label | `legend`, `legend_title`, `legend_item`, `legend_swatch`, `legend_label`; state attributes expose off/hover semantics | Scatter/line SVG handles inherit fill/stroke/width/dash from the swatch slot. Placement and live toggle opacity/filter remain controller state. | -| Tooltips | Container, title, row, field label, field value | `tooltip`, `tooltip_title`, `tooltip_row`, `tooltip_label`, `tooltip_value`; component-local class/style reaches the container | Tooltip position/visibility is live state. A framework-owned replacement is styled by that framework. | +| Tooltips | Container, title, row, field label, field value | `tooltip`, `tooltip_title`, `tooltip_row`, `tooltip_label`, `tooltip_value`, `tooltip_swatch`; component-local class/style reaches the container | Tooltip position/visibility is live state. A framework-owned replacement is styled by that framework. | | Colorbars | Container, ramp/bands, extension triangles, contour lines, tick labels, minor tick marks, title | `colorbar`, `colorbar_bar`, `colorbar_extension`, `colorbar_line`, `colorbar_tick`, `colorbar_minor_tick`, `colorbar_title` | Domain, colormap, levels, orientation, ticks, extension, and contour-line values remain semantic colorbar configuration and static-writer input. | | Modebars & controls | Toolbar, drag handle, control group, separator, button, top-level icon, zoom value, chevron, active selection icon, menu, menu separator, menu icon, menu label, history group | `modebar`, `modebar_drag_handle`, `modebar_control_group`, `modebar_separator`, `modebar_button`, `modebar_icon`, `modebar_zoom_value`, `modebar_indicator`, `modebar_selection_icon`, `modebar_menu`, `modebar_menu_separator`, `modebar_menu_icon`, `modebar_menu_label`, `modebar_history_controls` | Placement, open/closed display, fit visibility, dragging, focus routing, and disabled/active state remain interaction-owned; state is exposed through classes/ARIA/data attributes. | | Annotations | Whole shape canvas and each DOM label/callout | `annotation_layer`, `annotation_label`, plus per-annotation `class_name` and label CSS style | Rule/band/arrow/marker geometry uses annotation color, width, opacity, stroke, symbol, and offsets so browser, SVG, and native PNG agree. | diff --git a/tests/test_static_client_security.py b/tests/test_static_client_security.py index 4806e0c28..96765f9c6 100644 --- a/tests/test_static_client_security.py +++ b/tests/test_static_client_security.py @@ -329,6 +329,7 @@ def test_client_applies_every_public_dom_slot() -> None: "tooltip_row": '_applySlot(row, "tooltip_row")', "tooltip_label": '_applySlot(label, "tooltip_label")', "tooltip_value": '_applySlot(value, "tooltip_value")', + "tooltip_swatch": '_applySlot(swatch, "tooltip_swatch")', "modebar": '_applySlot(bar, "modebar")', "modebar_drag_handle": '_applySlot(dragPeek, "modebar_drag_handle")', "modebar_control_group": '_applySlot(toolGroup, "modebar_control_group")', diff --git a/tests/test_type_surface.py b/tests/test_type_surface.py index f5e12505a..979dc04e6 100644 --- a/tests/test_type_surface.py +++ b/tests/test_type_surface.py @@ -216,6 +216,7 @@ def test_chart_dom_slots_are_public_styling_contract() -> None: "tooltip_row", "tooltip_label", "tooltip_value", + "tooltip_swatch", "modebar", "modebar_drag_handle", "modebar_control_group", diff --git a/tests/test_unified_hover.py b/tests/test_unified_hover.py new file mode 100644 index 000000000..e441c8f5a --- /dev/null +++ b/tests/test_unified_hover.py @@ -0,0 +1,357 @@ +"""Unified hover — Plotly's ``hovermode="x unified"`` (interaction spec §7.1). + +Python half: the ``hover_mode`` switch validates, reaches the wire spec from +both the chart keyword and ``interaction_config``, and a ``silent`` pick +refines a unified row without firing ``on_hover`` again. Browser half drives +the real render client in headless Chromium: the cursor snaps to the nearest +x anywhere over the plot, every series reports its value there, the spike line +marks the snapped x, kernel exact-value replies refine each row, and closest +mode is unchanged. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +import xy +from conftest import run_browser_probe +from xy._figure import Figure +from xy.channel import ChannelCallbacks, handle_message +from xy.export import find_chromium + +_RENDER_CALL = 'xy.renderStandalone(document.getElementById("chart"), spec, buf);' +_DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri"] + + +def _weekly(**kwargs) -> xy.Chart: + return xy.line_chart( + xy.line(_DAYS, [5, 5, 5, 11, 0], name="Booked"), + xy.line(_DAYS, [0, 2, 5, 5, 0], name="Held"), + xy.line(_DAYS, [0, 1, 4, 3, 0], name="Qualified held"), + width=640, + height=360, + **kwargs, + ) + + +# -- Python surface ----------------------------------------------------------- + + +@pytest.mark.parametrize("mode", ["closest", "x unified", "y unified"]) +def test_hover_mode_reaches_the_wire_from_chart_and_config(mode: str) -> None: + by_kwarg = _weekly(hover_mode=mode).figure()._interaction_spec() + by_config = ( + xy.line_chart(xy.line([0, 1], [0, 1]), xy.interaction_config(hover_mode=mode)) + .figure() + ._interaction_spec() + ) + assert by_kwarg["hover_mode"] == mode + assert by_config["hover_mode"] == mode + + +def test_hover_mode_is_absent_until_set() -> None: + assert "hover_mode" not in _weekly().figure()._interaction_spec() + + +@pytest.mark.parametrize("bad", ["x", "y", "unified", "X Unified", True, 1]) +def test_hover_mode_rejects_unknown_modes(bad) -> None: + with pytest.raises(ValueError, match="hover_mode must be one of"): + Figure().set_interaction(hover_mode=bad) + + +def test_plain_axis_mode_names_the_unified_spelling() -> None: + with pytest.raises(ValueError, match="'x unified'"): + Figure().set_interaction(hover_mode="x") + + +def test_silent_pick_refines_without_firing_on_hover() -> None: + fig = Figure().scatter([0.0, 1.0, 2.0], [3.0, 4.0, 5.0]) + fired: list[dict] = [] + callbacks = ChannelCallbacks(on_hover=fired.append) + + loud = handle_message(fig, {"type": "pick", "seq": 7, "trace": 0, "index": 1}, None, callbacks) + quiet = handle_message( + fig, {"type": "pick", "seq": 8, "trace": 0, "index": 2, "silent": True}, None, callbacks + ) + + assert loud is not None and quiet is not None + assert loud[0]["seq"] == 7 and loud[0]["row"]["y"] == 4.0 + assert quiet[0]["seq"] == 8 and quiet[0]["row"]["y"] == 5.0 + assert [row["index"] for row in fired] == [1] + + +# -- browser ------------------------------------------------------------------ + + +def _run(tmp_path: Path, document: str, attribute: str, label: str) -> dict: + chromium = find_chromium() + if chromium is None: + pytest.skip("Chromium unavailable") + return run_browser_probe( + chromium, document, tmp_path / f"{attribute}.html", attribute, label=label + ) + + +_PROBE_PRELUDE = """ + const view = xy.renderStandalone(document.getElementById("chart"), spec, buf); + try { + view._drawNow(); + const c = view.canvas; + const r = c.getBoundingClientRect(); + const move = (cssX, cssY) => c.dispatchEvent(new PointerEvent("pointermove", { + clientX: r.left + cssX, clientY: r.top + cssY, bubbles: true, cancelable: true, + })); + // Canvas-relative pixel x of category `i` on the x axis. + const pxOf = (i) => view._projectDataPoint("x", "y", i, 0)[0] - view.plot.x; + const text = () => [...view.tooltip.children].map((row) => row.textContent); + const shown = () => view.tooltip.style.display === "block"; + const spike = () => view.root.querySelector('[data-xy-slot="crosshair_x"]'); + const hovers = []; + view.root.addEventListener("xy:hover", (e) => hovers.push(e.detail)); +""" + +_PROBE_CATCH = """ + } catch (err) { + document.body.setAttribute("%s-error", String((err && err.stack) || err)); + } +""" + +_UNIFIED_PROBE = ( + _PROBE_PRELUDE + + """ + // Between Wed (2) and Thu (3), nearer Thu, well away from any line. + const between = pxOf(2) + 0.7 * (pxOf(3) - pxOf(2)); + move(between, 4); + const lines = text(); + const snappedHeading = lines[0] === "Thu"; + const everySeries = JSON.stringify(lines.slice(1)) + === JSON.stringify(["Booked11", "Held5", "Qualified held3"]); + const swatches = [...view.tooltip.querySelectorAll('[data-xy-slot="tooltip_swatch"]')]; + const swatchesPainted = swatches.length === 3 && swatches.every( + (s) => /^rgb\\(/.test(s.style.getPropertyValue("--xy-tooltip-swatch-paint"))); + const line = spike(); + const spikeAtThu = !!line && line.style.display === "block" + && Math.abs(parseFloat(line.style.left) - (pxOf(3) + view.plot.x)) < 0.6; + // The readout sits beside the spike, never over it. + const tipLeft = parseFloat(view.tooltip.style.left); + const tipRight = tipLeft + view.tooltip.offsetWidth; + const besideSpike = tipLeft > parseFloat(line.style.left) + || tipRight < parseFloat(line.style.left); + + const event = hovers[hovers.length - 1]; + const eventCarriesEveryPoint = !!event && event.points.length === 3 + && event.hover_mode === "x unified" && event.row.x === "Thu" + && event.points.map((p) => p.trace).join("|") === "Booked|Held|Qualified held"; + + // Moving vertically at the same x keeps the readout: no new hover event. + const before = hovers.length; + move(between, view.plot.h - 4); + const stableAtSameX = hovers.length === before && text()[0] === "Thu" && shown(); + + // Crossing the midpoint re-snaps to Wed. + move(pxOf(2) + 0.3 * (pxOf(3) - pxOf(2)), 4); + const resnapped = text()[0] === "Wed" && hovers.length === before + 1; + + // Leaving clears the readout and the spike (crosshair is off). + c.dispatchEvent(new PointerEvent("pointerleave", { bubbles: true })); + const cleared = !shown() && spike().style.display === "none" && view._unified === null; + + document.body.setAttribute("data-xy-unified-probe", JSON.stringify({ + snappedHeading, everySeries, swatchesPainted, spikeAtThu, besideSpike, + eventCarriesEveryPoint, stableAtSameX, resnapped, cleared, + })); +""" + + _PROBE_CATCH % "data-xy-unified-probe" +) + + +def test_x_unified_snaps_to_nearest_x_and_lists_every_series(tmp_path: Path) -> None: + html = _weekly(hover_mode="x unified", hover=True).to_html() + assert _RENDER_CALL in html + result = _run( + tmp_path, + html.replace(_RENDER_CALL, _UNIFIED_PROBE), + "data-xy-unified-probe", + label="unified hover probe", + ) + assert result == {key: True for key in result}, result + + +_KERNEL_PROBE = ( + _PROBE_PRELUDE + + """ + const sent = []; + view.comm = { send: (m) => sent.push(m) }; + move(pxOf(3), 4); + const picks = sent.filter((m) => m.type === "pick"); + const onePickPerRow = picks.length === 3 + && picks.every((m, k) => m.seq === picks[0].seq + k) + && picks.map((m) => m.trace).join(",") === "0,1,2"; + // Exactly one pick may fire Python's on_hover. + const oneLoudPick = picks.filter((m) => m.silent !== true).length === 1; + + // The exact reply for "Held" refines that row only. + const held = picks[1]; + view._onKernelMsg({ type: "pick_result", seq: held.seq, + row: { trace: held.trace, index: held.index, x: 3, y: 5.25 } }, []); + const refined = JSON.stringify(text()) + === JSON.stringify(["Thu", "Booked11", "Held5.25", "Qualified held3"]); + // A null reply (a drill swap raced the pick) keeps the local value. + view._onKernelMsg({ type: "pick_result", seq: picks[2].seq, row: null }, []); + const nullKeepsRow = shown() && text()[3] === "Qualified held3"; + const exactBefore = hovers.filter((d) => d.exact).length; + view._onKernelMsg({ type: "pick_result", seq: picks[0].seq, + row: { trace: 0, index: 3, x: 3, y: 11 } }, []); + // Once every row has answered, one exact event carries all of them. + const exactEvents = hovers.filter((d) => d.exact); + const exactOnceComplete = exactBefore === 0 && exactEvents.length === 1 + && exactEvents[0].points.length === 3 + && exactEvents[0].points[1].row.y === 5.25; + + // A late reply for an abandoned readout must not resurrect it. + c.dispatchEvent(new PointerEvent("pointerleave", { bubbles: true })); + view._onKernelMsg({ type: "pick_result", seq: held.seq, + row: { trace: held.trace, index: held.index, x: 3, y: 5.25 } }, []); + const staleIgnored = !shown(); + + document.body.setAttribute("data-xy-unified-kernel-probe", JSON.stringify({ + onePickPerRow, oneLoudPick, refined, nullKeepsRow, exactOnceComplete, staleIgnored, + })); +""" + + _PROBE_CATCH % "data-xy-unified-kernel-probe" +) + + +def test_x_unified_refines_each_row_from_kernel_picks(tmp_path: Path) -> None: + html = _weekly(hover_mode="x unified", hover=True).to_html() + result = _run( + tmp_path, + html.replace(_RENDER_CALL, _KERNEL_PROBE), + "data-xy-unified-kernel-probe", + label="unified hover kernel probe", + ) + assert result == {key: True for key in result}, result + + +_CLOSEST_PROBE = ( + _PROBE_PRELUDE + + """ + move(pxOf(2) + 0.5 * (pxOf(3) - pxOf(2)), 4); + const nothingBetweenPoints = !shown(); + const noSpike = spike() === null; + document.body.setAttribute("data-xy-closest-probe", JSON.stringify({ + nothingBetweenPoints, noSpike, + })); +""" + + _PROBE_CATCH % "data-xy-closest-probe" +) + + +def test_closest_mode_is_unchanged(tmp_path: Path) -> None: + result = _run( + tmp_path, + _weekly().to_html().replace(_RENDER_CALL, _CLOSEST_PROBE), + "data-xy-closest-probe", + label="closest hover probe", + ) + assert result == {key: True for key in result}, result + + +_DISTANCE_PROBE = ( + _PROBE_PRELUDE + + """ + // "Dense" samples every 0.1; "Sparse" only at 0 and 10. At x=5 the sparse + // series has no point within the hover distance, so it is left out. + const xAt = (v) => view._projectDataPoint("x", "y", v, 0)[0] - view.plot.x; + move(xAt(5.02), 4); + const midOnlyDense = JSON.stringify(text().slice(1)) === JSON.stringify(["Dense5"]); + move(xAt(10), 4); + const endBoth = text().length === 3 && text()[0] === "10"; + // Binary search on the sorted column agrees with a full scan. + const g = view.gpuTraces[0]; + let agree = true; + for (let v = -1; v <= 11; v += 0.037) { + const fast = view._unifiedNearestIndex(g, "x", v); + let best = -1, bestDist = Infinity; + for (let i = 0; i < g._cpu.x.length; i++) { + const d = Math.abs(view._unifiedValue(g, "x", i) - v); + if (d < bestDist) { bestDist = d; best = i; } + } + const tie = Math.abs(Math.abs(view._unifiedValue(g, "x", fast) - v) - bestDist) < 1e-9; + if (fast !== best && !tie) agree = false; + } + const sortedCached = g._unifiedSortCache.x.sorted === true; + document.body.setAttribute("data-xy-distance-probe", JSON.stringify({ + midOnlyDense, endBoth, agree, sortedCached, + })); +""" + + _PROBE_CATCH % "data-xy-distance-probe" +) + + +def test_series_beyond_the_hover_distance_are_left_out(tmp_path: Path) -> None: + dense_x = [i / 10 for i in range(101)] + chart = xy.line_chart( + xy.line(dense_x, [round(v, 1) for v in dense_x], name="Dense"), + xy.line([0.0, 10.0], [1.0, 2.0], name="Sparse"), + width=640, + height=360, + hover_mode="x unified", + ) + result = _run( + tmp_path, + chart.to_html().replace(_RENDER_CALL, _DISTANCE_PROBE), + "data-xy-distance-probe", + label="unified hover distance probe", + ) + assert result == {key: True for key in result}, result + + +_Y_PROBE = ( + _PROBE_PRELUDE + + """ + const yAt = (v) => view._projectDataPoint("x", "y", 0, v)[1] - view.plot.y; + move(view.plot.w / 2, yAt(2.1)); + const heading = text()[0] === "2"; + const rows = JSON.stringify(text().slice(1)) === JSON.stringify(["A1", "B3"]); + const line = view.root.querySelector('[data-xy-slot="crosshair_y"]'); + const horizontalSpike = !!line && line.style.display === "block" + && Math.abs(parseFloat(line.style.top) - (yAt(2) + view.plot.y)) < 0.6 + && spike().style.display === "none"; + document.body.setAttribute("data-xy-y-probe", JSON.stringify({ + heading, rows, horizontalSpike, + })); +""" + + _PROBE_CATCH % "data-xy-y-probe" +) + + +def test_y_unified_is_the_transpose(tmp_path: Path) -> None: + chart = xy.scatter_chart( + xy.scatter([1.0, 5.0], [2.0, 8.0], name="A"), + xy.scatter([3.0, 6.0], [2.0, 9.0], name="B"), + width=640, + height=360, + hover_mode="y unified", + ) + result = _run( + tmp_path, + chart.to_html().replace(_RENDER_CALL, _Y_PROBE), + "data-xy-y-probe", + label="y unified probe", + ) + assert result == {key: True for key in result}, result + + +def test_polar_keeps_closest_hover() -> None: + chart = xy.polar_chart(xy.line([0.0, 1.0, 2.0], [1.0, 2.0, 3.0]), hover_mode="x unified") + spec = chart.figure()._interaction_spec() + # The setting rides the wire unchanged; the client resolves polar to + # closest (52_tooltip.ts `_hoverMode`), so pin that branch textually. + assert spec["hover_mode"] == "x unified" + source = (Path(__file__).resolve().parents[1] / "js" / "src" / "52_tooltip.ts").read_text() + assert 'if (this.spec?.coords === "polar") return "closest";' in source + assert json.dumps(spec) # wire-serializable From 2d4f3a424453f074b8326a4b32e69374a943a098 Mon Sep 17 00:00:00 2001 From: Farhan Date: Thu, 3 Dec 2026 19:46:09 +0000 Subject: [PATCH 02/14] Name the unified-hover news fragment after its PR --- news/{+unified-hover.feature.md => 562.feature.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename news/{+unified-hover.feature.md => 562.feature.md} (100%) diff --git a/news/+unified-hover.feature.md b/news/562.feature.md similarity index 100% rename from news/+unified-hover.feature.md rename to news/562.feature.md From aa0b9b42ee7451d31b42fcd1c93518cdf9d3a5a1 Mon Sep 17 00:00:00 2001 From: Farhan Date: Thu, 3 Dec 2026 19:54:15 +0000 Subject: [PATCH 03/14] Fix unified hover with filtered rows, hidden tooltips, and keyboard - Bound shipped rows by the full count when a legend category filter has compacted the drawn buffers (g.n shrinks to the drawn count), and map drawIndex through _visInv instead of a linear indexOf. - Keep tooltip(show=False) hidden when a later frame reprojects the unified anchor; the spike and events still describe the snapped x. - Clear unified state, spike, and highlights when a single-point (keyboard) readout takes over. - Name the hover_mode values as constants (HOVER_MODES in _figure.py, HOVER_* in 52_tooltip.ts). --- js/src/50_chartview.ts | 3 +- js/src/52_tooltip.ts | 50 ++++++++++++--- js/src/53_interaction.ts | 2 +- python/xy/_figure.py | 9 ++- spec/api/interaction.md | 5 ++ tests/test_unified_hover.py | 122 ++++++++++++++++++++++++++++++++++-- 6 files changed, 169 insertions(+), 22 deletions(-) diff --git a/js/src/50_chartview.ts b/js/src/50_chartview.ts index 633b04aed..ca2f08be0 100644 --- a/js/src/50_chartview.ts +++ b/js/src/50_chartview.ts @@ -9664,8 +9664,7 @@ export class ChartView { const rect = this.canvas.getBoundingClientRect(); const cssX = e.clientX - rect.left; const cssY = e.clientY - rect.top; - const mode = this._hoverMode(); - if (mode !== "closest" && this._unifiedHover(e, cssX, cssY, mode)) return; + if (this._unifiedHover(e, cssX, cssY)) return; // Nothing answered a unified readout here (or the mode is closest): drop // any unified state so the closest-point path below starts clean rather // than treating the old winner as "still hovered". diff --git a/js/src/52_tooltip.ts b/js/src/52_tooltip.ts index b0b9f2a29..277546c31 100644 --- a/js/src/52_tooltip.ts +++ b/js/src/52_tooltip.ts @@ -6,12 +6,23 @@ import { ChartView } from "./50_chartview"; // reported in a unified readout. const UNIFIED_HOVER_DISTANCE_PX = 20; +// `hover_mode` values (Plotly's `hovermode` spelling; `_figure.py` HOVER_MODES). +const HOVER_CLOSEST = "closest"; +const HOVER_X_UNIFIED = "x unified"; +const HOVER_Y_UNIFIED = "y unified"; + // ChartView tooltip resolution: map a hovered vertex back to its source // row, denormalize units, and compose the tooltip lines/DOM. Split out of // 50_chartview.js; augments the prototype so `this.*` is unchanged. Object.assign(ChartView.prototype, { _showTooltip(hit, clientX, clientY) { + // A single-point readout (keyboard traversal) replaces any unified one: + // its highlights, spike, and same-position fast path must not linger. + if (this._unified) { + this._unified = null; + this._hideUnifiedSpike(); + } const row = this._localRow(hit); this._lastRow = row; this._setTooltipAnchor(hit, row, clientX, clientY); @@ -574,9 +585,13 @@ Object.assign(ChartView.prototype, { if (this._unified) this._hideUnifiedSpike(); return; } + if (this._unified) { + // `tooltip(show=False)` keeps the box hidden; the spike still marks x. + this._positionUnifiedSpike(pos); + if (this.spec.show_tooltip === false) return; + } this.tooltip.style.display = "block"; this._placeTooltip(pos.lx, pos.ly, !!this._unified); - if (this._unified) this._positionUnifiedSpike(pos); }, _placeTooltip(lx, ly, flipX = false) { @@ -644,12 +659,16 @@ Object.assign(ChartView.prototype, { _hoverMode() { const mode = this.interaction?.hover_mode; - if (mode !== "x unified" && mode !== "y unified") return "closest"; + if (mode !== HOVER_X_UNIFIED && mode !== HOVER_Y_UNIFIED) return HOVER_CLOSEST; // Polar has no single "x" to align on; it keeps closest-point hover. - if (this.spec?.coords === "polar") return "closest"; + if (this.spec?.coords === "polar") return HOVER_CLOSEST; return mode; }, + _hoverUnified() { + return this._hoverMode() !== HOVER_CLOSEST; + }, + // Series that answer a unified readout: plain (x, y) marks with a retained // CPU column — line, scatter, area, bar/column. Area-shaped geometry with no // single value per position (rect marks, ribbons, funnels, heatmaps, @@ -664,9 +683,13 @@ Object.assign(ChartView.prototype, { return !!(cpu && cpu.x && cpu.y && cpu.x.length && cpu.y.length); }, + // Shipped-row count. A legend category filter compacts the drawn buffers + // and shrinks `g.n` to the drawn count, but snapping speaks shipped rows + // (`_visMap` selects which are visible), so bound by the full count. _unifiedCount(g) { const cpu = g._cpu; - return Math.min(cpu.x.length, cpu.y.length, g.n || cpu.x.length); + const rows = g._visMap ? (g._fullN ?? cpu.x.length) : (g.n || cpu.x.length); + return Math.min(cpu.x.length, cpu.y.length, rows); }, // Decoded data value of row `i` on one channel, following an in-flight @@ -802,7 +825,7 @@ Object.assign(ChartView.prototype, { // `index` is a shipped row (what _localRow and the kernel pick speak); // the hover marker addresses the drawn buffer, which a category filter // compacts. - const drawIndex = g._visMap ? g._visMap.indexOf(index) : index; + const drawIndex = g._visMap && g._visInv ? g._visInv[index] : index; hits.push({ trace: g.trace.id, index, drawIndex, g, synthetic: true, axis: axisOf(g) }); } const winner = hits.find((h) => h.g === win.g) || null; @@ -810,9 +833,11 @@ Object.assign(ChartView.prototype, { }, // Returns true when the unified readout handled this pointer position; false - // lets the caller run closest-point hover (nothing answered here). - _unifiedHover(e, cssX, cssY, mode) { - const dim = mode === "y unified" ? "y" : "x"; + // lets the caller run closest-point hover (closest mode, or nothing answered). + _unifiedHover(e, cssX, cssY) { + const mode = this._hoverMode(); + if (mode === HOVER_CLOSEST) return false; + const dim = mode === HOVER_Y_UNIFIED ? "y" : "x"; const found = this._unifiedHits(cssX, cssY, dim); if (!found) return false; const { hits, winner } = found; @@ -912,8 +937,13 @@ Object.assign(ChartView.prototype, { _renderUnifiedTooltip(options: any = {}) { const state = this._unified; - if (!state || this.spec.show_tooltip === false) { + if (!state) return; + if (this.spec.show_tooltip === false) { + // No box, but the spike and the hover events still describe the x. this.tooltip.style.display = "none"; + const pos = this._tooltipAnchorPx(); + if (pos) this._positionUnifiedSpike(pos); + else this._hideUnifiedSpike(); return; } const items = this._unifiedItems(state); @@ -975,7 +1005,7 @@ Object.assign(ChartView.prototype, { color: this._seriesColorCss(g), }; }); - payload.hover_mode = `${state.dim} unified`; + payload.hover_mode = state.dim === "x" ? HOVER_X_UNIFIED : HOVER_Y_UNIFIED; return payload; }, diff --git a/js/src/53_interaction.ts b/js/src/53_interaction.ts index a2ee64193..c52ceaf05 100644 --- a/js/src/53_interaction.ts +++ b/js/src/53_interaction.ts @@ -147,7 +147,7 @@ Object.assign(ChartView.prototype, { // Unified hover (`hover_mode`) draws its spike line with the crosshair's // line, so it needs the elements even when the cursor crosshair is off. - if (this._interactionFlag("crosshair") || this._hoverMode() !== "closest") { + if (this._interactionFlag("crosshair") || this._hoverUnified()) { this.crosshairX = document.createElement("div"); this.crosshairX.style.cssText = "position:absolute;display:none;pointer-events:none;z-index:3;width:1px;"; diff --git a/python/xy/_figure.py b/python/xy/_figure.py index 4bb6144d6..b838fbf91 100644 --- a/python/xy/_figure.py +++ b/python/xy/_figure.py @@ -47,6 +47,10 @@ _FigureCheckpoint: TypeAlias = tuple[ColumnStoreCheckpoint, int, dict[str, list[str]], int] +#: `hover_mode` values, Plotly's `hovermode` spelling (interaction spec §7.1). +#: The client mirrors them as HOVER_* constants in js/src/52_tooltip.ts. +HOVER_MODES: tuple[str, ...] = ("closest", "x unified", "y unified") + # "selection not passed" sentinel for state_patch_message: None is meaningful # there (clear the selection), so absence needs its own marker. _STATE_UNSET: Any = object() @@ -811,10 +815,9 @@ def _default_drag_action(value: Any) -> str: @staticmethod def _hover_mode(value: Any) -> str: """Validate a Plotly-style ``hovermode`` (interaction spec §7.1).""" - allowed = ("closest", "x unified", "y unified") - if isinstance(value, str) and value in allowed: + if isinstance(value, str) and value in HOVER_MODES: return value - choices = ", ".join(repr(mode) for mode in allowed) + choices = ", ".join(repr(mode) for mode in HOVER_MODES) hint = "" if value in ("x", "y"): hint = ( diff --git a/spec/api/interaction.md b/spec/api/interaction.md index 25e77f5ea..3ebc991d6 100644 --- a/spec/api/interaction.md +++ b/spec/api/interaction.md @@ -440,6 +440,11 @@ does not need to touch a mark. Implementation: `js/src/52_tooltip.ts` rides through pans and zooms like §7 — and sits beside the spike, flipping to the far side instead of clamping over it at the plot edge. Moving along the spike without changing the reported rows only repositions it. + `tooltip(show=False)` hides the box on every frame; the spike, highlights, + and events still describe the snapped position. +- **Hand-off.** A single-point readout (keyboard traversal) clears the + unified state, spike, and highlights before it shows; the next pointer + move builds a fresh unified readout. - **Highlight.** Every reported scatter point gets the hover marker (a line has none, matching closest mode). - **Events and picks.** `xy:hover` fires once per change of the reported row diff --git a/tests/test_unified_hover.py b/tests/test_unified_hover.py index e441c8f5a..f76aafcf2 100644 --- a/tests/test_unified_hover.py +++ b/tests/test_unified_hover.py @@ -26,11 +26,12 @@ _DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri"] -def _weekly(**kwargs) -> xy.Chart: - return xy.line_chart( - xy.line(_DAYS, [5, 5, 5, 11, 0], name="Booked"), - xy.line(_DAYS, [0, 2, 5, 5, 0], name="Held"), - xy.line(_DAYS, [0, 1, 4, 3, 0], name="Qualified held"), +def _weekly(*children, mark=xy.line, chart=xy.line_chart, **kwargs) -> xy.Chart: + return chart( + mark(_DAYS, [5, 5, 5, 11, 0], name="Booked"), + mark(_DAYS, [0, 2, 5, 5, 0], name="Held"), + mark(_DAYS, [0, 1, 4, 3, 0], name="Qualified held"), + *children, width=640, height=360, **kwargs, @@ -353,5 +354,114 @@ def test_polar_keeps_closest_hover() -> None: # closest (52_tooltip.ts `_hoverMode`), so pin that branch textually. assert spec["hover_mode"] == "x unified" source = (Path(__file__).resolve().parents[1] / "js" / "src" / "52_tooltip.ts").read_text() - assert 'if (this.spec?.coords === "polar") return "closest";' in source + assert 'if (this.spec?.coords === "polar") return HOVER_CLOSEST;' in source + assert 'const HOVER_CLOSEST = "closest";' in source assert json.dumps(spec) # wire-serializable + + +_FILTERED_PROBE = ( + _PROBE_PRELUDE + + """ + // Hide category "B" (code 1): rows 1 and 2 drop out, rows 0 and 3 stay, + // and the drawn count shrinks to 2 while shipped row 3 is still visible. + const g = view.gpuTraces[0]; + view._filterScatterRows(g, new Set([1])); + view._drawNow(); + const filtered = g.n === 2 && Array.from(g._visMap).join(",") === "0,3"; + const xAt = (v) => view._projectDataPoint("x", "y", v, 0)[0] - view.plot.x; + move(xAt(2.9), 4); + const snapsVisibleRow = text()[0] === "3"; + const hit = view._unified && view._unified.hits[0]; + const shippedAndDrawn = !!hit && hit.index === 3 && hit.drawIndex === 1; + // A hidden row never answers, even right under the cursor. + move(xAt(1.1), 4); + const hiddenSkipped = text()[0] === "0"; + document.body.setAttribute("data-xy-filtered-probe", JSON.stringify({ + filtered, snapsVisibleRow, shippedAndDrawn, hiddenSkipped, + })); +""" + + _PROBE_CATCH % "data-xy-filtered-probe" +) + + +def test_category_filtered_rows_keep_answering(tmp_path: Path) -> None: + chart = xy.scatter_chart( + xy.scatter([0.0, 1.0, 2.0, 3.0], [1.0, 2.0, 3.0, 4.0], color=["A", "B", "B", "A"]), + width=640, + height=360, + hover_mode="x unified", + ) + result = _run( + tmp_path, + chart.to_html().replace(_RENDER_CALL, _FILTERED_PROBE), + "data-xy-filtered-probe", + label="unified hover category filter probe", + ) + assert result == {key: True for key in result}, result + + +_HIDDEN_TOOLTIP_PROBE = ( + _PROBE_PRELUDE + + """ + move(pxOf(3), 4); + const hiddenOnHover = !shown(); + // A later frame reprojects the anchor; it must not reveal the box. + view._drawNow(); + const hiddenAfterDraw = !shown(); + const spikeStillMarksX = spike().style.display === "block"; + const eventsStillFire = hovers.length === 1 && hovers[0].points.length === 3; + document.body.setAttribute("data-xy-hidden-tooltip-probe", JSON.stringify({ + hiddenOnHover, hiddenAfterDraw, spikeStillMarksX, eventsStillFire, + })); +""" + + _PROBE_CATCH % "data-xy-hidden-tooltip-probe" +) + + +def test_hidden_tooltip_stays_hidden_in_unified_mode(tmp_path: Path) -> None: + html = _weekly(xy.tooltip(show=False), hover_mode="x unified", hover=True).to_html() + result = _run( + tmp_path, + html.replace(_RENDER_CALL, _HIDDEN_TOOLTIP_PROBE), + "data-xy-hidden-tooltip-probe", + label="unified hover hidden tooltip probe", + ) + assert result == {key: True for key in result}, result + + +_KEYBOARD_PROBE = ( + _PROBE_PRELUDE + + """ + move(pxOf(3), 4); + const unifiedFirst = !!view._unified && text().length === 4; + c.dispatchEvent(new KeyboardEvent("keydown", { + key: "ArrowRight", bubbles: true, cancelable: true, + })); + const unifiedCleared = view._unified === null; + const spikeHidden = spike().style.display === "none"; + const singlePoint = shown() + && !view.tooltip.querySelector('[data-xy-slot="tooltip_swatch"]'); + // Back to the same snapped x: a fresh unified readout, not the stale + // same-position fast path over keyboard content. + move(pxOf(3), 8); + const unifiedAgain = !!view._unified && text().length === 4 + && spike().style.display === "block"; + document.body.setAttribute("data-xy-keyboard-probe", JSON.stringify({ + unifiedFirst, unifiedCleared, spikeHidden, singlePoint, unifiedAgain, + })); +""" + + _PROBE_CATCH % "data-xy-keyboard-probe" +) + + +def test_keyboard_readout_replaces_unified_state(tmp_path: Path) -> None: + result = _run( + tmp_path, + # Keyboard traversal walks point marks, so the series are scatters. + _weekly(mark=xy.scatter, chart=xy.scatter_chart, hover_mode="x unified") + .to_html() + .replace(_RENDER_CALL, _KEYBOARD_PROBE), + "data-xy-keyboard-probe", + label="unified hover keyboard probe", + ) + assert result == {key: True for key in result}, result From d91dcf5d43ac56b986da8138c2309de08ae8a02b Mon Sep 17 00:00:00 2001 From: Farhan Date: Thu, 3 Dec 2026 20:01:04 +0000 Subject: [PATCH 04/14] Address unified-hover review findings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Drop hover state when traces are replaced (updatePayload, GL rebuild, or an append that rebuilds a trace) so highlights never draw through retired trace buffers; in-place appends keep the hover. - Repaint when a unified readout falls through to closest with no hit, so its point highlights do not linger. - Create the spike lines on first unified use, not only at mount. - Append Interaction.hover_mode after `history` to keep positional order. - Polar fallback is now asserted in a browser probe, not by source text. - Docs/spec: eligible-series wording, y-dimension distance rule, rejected "x"/"y" modes, on_hover winner semantics, labels scope, 49-slot export tables, hover_mode in the interaction §1/§2 key lists, per-series pick cost in dossier §17, and why hover_mode/silent need no protocol bump. - Leave the dated 2026-07-30 CSS audit as recorded. --- docs/components/tooltips.md | 20 ++- docs/core-concepts/interactions.md | 5 +- docs/styling/chrome-slots.md | 7 +- docs/styling/component-variations.md | 2 +- docs/styling/customize.md | 4 +- js/src/50_chartview.ts | 4 + js/src/52_tooltip.ts | 30 +++- js/src/53_interaction.ts | 24 +-- js/src/54_kernel.ts | 1 + js/src/56_animation.ts | 1 + news/562.feature.md | 2 +- python/xy/components.py | 13 +- spec/api/export.md | 4 +- spec/api/interaction.md | 11 +- spec/design-dossier.md | 10 +- spec/design/wire-protocol.md | 7 +- .../css-tailwind-surface-audit-2026-07-30.md | 2 +- tests/test_unified_hover.py | 147 ++++++++++++++++-- 18 files changed, 240 insertions(+), 54 deletions(-) diff --git a/docs/components/tooltips.md b/docs/components/tooltips.md index 80b746154..626973d6f 100644 --- a/docs/components/tooltips.md +++ b/docs/components/tooltips.md @@ -146,7 +146,9 @@ By default the tooltip reports the mark under the cursor, so comparing series means hovering each point in turn. Set `hover_mode="x unified"` (Plotly's `hovermode` spelling) and the cursor only has to be somewhere over the plot: it snaps to the nearest x, a vertical spike line marks it, and one tooltip -lists every series' value there under the x value as its heading. +lists each series that has a point there, under the x value as its heading. +Plotly's per-series `"x"`/`"y"` modes are not available; passing either raises +an error naming `"x unified"`/`"y unified"`. ~~~python demo exec import reflex_xy @@ -171,17 +173,20 @@ def unified_hover_demo(): - `"x unified"` snaps along x; `"y unified"` snaps along y and draws a horizontal spike. `"closest"` is the default. - Line, scatter, area, and bar/column series take part. A series whose nearest - point is more than 20 px from the snapped x is left out rather than reported - at the wrong x. Charts with no such series, and polar charts, keep + point is more than 20 px from the snapped position along the hover dimension + (x for `"x unified"`, y for `"y unified"`) is left out rather than reported + at the wrong coordinate. Charts with no such series, and polar charts, keep closest-point hover. - Each row shows a color chip (`tooltip_swatch` slot), the series name (`tooltip_label`), and its value (`tooltip_value`). `tooltip(format=...)` - and `labels=` keyed by `"x"`/`"y"` apply; `title=` and `fields=` templates - describe one hovered row and are not used by the unified readout. + keyed by `"x"`/`"y"` formats the heading and values, and `labels=` keyed by + `"x"`/`"y"` names unnamed series; `title=` and `fields=` templates describe + one hovered row and are not used by the unified readout. - The spike line is the crosshair line, so the `crosshair_x`/`crosshair_y` slots and the `--chart-crosshair` token style it. - The `xy:hover` event lists every reported series in `points`. Python - `on_hover` still fires once per hover, with the row nearest the cursor. + `on_hover` still fires once per hover, with the row that set the snapped + position (the one nearest the cursor along the hover dimension). The same setting is available as `xy.interaction_config(hover_mode=...)`. @@ -263,7 +268,8 @@ each placeholder is replaced with the value from the hovered row. Pass `hover_mode="x unified"` to the chart, e.g. `xy.line_chart(..., hover_mode="x unified")`. The cursor snaps to the nearest x -anywhere over the plot and one tooltip lists every series at that x. +anywhere over the plot and one tooltip lists each series that has a point at +that x. ### How do I disable tooltips on a chart? diff --git a/docs/core-concepts/interactions.md b/docs/core-concepts/interactions.md index d411bfa82..c127a2225 100644 --- a/docs/core-concepts/interactions.md +++ b/docs/core-concepts/interactions.md @@ -41,8 +41,9 @@ def browser_behavior_demo(): `hover_mode` chooses what hover reports. The default, `"closest"`, reads the mark under the cursor. `"x unified"` snaps to the nearest x anywhere over the -plot and lists every series' value there in one tooltip, with a spike line at -that x; `"y unified"` does the same along y. See +plot and lists the series that have a point there in one tooltip, with a spike +line at that x; `"y unified"` does the same along y. Polar charts keep +`"closest"`. See [Show Every Series at One X](/docs/xy/components/tooltips/#show-every-series-at-one-x). Standalone HTML keeps these local browser behaviors. It cannot invoke Python diff --git a/docs/styling/chrome-slots.md b/docs/styling/chrome-slots.md index 75dcfd9be..5516c6dcc 100644 --- a/docs/styling/chrome-slots.md +++ b/docs/styling/chrome-slots.md @@ -233,7 +233,8 @@ portable file. ## One tooltip, three styling approaches All three examples target the tooltip container. The same mechanisms also -target `tooltip_title`, `tooltip_row`, `tooltip_label`, and `tooltip_value`. +target `tooltip_title`, `tooltip_row`, `tooltip_label`, `tooltip_value`, and +the unified-hover `tooltip_swatch`. Choose based on where the style originates; do not combine them unless you intentionally want normal CSS cascade precedence. @@ -359,8 +360,8 @@ apply it with. Rather than leave that to be discovered, it is a contract: | --- | --- | --- | --- | | mark / axis `style=` | yes | yes | yes | | chart-level `style=` (design tokens) | yes | yes | yes | -| `styles={slot: {...}}` | yes, all 48 slots | text subset, 9 slots | text subset, 9 slots | -| `class_names={slot: "..."}` | yes, all 48 slots | dropped | dropped | +| `styles={slot: {...}}` | yes, all 49 slots | text subset, 9 slots | text subset, 9 slots | +| `class_names={slot: "..."}` | yes, all 49 slots | dropped | dropped | | `custom_css=` | yes | raises | raises | | `xy.legend(style=...)` | yes | 6 keys | 6 keys | | `xy.colorbar(style=...)` | yes | dropped | dropped | diff --git a/docs/styling/component-variations.md b/docs/styling/component-variations.md index 2bee103a9..781834249 100644 --- a/docs/styling/component-variations.md +++ b/docs/styling/component-variations.md @@ -35,7 +35,7 @@ styles it. | Surface | Configure content or behavior | Style it | | --- | --- | --- | | Built-in legend | `legend(loc=..., ncols=..., title=...)` | `legend(class_name=..., style=...)`; `legend`, `legend_title`, `legend_item`, `legend_swatch`, and `legend_label` slots | -| Built-in tooltip | `tooltip(fields=..., labels=..., title=..., format=...)` | `tooltip(class_name=..., style=...)`; `tooltip`, `tooltip_title`, `tooltip_row`, `tooltip_label`, and `tooltip_value` slots | +| Built-in tooltip | `tooltip(fields=..., labels=..., title=..., format=...)` | `tooltip(class_name=..., style=...)`; `tooltip`, `tooltip_title`, `tooltip_row`, `tooltip_label`, `tooltip_value`, and `tooltip_swatch` slots | | Colorbar chrome | `colorbar(title=..., orientation=..., ticks=...)` on a supported continuous mark | `colorbar`, `colorbar_bar`, `colorbar_tick`, `colorbar_title`, `colorbar_extension`, `colorbar_line`, and `colorbar_minor_tick` slots | | X and Y axes | `x_axis(...)`, `y_axis(...)`, including named secondary axes | Validated axis `style`; `axis_line`, `tick_mark`, `tick_label`, `axis_title`, and `axis_band` DOM slots | | Reference lines | `vline(x)` and `hline(y)` | Geometry through `color`, `width`, and `opacity`; label through `class_name` and `style` | diff --git a/docs/styling/customize.md b/docs/styling/customize.md index 590648a2d..f6d2bd7d0 100644 --- a/docs/styling/customize.md +++ b/docs/styling/customize.md @@ -672,8 +672,8 @@ beside it. Host-owned UI is not included in standalone XY exports. Tooltip fields must already be resident in a rendered data channel. Use named data columns for stable lookup, map them to readable display text with `labels=`, and format them with `format=`. Style the built-in container -directly or target `tooltip_title`, `tooltip_row`, `tooltip_label`, and -`tooltip_value` independently. +directly or target `tooltip_title`, `tooltip_row`, `tooltip_label`, +`tooltip_value`, and the unified-hover `tooltip_swatch` independently. ~~~python demo exec toggle preview-code id=customize-tooltip-demo data = { diff --git a/js/src/50_chartview.ts b/js/src/50_chartview.ts index ca2f08be0..73c95b77d 100644 --- a/js/src/50_chartview.ts +++ b/js/src/50_chartview.ts @@ -4959,6 +4959,7 @@ export class ChartView { // Build transactionally. A lost context or allocation failure midway // through a trace list must not strand the buffers/programs already made // for its prefix — shared-host recovery may retry this client in place. + this._dropHoverForRebuild?.(); this.gpuTraces = []; try { for (const trace of this.spec.traces) { @@ -9672,6 +9673,9 @@ export class ChartView { this._hideTooltip(); this._hoverId = -1; this._hoverTarget = null; + // Repaint so the dropped readout's point highlights go with it; the + // `!hit` branch below no longer sees a hover to clear. + this._drawKeepPick(); } const hit = this._pickAt(cssX, cssY) || this._hoverAt(cssX, cssY); if (!hit) { diff --git a/js/src/52_tooltip.ts b/js/src/52_tooltip.ts index 277546c31..414235bcd 100644 --- a/js/src/52_tooltip.ts +++ b/js/src/52_tooltip.ts @@ -969,7 +969,7 @@ Object.assign(ChartView.prototype, { _positionUnifiedSpike(pos) { const state = this._unified; if (!state) return; - const line = state.dim === "x" ? this.crosshairX : this.crosshairY; + const line = this._unifiedSpikeLine(state.dim); if (!line) return; line.style.display = "block"; if (state.dim === "x") { @@ -983,6 +983,34 @@ Object.assign(ChartView.prototype, { } }, + // Every hover reference (unified hits, the closest target, the cached row) + // names a trace in the current `gpuTraces`. A payload swap or GL rebuild + // replaces those traces, and drawing a highlight through a retired one reads + // freed buffers, so the readout is dropped and the next pointer move + // rebuilds it against the new data (§16: never show a dead index's values). + // `retired`, when given, narrows the drop to a hover that references one of + // those traces (an append that rebuilt one trace keeps a hover elsewhere). + _dropHoverForRebuild(retired = null) { + const active = !!this._unified || !!this._hoverTarget || this._hoverId >= 0; + if (!active) return; + if (retired) { + const held = this._unified ? this._unified.hits : [this._hoverTarget]; + if (!held.some((hit) => hit && retired.includes(hit.g))) return; + } + this._hideTooltip(); + this._hoverId = -1; + this._hoverTarget = null; + this._lastRow = null; + this._pickSeq = (this._pickSeq || 0) + 1; + }, + + // The hover-dimension crosshair line, created on first use so a chart whose + // interaction spec turns unified hover on after mount still gets its spike. + _unifiedSpikeLine(dim) { + if (!this.crosshairX) this._createCrosshairLines(); + return dim === "x" ? this.crosshairX : this.crosshairY; + }, + _hideUnifiedSpike() { if (this._interactionFlag("crosshair")) return; // the cursor owns the lines if (this.crosshairX) this.crosshairX.style.display = "none"; diff --git a/js/src/53_interaction.ts b/js/src/53_interaction.ts index c52ceaf05..513d7c768 100644 --- a/js/src/53_interaction.ts +++ b/js/src/53_interaction.ts @@ -148,16 +148,7 @@ Object.assign(ChartView.prototype, { // Unified hover (`hover_mode`) draws its spike line with the crosshair's // line, so it needs the elements even when the cursor crosshair is off. if (this._interactionFlag("crosshair") || this._hoverUnified()) { - this.crosshairX = document.createElement("div"); - this.crosshairX.style.cssText = - "position:absolute;display:none;pointer-events:none;z-index:3;width:1px;"; - this._applySlot(this.crosshairX, "crosshair_x"); - this.root.appendChild(this.crosshairX); - this.crosshairY = document.createElement("div"); - this.crosshairY.style.cssText = - "position:absolute;display:none;pointer-events:none;z-index:3;height:1px;"; - this._applySlot(this.crosshairY, "crosshair_y"); - this.root.appendChild(this.crosshairY); + this._createCrosshairLines(); } const dataAt = (clientX, clientY) => { @@ -617,6 +608,19 @@ Object.assign(ChartView.prototype, { this._drawKeepPick(); }, + _createCrosshairLines() { + this.crosshairX = document.createElement("div"); + this.crosshairX.style.cssText = + "position:absolute;display:none;pointer-events:none;z-index:3;width:1px;"; + this._applySlot(this.crosshairX, "crosshair_x"); + this.root.appendChild(this.crosshairX); + this.crosshairY = document.createElement("div"); + this.crosshairY.style.cssText = + "position:absolute;display:none;pointer-events:none;z-index:3;height:1px;"; + this._applySlot(this.crosshairY, "crosshair_y"); + this.root.appendChild(this.crosshairY); + }, + _updateCrosshair(e) { if (!this.crosshairX || !this.crosshairY || !this._interactionFlag("crosshair")) return; const rect = this.canvas.getBoundingClientRect(); diff --git a/js/src/54_kernel.ts b/js/src/54_kernel.ts index 9f7a95dc5..1cc303bfe 100644 --- a/js/src/54_kernel.ts +++ b/js/src/54_kernel.ts @@ -495,6 +495,7 @@ Object.assign(ChartView.prototype, { ? prevSpec.traces.find((t) => t.id === id) : null; if (this._appendTraceInPlace(this.gpuTraces[i], prevTs, prevSpec, ts, payload)) continue; + this._dropHoverForRebuild([this.gpuTraces[i]]); this._destroyTraceResources(this.gpuTraces[i], texSeen); this.gpuTraces[i] = this._buildTrace(payload, ts); } diff --git a/js/src/56_animation.ts b/js/src/56_animation.ts index d803e5771..8496795de 100644 --- a/js/src/56_animation.ts +++ b/js/src/56_animation.ts @@ -560,6 +560,7 @@ Object.assign(ChartView.prototype, { this._markBestLegendsDirty?.(); return true; } + this._dropHoverForRebuild(); this.gpuTraces = spec.traces.map((trace) => this._buildTrace(buffer, trace)); // The legend DOM is unchanged on updatePayload, but every rendered mark // underneath it was replaced. Keep this pending through `_dataAnim`; the diff --git a/news/562.feature.md b/news/562.feature.md index 4b4d4b194..e0b42d91e 100644 --- a/news/562.feature.md +++ b/news/562.feature.md @@ -1 +1 @@ -Add `hover_mode="x unified"` and `"y unified"` (Plotly's `hovermode`) to charts and `xy.interaction_config`. The cursor no longer has to sit on a point: it snaps to the nearest x anywhere over the plot, a spike line marks that x, and one tooltip lists every series' value there with a color chip (new `tooltip_swatch` slot). Sorted series snap with a binary search, and live kernels refine every row to exact f64 values while `on_hover` still fires once per hover. +Add `hover_mode="x unified"` and `"y unified"` (Plotly's `hovermode`) to charts and `xy.interaction_config`. The cursor no longer has to sit on a point: it snaps to the nearest x anywhere over the plot, a spike line marks that x, and one tooltip lists each line, scatter, area, or bar series with a point there, with a color chip (new `tooltip_swatch` slot). Polar charts keep closest-point hover. Sorted series snap with a binary search, and live kernels refine every row to exact f64 values while `on_hover` still fires once per hover. diff --git a/python/xy/components.py b/python/xy/components.py index d70067c6c..7d4af4280 100644 --- a/python/xy/components.py +++ b/python/xy/components.py @@ -356,7 +356,6 @@ class Interaction(Component): select: Optional[bool] = None brush: Optional[bool] = None crosshair: Optional[bool] = None - hover_mode: Optional[HoverMode] = None navigation: Optional[bool] = None pan: Optional[bool] = None pan_axes: Optional[tuple[str, ...]] = None @@ -372,6 +371,8 @@ class Interaction(Component): link_group: Optional[str] = None link_axes: Optional[tuple[str, ...]] = None history: Optional[bool] = None + # Appended, not grouped with `crosshair`: fields keep their positional order. + hover_mode: Optional[HoverMode] = None @dataclass(frozen=True) @@ -3519,10 +3520,12 @@ def interaction_config( hover_mode: How hover finds what to report, named after Plotly's ``hovermode``. ``"closest"`` (the default) reports the mark under the cursor. ``"x unified"`` snaps to the nearest x anywhere over - the plot and lists every series' value at that x in one tooltip, - with a vertical spike line; ``"y unified"`` is the same along y. - Series whose point at that position is more than 20 px away are - left out. Polar charts keep closest-point hover. + the plot and lists each eligible series' value at that x in one + tooltip, with a vertical spike line; ``"y unified"`` is the same + along y. Line, scatter, area, and bar/column series are eligible; + one whose point at that position is more than 20 px away is left + out. Where no series is eligible, and on polar charts, hover + stays closest-point. navigation: Whether pointer drag and wheel gestures pan or zoom the chart. pan: Whether plain-drag pan is enabled. ``False`` ignores plain-drag pan gestures and contains every zoom-enabled axis to its home diff --git a/spec/api/export.md b/spec/api/export.md index 4d37d2195..c63c52440 100644 --- a/spec/api/export.md +++ b/spec/api/export.md @@ -262,8 +262,8 @@ vector** (`_svg.to_svg`, and `_pdf.svg_to_pdf` on top of it). | `style={...}` on a mark | yes | yes | yes | validated CSS subset, `styles.compile_mark_style` | | `style={...}` on an axis | yes | yes | yes | validated vocabulary, `styles.compile_axis_style` | | `style={...}` on the chart (token bag) | yes | yes | yes | `spec["dom"]["style"]`, read at `_svg.py:767,1481` and `_raster.py:662` | -| `styles={slot: {...}}` (per-slot inline) | yes, all 48 slots | text subset, 9 slots | text subset, 9 slots | `_svg.STATIC_STYLED_SLOTS`; the rest is live-only chrome | -| `class_names={slot: "..."}` | yes, all 48 slots | **dropped** | **dropped** | silent — the SVG writer emits no `class` at all | +| `styles={slot: {...}}` (per-slot inline) | yes, all 49 slots | text subset, 9 slots | text subset, 9 slots | `_svg.STATIC_STYLED_SLOTS`; the rest is live-only chrome | +| `class_names={slot: "..."}` | yes, all 49 slots | **dropped** | **dropped** | silent — the SVG writer emits no `class` at all | | `custom_css="..."` | yes (HTML + Chromium capture) | **raises** | **raises** | `_resolve_image_engine`, `export.py:812` | | `xy.legend(style=...)` | yes | 6 keys | 6 keys | merged with the slot and the theme token before the writers see it | | `xy.colorbar(style=...)` | yes | **dropped** | **dropped** | no native channel; use `styles={"colorbar_title"/"colorbar_tick": ...}` | diff --git a/spec/api/interaction.md b/spec/api/interaction.md index 3ebc991d6..287635d0a 100644 --- a/spec/api/interaction.md +++ b/spec/api/interaction.md @@ -26,11 +26,11 @@ not `False`. The client resolves each read through site's fallback; a present key is enabled only when it is exactly `true`. The fallback therefore *is* the default, and it differs per switch. -The viewport keys that are not plain booleans — `default_drag_action` (a -string), `pan_axes`/`zoom_axes`/`reset_axes` (axis-ID tuples), and +The keys that are not plain booleans — `hover_mode` (a string, §7.1), +`default_drag_action` (a string), `pan_axes`/`zoom_axes`/`reset_axes` (axis-ID tuples), and `zoom_limits` (an axis-keyed magnification map) — serialize verbatim when set -and are absent otherwise; the client fills their defaults (all declared axes, -`"auto"`, `(1.0, None)`). Python validates them at chart construction, so a +and are absent otherwise; the client fills their defaults (`"closest"`, all +declared axes, `"auto"`, `(1.0, None)`). Python validates them at chart construction, so a malformed policy fails before it reaches the wire (§2.1). `Chart` writes the interaction dict in three passes: chart-level keyword @@ -44,7 +44,8 @@ together with `hover=False` yields `hover=True`. `python/xy/components.py:2437`. The boolean switches below are `Optional[bool]` and default to `None` (leave unset). "Default" is the client-side behavior when the switch is never set. The non-boolean viewport keys — `default_drag_action`, -`pan_axes`, `zoom_axes`, `zoom_limits`, and `reset_axes` — are in §2.1. +`pan_axes`, `zoom_axes`, `zoom_limits`, and `reset_axes` — are in §2.1. The +table's one string-valued row, `hover_mode`, is specified in §7.1. | Switch | Default | Effect when disabled | | --- | --- | --- | diff --git a/spec/design-dossier.md b/spec/design-dossier.md index 3a51d6ed6..5c1dc287e 100644 --- a/spec/design-dossier.md +++ b/spec/design-dossier.md @@ -717,8 +717,14 @@ Part I said "60fps" without defining what has to happen inside a frame. The budg **Hover semantics per tier** (the doc previously defined hover only for direct draws): - *Tier 0/1:* GPU pick → point ID → exact source-row readout (f64/i64, via §16). Unified hover (`hover_mode="x unified"`, interaction spec §7.1) replaces the - pick with a CPU snap along one axis — binary search on sorted columns — and - refines every reported row through the same exact pick. + pick with a CPU snap along one axis — binary search on sorted columns. With a + kernel attached it refines every reported row through the same exact pick: + one kernel `pick` per reported series each time the reported row set + changes (not per pointermove — moves along the same snapped position send + nothing), the winner live and the rest `silent`. The local f32 readout + shows first, so the ≤2-frame highlight budget holds; the exact values + arrive one round-trip later, as for a single pick. Standalone charts have + no exact upgrade. - *Tier 2 (aggregated):* the pick target is a **bin**, not a point. Hover shows bin summary (count, x/y range, aggregate value). Click-to-drill spawns a worker query that returns the top-k underlying rows from the column store — honest about diff --git a/spec/design/wire-protocol.md b/spec/design/wire-protocol.md index 56fe43b39..df8591fa3 100644 --- a/spec/design/wire-protocol.md +++ b/spec/design/wire-protocol.md @@ -570,7 +570,12 @@ Two independent version constants: **not** increment v13: it accompanies an already concrete `legend.loc`, so a cached client that does not recognize the hint renders the same correct first placement and merely forgoes later adaptive re-scoring. Ignoring it - cannot produce a structurally wrong first-paint scene. + cannot produce a structurally wrong first-paint scene. The interaction key + `hover_mode` (interaction spec §7.1) and the `pick` request's `silent` flag + likewise did **not** increment v14: a cached client ignores `hover_mode` + and draws the identical scene with closest-point hover (a missing + interaction, not a misrender), and only the client that knows + `hover_mode` ever sends `silent`, to a kernel from the same distribution. - **Transport frame.** `FRAME_MAGIC` `"XYBF"` with `FRAME_VERSION = 1` versions the binary envelope separately, so the transport and the renderer can evolve without coupling. diff --git a/spec/process/css-tailwind-surface-audit-2026-07-30.md b/spec/process/css-tailwind-surface-audit-2026-07-30.md index 4a9bf62e8..dc6ec3f39 100644 --- a/spec/process/css-tailwind-surface-audit-2026-07-30.md +++ b/spec/process/css-tailwind-surface-audit-2026-07-30.md @@ -39,7 +39,7 @@ from the same tuple, so documentation and implementation cannot drift. | Marks | Fill, stroke, fill/stroke opacity, stroke width/dash/cap where the renderer supports them, rectangle radius/wedge gap, scatter shape, and mark-specific typed channels/geometry | Root CSS variables may supply any constant CSS color expression; Tailwind can set those variables | Individual marks are WebGL pixels, not DOM. `mark(style={...})` compiles the supported CSS subset identically for WebGL, SVG, and native raster. Unsupported declarations raise. | | Axes | Gesture band, Cartesian spine, major/minor tick marks, tick labels, axis titles | `axis_band`, `axis_line`, `tick_mark`, `tick_label`, `axis_title`; `data-xy-axis`, `data-xy-axis-side`, and `data-xy-tick-kind` refine selectors | Grid lines, polar rings/spokes/frame, and static export use validated axis `style` (`grid_*`, `axis_*`, `tick_*`, label paint/type). | | Legends | Container, title, row, swatch, label | `legend`, `legend_title`, `legend_item`, `legend_swatch`, `legend_label`; state attributes expose off/hover semantics | Scatter/line SVG handles inherit fill/stroke/width/dash from the swatch slot. Placement and live toggle opacity/filter remain controller state. | -| Tooltips | Container, title, row, field label, field value | `tooltip`, `tooltip_title`, `tooltip_row`, `tooltip_label`, `tooltip_value`, `tooltip_swatch`; component-local class/style reaches the container | Tooltip position/visibility is live state. A framework-owned replacement is styled by that framework. | +| Tooltips | Container, title, row, field label, field value | `tooltip`, `tooltip_title`, `tooltip_row`, `tooltip_label`, `tooltip_value`; component-local class/style reaches the container | Tooltip position/visibility is live state. A framework-owned replacement is styled by that framework. | | Colorbars | Container, ramp/bands, extension triangles, contour lines, tick labels, minor tick marks, title | `colorbar`, `colorbar_bar`, `colorbar_extension`, `colorbar_line`, `colorbar_tick`, `colorbar_minor_tick`, `colorbar_title` | Domain, colormap, levels, orientation, ticks, extension, and contour-line values remain semantic colorbar configuration and static-writer input. | | Modebars & controls | Toolbar, drag handle, control group, separator, button, top-level icon, zoom value, chevron, active selection icon, menu, menu separator, menu icon, menu label, history group | `modebar`, `modebar_drag_handle`, `modebar_control_group`, `modebar_separator`, `modebar_button`, `modebar_icon`, `modebar_zoom_value`, `modebar_indicator`, `modebar_selection_icon`, `modebar_menu`, `modebar_menu_separator`, `modebar_menu_icon`, `modebar_menu_label`, `modebar_history_controls` | Placement, open/closed display, fit visibility, dragging, focus routing, and disabled/active state remain interaction-owned; state is exposed through classes/ARIA/data attributes. | | Annotations | Whole shape canvas and each DOM label/callout | `annotation_layer`, `annotation_label`, plus per-annotation `class_name` and label CSS style | Rule/band/arrow/marker geometry uses annotation color, width, opacity, stroke, symbol, and offsets so browser, SVG, and native PNG agree. | diff --git a/tests/test_unified_hover.py b/tests/test_unified_hover.py index f76aafcf2..882e4c29d 100644 --- a/tests/test_unified_hover.py +++ b/tests/test_unified_hover.py @@ -11,7 +11,7 @@ from __future__ import annotations -import json +import dataclasses from pathlib import Path import pytest @@ -347,16 +347,47 @@ def test_y_unified_is_the_transpose(tmp_path: Path) -> None: assert result == {key: True for key in result}, result -def test_polar_keeps_closest_hover() -> None: - chart = xy.polar_chart(xy.line([0.0, 1.0, 2.0], [1.0, 2.0, 3.0]), hover_mode="x unified") - spec = chart.figure()._interaction_spec() - # The setting rides the wire unchanged; the client resolves polar to - # closest (52_tooltip.ts `_hoverMode`), so pin that branch textually. - assert spec["hover_mode"] == "x unified" - source = (Path(__file__).resolve().parents[1] / "js" / "src" / "52_tooltip.ts").read_text() - assert 'if (this.spec?.coords === "polar") return HOVER_CLOSEST;' in source - assert 'const HOVER_CLOSEST = "closest";' in source - assert json.dumps(spec) # wire-serializable +_POLAR_PROBE = ( + _PROBE_PRELUDE + + """ + // Hover right on the r=2 point at theta=1: closest-point readout, no + // unified heading, swatches, or spike. + const [px, py] = view._projectDataPoint("x", "y", 1.0, 2.0); + move(px - view.plot.x, py - view.plot.y); + const closestReadout = shown() && view._unified == null + && !view.tooltip.querySelector('[data-xy-slot="tooltip_swatch"]'); + const noSpike = spike() === null; + const resolvedClosest = view._hoverMode() === "closest"; + document.body.setAttribute("data-xy-polar-probe", JSON.stringify({ + closestReadout, noSpike, resolvedClosest, + })); +""" + + _PROBE_CATCH % "data-xy-polar-probe" +) + + +def test_polar_keeps_closest_hover(tmp_path: Path) -> None: + chart = xy.polar_chart( + xy.scatter([0.0, 1.0, 2.0], [1.0, 2.0, 3.0], size=8), + width=480, + height=480, + hover_mode="x unified", + ) + # The setting rides the wire unchanged; the client resolves polar to closest. + assert chart.figure()._interaction_spec()["hover_mode"] == "x unified" + result = _run( + tmp_path, + chart.to_html().replace(_RENDER_CALL, _POLAR_PROBE), + "data-xy-polar-probe", + label="polar unified fallback probe", + ) + assert result == {key: True for key in result}, result + + +def test_interaction_field_is_appended_for_positional_callers() -> None: + names = [f.name for f in dataclasses.fields(xy.Interaction)] + assert names[-1] == "hover_mode" + assert names.index("crosshair") + 1 == names.index("navigation") _FILTERED_PROBE = ( @@ -465,3 +496,97 @@ def test_keyboard_readout_replaces_unified_state(tmp_path: Path) -> None: label="unified hover keyboard probe", ) assert result == {key: True for key in result}, result + + +_REBUILD_PROBE = ( + _PROBE_PRELUDE + + """ + move(pxOf(3), 4); + const before = !!view._unified && shown(); + // A full payload swap retires every trace the readout points at. + const swapped = view.updatePayload(view.spec, view._payload); + const dropped = view._unified === null && view._hoverTarget === null && !shown() + && spike().style.display === "none"; + view._destroyTransitionOldTraces(); + let drawOk = true; + try { view._drawNow(); } catch (err) { drawOk = false; } + move(pxOf(2), 4); + const rebuilt = !!view._unified && text()[0] === "Wed" + && view._unified.hits.every((h) => view.gpuTraces.includes(h.g)); + document.body.setAttribute("data-xy-rebuild-probe", JSON.stringify({ + before, swapped, dropped, drawOk, rebuilt, + })); +""" + + _PROBE_CATCH % "data-xy-rebuild-probe" +) + + +def test_payload_swap_drops_unified_hover(tmp_path: Path) -> None: + result = _run( + tmp_path, + _weekly(mark=xy.scatter, chart=xy.scatter_chart, hover_mode="x unified") + .to_html() + .replace(_RENDER_CALL, _REBUILD_PROBE), + "data-xy-rebuild-probe", + label="unified hover payload swap probe", + ) + assert result == {key: True for key in result}, result + + +_FALLBACK_PROBE = ( + _PROBE_PRELUDE + + """ + move(pxOf(3), 4); + const unified = !!view._unified; + // Nothing eligible answers (every series legend-hidden): the readout + // falls through, and its point highlights must be repainted away. + for (const g of view.gpuTraces) g._legendHidden = true; + let repaints = 0; + const real = view._drawKeepPick.bind(view); + view._drawKeepPick = () => { repaints += 1; real(); }; + move(pxOf(3), 8); + const cleared = view._unified === null && !shown() && repaints >= 1; + document.body.setAttribute("data-xy-fallback-probe", JSON.stringify({ + unified, cleared, + })); +""" + + _PROBE_CATCH % "data-xy-fallback-probe" +) + + +def test_fallback_repaints_away_unified_highlights(tmp_path: Path) -> None: + result = _run( + tmp_path, + _weekly(mark=xy.scatter, chart=xy.scatter_chart, hover_mode="x unified") + .to_html() + .replace(_RENDER_CALL, _FALLBACK_PROBE), + "data-xy-fallback-probe", + label="unified hover fallback repaint probe", + ) + assert result == {key: True for key in result}, result + + +_LATE_MODE_PROBE = ( + _PROBE_PRELUDE + + """ + // Mounted closest (no crosshair lines), then switched to unified. + const noLinesAtMount = spike() === null; + view.interaction.hover_mode = "x unified"; + move(pxOf(3), 4); + const spikeCreated = !!spike() && spike().style.display === "block"; + document.body.setAttribute("data-xy-late-mode-probe", JSON.stringify({ + noLinesAtMount, spikeCreated, + })); +""" + + _PROBE_CATCH % "data-xy-late-mode-probe" +) + + +def test_spike_lines_are_created_on_first_unified_use(tmp_path: Path) -> None: + result = _run( + tmp_path, + _weekly().to_html().replace(_RENDER_CALL, _LATE_MODE_PROBE), + "data-xy-late-mode-probe", + label="unified hover late mode probe", + ) + assert result == {key: True for key in result}, result From 68937cceb58287dd22cdc0e3edc24050ea7924d4 Mon Sep 17 00:00:00 2001 From: Farhan Date: Thu, 3 Dec 2026 20:08:26 +0000 Subject: [PATCH 05/14] Default line and area charts to x-unified hover; fix review findings Line and area charts now use hover_mode="x unified" when the mode is unset; other charts keep "closest". A chart whose tooltip sets title=, fields= or a custom render keeps closest, since those describe a single row the unified readout does not use. An explicit mode always wins. Review fixes in the unified readout: - include the winner in the readout key so crossing the midpoint between two series re-snaps the heading and spike - match kernel replies by sequence slot and trace, not index, so a canonical row index (after NaN or LOD removal) still refines - dispatch exact: true only when the winner's own row was refined - advance the pick sequence on drag starts so an in-flight reply cannot reopen a dismissed tooltip - let no off-plot candidate win the snap - set the swatch paint before slot styles so an author value wins - follow the moving row during position transitions - honor XY_REQUIRE_BROWSER in the unified-hover browser probes --- docs/components/tooltips.md | 27 +++--- docs/core-concepts/interactions.md | 5 +- js/src/52_tooltip.ts | 47 +++++++--- js/src/53_interaction.ts | 3 + news/562.feature.md | 2 +- python/xy/components.py | 28 +++++- spec/api/interaction.md | 35 ++++++-- spec/design/view-state.md | 3 +- tests/test_unified_hover.py | 133 ++++++++++++++++++++++++++++- 9 files changed, 242 insertions(+), 41 deletions(-) diff --git a/docs/components/tooltips.md b/docs/components/tooltips.md index 626973d6f..f1a08f32c 100644 --- a/docs/components/tooltips.md +++ b/docs/components/tooltips.md @@ -142,11 +142,13 @@ def tooltip_title_demo(): ## Show Every Series at One X -By default the tooltip reports the mark under the cursor, so comparing series -means hovering each point in turn. Set `hover_mode="x unified"` (Plotly's -`hovermode` spelling) and the cursor only has to be somewhere over the plot: -it snaps to the nearest x, a vertical spike line marks it, and one tooltip -lists each series that has a point there, under the x value as its heading. +Line and area charts use unified hover by default (`hover_mode="x unified"`, +Plotly's `hovermode` spelling): the cursor only has to be somewhere over the +plot. It snaps to the nearest x, a vertical spike line marks it, and one +tooltip lists each series that has a point there, under the x value as its +heading. Other charts report the mark under the cursor (`"closest"`); pass +`hover_mode="x unified"` to opt them in, or `hover_mode="closest"` to opt a +line or area chart out. Plotly's per-series `"x"`/`"y"` modes are not available; passing either raises an error naming `"x unified"`/`"y unified"`. @@ -162,7 +164,6 @@ unified_hover_chart = xy.line_chart( xy.line(unified_days, [0, 1, 4, 3, 0, 0, 0], name="Qualified held"), xy.legend(), title="Weekly momentum", - hover_mode="x unified", ) @@ -171,7 +172,7 @@ def unified_hover_demo(): ~~~ - `"x unified"` snaps along x; `"y unified"` snaps along y and draws a - horizontal spike. `"closest"` is the default. + horizontal spike. `"closest"` reports only the mark under the cursor. - Line, scatter, area, and bar/column series take part. A series whose nearest point is more than 20 px from the snapped position along the hover dimension (x for `"x unified"`, y for `"y unified"`) is left out rather than reported @@ -181,7 +182,8 @@ def unified_hover_demo(): (`tooltip_label`), and its value (`tooltip_value`). `tooltip(format=...)` keyed by `"x"`/`"y"` formats the heading and values, and `labels=` keyed by `"x"`/`"y"` names unnamed series; `title=` and `fields=` templates describe - one hovered row and are not used by the unified readout. + one hovered row and are not used by the unified readout, so a line or area + chart with either keeps `"closest"` unless you set `hover_mode` yourself. - The spike line is the crosshair line, so the `crosshair_x`/`crosshair_y` slots and the `--chart-crosshair` token style it. - The `xy:hover` event lists every reported series in `points`. Python @@ -266,10 +268,11 @@ each placeholder is replaced with the value from the hovered row. ### How do I show all series values at the hovered x, like Plotly's unified hover? -Pass `hover_mode="x unified"` to the chart, e.g. -`xy.line_chart(..., hover_mode="x unified")`. The cursor snaps to the nearest x -anywhere over the plot and one tooltip lists each series that has a point at -that x. +Line and area charts already do this by default. For other charts, pass +`hover_mode="x unified"`, e.g. `xy.scatter_chart(..., hover_mode="x unified")`. +The cursor snaps to the nearest x anywhere over the plot and one tooltip lists +each series that has a point at that x. Pass `hover_mode="closest"` to turn it +off on a line or area chart. ### How do I disable tooltips on a chart? diff --git a/docs/core-concepts/interactions.md b/docs/core-concepts/interactions.md index c127a2225..d162afb96 100644 --- a/docs/core-concepts/interactions.md +++ b/docs/core-concepts/interactions.md @@ -39,8 +39,9 @@ def browser_behavior_demo(): return reflex_xy.chart(chart, height="360px") ~~~ -`hover_mode` chooses what hover reports. The default, `"closest"`, reads the -mark under the cursor. `"x unified"` snaps to the nearest x anywhere over the +`hover_mode` chooses what hover reports. `"closest"`, the default for most +charts, reads the mark under the cursor. `"x unified"`, the default for line +and area charts, snaps to the nearest x anywhere over the plot and lists the series that have a point there in one tooltip, with a spike line at that x; `"y unified"` does the same along y. Polar charts keep `"closest"`. See diff --git a/js/src/52_tooltip.ts b/js/src/52_tooltip.ts index 414235bcd..4b25d812f 100644 --- a/js/src/52_tooltip.ts +++ b/js/src/52_tooltip.ts @@ -513,8 +513,10 @@ Object.assign(ChartView.prototype, { // legend does. The color rides a custom property so `tooltip_swatch` // styles can restyle (or replace) the chip without losing it. const swatch = document.createElement("span"); - this._applySlot(swatch, "tooltip_swatch"); + // Series paint first, so an author's `tooltip_swatch` style that + // sets `--xy-tooltip-swatch-paint` is applied after it and wins. if (item.color) swatch.style.setProperty("--xy-tooltip-swatch-paint", item.color); + this._applySlot(swatch, "tooltip_swatch"); row.appendChild(swatch); } if (item.kind === "field" || item.kind === "series") { @@ -796,6 +798,7 @@ Object.assign(ChartView.prototype, { const along = (p) => (dim === "x" ? p[0] : p[1]); const cursor = dim === "x" ? cssX : cssY; const traces = (this.gpuTraces || []).filter((g) => this._unifiedHoverable(g)); + const extent = dim === "x" ? this.plot.w : this.plot.h; let win = null; for (const g of traces) { const value = cursorValue(g, cursor); @@ -804,13 +807,15 @@ Object.assign(ChartView.prototype, { if (index < 0) continue; const p = this._unifiedPx(g, index); if (!p) continue; - const dist = Math.abs(along(p) - cursor); + // A point scrolled past the plot edge cannot be the snapped position, + // and must not shadow another series' point inside the plot. + const at = along(p); + if (at < -0.5 || at > extent + 0.5) continue; + const dist = Math.abs(at - cursor); if (!win || dist < win.dist) win = { g, index, p, dist }; } if (!win) return null; const position = along(win.p); - const extent = dim === "x" ? this.plot.w : this.plot.h; - if (position < -0.5 || position > extent + 0.5) return null; const hits = []; for (const g of traces) { let index = win.index; @@ -841,7 +846,11 @@ Object.assign(ChartView.prototype, { const found = this._unifiedHits(cssX, cssY, dim); if (!found) return false; const { hits, winner } = found; - const key = hits.map((h) => `${h.trace}:${h.index}`).join(","); + // The winner is part of the identity: two series can report the same + // rows while the snapped position (heading, spike, on_hover row) moves + // from one to the other across their midpoint. + const key = `${winner.trace}:${winner.index}|` + + hits.map((h) => `${h.trace}:${h.index}`).join(","); this._lastHoverXY = { clientX: e.clientX, clientY: e.clientY }; const g = winner.g; const xAxis = g.xAxis || "x"; @@ -854,6 +863,11 @@ Object.assign(ChartView.prototype, { if (this._tooltipAnchor) { if (dim === "x") this._tooltipAnchor.y = cursorY; else this._tooltipAnchor.x = cursorX; + // Mid-transition the same row moves, so the spike follows it; a + // settled frame keeps the (possibly exact) snapped coordinate. + if (Number.isFinite(g._transitionPositionProgress) && Number.isFinite(snapped)) { + this._tooltipAnchor[dim] = snapped; + } this._repositionTooltip(); } return true; @@ -861,7 +875,9 @@ Object.assign(ChartView.prototype, { if (this._unified || this._hoverId !== -1) this._hideTooltip(); const rows = hits.map((h) => this._localRow(h)); const winnerAt = hits.indexOf(winner); - this._unified = { dim, key, hits, rows, winnerAt, pending: 0, pickBase: -1 }; + this._unified = { + dim, key, hits, rows, winnerAt, pending: 0, pickBase: -1, winnerExact: false, + }; this._hoverId = winner.trace * 1e9 + winner.index; this._hoverTarget = winner; this._lastRow = rows[winnerAt]; @@ -1046,20 +1062,24 @@ Object.assign(ChartView.prototype, { // Exact f64 replacement for one row of the unified readout (§16). A null // row (a drill swap raced the pick) keeps the instant local value rather - // than collapsing the whole readout. + // than collapsing the whole readout. The reply is matched to its row by + // sequence slot and trace, not index: the kernel answers with the canonical + // row index, which differs from the shipped one once NaN rows or an LOD + // subset were dropped from the shipped copy (interaction.py `resolve_pick`). _applyUnifiedPick(msg) { const state = this._unified; const k = msg.seq - state.pickBase; state.pending = Math.max(0, state.pending - 1); const local = state.rows[k]; const exact = msg.row && this._normalizePickRow(msg.row); - if (exact && local && exact.trace === local.trace && exact.index === local.index) { + if (exact && local && exact.trace === local.trace) { for (const [key, value] of Object.entries(local)) { if (exact[key] === undefined) exact[key] = value; } this._applySharedTooltipFields(exact); state.rows[k] = exact; if (k === state.winnerAt) { + state.winnerExact = true; this._lastRow = exact; const snapped = exact[state.dim]; if (this._tooltipAnchor && typeof snapped === "number" && Number.isFinite(snapped)) { @@ -1068,13 +1088,18 @@ Object.assign(ChartView.prototype, { } this._renderUnifiedTooltip({ announce: false }); } - if (state.pending === 0 && this._interactionFlag("hover") && this._lastHoverXY) { + // One exact event once every row answered — only when the winner's own + // row was refined, so `exact: true` never labels an approximate row (a + // null winner reply leaves the instant event standing, as closest does). + if (state.pending === 0 && state.winnerExact && this._interactionFlag("hover") + && this._lastHoverXY) { const xy = this._lastHoverXY; const winner = state.hits[state.winnerAt]; + const row = state.rows[state.winnerAt]; this._dispatchChartEvent("hover", { - row: state.rows[state.winnerAt], + row, trace: winner.trace, - index: winner.index, + index: row.index, exact: true, view: this._eventView("hover"), ...this._unifiedHoverPayload(xy.clientX, xy.clientY, true), diff --git a/js/src/53_interaction.ts b/js/src/53_interaction.ts index 513d7c768..7df722316 100644 --- a/js/src/53_interaction.ts +++ b/js/src/53_interaction.ts @@ -112,6 +112,7 @@ Object.assign(ChartView.prototype, { cancelLassoHandleDrag, ); handle.dataset.xyActive = ""; + this._pickSeq = (this._pickSeq || 0) + 1; // a reply in flight must not reopen it this._hideTooltip(); e.preventDefault(); e.stopPropagation(); @@ -263,6 +264,7 @@ Object.assign(ChartView.prototype, { replacingLasso: false, }; band.capture = this._captureGesturePointer(c, e, endGestureWithoutRelease); + this._pickSeq = (this._pickSeq || 0) + 1; // a reply in flight must not reopen it this._hideTooltip(); return; } @@ -283,6 +285,7 @@ Object.assign(ChartView.prototype, { changedAxes: [], }; drag.capture = this._captureGesturePointer(c, e, endGestureWithoutRelease); + this._pickSeq = (this._pickSeq || 0) + 1; // a reply in flight must not reopen it this._hideTooltip(); } }); diff --git a/news/562.feature.md b/news/562.feature.md index e0b42d91e..a4dcfdc5b 100644 --- a/news/562.feature.md +++ b/news/562.feature.md @@ -1 +1 @@ -Add `hover_mode="x unified"` and `"y unified"` (Plotly's `hovermode`) to charts and `xy.interaction_config`. The cursor no longer has to sit on a point: it snaps to the nearest x anywhere over the plot, a spike line marks that x, and one tooltip lists each line, scatter, area, or bar series with a point there, with a color chip (new `tooltip_swatch` slot). Polar charts keep closest-point hover. Sorted series snap with a binary search, and live kernels refine every row to exact f64 values while `on_hover` still fires once per hover. +Add `hover_mode="x unified"` and `"y unified"` (Plotly's `hovermode`) to charts and `xy.interaction_config`. The cursor no longer has to sit on a point: it snaps to the nearest x anywhere over the plot, a spike line marks that x, and one tooltip lists each line, scatter, area, or bar series with a point there, with a color chip (new `tooltip_swatch` slot). Line and area charts now use `"x unified"` by default (pass `hover_mode="closest"` to keep the old behavior); other charts, and line or area charts whose tooltip sets `title=`, `fields=` or a custom `render`, keep `"closest"`. Polar charts keep closest-point hover. Sorted series snap with a binary search, and live kernels refine every row to exact f64 values while `on_hover` still fires once per hover. diff --git a/python/xy/components.py b/python/xy/components.py index 7d4af4280..65cc216cd 100644 --- a/python/xy/components.py +++ b/python/xy/components.py @@ -168,6 +168,10 @@ "auto", "none", "pan", "zoom", "select", "select-x", "select-y", "select-lasso" ] HoverMode: TypeAlias = Literal["closest", "x unified", "y unified"] +#: Chart kinds whose unset `hover_mode` defaults to ``"x unified"``: their +#: series share x positions, so one readout per x is the useful hover +#: (interaction spec §7.1). Every other chart defaults to ``"closest"``. +_UNIFIED_HOVER_DEFAULT_KINDS = frozenset({"line_chart", "area_chart"}) ZoomLimit: TypeAlias = tuple[Optional[float], Optional[float]] ZoomLimits: TypeAlias = Union[ZoomLimit, Mapping[str, ZoomLimit]] @@ -3731,8 +3735,9 @@ def __init__( select: Whether shift-drag box selection is enabled. brush: Whether brush selection is enabled. crosshair: Whether plot-aligned hover guides are shown. - hover_mode: ``"closest"`` (default), ``"x unified"``, or - ``"y unified"``; see :func:`interaction_config`. + hover_mode: ``"closest"``, ``"x unified"``, or ``"y unified"``; + see :func:`interaction_config`. Unset, line and area charts + use ``"x unified"`` and every other chart ``"closest"``. navigation: Whether browser pan and zoom navigation is enabled. pan: Whether plain-drag panning is enabled. pan_axes: Declared axis IDs translated by pan gestures. @@ -3981,6 +3986,12 @@ def figure(self) -> Figure: link_axes=node.link_axes, history=node.history, ) + if ( + "hover_mode" not in fig.interaction + and self.kind in _UNIFIED_HOVER_DEFAULT_KINDS + and not _tooltip_is_per_row(tooltips) + ): + fig.set_interaction(hover_mode="x unified") fig.set_interaction( hover=True if self.on_hover is not None else None, click=True if self.on_click is not None else None, @@ -5259,6 +5270,19 @@ def _apply_chrome_node( fig.chrome_styles[slot] = {**fig.chrome_styles.get(slot, {}), **style} +def _tooltip_is_per_row(tooltips: list[Tooltip]) -> bool: + """Whether the effective tooltip is written for one row at a time. + + A ``title``/``fields`` template or a custom ``render`` describes a single + hovered row, which the unified readout does not use, so such a chart keeps + ``"closest"`` unless it asks for a unified mode explicitly. + """ + if not tooltips: + return False + node = tooltips[-1] + return bool(node.fields) or node.title is not None or node.render is not None + + def _tooltip_spec( node: Tooltip, aliases: dict[str, str], diff --git a/spec/api/interaction.md b/spec/api/interaction.md index 287635d0a..883c60c2a 100644 --- a/spec/api/interaction.md +++ b/spec/api/interaction.md @@ -54,7 +54,7 @@ table's one string-valued row, `hover_mode`, is specified in §7.1. | `select` | on | Suppresses the `xy:select` event and the `select_clear` message, removes the modebar Selection menu, and (with `brush`) disables shift-drag. | | `brush` | on | Same conjunction: `canBrush = brush && select` (`53_interaction.ts:115`) gates every selection drag and the modebar Selection menu. | | `crosshair` | off | The two guide elements are created only when the flag is true (or `hover_mode` is unified, which borrows one as its spike line, §7.1), at init (`53_interaction.ts`). Not togglable after mount. | -| `hover_mode` | `"closest"` | Not a boolean: `"closest"`, `"x unified"`, or `"y unified"` (Plotly's `hovermode` spelling). Unified modes are specified in §7.1. Validated at construction; Plotly's per-series `"x"`/`"y"` modes raise with a pointer to the unified spelling. Polar charts resolve to `"closest"` client-side. Not togglable after mount. | +| `hover_mode` | `"x unified"` for `line_chart`/`area_chart`, else `"closest"` | Not a boolean: `"closest"`, `"x unified"`, or `"y unified"` (Plotly's `hovermode` spelling). Unified modes are specified in §7.1. Validated at construction; Plotly's per-series `"x"`/`"y"` modes raise with a pointer to the unified spelling. Polar charts resolve to `"closest"` client-side. Not togglable after mount. | | `navigation` | on | Master gate on pointer-drag pan, wheel zoom, box-zoom drags, dblclick reset, and every modebar viewport control. Selection-mode double-click clear is a selection action and is unaffected. | | `pan` | on | Plain-drag pan is ignored, the modebar Pan button is not built, and every zoom-enabled axis is contained (§2.2). Requires `navigation`. Pans `pan_axes` (§2.1). | | `zoom` | on | Master zoom gate: wheel zoom, box zoom, and the zoom actions inside the modebar menu are all ignored. The same dropdown can remain for view history when `history` is on. Requires `navigation`. Zooms `zoom_axes` (§2.1). | @@ -407,6 +407,15 @@ does not need to touch a mark. Implementation: `js/src/52_tooltip.ts` (`_unifiedHits`, `_unifiedHover`), wired from `_hover` in `50_chartview.ts`. `"y unified"` is the same contract with the axes swapped. +- **Default.** An unset `hover_mode` resolves in `Chart.figure()` + (`components.py`): `line_chart` and `area_chart` get `"x unified"`, because + their series share x positions; every other chart kind stays `"closest"`. + A chart whose effective `tooltip()` sets `title=`, `fields=`, or a custom + `render` also stays `"closest"`, since those describe one hovered row and + the unified readout does not use them. An explicit value from the chart + prop or `interaction_config` always wins. The internal `Figure` and the + matplotlib shim have no per-kind default (`"closest"`). + - **Eligible series.** Plain (x, y) marks with a retained CPU column: line, scatter, area, bar/column. Rect marks (histogram, box), ribbons, funnels, heatmaps, segments, density tiers, legend-hidden series, and `error_band` @@ -415,8 +424,9 @@ does not need to touch a mark. Implementation: `js/src/52_tooltip.ts` - **Snap.** Pass 1: every eligible series finds its row nearest the cursor along the hover dimension (in axis-coordinate space, so log axes snap by screen distance); the row nearest in pixels wins and fixes the hover - position. There is no distance cap on the winner — anywhere over the plot - snaps. Pass 2: every series reports its row nearest that position, kept only + position. A candidate outside the plot rect (scrolled past an edge) cannot + win, so it never shadows another series' point inside the plot. There is no + distance cap on the winner — anywhere over the plot snaps. Pass 2: every series reports its row nearest that position, kept only within 20 CSS px of it (Plotly's default `hoverdistance`), so a series that ends early or samples elsewhere is not reported as if it were at that x. Rows hidden by a legend category filter never answer. @@ -429,7 +439,8 @@ does not need to touch a mark. Implementation: `js/src/52_tooltip.ts` category label, or the value formatted with `tooltip(format={"x": ...})` when set). One `series` row per reported series in trace order: a `tooltip_swatch` chip painted with the series color (via - `--xy-tooltip-swatch-paint`), the series name (or the other axis's tooltip + `--xy-tooltip-swatch-paint`, set before the slot's `styles` so an author + value for that property wins), the series name (or the other axis's tooltip label, defaulting to `"y"`/`"x"`) in `tooltip_label`, and its value in `tooltip_value`. Rows with an identical name, value, and color collapse (one composed series drawn as two marks). @@ -453,10 +464,18 @@ does not need to touch a mark. Implementation: `js/src/52_tooltip.ts` every reported series, and `hover_mode` names the mode. With a kernel attached the client sends one `pick` per row on consecutive `seq` values; all but the winner's carry `silent: true`, so Python `on_hover` still fires - once per hover. Each `pick_result` refines its own row in place (a `null` - row keeps the local value). When every row has answered, one `exact: true` - `xy:hover` carries all of them. Replies for an abandoned readout are - ignored. + once per hover. Each `pick_result` refines its own row in place, matched by + its sequence slot and trace — not by index, because the kernel answers with + the canonical row index, which differs from the shipped one once NaN rows + or an LOD subset were dropped. A `null` row keeps the local value. When + every row has answered and the winner's own row was refined, one + `exact: true` `xy:hover` carries all of them (with the winner's canonical + `index`); a `null` winner reply sends no exact event, as in closest mode. + The readout's identity includes the winner, so crossing the midpoint + between two series that report the same rows re-snaps. Replies for an + abandoned readout are ignored; Escape, pointer leave, and every drag start + (pan, box, lasso handle) advance the pick sequence so an in-flight reply + cannot reopen a dismissed readout. - **Unchanged.** Click picks the mark under the cursor; keyboard traversal walks points one at a time (§8). Standalone HTML keeps unified hover from its retained CPU columns. diff --git a/spec/design/view-state.md b/spec/design/view-state.md index 03d97d9ad..661eef46f 100644 --- a/spec/design/view-state.md +++ b/spec/design/view-state.md @@ -312,7 +312,8 @@ on static/standalone charts `points[].row` comes from browser-resident data with no exact upgrade — the same honesty rule the LOD tiers follow. Under a unified `hover_mode` (interaction spec §7.1) `points` lists every series reported at the snapped position, the payload adds `"hover_mode"`, -and the `exact: true` re-dispatch waits until every row's pick has answered. +and the `exact: true` re-dispatch waits until every row's pick has answered +(and is skipped when the winner's own reply came back `null`). **The active flag is trustworthy.** `active: true` is always eventually followed by an `active: false` when the pointer leaves the chart, even when diff --git a/tests/test_unified_hover.py b/tests/test_unified_hover.py index 882e4c29d..63a4adfc0 100644 --- a/tests/test_unified_hover.py +++ b/tests/test_unified_hover.py @@ -12,6 +12,7 @@ from __future__ import annotations import dataclasses +import os from pathlib import Path import pytest @@ -53,8 +54,45 @@ def test_hover_mode_reaches_the_wire_from_chart_and_config(mode: str) -> None: assert by_config["hover_mode"] == mode -def test_hover_mode_is_absent_until_set() -> None: - assert "hover_mode" not in _weekly().figure()._interaction_spec() +def _mode(chart: xy.Chart) -> str | None: + return chart.figure()._interaction_spec().get("hover_mode") + + +@pytest.mark.parametrize("chart", [xy.line_chart, xy.area_chart]) +def test_line_and_area_charts_default_to_x_unified(chart) -> None: + mark = xy.area if chart is xy.area_chart else xy.line + assert _mode(_weekly(mark=mark, chart=chart)) == "x unified" + + +@pytest.mark.parametrize("chart", [xy.scatter_chart, xy.bar_chart]) +def test_other_charts_leave_hover_mode_unset(chart) -> None: + mark = xy.bar if chart is xy.bar_chart else xy.scatter + assert _mode(_weekly(mark=mark, chart=chart)) is None + + +def test_explicit_closest_overrides_the_line_default() -> None: + assert _mode(_weekly(hover_mode="closest")) == "closest" + assert _mode(_weekly(xy.interaction_config(hover_mode="closest"))) == "closest" + + +@pytest.mark.parametrize( + "tooltip", + [ + xy.tooltip(title="Day {x}"), + xy.tooltip(fields=["y"]), + xy.tooltip(render=lambda row: row), + ], + ids=["title", "fields", "render"], +) +def test_per_row_tooltips_keep_closest_on_line_charts(tooltip) -> None: + # A one-row template is ignored by the unified readout, so the default + # does not silently drop it; an explicit mode still wins. + assert _mode(_weekly(tooltip)) is None + assert _mode(_weekly(tooltip, hover_mode="x unified")) == "x unified" + + +def test_format_only_tooltip_keeps_the_unified_default() -> None: + assert _mode(_weekly(xy.tooltip(format={"y": ".1f"}))) == "x unified" @pytest.mark.parametrize("bad", ["x", "y", "unified", "X Unified", True, 1]) @@ -90,6 +128,10 @@ def test_silent_pick_refines_without_firing_on_hover() -> None: def _run(tmp_path: Path, document: str, attribute: str, label: str) -> dict: chromium = find_chromium() if chromium is None: + # `run_browser_probe` enforces XY_REQUIRE_BROWSER, so a skip before + # reaching it must honor the variable too. + if os.environ.get("XY_REQUIRE_BROWSER"): + pytest.fail(f"{label}: XY_REQUIRE_BROWSER is set but no chromium was found") pytest.skip("Chromium unavailable") return run_browser_probe( chromium, document, tmp_path / f"{attribute}.html", attribute, label=label @@ -254,7 +296,7 @@ def test_x_unified_refines_each_row_from_kernel_picks(tmp_path: Path) -> None: def test_closest_mode_is_unchanged(tmp_path: Path) -> None: result = _run( tmp_path, - _weekly().to_html().replace(_RENDER_CALL, _CLOSEST_PROBE), + _weekly(hover_mode="closest").to_html().replace(_RENDER_CALL, _CLOSEST_PROBE), "data-xy-closest-probe", label="closest hover probe", ) @@ -585,8 +627,91 @@ def test_fallback_repaints_away_unified_highlights(tmp_path: Path) -> None: def test_spike_lines_are_created_on_first_unified_use(tmp_path: Path) -> None: result = _run( tmp_path, - _weekly().to_html().replace(_RENDER_CALL, _LATE_MODE_PROBE), + _weekly(hover_mode="closest").to_html().replace(_RENDER_CALL, _LATE_MODE_PROBE), "data-xy-late-mode-probe", label="unified hover late mode probe", ) assert result == {key: True for key in result}, result + + +_REVIEW_PROBE = ( + _PROBE_PRELUDE + + """ + const at = (v) => view._projectDataPoint("x", "y", v, 0)[0] - view.plot.x; + const low = view.plot.h - 2; + + // Two series 0.2 apart report the same rows on both sides of their + // midpoint; the heading (the winner) must still follow the cursor. + move(at(5.0) + 1, low); + const headingA = text()[0]; + move(at(5.2) - 1, low); + const headingB = text()[0]; + const winnerFollowsCursor = headingA === "5" && headingB === "5.2"; + + // An author's swatch paint beats the series color. + const swatch = view.tooltip.querySelector('[data-xy-slot="tooltip_swatch"]'); + const authorPaintWins = !!swatch + && swatch.style.getPropertyValue("--xy-tooltip-swatch-paint").trim() === "rgb(1, 2, 3)"; + + // At the left plot edge, A's nearest point (x=0.45) is scrolled out of + // view; B's point inside the plot must still answer. + move(0, low); + const edgeHeading = view._unified ? text()[0] : null; + const edgeKeepsUnified = edgeHeading === "0.6"; + + // Kernel replies carry the canonical row index, which can differ from the + // shipped one; the reply is matched by its sequence slot. + const sent = []; + view.comm = { send: (m) => sent.push(m) }; + move(at(9.8) - 1, low); + let picks = sent.filter((m) => m.type === "pick"); + const winnerSlot = picks.findIndex((m) => m.silent !== true); + const other = picks[1 - winnerSlot]; + view._onKernelMsg({ type: "pick_result", seq: other.seq, + row: { trace: other.trace, index: other.index + 40, x: 9.6, y: 3.25 } }, []); + const canonicalIndexRefines = text().some((t) => t.endsWith("3.25")); + // A null reply for the winner leaves no row to call exact. + const exactBefore = hovers.filter((d) => d.exact).length; + view._onKernelMsg({ type: "pick_result", seq: picks[winnerSlot].seq, row: null }, []); + const noExactWithoutWinner = hovers.filter((d) => d.exact).length === exactBefore; + + // A drag that starts while picks are in flight must stay dismissed. + sent.length = 0; + move(at(5.0) + 1, low); + picks = sent.filter((m) => m.type === "pick"); + c.dispatchEvent(new PointerEvent("pointerdown", { + clientX: r.left + at(5.0) + 1, clientY: r.top + low, button: 0, buttons: 1, + pointerId: 1, bubbles: true, cancelable: true, + })); + const last = picks[picks.length - 1]; + view._onKernelMsg({ type: "pick_result", seq: last.seq, + row: { trace: last.trace, index: last.index, x: 5.2, y: 5 } }, []); + const dragStaysDismissed = !shown(); + + document.body.setAttribute("data-xy-review-probe", JSON.stringify({ + winnerFollowsCursor, headingA, headingB, authorPaintWins, edgeKeepsUnified, + edgeHeading, canonicalIndexRefines, noExactWithoutWinner, dragStaysDismissed, + })); +""" + + _PROBE_CATCH % "data-xy-review-probe" +) + + +def test_unified_review_edge_cases(tmp_path: Path) -> None: + chart = xy.line_chart( + xy.line([0.45, 5.0, 9.6], [1, 2, 3], name="A"), + xy.line([0.6, 5.2, 9.8], [4, 5, 6], name="B"), + xy.x_axis(domain=(0.5, 10.0)), + width=640, + height=360, + hover=True, + styles={"tooltip_swatch": {"--xy-tooltip-swatch-paint": "rgb(1, 2, 3)"}}, + ) + result = _run( + tmp_path, + chart.to_html().replace(_RENDER_CALL, _REVIEW_PROBE), + "data-xy-review-probe", + label="unified hover review probe", + ) + checks = {k: v for k, v in result.items() if k not in {"headingA", "headingB", "edgeHeading"}} + assert checks == {key: True for key in checks}, result From 90cdb1ee7d48d54b5d9df2e0f1ca061e54945d9e Mon Sep 17 00:00:00 2001 From: Farhan Date: Thu, 3 Dec 2026 20:12:24 +0000 Subject: [PATCH 06/14] Clarify unified-hover labels, hover distance, and y-unified wording in docs --- docs/components/tooltips.md | 8 +++++--- news/562.feature.md | 2 +- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/components/tooltips.md b/docs/components/tooltips.md index f1a08f32c..3faeed78e 100644 --- a/docs/components/tooltips.md +++ b/docs/components/tooltips.md @@ -180,8 +180,10 @@ def unified_hover_demo(): closest-point hover. - Each row shows a color chip (`tooltip_swatch` slot), the series name (`tooltip_label`), and its value (`tooltip_value`). `tooltip(format=...)` - keyed by `"x"`/`"y"` formats the heading and values, and `labels=` keyed by - `"x"`/`"y"` names unnamed series; `title=` and `fields=` templates describe + keyed by `"x"`/`"y"` formats the heading and values. A series' name labels + its row; for an unnamed series, `labels=` supplies the label from the other + axis (`labels["y"]` under `"x unified"`, `labels["x"]` under `"y unified"`). + `title=` and `fields=` templates describe one hovered row and are not used by the unified readout, so a line or area chart with either keeps `"closest"` unless you set `hover_mode` yourself. - The spike line is the crosshair line, so the `crosshair_x`/`crosshair_y` @@ -271,7 +273,7 @@ each placeholder is replaced with the value from the hovered row. Line and area charts already do this by default. For other charts, pass `hover_mode="x unified"`, e.g. `xy.scatter_chart(..., hover_mode="x unified")`. The cursor snaps to the nearest x anywhere over the plot and one tooltip lists -each series that has a point at that x. Pass `hover_mode="closest"` to turn it +each series whose nearest point is within 20 px of that x. Pass `hover_mode="closest"` to turn it off on a line or area chart. ### How do I disable tooltips on a chart? diff --git a/news/562.feature.md b/news/562.feature.md index a4dcfdc5b..616c3eab1 100644 --- a/news/562.feature.md +++ b/news/562.feature.md @@ -1 +1 @@ -Add `hover_mode="x unified"` and `"y unified"` (Plotly's `hovermode`) to charts and `xy.interaction_config`. The cursor no longer has to sit on a point: it snaps to the nearest x anywhere over the plot, a spike line marks that x, and one tooltip lists each line, scatter, area, or bar series with a point there, with a color chip (new `tooltip_swatch` slot). Line and area charts now use `"x unified"` by default (pass `hover_mode="closest"` to keep the old behavior); other charts, and line or area charts whose tooltip sets `title=`, `fields=` or a custom `render`, keep `"closest"`. Polar charts keep closest-point hover. Sorted series snap with a binary search, and live kernels refine every row to exact f64 values while `on_hover` still fires once per hover. +Add `hover_mode="x unified"` and `"y unified"` (Plotly's `hovermode`) to charts and `xy.interaction_config`. The cursor no longer has to sit on a point: `"x unified"` snaps to the nearest x anywhere over the plot and marks it with a vertical spike line, and `"y unified"` does the same along y with a horizontal one. One tooltip lists each line, scatter, area, or bar series with a point within 20 px of that position, with a color chip (new `tooltip_swatch` slot). Line and area charts now use `"x unified"` by default (pass `hover_mode="closest"` to keep the old behavior); other charts, and line or area charts whose tooltip sets `title=`, `fields=` or a custom `render`, keep `"closest"`. Polar charts keep closest-point hover. Sorted series snap with a binary search, and live kernels refine every row to exact f64 values while `on_hover` still fires once per hover. From 48b9f945fb180d874c1255bc3b0e5b559fa67a02 Mon Sep 17 00:00:00 2001 From: Farhan Date: Thu, 3 Dec 2026 20:15:21 +0000 Subject: [PATCH 07/14] Resolve unified-hover labels and formats through source-column aliases Line charts now default to unified hover, so tooltip(labels=..., format=...) keyed by the source column (e.g. "revenue") must keep working there as it does in the closest-point readout. --- docs/components/tooltips.md | 14 ++++++++------ js/src/52_tooltip.ts | 13 +++++++++++-- spec/api/interaction.md | 7 +++++-- tests/test_unified_hover.py | 34 ++++++++++++++++++++++++++++++++++ 4 files changed, 58 insertions(+), 10 deletions(-) diff --git a/docs/components/tooltips.md b/docs/components/tooltips.md index 3faeed78e..d2bbd3303 100644 --- a/docs/components/tooltips.md +++ b/docs/components/tooltips.md @@ -180,12 +180,14 @@ def unified_hover_demo(): closest-point hover. - Each row shows a color chip (`tooltip_swatch` slot), the series name (`tooltip_label`), and its value (`tooltip_value`). `tooltip(format=...)` - keyed by `"x"`/`"y"` formats the heading and values. A series' name labels - its row; for an unnamed series, `labels=` supplies the label from the other - axis (`labels["y"]` under `"x unified"`, `labels["x"]` under `"y unified"`). - `title=` and `fields=` templates describe - one hovered row and are not used by the unified readout, so a line or area - chart with either keeps `"closest"` unless you set `hover_mode` yourself. + formats the heading and values. A series' name labels its row; for an + unnamed series, `labels=` supplies the label from the other axis + (`labels["y"]` under `"x unified"`, `labels["x"]` under `"y unified"`). Both + accept the channel name or the source column, e.g. + `xy.tooltip(labels={"revenue": "Revenue"}, format={"revenue": ".1f"})`. + `title=` and `fields=` templates describe one hovered row and are not used + by the unified readout, so a line or area chart with either keeps + `"closest"` unless you set `hover_mode` yourself. - The spike line is the crosshair line, so the `crosshair_x`/`crosshair_y` slots and the `--chart-crosshair` token style it. - The `xy:hover` event lists every reported series in `points`. Python diff --git a/js/src/52_tooltip.ts b/js/src/52_tooltip.ts index 4b25d812f..01dc727c3 100644 --- a/js/src/52_tooltip.ts +++ b/js/src/52_tooltip.ts @@ -923,18 +923,27 @@ Object.assign(ChartView.prototype, { const tooltip = this.spec.tooltip || {}; const formats = tooltip.format || {}; const labels = tooltip.labels || {}; + const aliases = tooltip.aliases || {}; const dim = state.dim; const other = dim === "x" ? "y" : "x"; + // Keys may name the channel ("y") or the source column bound to it + // ("revenue"), exactly as the closest-point readout resolves labels. + const formatFor = (channel) => { + for (const [field, alias] of Object.entries(aliases)) { + if (alias === channel && typeof formats[field] === "string") return formats[field]; + } + return formats[channel]; + }; const text = (row, channel) => { const value = row[channel]; if (value === undefined || value === null) return null; if (typeof value === "string") return value; - return this._formatTooltipValue(value, row[`${channel}_kind`], formats[channel]); + return this._formatTooltipValue(value, row[`${channel}_kind`], formatFor(channel)); }; const items = []; const heading = text(state.rows[state.winnerAt], dim); if (heading) items.push({ kind: "title", value: heading }); - const fallbackLabel = typeof labels[other] === "string" ? labels[other] : other; + const fallbackLabel = this._defaultTooltipLabel(other, other, labels, aliases).label; const seen = new Set(); state.rows.forEach((row, k) => { const value = text(row, other); diff --git a/spec/api/interaction.md b/spec/api/interaction.md index 883c60c2a..b894faca3 100644 --- a/spec/api/interaction.md +++ b/spec/api/interaction.md @@ -442,8 +442,11 @@ does not need to touch a mark. Implementation: `js/src/52_tooltip.ts` `--xy-tooltip-swatch-paint`, set before the slot's `styles` so an author value for that property wins), the series name (or the other axis's tooltip label, defaulting to `"y"`/`"x"`) in `tooltip_label`, and its value in - `tooltip_value`. Rows with an identical name, value, and color collapse - (one composed series drawn as two marks). + `tooltip_value`. `format=` and `labels=` keys may name the channel + (`"x"`/`"y"`) or the source column bound to it (`"revenue"`, via the + tooltip `aliases`), resolved as the closest-point readout resolves labels + (`_defaultTooltipLabel`). Rows with an identical name, value, and color + collapse (one composed series drawn as two marks). - **Spike and placement.** The hover-dimension crosshair line (`crosshair_x` for x unified) is the spike: it marks the snapped position across the plot and is styled by the existing crosshair slot and `--chart-crosshair` token. diff --git a/tests/test_unified_hover.py b/tests/test_unified_hover.py index 63a4adfc0..e6d2edd29 100644 --- a/tests/test_unified_hover.py +++ b/tests/test_unified_hover.py @@ -715,3 +715,37 @@ def test_unified_review_edge_cases(tmp_path: Path) -> None: ) checks = {k: v for k, v in result.items() if k not in {"headingA", "headingB", "edgeHeading"}} assert checks == {key: True for key in checks}, result + + +_SOURCE_KEYS_PROBE = ( + _PROBE_PRELUDE + + """ + const at = (v) => view._projectDataPoint("x", "y", v, 0)[0] - view.plot.x; + move(at(1), 4); + document.body.setAttribute("data-xy-source-keys-probe", JSON.stringify({ + lines: text(), + })); +""" + + _PROBE_CATCH % "data-xy-source-keys-probe" +) + + +def test_unified_readout_honors_source_column_labels_and_formats(tmp_path: Path) -> None: + # Line charts default to unified hover, so a tooltip keyed by the source + # column (as the closest readout accepts) must keep naming and formatting + # the unnamed series. + data = {"day": [1, 2, 3], "revenue": [1.234, 2.5, 3.75]} + chart = xy.line_chart( + xy.line(x="day", y="revenue", data=data), + xy.tooltip(labels={"revenue": "Revenue"}, format={"revenue": ".1f"}), + width=640, + height=360, + ) + assert _mode(chart) == "x unified" + result = _run( + tmp_path, + chart.to_html().replace(_RENDER_CALL, _SOURCE_KEYS_PROBE), + "data-xy-source-keys-probe", + label="unified hover source-key probe", + ) + assert result["lines"] == ["1", "Revenue1.2"], result From 1bb3b0a9ffdf741bef4040bf1572cbad315a74ac Mon Sep 17 00:00:00 2001 From: Farhan Date: Thu, 3 Dec 2026 20:18:45 +0000 Subject: [PATCH 08/14] Match closest-mode exact replies to the hovered row by trace The kernel answers a pick with the canonical row index, which differs from the shipped index once NaN rows or an LOD subset were dropped. Comparing the two skipped the merge of the hovered row's fields, so a same-trace tooltip field was re-read at the canonical index, from a different shipped row. The reply's seq already ties it to the current hover, so match by trace. --- js/src/54_kernel.ts | 8 ++++++- spec/api/interaction.md | 7 +++++- tests/test_unified_hover.py | 44 +++++++++++++++++++++++++++++++++++++ 3 files changed, 57 insertions(+), 2 deletions(-) diff --git a/js/src/54_kernel.ts b/js/src/54_kernel.ts index 1cc303bfe..254f40262 100644 --- a/js/src/54_kernel.ts +++ b/js/src/54_kernel.ts @@ -882,8 +882,14 @@ Object.assign(ChartView.prototype, { // while the pick was in flight) has no mapping source and describes a // mark that no longer exists — a miss. if (!this._normalizePickRow(msg.row)) { this._hideTooltip(); return; } + // The sequence check above already ties this reply to the current + // hover, so match the local row by trace alone: the kernel answers with + // the canonical row index, which differs from the shipped one once NaN + // rows or an LOD subset were dropped (interaction.py `resolve_pick`). + // Comparing indices would skip the merge and re-read same-trace fields + // at the canonical index, i.e. from a different shipped row. const local = this._lastRow; - if (local && local.trace === msg.row.trace && local.index === msg.row.index) { + if (local && local.trace === msg.row.trace) { for (const [key, value] of Object.entries(local)) { if (msg.row[key] === undefined) msg.row[key] = value; } diff --git a/spec/api/interaction.md b/spec/api/interaction.md index b894faca3..f53bcbc25 100644 --- a/spec/api/interaction.md +++ b/spec/api/interaction.md @@ -383,7 +383,12 @@ The hover tooltip is anchored in data space, not at the cursor trace's own axis pair. Category rows carry labels rather than numbers, so their numeric anchor is derived from the pick position instead. The kernel's exact-pick reply sharpens the f32-decoded anchor to full f64 - (dossier §16). + (dossier §16). The reply's `seq` ties it to the current hover, so it keeps + the fields already resolved for the hovered row when its trace matches. + It does not compare row indices: the reply carries the canonical index, + which differs from the shipped one once NaN rows or an LOD subset were + dropped. Without the merge, a same-trace field would be re-read from a + different shipped row. - Every draw reprojects the anchor, so the tooltip rides its point through pans, zooms, and reset animations — including view changes that happen without a pointermove: modebar Reset View, dblclick home, wheel zoom, and diff --git a/tests/test_unified_hover.py b/tests/test_unified_hover.py index e6d2edd29..80768b154 100644 --- a/tests/test_unified_hover.py +++ b/tests/test_unified_hover.py @@ -749,3 +749,47 @@ def test_unified_readout_honors_source_column_labels_and_formats(tmp_path: Path) label="unified hover source-key probe", ) assert result["lines"] == ["1", "Revenue1.2"], result + + +_CLOSEST_CANONICAL_PROBE = ( + _PROBE_PRELUDE + + """ + const sent = []; + view.comm = { send: (m) => sent.push(m) }; + const [px, py] = view._projectDataPoint("x", "y", 2, 20); + move(px - view.plot.x, py - view.plot.y); + const pick = sent.find((m) => m.type === "pick"); + const before = text()[0]; + // The kernel answers with the canonical row: the NaN row 0 was dropped + // from the shipped copy, so it is one past the shipped index. + view._onKernelMsg({ type: "pick_result", seq: pick.seq, + row: { trace: pick.trace, index: pick.index + 1, x: 2, y: 20 } }, []); + document.body.setAttribute("data-xy-closest-canonical-probe", JSON.stringify({ + before, after: text()[0], shipped: pick.index, + })); +""" + + _PROBE_CATCH % "data-xy-closest-canonical-probe" +) + + +def test_closest_exact_reply_keeps_the_hovered_rows_fields(tmp_path: Path) -> None: + # The kernel's canonical index can differ from the shipped one (NaN rows + # are dropped before shipping, §19). The reply answers the current hover, + # so a field resolved for the hovered row must not be re-read at the + # canonical index, which names a different shipped row. + data = {"day": [0, 1, 2, 3], "revenue": [float("nan"), 10.0, 20.0, 30.0]} + chart = xy.line_chart( + xy.line(x="day", y="revenue", data=data), + xy.tooltip(title="{revenue}"), + width=640, + height=360, + hover=True, + ) + assert _mode(chart) is None + result = _run( + tmp_path, + chart.to_html().replace(_RENDER_CALL, _CLOSEST_CANONICAL_PROBE), + "data-xy-closest-canonical-probe", + label="closest canonical-index probe", + ) + assert result == {"before": "20", "after": "20", "shipped": 1}, result From 6d6cdefe4fcf8cf60f4112dc8e986ea55ee43799 Mon Sep 17 00:00:00 2001 From: Farhan Date: Thu, 3 Dec 2026 20:21:47 +0000 Subject: [PATCH 09/14] Resolve unified-hover source-column keys per series Tooltip aliases map a source column to a channel without saying which series it feeds, so two series binding revenue and margin to y both took the first column's format and label. Resolve column keys through tooltip sources, which record the trace each column feeds, and fall back to the channel key. --- docs/components/tooltips.md | 3 ++- js/src/52_tooltip.ts | 24 +++++++++++++++--------- spec/api/interaction.md | 8 +++++--- tests/test_unified_hover.py | 23 +++++++++++++++++++++++ 4 files changed, 45 insertions(+), 13 deletions(-) diff --git a/docs/components/tooltips.md b/docs/components/tooltips.md index d2bbd3303..97991742d 100644 --- a/docs/components/tooltips.md +++ b/docs/components/tooltips.md @@ -184,7 +184,8 @@ def unified_hover_demo(): unnamed series, `labels=` supplies the label from the other axis (`labels["y"]` under `"x unified"`, `labels["x"]` under `"y unified"`). Both accept the channel name or the source column, e.g. - `xy.tooltip(labels={"revenue": "Revenue"}, format={"revenue": ".1f"})`. + `xy.tooltip(labels={"revenue": "Revenue"}, format={"revenue": ".1f"})`. A + source-column key applies only to the series drawn from that column. `title=` and `fields=` templates describe one hovered row and are not used by the unified readout, so a line or area chart with either keeps `"closest"` unless you set `hover_mode` yourself. diff --git a/js/src/52_tooltip.ts b/js/src/52_tooltip.ts index 01dc727c3..9fba0b215 100644 --- a/js/src/52_tooltip.ts +++ b/js/src/52_tooltip.ts @@ -923,32 +923,38 @@ Object.assign(ChartView.prototype, { const tooltip = this.spec.tooltip || {}; const formats = tooltip.format || {}; const labels = tooltip.labels || {}; - const aliases = tooltip.aliases || {}; + const sources = tooltip.sources || {}; const dim = state.dim; const other = dim === "x" ? "y" : "x"; // Keys may name the channel ("y") or the source column bound to it - // ("revenue"), exactly as the closest-point readout resolves labels. - const formatFor = (channel) => { - for (const [field, alias] of Object.entries(aliases)) { - if (alias === channel && typeof formats[field] === "string") return formats[field]; + // ("revenue"). Several series can bind different columns to the same + // channel, so a column key applies only to the series whose trace it + // feeds (`tooltip.sources`), never to every row on that channel. + const keyFor = (dict, trace, channel) => { + for (const [field, entries] of Object.entries(sources)) { + if (typeof dict[field] !== "string" || !Array.isArray(entries)) continue; + if (entries.some((e) => e && e.trace === trace && e.channel === channel)) { + return dict[field]; + } } - return formats[channel]; + return typeof dict[channel] === "string" ? dict[channel] : undefined; }; const text = (row, channel) => { const value = row[channel]; if (value === undefined || value === null) return null; if (typeof value === "string") return value; - return this._formatTooltipValue(value, row[`${channel}_kind`], formatFor(channel)); + return this._formatTooltipValue( + value, row[`${channel}_kind`], keyFor(formats, row.trace, channel), + ); }; const items = []; const heading = text(state.rows[state.winnerAt], dim); if (heading) items.push({ kind: "title", value: heading }); - const fallbackLabel = this._defaultTooltipLabel(other, other, labels, aliases).label; const seen = new Set(); state.rows.forEach((row, k) => { const value = text(row, other); if (value === null) return; - const label = this._tooltipSeriesName(row) ?? fallbackLabel; + const label = this._tooltipSeriesName(row) ?? keyFor(labels, row.trace, other) ?? other; const color = this._seriesColorCss(state.hits[k].g); // A composed series can emit more than one mark for the same data // (a line plus its point markers); one row per visible series. diff --git a/spec/api/interaction.md b/spec/api/interaction.md index f53bcbc25..ebb4fdb28 100644 --- a/spec/api/interaction.md +++ b/spec/api/interaction.md @@ -448,9 +448,11 @@ does not need to touch a mark. Implementation: `js/src/52_tooltip.ts` value for that property wins), the series name (or the other axis's tooltip label, defaulting to `"y"`/`"x"`) in `tooltip_label`, and its value in `tooltip_value`. `format=` and `labels=` keys may name the channel - (`"x"`/`"y"`) or the source column bound to it (`"revenue"`, via the - tooltip `aliases`), resolved as the closest-point readout resolves labels - (`_defaultTooltipLabel`). Rows with an identical name, value, and color + (`"x"`/`"y"`) or the source column bound to it (`"revenue"`). A column + key applies only to the row whose trace that column feeds (tooltip + `sources`), so two series that bind `revenue` and `margin` to `y` each get + their own format and label; otherwise the channel key applies. Rows with + an identical name, value, and color collapse (one composed series drawn as two marks). - **Spike and placement.** The hover-dimension crosshair line (`crosshair_x` for x unified) is the spike: it marks the snapped position across the plot diff --git a/tests/test_unified_hover.py b/tests/test_unified_hover.py index 80768b154..e1f8fdd03 100644 --- a/tests/test_unified_hover.py +++ b/tests/test_unified_hover.py @@ -793,3 +793,26 @@ def test_closest_exact_reply_keeps_the_hovered_rows_fields(tmp_path: Path) -> No label="closest canonical-index probe", ) assert result == {"before": "20", "after": "20", "shipped": 1}, result + + +def test_unified_readout_resolves_source_keys_per_series(tmp_path: Path) -> None: + # Two unnamed series bind different source columns to "y"; each row must + # take its own column's format and label, not the first alias for "y". + data = {"day": [1, 2, 3], "revenue": [1234.0, 2000.0, 3000.0], "margin": [0.183, 0.2, 0.25]} + chart = xy.line_chart( + xy.line(x="day", y="revenue", data=data), + xy.line(x="day", y="margin", data=data), + xy.tooltip( + labels={"revenue": "Revenue", "margin": "Margin"}, + format={"revenue": ",.0f", "margin": ".1%"}, + ), + width=640, + height=360, + ) + result = _run( + tmp_path, + chart.to_html().replace(_RENDER_CALL, _SOURCE_KEYS_PROBE), + "data-xy-source-keys-probe", + label="unified hover per-series source-key probe", + ) + assert result["lines"] == ["1", "Revenue1,234", "Margin18.3%"], result From fb3a3926f1f251fe2718adfa414e2176b85b096e Mon Sep 17 00:00:00 2001 From: Farhan Date: Thu, 3 Dec 2026 20:31:50 +0000 Subject: [PATCH 10/14] Document the per-row tooltip exception and the new hover default State that line and area charts keep closest hover when their tooltip sets title, fields or render in the docstring, spec table and interactions page; say the unified readout lists series within 20 px; record that the off-plot check is along the hover dimension only; and file the line/area default as a breaking-change fragment with the hover_mode="closest" opt-out. --- docs/components/tooltips.md | 4 ++-- docs/core-concepts/interactions.md | 6 +++--- news/562.breaking.md | 1 + news/562.feature.md | 2 +- python/xy/components.py | 4 +++- spec/api/interaction.md | 12 ++++++++---- 6 files changed, 18 insertions(+), 11 deletions(-) create mode 100644 news/562.breaking.md diff --git a/docs/components/tooltips.md b/docs/components/tooltips.md index 97991742d..f058f5633 100644 --- a/docs/components/tooltips.md +++ b/docs/components/tooltips.md @@ -145,8 +145,8 @@ def tooltip_title_demo(): Line and area charts use unified hover by default (`hover_mode="x unified"`, Plotly's `hovermode` spelling): the cursor only has to be somewhere over the plot. It snaps to the nearest x, a vertical spike line marks it, and one -tooltip lists each series that has a point there, under the x value as its -heading. Other charts report the mark under the cursor (`"closest"`); pass +tooltip lists each series with a point within 20 px of that x, under the x +value as its heading. Other charts report the mark under the cursor (`"closest"`); pass `hover_mode="x unified"` to opt them in, or `hover_mode="closest"` to opt a line or area chart out. Plotly's per-series `"x"`/`"y"` modes are not available; passing either raises diff --git a/docs/core-concepts/interactions.md b/docs/core-concepts/interactions.md index d162afb96..0133c93ba 100644 --- a/docs/core-concepts/interactions.md +++ b/docs/core-concepts/interactions.md @@ -41,9 +41,9 @@ def browser_behavior_demo(): `hover_mode` chooses what hover reports. `"closest"`, the default for most charts, reads the mark under the cursor. `"x unified"`, the default for line -and area charts, snaps to the nearest x anywhere over the -plot and lists the series that have a point there in one tooltip, with a spike -line at that x; `"y unified"` does the same along y. Polar charts keep +and area charts (unless their tooltip sets `title=`, `fields=`, or `render=`), +snaps to the nearest x anywhere over the plot and lists the series with a +point within 20 px of it in one tooltip, with a spike line at that x; `"y unified"` does the same along y. Polar charts keep `"closest"`. See [Show Every Series at One X](/docs/xy/components/tooltips/#show-every-series-at-one-x). diff --git a/news/562.breaking.md b/news/562.breaking.md new file mode 100644 index 000000000..4297db001 --- /dev/null +++ b/news/562.breaking.md @@ -0,0 +1 @@ +Line and area charts now default to `hover_mode="x unified"`: hovering anywhere over the plot shows every nearby series at the nearest x, and `on_hover` receives the row that set that x instead of firing only over a point. Pass `hover_mode="closest"` to keep the previous behavior. Other charts, and line or area charts whose tooltip sets `title=`, `fields=` or a custom `render`, keep `"closest"`. diff --git a/news/562.feature.md b/news/562.feature.md index 616c3eab1..8d91fb49c 100644 --- a/news/562.feature.md +++ b/news/562.feature.md @@ -1 +1 @@ -Add `hover_mode="x unified"` and `"y unified"` (Plotly's `hovermode`) to charts and `xy.interaction_config`. The cursor no longer has to sit on a point: `"x unified"` snaps to the nearest x anywhere over the plot and marks it with a vertical spike line, and `"y unified"` does the same along y with a horizontal one. One tooltip lists each line, scatter, area, or bar series with a point within 20 px of that position, with a color chip (new `tooltip_swatch` slot). Line and area charts now use `"x unified"` by default (pass `hover_mode="closest"` to keep the old behavior); other charts, and line or area charts whose tooltip sets `title=`, `fields=` or a custom `render`, keep `"closest"`. Polar charts keep closest-point hover. Sorted series snap with a binary search, and live kernels refine every row to exact f64 values while `on_hover` still fires once per hover. +Add `hover_mode="x unified"` and `"y unified"` (Plotly's `hovermode`) to charts and `xy.interaction_config`. The cursor no longer has to sit on a point: `"x unified"` snaps to the nearest x anywhere over the plot and marks it with a vertical spike line, and `"y unified"` does the same along y with a horizontal one. One tooltip lists each line, scatter, area, or bar series with a point within 20 px of that position, with a color chip (new `tooltip_swatch` slot). Polar charts keep closest-point hover. Sorted series snap with a binary search, and live kernels refine every row to exact f64 values while `on_hover` still fires once per hover. diff --git a/python/xy/components.py b/python/xy/components.py index 65cc216cd..0f171863e 100644 --- a/python/xy/components.py +++ b/python/xy/components.py @@ -3737,7 +3737,9 @@ def __init__( crosshair: Whether plot-aligned hover guides are shown. hover_mode: ``"closest"``, ``"x unified"``, or ``"y unified"``; see :func:`interaction_config`. Unset, line and area charts - use ``"x unified"`` and every other chart ``"closest"``. + use ``"x unified"`` unless their tooltip sets ``title``, + ``fields``, or ``render``; every other chart uses + ``"closest"``. navigation: Whether browser pan and zoom navigation is enabled. pan: Whether plain-drag panning is enabled. pan_axes: Declared axis IDs translated by pan gestures. diff --git a/spec/api/interaction.md b/spec/api/interaction.md index ebb4fdb28..501269e27 100644 --- a/spec/api/interaction.md +++ b/spec/api/interaction.md @@ -54,7 +54,7 @@ table's one string-valued row, `hover_mode`, is specified in §7.1. | `select` | on | Suppresses the `xy:select` event and the `select_clear` message, removes the modebar Selection menu, and (with `brush`) disables shift-drag. | | `brush` | on | Same conjunction: `canBrush = brush && select` (`53_interaction.ts:115`) gates every selection drag and the modebar Selection menu. | | `crosshair` | off | The two guide elements are created only when the flag is true (or `hover_mode` is unified, which borrows one as its spike line, §7.1), at init (`53_interaction.ts`). Not togglable after mount. | -| `hover_mode` | `"x unified"` for `line_chart`/`area_chart`, else `"closest"` | Not a boolean: `"closest"`, `"x unified"`, or `"y unified"` (Plotly's `hovermode` spelling). Unified modes are specified in §7.1. Validated at construction; Plotly's per-series `"x"`/`"y"` modes raise with a pointer to the unified spelling. Polar charts resolve to `"closest"` client-side. Not togglable after mount. | +| `hover_mode` | `"x unified"` for `line_chart`/`area_chart` (unless the tooltip sets `title`, `fields`, or `render`), else `"closest"` | Not a boolean: `"closest"`, `"x unified"`, or `"y unified"` (Plotly's `hovermode` spelling). Unified modes are specified in §7.1. Validated at construction; Plotly's per-series `"x"`/`"y"` modes raise with a pointer to the unified spelling. Polar charts resolve to `"closest"` client-side. Not togglable after mount. | | `navigation` | on | Master gate on pointer-drag pan, wheel zoom, box-zoom drags, dblclick reset, and every modebar viewport control. Selection-mode double-click clear is a selection action and is unaffected. | | `pan` | on | Plain-drag pan is ignored, the modebar Pan button is not built, and every zoom-enabled axis is contained (§2.2). Requires `navigation`. Pans `pan_axes` (§2.1). | | `zoom` | on | Master zoom gate: wheel zoom, box zoom, and the zoom actions inside the modebar menu are all ignored. The same dropdown can remain for view history when `history` is on. Requires `navigation`. Zooms `zoom_axes` (§2.1). | @@ -429,9 +429,13 @@ does not need to touch a mark. Implementation: `js/src/52_tooltip.ts` - **Snap.** Pass 1: every eligible series finds its row nearest the cursor along the hover dimension (in axis-coordinate space, so log axes snap by screen distance); the row nearest in pixels wins and fixes the hover - position. A candidate outside the plot rect (scrolled past an edge) cannot - win, so it never shadows another series' point inside the plot. There is no - distance cap on the winner — anywhere over the plot snaps. Pass 2: every series reports its row nearest that position, kept only + position. A candidate outside the plot along the hover dimension (scrolled + past the left or right edge under x unified) cannot win, so it never shadows + another series' point inside the plot. The check is one-dimensional on + purpose: a point above or below the visible y range still answers for its x, + as in Plotly, since the readout reports values at the snapped x rather than + marks on screen. There is no distance cap on the winner — anywhere over the + plot snaps. Pass 2: every series reports its row nearest that position, kept only within 20 CSS px of it (Plotly's default `hoverdistance`), so a series that ends early or samples elsewhere is not reported as if it were at that x. Rows hidden by a legend category filter never answer. From 6c9d9ea5ce2bc0ce323fe6a00260b5bec0ec7b4c Mon Sep 17 00:00:00 2001 From: Farhan Date: Thu, 3 Dec 2026 20:36:21 +0000 Subject: [PATCH 11/14] Name the render= exception on the tooltips page A line or area chart whose tooltip sets render= keeps closest hover, as title= and fields= do; say so in both places the page describes the default. --- docs/components/tooltips.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/components/tooltips.md b/docs/components/tooltips.md index f058f5633..ee3aaadc1 100644 --- a/docs/components/tooltips.md +++ b/docs/components/tooltips.md @@ -148,7 +148,8 @@ plot. It snaps to the nearest x, a vertical spike line marks it, and one tooltip lists each series with a point within 20 px of that x, under the x value as its heading. Other charts report the mark under the cursor (`"closest"`); pass `hover_mode="x unified"` to opt them in, or `hover_mode="closest"` to opt a -line or area chart out. +line or area chart out. A line or area chart whose tooltip sets `title=`, +`fields=`, or `render=` also keeps `"closest"`. Plotly's per-series `"x"`/`"y"` modes are not available; passing either raises an error naming `"x unified"`/`"y unified"`. @@ -186,9 +187,9 @@ def unified_hover_demo(): accept the channel name or the source column, e.g. `xy.tooltip(labels={"revenue": "Revenue"}, format={"revenue": ".1f"})`. A source-column key applies only to the series drawn from that column. - `title=` and `fields=` templates describe one hovered row and are not used - by the unified readout, so a line or area chart with either keeps - `"closest"` unless you set `hover_mode` yourself. + `title=` and `fields=` templates and a custom `render=` describe one hovered + row and are not used by the unified readout, so a line or area chart with + any of them keeps `"closest"` unless you set `hover_mode` yourself. - The spike line is the crosshair line, so the `crosshair_x`/`crosshair_y` slots and the `--chart-crosshair` token style it. - The `xy:hover` event lists every reported series in `points`. Python From 1637bb422c3196ee902508fa3f8c3fedd73c48cc Mon Sep 17 00:00:00 2001 From: Farhan Date: Thu, 3 Dec 2026 20:42:57 +0000 Subject: [PATCH 12/14] Snap a unified-hover series to its in-plot neighbor at the plot edge Pass 1 took each series' nearest row and then dropped the series when that row was just past the plot edge, even if its next row was inside the plot. Search only the visible span along the hover dimension instead: on a sorted column the two rows bracketing the cursor are still the only candidates, so the binary search stays O(log n). --- js/src/52_tooltip.ts | 31 +++++++++++++++++++++++------ spec/api/interaction.md | 8 +++++--- tests/test_unified_hover.py | 39 +++++++++++++++++++++++++++++++++++++ 3 files changed, 69 insertions(+), 9 deletions(-) diff --git a/js/src/52_tooltip.ts b/js/src/52_tooltip.ts index 9fba0b215..6b5c3c471 100644 --- a/js/src/52_tooltip.ts +++ b/js/src/52_tooltip.ts @@ -729,13 +729,17 @@ Object.assign(ChartView.prototype, { }, // Row whose `dim` coordinate is nearest `value`, measured in axis-coordinate - // space so log and other monotone scales snap by what the eye sees. - _unifiedNearestIndex(g, dim, value) { + // space so log and other monotone scales snap by what the eye sees. With + // `range` ([lo, hi] in that space), only rows inside it may answer: pass 1 + // uses it to search the visible span, so a point just past the plot edge + // yields to the same series' neighbor inside the plot. + _unifiedNearestIndex(g, dim, value, range = null) { const axis = this._axis(dim === "x" ? g.xAxis : g.yAxis); const target = this._axisCoord(axis, value); const n = this._unifiedCount(g); if (!n || !Number.isFinite(target)) return -1; const coordAt = (i) => this._axisCoord(axis, this._unifiedValue(g, dim, i)); + const inRange = (c) => !range || (c >= range[0] && c <= range[1]); const transitioning = Number.isFinite(g._transitionPositionProgress) && !!(g._transitionPrevXValues || g._transitionPrevYValues); if (!transitioning && !g._visMap && this._unifiedSorted(g, dim, n)) { @@ -749,11 +753,16 @@ Object.assign(ChartView.prototype, { if (values[mid] < encoded) lo = mid + 1; else hi = mid; } + // The two rows bracketing the target are the only candidates: on a + // monotone axis every other row lies beyond one of them, so when both + // fall outside `range` no row of this series is inside it. let best = -1; let bestDist = Infinity; for (const i of [lo - 1, lo]) { if (i < 0 || i >= n) continue; - const d = Math.abs(coordAt(i) - target); + const c = coordAt(i); + if (!inRange(c)) continue; + const d = Math.abs(c - target); if (d < bestDist) { bestDist = d; best = i; } } return best; @@ -767,7 +776,9 @@ Object.assign(ChartView.prototype, { for (let k = 0; k < count; k++) { const i = rows ? rows[k] : k; if (i >= n) continue; - const d = Math.abs(coordAt(i) - target); + const c = coordAt(i); + if (!inRange(c)) continue; + const d = Math.abs(c - target); if (d < bestDist) { bestDist = d; best = i; } } return best; @@ -800,15 +811,23 @@ Object.assign(ChartView.prototype, { const traces = (this.gpuTraces || []).filter((g) => this._unifiedHoverable(g)); const extent = dim === "x" ? this.plot.w : this.plot.h; let win = null; + // The visible span along `dim`, in each trace's axis-coordinate space. + const visibleRange = (g) => { + const axis = this._axis(axisOf(g)); + const a = this._axisCoord(axis, cursorValue(g, -0.5)); + const b = this._axisCoord(axis, cursorValue(g, extent + 0.5)); + return Number.isFinite(a) && Number.isFinite(b) ? [Math.min(a, b), Math.max(a, b)] : null; + }; for (const g of traces) { const value = cursorValue(g, cursor); if (!Number.isFinite(value)) continue; - const index = this._unifiedNearestIndex(g, dim, value); + const index = this._unifiedNearestIndex(g, dim, value, visibleRange(g)); if (index < 0) continue; const p = this._unifiedPx(g, index); if (!p) continue; // A point scrolled past the plot edge cannot be the snapped position, - // and must not shadow another series' point inside the plot. + // and must not shadow another series' point inside the plot. The range + // above already excludes such rows; this guards rounding at the edge. const at = along(p); if (at < -0.5 || at > extent + 0.5) continue; const dist = Math.abs(at - cursor); diff --git a/spec/api/interaction.md b/spec/api/interaction.md index 501269e27..f0d2dfc72 100644 --- a/spec/api/interaction.md +++ b/spec/api/interaction.md @@ -429,9 +429,11 @@ does not need to touch a mark. Implementation: `js/src/52_tooltip.ts` - **Snap.** Pass 1: every eligible series finds its row nearest the cursor along the hover dimension (in axis-coordinate space, so log axes snap by screen distance); the row nearest in pixels wins and fixes the hover - position. A candidate outside the plot along the hover dimension (scrolled - past the left or right edge under x unified) cannot win, so it never shadows - another series' point inside the plot. The check is one-dimensional on + position. Pass 1 searches only the visible span along the hover dimension: + a row scrolled past the left or right edge (under x unified) cannot win, so + it never shadows another series' point inside the plot, and a series whose + nearest row is just past the edge answers with its nearest row inside the + plot instead of dropping out. The check is one-dimensional on purpose: a point above or below the visible y range still answers for its x, as in Plotly, since the readout reports values at the snapped x rather than marks on screen. There is no distance cap on the winner — anywhere over the diff --git a/tests/test_unified_hover.py b/tests/test_unified_hover.py index e1f8fdd03..a6990f08d 100644 --- a/tests/test_unified_hover.py +++ b/tests/test_unified_hover.py @@ -816,3 +816,42 @@ def test_unified_readout_resolves_source_keys_per_series(tmp_path: Path) -> None label="unified hover per-series source-key probe", ) assert result["lines"] == ["1", "Revenue1,234", "Margin18.3%"], result + + +_EDGE_NEIGHBOR_PROBE = ( + _PROBE_PRELUDE + + """ + const at = (v) => view._projectDataPoint("x", "y", v, 0)[0] - view.plot.x; + move(0, view.plot.h - 2); + document.body.setAttribute("data-xy-edge-neighbor-probe", JSON.stringify({ + offPlot: at(-0.03), inPlot: at(0.17), + unified: !!view._unified, heading: view._unified ? text()[0] : null, + })); +""" + + _PROBE_CATCH % "data-xy-edge-neighbor-probe" +) + + +@pytest.mark.parametrize("ordered", [True, False], ids=["sorted", "unsorted"]) +def test_edge_snap_uses_the_series_in_plot_neighbor(tmp_path: Path, ordered: bool) -> None: + # The cursor sits on the left plot edge. The series' nearest point is just + # past that edge, but its next point is inside the plot and must answer + # instead of the whole series dropping out of the readout. + xs = [-0.03, 0.17, 5.0, 9.0] + ys = [1.0, 2.0, 3.0, 4.0] + if not ordered: + xs, ys = xs[::-1], ys[::-1] + chart = xy.line_chart( + xy.line(xs, ys, name="A"), + xy.x_axis(domain=(0.0, 10.0)), + width=640, + height=360, + ) + result = _run( + tmp_path, + chart.to_html().replace(_RENDER_CALL, _EDGE_NEIGHBOR_PROBE), + "data-xy-edge-neighbor-probe", + label="unified hover edge-neighbor probe", + ) + assert result["offPlot"] < -0.5 < 0.5 < result["inPlot"] < 20, result + assert result["unified"] is True and result["heading"] == "0.17", result From 9629fcc0f2e74952f0a845accc774d90edea3f32 Mon Sep 17 00:00:00 2001 From: Farhan Date: Thu, 3 Dec 2026 20:43:50 +0000 Subject: [PATCH 13/14] Name the per-row tooltip exception in the unified-hover FAQ --- docs/components/tooltips.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/components/tooltips.md b/docs/components/tooltips.md index ee3aaadc1..7da284444 100644 --- a/docs/components/tooltips.md +++ b/docs/components/tooltips.md @@ -274,7 +274,8 @@ each placeholder is replaced with the value from the hovered row. ### How do I show all series values at the hovered x, like Plotly's unified hover? -Line and area charts already do this by default. For other charts, pass +Line and area charts already do this by default, unless their tooltip sets +`title=`, `fields=`, or `render=`. For those, and for other charts, pass `hover_mode="x unified"`, e.g. `xy.scatter_chart(..., hover_mode="x unified")`. The cursor snaps to the nearest x anywhere over the plot and one tooltip lists each series whose nearest point is within 20 px of that x. Pass `hover_mode="closest"` to turn it From 4e8cc3630740f687f085a51e3d31aab482d11696 Mon Sep 17 00:00:00 2001 From: Farhan Date: Thu, 3 Dec 2026 20:56:55 +0000 Subject: [PATCH 14/14] Stop a timed-out benchmark worker before it has made its process group The hard benchmark deadline signals the worker's process group, which exists only once the forked worker has run os.setsid(). When the deadline expired first (a slow fork from a large test process on a loaded runner), killpg raised ProcessLookupError, nothing was signalled, and the parent waited out the SIGTERM grace period and sometimes the whole measurement. That made test_run_enforces_budget_as_hard_measurement_timeout fail on CI (0.59s against its 0.5s bound). Signal the worker itself when the group is missing; it has no descendants yet. --- benchmarks/bench_vs.py | 14 ++++++++------ tests/test_bench_vs.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/benchmarks/bench_vs.py b/benchmarks/bench_vs.py index 8cd2ab128..86e34ce31 100644 --- a/benchmarks/bench_vs.py +++ b/benchmarks/bench_vs.py @@ -244,22 +244,24 @@ def _measurement_worker(send, factory, x, y, n, capture_artifact, chromium) -> N def _stop_process_tree(process) -> None: - """Terminate a worker and renderer descendants, escalating to SIGKILL.""" + """Terminate a worker and renderer descendants, escalating to SIGKILL. + + The worker's process group exists only once it has run ``os.setsid()``. A + deadline can expire before that (a slow fork on a loaded host), and then + ``killpg`` finds no group; signal the worker itself instead, which has no + descendants yet, rather than leaving it to run out its measurement. + """ if not process.is_alive(): process.join() return try: os.killpg(process.pid, signal.SIGTERM) - except ProcessLookupError: - pass - except OSError: + except OSError: # includes ProcessLookupError: no group yet process.terminate() process.join(timeout=0.25) if process.is_alive(): try: os.killpg(process.pid, signal.SIGKILL) - except ProcessLookupError: - pass except OSError: process.kill() process.join() diff --git a/tests/test_bench_vs.py b/tests/test_bench_vs.py index 5f879d42f..ac0c78dc0 100644 --- a/tests/test_bench_vs.py +++ b/tests/test_bench_vs.py @@ -40,6 +40,38 @@ def slow_measure(_build, _render, _artifact): assert elapsed < 0.5 +def test_hard_timeout_stops_a_worker_that_has_not_yet_made_its_group(monkeypatch) -> None: + # The deadline can expire before the forked worker reaches os.setsid() (a + # slow fork from a large test process on a loaded runner). Its process + # group does not exist yet, so killpg finds nothing; the worker itself + # must still be stopped instead of being left to run out its measurement. + real_setsid = bench_vs.os.setsid + + def late_setsid(): + time.sleep(0.6) + real_setsid() + + monkeypatch.setattr(bench_vs.os, "setsid", late_setsid) + monkeypatch.setattr( + bench_vs, + "ADAPTERS", + {"slow": lambda _x, _y: (lambda: None, lambda _fig: 0)}, + ) + + def slow_measure(_build, _render, _artifact): + time.sleep(1) + raise AssertionError("the hard deadline did not interrupt the measurement") + + monkeypatch.setattr(bench_vs, "_measure", slow_measure) + + started = time.perf_counter() + report = bench_vs.run([10], 0.02, libraries=["slow"]) + elapsed = time.perf_counter() - started + + assert report["results"]["slow"][0]["status"] == "skipped(hard timeout after 0.02s budget)" + assert elapsed < 0.5 + + def test_hard_timeout_includes_browser_ttfr(monkeypatch) -> None: monkeypatch.setattr( bench_vs,