bevy-react 0.1.1

Drive bevy_ui from a React app over an embedded V8 runtime.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
//! Mouse-wheel scrolling for `overflow: scroll` nodes.
//!
//! `bevy_ui` clips an `OverflowAxis::Scroll` node's content and offsets its
//! children by the node's [`ScrollPosition`], but nothing drives that component
//! from input — Bevy leaves the wheel handling to the app. [`apply_scroll`] is
//! that handler: each frame it reads the accumulated wheel delta, finds the
//! scroll container under the cursor, and moves its `ScrollPosition`.

use bevy::input::mouse::{AccumulatedMouseScroll, MouseScrollUnit};
use bevy::prelude::*;
use bevy::ui::{ComputedNode, ScrollPosition, UiGlobalTransform, UiStack};
use bevy::window::PrimaryWindow;

use crate::bridge::{JsBridge, RNode, ScrollStep, WheelListener};
use crate::plugin::PointerCapture;
use crate::protocol::{Outbound, UiEvent};
use crate::transition::ScrollTransitionState;

/// Default logical pixels scrolled per wheel "line" (mice report `Line` units;
/// trackpads report `Pixel`). A middling value that feels close to a typical
/// desktop. A node's `scrollStep` prop ([`ScrollStep`]) overrides it per container.
const LINE_HEIGHT: f32 = 20.0;

/// Whether a node opts into scrolling on either axis.
fn is_scroll_container(node: &Node) -> bool {
    node.overflow.x == OverflowAxis::Scroll || node.overflow.y == OverflowAxis::Scroll
}

