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/docs/components/tooltips.md b/docs/components/tooltips.md index 74803b17b..7da284444 100644 --- a/docs/components/tooltips.md +++ b/docs/components/tooltips.md @@ -140,6 +140,64 @@ def tooltip_title_demo(): return reflex_xy.chart(tooltip_title_chart, height="320px") ~~~ +## Show Every Series at One X + +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 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. 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"`. + +~~~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", +) + + +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"` 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 + 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=...)` + 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"})`. A + source-column key applies only to the series drawn from that column. + `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 + `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=...)`. + ## Exact and Resident Readout Standalone HTML composes tooltips from the values resident in its payload. @@ -214,6 +272,15 @@ 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? + +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 +off on a line or area chart. + ### 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..0133c93ba 100644 --- a/docs/core-concepts/interactions.md +++ b/docs/core-concepts/interactions.md @@ -39,6 +39,14 @@ def browser_behavior_demo(): return reflex_xy.chart(chart, height="360px") ~~~ +`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 (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). + 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..5516c6dcc 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 | @@ -232,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. @@ -358,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/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..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) { @@ -7280,7 +7281,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 +9665,18 @@ export class ChartView { const rect = this.canvas.getBoundingClientRect(); const cssX = e.clientX - rect.left; const cssY = e.clientY - rect.top; + 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". + if (this._unified) { + 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) { const hadHover = this._hoverId !== -1; diff --git a/js/src/52_tooltip.ts b/js/src/52_tooltip.ts index 73e26d097..6b5c3c471 100644 --- a/js/src/52_tooltip.ts +++ b/js/src/52_tooltip.ts @@ -1,12 +1,28 @@ 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; + +// `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); @@ -479,7 +495,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 +508,18 @@ 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"); + // 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") { const label = document.createElement("span"); this._applySlot(label, "tooltip_label"); label.textContent = item.label; @@ -545,6 +572,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 +584,29 @@ Object.assign(ChartView.prototype, { const pos = this._tooltipAnchorPx(); if (!pos) { this.tooltip.style.display = "none"; + 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._placeTooltip(pos.lx, pos.ly, !!this._unified); }, - _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 +650,511 @@ 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 !== 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 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, + // 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); + }, + + // 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; + 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 + // 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. 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)) { + 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; + } + // 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 c = coordAt(i); + if (!inRange(c)) continue; + const d = Math.abs(c - 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 c = coordAt(i); + if (!inRange(c)) continue; + const d = Math.abs(c - 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)); + 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, 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. 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); + if (!win || dist < win.dist) win = { g, index, p, dist }; + } + if (!win) return null; + const position = along(win.p); + 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._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; + 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 (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; + // 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"; + 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; + // 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; + } + 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, winnerExact: false, + }; + 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 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"). 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 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`], keyFor(formats, row.trace, channel), + ); + }; + const items = []; + const heading = text(state.rows[state.winnerAt], dim); + if (heading) items.push({ kind: "title", value: heading }); + const seen = new Set(); + state.rows.forEach((row, k) => { + const value = text(row, other); + if (value === null) return; + 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. + 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) 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); + 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 = this._unifiedSpikeLine(state.dim); + 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"; + } + }, + + // 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"; + 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 === "x" ? HOVER_X_UNIFIED : HOVER_Y_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. 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) { + 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)) { + this._tooltipAnchor[state.dim] = snapped; + } + } + this._renderUnifiedTooltip({ announce: false }); + } + // 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, + trace: winner.trace, + index: row.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..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(); @@ -145,17 +146,10 @@ Object.assign(ChartView.prototype, { }); this._listen(this.selLasso, "pointercancel", cancelLassoHandleDrag); - if (this._interactionFlag("crosshair")) { - 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); + // 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._createCrosshairLines(); } const dataAt = (clientX, clientY) => { @@ -270,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; } @@ -290,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(); } }); @@ -615,8 +611,21 @@ 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) 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..254f40262 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); } @@ -861,6 +862,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,18 +881,15 @@ 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; } + // 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/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.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 new file mode 100644 index 000000000..8d91fb49c --- /dev/null +++ b/news/562.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: `"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/_figure.py b/python/xy/_figure.py index 3f94bb5e6..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() @@ -490,6 +494,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 +543,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 +812,20 @@ 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).""" + if isinstance(value, str) and value in HOVER_MODES: + return value + choices = ", ".join(repr(mode) for mode in HOVER_MODES) + 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 +1890,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..0f171863e 100644 --- a/python/xy/components.py +++ b/python/xy/components.py @@ -167,6 +167,11 @@ DefaultDragAction: TypeAlias = Literal[ "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]] @@ -370,6 +375,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) @@ -3489,6 +3496,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 +3521,15 @@ 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 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 @@ -3559,6 +3576,7 @@ def interaction_config( select=select, brush=brush, crosshair=crosshair, + hover_mode=hover_mode, navigation=navigation, pan=pan, pan_axes=pan_axes, @@ -3675,6 +3693,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 +3735,11 @@ 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"``, ``"x unified"``, or ``"y unified"``; + see :func:`interaction_config`. Unset, line and area charts + 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. @@ -3761,6 +3785,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 +3927,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 +3948,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 +3971,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, @@ -3960,6 +3988,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, @@ -5238,6 +5272,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/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/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 33870d820..f0d2dfc72 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 | | --- | --- | --- | @@ -52,7 +53,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` | `"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). | @@ -163,7 +165,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. | @@ -381,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 @@ -398,6 +405,97 @@ 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. + +- **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` + 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. 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 + 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`, 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`. `format=` and `labels=` keys may name the channel + (`"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 + 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. + `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 + 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, 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. + ## 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..5c1dc287e 100644 --- a/spec/design-dossier.md +++ b/spec/design-dossier.md @@ -716,6 +716,15 @@ 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. 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/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..661eef46f 100644 --- a/spec/design/view-state.md +++ b/spec/design/view-state.md @@ -310,6 +310,10 @@ 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 +(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/spec/design/wire-protocol.md b/spec/design/wire-protocol.md index 5900984ee..df8591fa3 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. @@ -567,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/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, 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..a6990f08d --- /dev/null +++ b/tests/test_unified_hover.py @@ -0,0 +1,857 @@ +"""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 dataclasses +import os +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(*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, + ) + + +# -- 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 _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]) +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: + # `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 + ) + + +_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(hover_mode="closest").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 + + +_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 = ( + _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 + + +_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(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 + + +_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 + + +_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 + + +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 + + +_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