/// Move the `ScrollPosition` of the scroll container under the cursor by the
/// frame's wheel delta. Runs in `PointerCaptureSet` after `collect_pointer_events`
/// so that, when it actually scrolls, it can flag the pointer as UI-owned and stop
/// world systems (e.g. a wheel-zoom camera) from also consuming the same wheel.
///
/// The pointer is only claimed (`PointerCapture::over_ui`) when a container actually
/// moves — a scroll container whose content fits (no scroll range on the wheeled axis)
/// lets the wheel fall through, so a camera behind a transparent, non-overflowing
/// scroll pane can still zoom.
///
/// Target selection is by **geometry, topmost-first**. Every `Node` carries a
/// `ScrollPosition` (it's a required component), so "has a `ScrollPosition`" is
/// meaningless — we must check `Node.overflow`. We walk the `UiStack` top to bottom
/// and hit-test the cursor against each node's rectangle with
/// [`ComputedNode::contains_point`]:
/// - The topmost node under the cursor that declared `onWheel` (a [`WheelListener`])
///   **claims** the wheel: it emits via [`collect_wheel_events`], and here we stop
///   without scrolling anything beneath it. That is what lets an `onWheel` node
///   (e.g. a zoomable map) sit inside a scroll page and swallow the wheel instead of
///   also scrolling its ancestor — DOM `preventDefault` semantics.
/// - Otherwise the topmost real scroll container under the cursor scrolls. This stays
///   content-agnostic: plain nodes on top (text glyphs, images) are transparent
///   because they are neither listeners nor scroll containers.
///
/// Bevy's layout clamps the *applied* offset to `[0, max]`, so writing freely here
/// never overscrolls.
#[allow(clippy::type_complexity)]
pub fn apply_scroll(
    accumulated: Res<AccumulatedMouseScroll>,
    windows: Query<&Window, With<PrimaryWindow>>,
    ui_stack: Res<UiStack>,
    mut scrollables: Query<(
        &ComputedNode,
        &UiGlobalTransform,
        &Node,
        &mut ScrollPosition,
        Option<&ScrollStep>,
        Option<&mut ScrollTransitionState>,
    )>,
    wheel_listeners: Query<(), With<WheelListener>>,
    mut capture: ResMut<PointerCapture>,
) {
    if accumulated.delta == Vec2::ZERO {
        return;
    }
    let Ok(window) = windows.single() else {
        return;
    };
    let Some(cursor) = window.cursor_position() else {
        return;
    };
    // `ComputedNode`/`UiGlobalTransform` are in physical pixels; the window cursor is
    // logical with a top-left origin. Scaling matches them for a window-filling camera
    // (the host app's UI camera); a camera with a custom viewport offset is not handled
    // here.
    let cursor = cursor * window.scale_factor();

    // `uinodes` is ordered back-to-front, so reversed is topmost-first: the first
    // node under the cursor that claims the wheel wins. This also resolves nested
    // scroll areas correctly (an inner one sits later in the stack, so it's hit first).
    for &entity in ui_stack.uinodes.iter().rev() {
        let Ok((computed, transform, node, mut pos, step, scroll_state)) =
            scrollables.get_mut(entity)
        else {
            continue;
        };
        if !computed.contains_point(*transform, cursor) {
            continue; // cursor not over this node — transparent, keep scanning
        }
        // An `onWheel` node on top claims the wheel: stop before scrolling anything
        // beneath it. `collect_wheel_events` does the emission (+ the `over_ui`
        // claim); we only need to make sure no ancestor scroll container also moves.
        if wheel_listeners.contains(entity) {
            return;
        }
        if !is_scroll_container(node) {
            continue; // a plain node over the cursor is transparent to scrolling
        }
        // Wheel delta → logical pixels, scaled by this container's step. A positive
        // wheel delta scrolls the view up (content down), i.e. *decreases* the offset.
        let delta = match accumulated.unit {
            MouseScrollUnit::Line => accumulated.delta * step.map(|s| s.0).unwrap_or(LINE_HEIGHT),
            MouseScrollUnit::Pixel => accumulated.delta,
        };
        // Clamp to the scrollable range so the offset can't accumulate past the
        // ends (otherwise you'd have to "unscroll" the slack before it moves).
        // Bevy clamps the offset it *applies* for rendering but never writes that
        // back to this component, so we must clamp it ourselves. `ComputedNode`
        // sizes are physical; the component is logical, so convert with
        // `inverse_scale_factor`. Mirrors `ui_layout_system`'s own formula.
        let max = (computed.content_size - computed.size + computed.scrollbar_size).max(Vec2::ZERO)
            * computed.inverse_scale_factor;
        // Move from the eased target if a scroll transition owns the offset (so
        // ticks accumulate toward a farther target), else from the live position.
        let base = scroll_state.as_ref().map_or(pos.0, |s| s.target);
        // Only the axes with actual scroll range (`max > 0`) consume the wheel;
        // a container whose content fits has nothing to move.
        let mut next = base;
        let mut consumed = false;
        if node.overflow.x == OverflowAxis::Scroll && delta.x != 0.0 && max.x > 0.0 {
            next.x = (base.x - delta.x).clamp(0.0, max.x);
            consumed = true;
        }
        if node.overflow.y == OverflowAxis::Scroll && delta.y != 0.0 && max.y > 0.0 {
            next.y = (base.y - delta.y).clamp(0.0, max.y);
            consumed = true;
        }
        if consumed {
            // With a transition, set the eased target (`drive_scroll_transition`
            // moves `ScrollPosition`); otherwise move the offset directly.
            match scroll_state {
                Some(mut state) => state.target = next,
                None => pos.0 = next,
            }
            // The wheel actually moved this container — claim it for the UI so
            // world-input systems that honor `PointerCapture` (the orbit camera's
            // wheel-zoom, etc.) ignore the same wheel this frame.
            capture.over_ui = true;
            break;
        }
        // Nothing to scroll here (content fits the container) — keep scanning lower
        // containers, and ultimately leave the wheel for world input so e.g. a
        // camera behind a transparent, non-overflowing scroll pane can still zoom.
    }
}

/// Deliver raw mouse-wheel deltas to the topmost `onWheel` node under the cursor.
///
/// Unlike [`apply_scroll`] (which only moves `overflow: scroll` containers), this
/// fires for **any** node that declared an `onWheel` handler — e.g. a zoomable
/// `<canvas>` map. The delta is passed through untouched (no `ScrollStep` scaling);
/// `deltaMode` (`"line"`/`"pixel"`) tells the app how to read it, like DOM
/// `WheelEvent`.
///
/// Target selection mirrors [`apply_scroll`]: a geometric hit-test over the
/// `UiStack`, topmost first, filtered to [`WheelListener`] nodes — no `Interaction`
/// needed, so it composes cleanly with the `onPointer*` machinery. Runs in
/// `PointerCaptureSet` after `collect_pointer_events` so the `PointerCapture::over_ui`
/// claim survives (that system *assigns* `over_ui`), letting world wheel-consumers
/// (a zoom camera) ignore a wheel a node just handled.
pub fn collect_wheel_events(
    accumulated: Res<AccumulatedMouseScroll>,
    windows: Query<&Window, With<PrimaryWindow>>,
    ui_stack: Res<UiStack>,
    bridge: Res<JsBridge>,
    listeners: Query<(&ComputedNode, &UiGlobalTransform, &RNode), With<WheelListener>>,
    mut capture: ResMut<PointerCapture>,
) {
    if accumulated.delta == Vec2::ZERO {
        return;
    }
    let Ok(window) = windows.single() else {
        return;
    };
    let Some(cursor_logical) = window.cursor_position() else {
        return;
    };
    // `ComputedNode`/`UiGlobalTransform` are physical; the window cursor is logical
    // (see the note in `apply_scroll`). Match them for the hit-test.
    let cursor = cursor_logical * window.scale_factor();

    let delta_mode = match accumulated.unit {
        MouseScrollUnit::Line => "line",
        MouseScrollUnit::Pixel => "pixel",
    };

    // `uinodes` is back-to-front, so reversed is topmost-first: the first `onWheel`
    // node whose rect contains the cursor wins.
    for &entity in ui_stack.uinodes.iter().rev() {
        let Ok((computed, transform, rnode)) = listeners.get(entity) else {
            continue;
        };
        if !computed.contains_point(*transform, cursor) {
            continue;
        }
        // Normalized 0..1 position within the node (top-left origin), matching the
        // pointer events' `x`/`y`. A successful `contains_point` implies a non-zero
        // size, so the divide is safe.
        let size = computed.size;
        let min = transform.translation - size * 0.5;
        let norm = ((cursor - min) / size).clamp(Vec2::ZERO, Vec2::ONE);
        let _ = bridge.outbound_tx.send(Outbound::UiEvent {
            event: UiEvent {
                id: rnode.0,
                kind: "wheel".to_string(),
                x: Some(norm.x),
                y: Some(norm.y),
                client_x: Some(cursor_logical.x),
                client_y: Some(cursor_logical.y),
                delta_x: Some(accumulated.delta.x),
                delta_y: Some(accumulated.delta.y),
                delta_mode: Some(delta_mode.to_string()),
                ..default()
            },
        });
        // The node handled the wheel — claim the pointer so world-input systems that
        // honor `PointerCapture` ignore the same wheel this frame.
        capture.over_ui = true;
        break;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bevy::ecs::system::RunSystemOnce;

    /// Drive `apply_scroll` against a 200×100 scroll container centered at (300, 200)
    /// holding `content_h`px of content (so the scroll range is `[0, content_h - 100]`
    /// logical), with a non-scrolling child node ("text") on top of it (also carrying a
    /// `ScrollPosition`, since every `Node` does). Starts the container at `start`,
    /// applies one `Line` wheel tick of `wheel`, and returns the container's resulting
    /// `ScrollPosition` plus whether the pointer was flagged as UI-owned.
    fn run_with_content(cursor: Vec2, start: Vec2, wheel: Vec2, content_h: f32) -> (Vec2, bool) {
        let mut world = World::new();

        let mut window = Window::default();
        window.set_physical_cursor_position(Some(cursor.as_dvec2()));
        world.spawn((window, PrimaryWindow));

        let container = world
            .spawn((
                Node {
                    overflow: Overflow::scroll_y(),
                    ..default()
                },
                ComputedNode {
                    size: Vec2::new(200.0, 100.0),
                    content_size: Vec2::new(200.0, content_h),
                    inverse_scale_factor: 1.0,
                    ..default()
                },
                UiGlobalTransform::from_translation(Vec2::new(300.0, 200.0)),
                ScrollPosition(start),
            ))
            .id();
        // A child "text" node fully inside the container. It is NOT a scroll container
        // (overflow visible) yet still carries a `ScrollPosition` — exactly the case
        // that broke before. It sits in front of the container in the stack.
        let child = world
            .spawn((
                Node::default(),
                ComputedNode {
                    size: Vec2::new(80.0, 20.0),
                    inverse_scale_factor: 1.0,
                    ..default()
                },
                UiGlobalTransform::from_translation(Vec2::new(300.0, 200.0)),
                ScrollPosition::default(),
            ))
            .id();

        // Back-to-front: container behind, child in front (so the child is hit first
        // when iterating topmost-first, and must be skipped for not opting into scroll).
        world.insert_resource(UiStack {
            uinodes: vec![container, child],
            partition: Vec::new(),
        });
        world.insert_resource(AccumulatedMouseScroll {
            unit: MouseScrollUnit::Line,
            delta: wheel,
        });
        world.insert_resource(PointerCapture::default());

        world.run_system_once(apply_scroll).unwrap();

        let pos = world.entity(container).get::<ScrollPosition>().unwrap().0;
        let over_ui = world.resource::<PointerCapture>().over_ui;
        (pos, over_ui)
    }

    /// Like [`run_with_content`] with the default 300px content (scroll range `[0, 200]`).
    fn run(cursor: Vec2, start: Vec2, wheel: Vec2) -> (Vec2, bool) {
        run_with_content(cursor, start, wheel, 300.0)
    }

    /// A 200×100 scroll container holding 300px of content, plus any extra components
    /// the caller adds (e.g. `ScrollStep`, `ScrollTransitionState`). Cursor centered,
    /// one `Line` wheel tick of `wheel`. Returns the container entity + world.
    fn run_with(extra: impl Bundle, wheel: Vec2) -> (World, Entity) {
        let mut world = World::new();
        let mut window = Window::default();
        window.set_physical_cursor_position(Some(Vec2::new(300.0, 200.0).as_dvec2()));
        world.spawn((window, PrimaryWindow));
        let container = world
            .spawn((
                Node {
                    overflow: Overflow::scroll_y(),
                    ..default()
                },
                ComputedNode {
                    size: Vec2::new(200.0, 100.0),
                    content_size: Vec2::new(200.0, 300.0),
                    inverse_scale_factor: 1.0,
                    ..default()
                },
                UiGlobalTransform::from_translation(Vec2::new(300.0, 200.0)),
                ScrollPosition::default(),
                extra,
            ))
            .id();
        world.insert_resource(UiStack {
            uinodes: vec![container],
            partition: Vec::new(),
        });
        world.insert_resource(AccumulatedMouseScroll {
            unit: MouseScrollUnit::Line,
            delta: wheel,
        });
        world.insert_resource(PointerCapture::default());
        world.run_system_once(apply_scroll).unwrap();
        (world, container)
    }

    #[test]
    fn scroll_step_scales_the_wheel_delta() {
        // A custom step of 40 moves twice the default 20 per line tick (wheel down).
        let (world, container) = run_with(ScrollStep(40.0), Vec2::new(0.0, -1.0));
        let pos = world.entity(container).get::<ScrollPosition>().unwrap().0;
        assert_eq!(pos, Vec2::new(0.0, 40.0));
    }

    #[test]
    fn wheel_feeds_target_when_scroll_transition_present() {
        // With a `ScrollTransitionState`, the wheel sets the eased *target*, leaving
        // `ScrollPosition` untouched (the drive system moves it later).
        let (world, container) = run_with(ScrollTransitionState::default(), Vec2::new(0.0, -1.0));
        assert_eq!(
            world.entity(container).get::<ScrollPosition>().unwrap().0,
            Vec2::ZERO,
            "the wheel must not move the offset directly when easing"
        );
        assert_eq!(
            world
                .entity(container)
                .get::<ScrollTransitionState>()
                .unwrap()
                .target,
            Vec2::new(0.0, 20.0),
            "the wheel accumulates into the eased target"
        );
    }

    #[test]
    fn scrolls_container_when_cursor_is_over_its_child_text() {
        // Cursor over the child "text"; wheel down (delta.y < 0) reveals lower content
        // → offset.y increases by LINE_HEIGHT, within the [0, 200] range.
        let (pos, over_ui) = run(Vec2::new(300.0, 200.0), Vec2::ZERO, Vec2::new(0.0, -1.0));
        assert_eq!(pos, Vec2::new(0.0, LINE_HEIGHT));
        assert!(over_ui, "scrolling should claim the pointer for the UI");
    }

    #[test]
    fn clamps_at_the_bottom() {
        // Near the end (190) + a 20px wheel-down tick would reach 210, but the max is
        // 200 (content 300 − size 100), so it clamps instead of accumulating slack.
        let (pos, _) = run(
            Vec2::new(300.0, 200.0),
            Vec2::new(0.0, 190.0),
            Vec2::new(0.0, -1.0),
        );
        assert_eq!(pos, Vec2::new(0.0, 200.0));
    }

    #[test]
    fn clamps_at_the_top() {
        // Near the start (10) + a 20px wheel-up tick would reach −10, but it clamps to 0.
        let (pos, _) = run(
            Vec2::new(300.0, 200.0),
            Vec2::new(0.0, 10.0),
            Vec2::new(0.0, 1.0),
        );
        assert_eq!(pos, Vec2::new(0.0, 0.0));
    }

    #[test]
    fn ignores_wheel_when_cursor_is_outside_the_container() {
        // In-window but outside the container's rect (x:200..400, y:150..250).
        let (pos, over_ui) = run(
            Vec2::new(50.0, 50.0),
            Vec2::new(0.0, 30.0),
            Vec2::new(0.0, -1.0),
        );
        assert_eq!(pos, Vec2::new(0.0, 30.0));
        assert!(!over_ui);
    }

    #[test]
    fn does_not_claim_wheel_when_content_fits() {
        // A scroll container whose content fits (content 100 == size 100, so the scroll
        // range is empty) under the cursor. The wheel must NOT be consumed: position stays
        // put and the pointer is left un-owned so a world system (e.g. the orbit camera's
        // wheel-zoom behind a transparent, non-overflowing scroll pane) still receives it.
        let (pos, over_ui) = run_with_content(
            Vec2::new(300.0, 200.0),
            Vec2::ZERO,
            Vec2::new(0.0, -1.0),
            100.0,
        );
        assert_eq!(pos, Vec2::ZERO);
        assert!(
            !over_ui,
            "a container with nothing to scroll must not claim the wheel"
        );
    }

    #[test]
    fn wheel_listener_on_top_blocks_ancestor_scroll() {
        // A scroll container with a `WheelListener` child on top of it (the reported
        // bug shape: an `onWheel` box inside a scrollable page). Cursor over the child
        // → `apply_scroll` must yield, leaving the ancestor container un-scrolled. The
        // event itself is emitted separately by `collect_wheel_events`.
        let mut world = World::new();
        let mut window = Window::default();
        window.set_physical_cursor_position(Some(Vec2::new(300.0, 200.0).as_dvec2()));
        world.spawn((window, PrimaryWindow));

        let container = world
            .spawn((
                Node {
                    overflow: Overflow::scroll_y(),
                    ..default()
                },
                ComputedNode {
                    size: Vec2::new(200.0, 100.0),
                    content_size: Vec2::new(200.0, 300.0),
                    inverse_scale_factor: 1.0,
                    ..default()
                },
                UiGlobalTransform::from_translation(Vec2::new(300.0, 200.0)),
                ScrollPosition::default(),
            ))
            .id();
        let child = world
            .spawn((
                Node::default(),
                ComputedNode {
                    size: Vec2::new(80.0, 20.0),
                    inverse_scale_factor: 1.0,
                    ..default()
                },
                UiGlobalTransform::from_translation(Vec2::new(300.0, 200.0)),
                ScrollPosition::default(),
                WheelListener,
            ))
            .id();
        // Container behind, `onWheel` child in front (topmost-first hits the child).
        world.insert_resource(UiStack {
            uinodes: vec![container, child],
            partition: Vec::new(),
        });
        world.insert_resource(AccumulatedMouseScroll {
            unit: MouseScrollUnit::Line,
            delta: Vec2::new(0.0, -1.0),
        });
        world.insert_resource(PointerCapture::default());
        world.run_system_once(apply_scroll).unwrap();

        assert_eq!(
            world.entity(container).get::<ScrollPosition>().unwrap().0,
            Vec2::ZERO,
            "an onWheel node on top must block its ancestor scroll container"
        );
    }

    /// Drive `collect_wheel_events` against a single 200×100 `WheelListener` node (id 7)
    /// centered at (300, 200), with one wheel tick of `wheel` in `unit`. Returns the
    /// emitted `wheel` `UiEvent` (if any) and whether the pointer was flagged UI-owned.
    fn run_wheel(cursor: Vec2, wheel: Vec2, unit: MouseScrollUnit) -> (Option<UiEvent>, bool) {
        let mut world = World::new();

        let mut window = Window::default();
        window.set_physical_cursor_position(Some(cursor.as_dvec2()));
        world.spawn((window, PrimaryWindow));

        let (_ops_tx, ops_rx) = crossbeam_channel::unbounded::<Vec<crate::protocol::Op>>();
        let (out_tx, mut out_rx) = tokio::sync::mpsc::unbounded_channel::<Outbound>();
        let root = world.spawn_empty().id();
        world.insert_resource(JsBridge::new(ops_rx, out_tx, root));

        let node = world
            .spawn((
                RNode(7),
                ComputedNode {
                    size: Vec2::new(200.0, 100.0),
                    inverse_scale_factor: 1.0,
                    ..default()
                },
                UiGlobalTransform::from_translation(Vec2::new(300.0, 200.0)),
                WheelListener,
            ))
            .id();
        world.insert_resource(UiStack {
            uinodes: vec![node],
            partition: Vec::new(),
        });
        world.insert_resource(AccumulatedMouseScroll { unit, delta: wheel });
        world.insert_resource(PointerCapture::default());

        world.run_system_once(collect_wheel_events).unwrap();

        let event = out_rx.try_recv().ok().map(|o| match o {
            Outbound::UiEvent { event } => event,
            other => panic!("expected a UiEvent, got {other:?}"),
        });
        let over_ui = world.resource::<PointerCapture>().over_ui;
        (event, over_ui)
    }

    #[test]
    fn wheel_over_listener_emits_raw_delta_and_claims() {
        // Cursor over the node; the raw delta rides through untouched (no ScrollStep
        // scaling), tagged with its unit, and the wheel is claimed for the UI.
        let (event, over_ui) = run_wheel(
            Vec2::new(300.0, 200.0),
            Vec2::new(3.0, -2.0),
            MouseScrollUnit::Line,
        );
        let event = event.expect("a wheel event over the listener");
        assert_eq!(event.id, 7);
        assert_eq!(event.kind, "wheel");
        assert_eq!(event.delta_x, Some(3.0));
        assert_eq!(event.delta_y, Some(-2.0));
        assert_eq!(event.delta_mode.as_deref(), Some("line"));
        // Cursor at the node's center → normalized (0.5, 0.5), absolute = logical cursor.
        assert_eq!(event.x, Some(0.5));
        assert_eq!(event.y, Some(0.5));
        assert_eq!(event.client_x, Some(300.0));
        assert_eq!(event.client_y, Some(200.0));
        assert!(
            over_ui,
            "handling the wheel must claim the pointer for the UI"
        );
    }

    #[test]
    fn wheel_reports_pixel_unit_for_trackpads() {
        let (event, _) = run_wheel(
            Vec2::new(300.0, 200.0),
            Vec2::new(0.0, 12.0),
            MouseScrollUnit::Pixel,
        );
        assert_eq!(
            event.expect("a wheel event").delta_mode.as_deref(),
            Some("pixel")
        );
    }

    #[test]
    fn wheel_outside_listener_emits_nothing() {
        // In-window but outside the node's rect (x:200..400, y:150..250) → no event, and
        // the wheel is left un-owned so world systems still receive it.
        let (event, over_ui) = run_wheel(
            Vec2::new(50.0, 50.0),
            Vec2::new(0.0, -1.0),
            MouseScrollUnit::Line,
        );
        assert!(event.is_none(), "no listener under the cursor");
        assert!(!over_ui);
    }

    #[test]
    fn zero_wheel_emits_nothing() {
        let (event, over_ui) =
            run_wheel(Vec2::new(300.0, 200.0), Vec2::ZERO, MouseScrollUnit::Line);
        assert!(event.is_none(), "a zero delta must not emit a wheel event");
        assert!(!over_ui);
    }
}