rdom-core 0.5.0

Arena-backed DOM for Rust — pure tree + events, no renderer. Can be used headlessly or paired with rdom-tui for terminal rendering.
Documentation
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
//! Event listener storage + `dispatch_event` (capture → target → bubble).
//!
//! Listeners are held in a side `HashMap<NodeId, Vec<Listener<Ext>>>` on
//! `Dom` — nodes without listeners don't pay any per-element cost. A
//! listener handle (`ListenerId`) is returned from `add_event_listener`
//! so callers can remove the exact registration later.
//!
//! Dispatch algorithm (mirrors the DOM spec):
//!
//! 1. Compute the ancestor path from target up to root (inclusive).
//! 2. **Capture phase** — iterate path root→target (excluding target); on
//!    each node fire listeners whose `capture == true`.
//! 3. **Target phase** — on target fire every listener (both capture and
//!    bubble variants).
//! 4. **Bubble phase** — if `event.bubbles`, iterate target→root
//!    (excluding target); on each node fire listeners whose `capture == false`.
//!
//! `stop_propagation` cuts at node-boundaries. `stop_immediate_propagation`
//! cuts mid-node (no further listeners on the current node run).
//!
//! Handlers are `FnMut(&mut EventCtx<'_, Ext>)`. They receive a mutable
//! reference to the Dom via the context — mutations during dispatch are
//! allowed; the dispatcher captures the ancestor path up-front so removed
//! nodes mid-flight don't break iteration. Listeners added during a
//! handler fire on *subsequent* dispatches, not the current one.

use std::collections::HashMap;

use crate::abort::AbortSignal;
use crate::dom::Dom;
use crate::error::{DomError, Result};
use crate::event::{Event, EventPhase};
use crate::node_id::NodeId;

/// Handle returned from `add_event_listener` — pass to `remove_event_listener`
/// to detach this specific registration.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ListenerId {
    pub node: NodeId,
    pub seq: u32,
}

/// A single registration.
///
/// `handler` is `Option` so the dispatcher can `take` it out (handing
/// `&mut Dom` to the handler) and put it back after the call. `None`
/// during a call means "currently firing".
pub(crate) struct Listener<Ext: 'static> {
    seq: u32,
    event_type: String,
    capture: bool,
    once: bool,
    /// If `Some`, the listener is dropped + skipped on the next
    /// dispatch visit once `signal.is_aborted()` returns true.
    signal: Option<AbortSignal>,
    handler: Option<EventHandler<Ext>>,
}

/// Boxed event handler stored on a [`Listener`].
pub(crate) type EventHandler<Ext> = Box<dyn FnMut(&mut EventCtx<'_, Ext>) + 'static>;

/// Context passed to a handler: mutable Event + mutable Dom.
pub struct EventCtx<'a, Ext: 'static> {
    pub event: &'a mut Event,
    pub dom: &'a mut Dom<Ext>,
}

impl<Ext: 'static> EventCtx<'_, Ext> {
    /// Ask the rendering host to repaint after this event completes.
    ///
    /// Mutations made through `ctx.dom` are already seen by the host's
    /// mutation tracker. Use this for the case the tracker *can't* see:
    /// a handler that changed state living **outside** the DOM that the
    /// next paint will read — e.g. a `<canvas>` whose paint callback
    /// reads external application state. Without this, such a change
    /// produces no repaint until something else dirties the tree.
    ///
    /// Sets a flag on the event ([`Event::redraw_requested`]) that the
    /// host harvests after dispatch; `rdom-core` itself does nothing
    /// with it.
    pub fn request_redraw(&mut self) {
        self.event.redraw_requested = true;
    }
}

/// Which activation step the Dom's hook is being asked to run.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ActivationPhase {
    /// Before any listener: the legacy-pre-activation step (a checkbox
    /// flips its state here so click listeners see the new value).
    Pre,
    /// After dispatch. `canceled` is the event's canceled flag: run the
    /// legacy-canceled-activation step (revert) when true, the
    /// activation behavior proper (fire `input` / `change`, submit,
    /// navigate) when false.
    Post { canceled: bool },
}

/// The Dom's activation-behavior hook (DOM §2.9 steps 5.5 and 11). One
/// per `Dom`; it receives every dispatched event and decides by target
/// and event type whether the target has activation behavior. Runs
/// regardless of `stopPropagation()`.
pub type ActivationHook<Ext> =
    Box<dyn FnMut(&mut Dom<Ext>, NodeId, &Event, ActivationPhase) + 'static>;

/// The DOM "dispatch flag" of one [`Dom::dispatch_event`] call: set on
/// construction, cleared on drop, so no return path — an early error,
/// a listener panic unwinding through — leaves an `Event` flagged as in
/// flight (`P7G-DISPATCH-FLAG-1`).
struct DispatchFlag<'e>(&'e mut Event);

impl<'e> DispatchFlag<'e> {
    fn set(event: &'e mut Event) -> Self {
        event.dispatching = true;
        Self(event)
    }
}

impl Drop for DispatchFlag<'_> {
    fn drop(&mut self) {
        self.0.dispatching = false;
    }
}

impl std::ops::Deref for DispatchFlag<'_> {
    type Target = Event;
    fn deref(&self) -> &Event {
        self.0
    }
}

impl std::ops::DerefMut for DispatchFlag<'_> {
    fn deref_mut(&mut self) -> &mut Event {
        self.0
    }
}

/// Storage for the hook with a `Debug` impl (the closure has none).
pub(crate) struct ActivationSlot<Ext: 'static>(pub(crate) Option<ActivationHook<Ext>>);

impl<Ext: 'static> std::fmt::Debug for ActivationSlot<Ext> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(if self.0.is_some() {
            "ActivationSlot(Some(hook))"
        } else {
            "ActivationSlot(None)"
        })
    }
}
/// Options for `add_event_listener` — matches the DOM spec object.
///
/// Not `Copy` because `signal: Option<AbortSignal>` holds an `Rc`.
/// Cloning is cheap (refcount bump).
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct ListenerOptions {
    /// Fire during the capture phase instead of the bubble phase.
    pub capture: bool,
    /// Remove the listener after it fires once.
    pub once: bool,
    /// If `Some`, the listener auto-removes once the signal is
    /// aborted. See [`AbortController`] / [`AbortSignal`] for the
    /// lifetime-management pattern.
    ///
    /// [`AbortController`]: crate::AbortController
    /// [`AbortSignal`]: crate::AbortSignal
    pub signal: Option<AbortSignal>,
}

impl ListenerOptions {
    pub fn capture() -> Self {
        Self {
            capture: true,
            ..Default::default()
        }
    }
    pub fn once() -> Self {
        Self {
            once: true,
            ..Default::default()
        }
    }
    /// Builder-style: set `capture`.
    pub fn with_capture(mut self, capture: bool) -> Self {
        self.capture = capture;
        self
    }
    /// Builder-style: set `once`.
    pub fn with_once(mut self, once: bool) -> Self {
        self.once = once;
        self
    }
    /// Builder-style: attach an abort signal. When the signal fires,
    /// this listener is removed on the next dispatch visit.
    pub fn with_signal(mut self, signal: AbortSignal) -> Self {
        self.signal = Some(signal);
        self
    }
}

/// Per-Dom listener storage. One entry per node that has at least one
/// registered listener.
#[derive(Default)]
pub(crate) struct ListenerStore<Ext: 'static> {
    by_node: HashMap<NodeId, Vec<Listener<Ext>>>,
    /// Monotonic sequence counter for unique ListenerIds.
    next_seq: u32,
}

impl<Ext: 'static> ListenerStore<Ext> {
    fn next(&mut self) -> u32 {
        let n = self.next_seq;
        self.next_seq = self.next_seq.wrapping_add(1);
        n
    }
}

impl<Ext: 'static> std::fmt::Debug for ListenerStore<Ext> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ListenerStore")
            .field("nodes_with_listeners", &self.by_node.len())
            .field("next_seq", &self.next_seq)
            .finish()
    }
}

// Listeners don't Clone — cloning a Dom that owns closures is nonsensical.
// Provide a manual `Clone` impl on Dom that resets listeners to empty (see
// dom.rs). For now ListenerStore is `Default` but not `Clone`.

impl<Ext> Dom<Ext> {
    /// Register a listener on `node` for events of type `event_type`.
    /// Returns a `ListenerId` that can be passed to `remove_event_listener`.
    pub fn add_event_listener(
        &mut self,
        node: NodeId,
        event_type: impl Into<String>,
        options: ListenerOptions,
        handler: impl FnMut(&mut EventCtx<'_, Ext>) + 'static,
    ) -> Result<ListenerId> {
        self.node_or_err(node)?;
        let seq = self.listeners.next();
        let listener = Listener {
            seq,
            event_type: event_type.into(),
            capture: options.capture,
            once: options.once,
            signal: options.signal,
            handler: Some(Box::new(handler)),
        };
        // Registering with an already-aborted signal still succeeds —
        // the listener goes into storage and gets dropped on the
        // first dispatch visit (never fires). Matches browser
        // behavior; tests exercise this path explicitly.
        self.listeners
            .by_node
            .entry(node)
            .or_default()
            .push(listener);
        Ok(ListenerId { node, seq })
    }

    /// Remove a previously-registered listener. Returns `true` if the
    /// listener existed and was removed; `false` if it was already gone
    /// (e.g. a `once` handler that already fired).
    pub fn remove_event_listener(&mut self, handle: ListenerId) -> bool {
        let Some(vec) = self.listeners.by_node.get_mut(&handle.node) else {
            return false;
        };
        let before = vec.len();
        vec.retain(|l| l.seq != handle.seq);
        let removed = vec.len() < before;
        if vec.is_empty() {
            self.listeners.by_node.remove(&handle.node);
        }
        removed
    }

    /// How many listeners are currently registered on `node`.
    pub fn listener_count(&self, node: NodeId) -> usize {
        self.listeners.by_node.get(&node).map_or(0, Vec::len)
    }

    /// Install (or remove, with `None`) the Dom's activation-behavior hook.
    /// See [`ActivationHook`]. A backend installs one hook for all its
    /// elements with activation behavior and dispatches on tag / type
    /// inside it.
    pub fn set_activation_hook(&mut self, hook: Option<ActivationHook<Ext>>) {
        self.activation_hook = ActivationSlot(hook);
    }

    /// Run the activation hook for `phase`, taking it out of `self` for
    /// the call so the hook can receive `&mut Dom` (and re-enter
    /// dispatch without recursion into itself). A hook installed by the
    /// hook itself during the call replaces the old one.
    fn run_activation_hook(&mut self, target: NodeId, event: &Event, phase: ActivationPhase) {
        let Some(mut hook) = self.activation_hook.0.take() else {
            return;
        };
        hook(self, target, event, phase);
        if self.activation_hook.0.is_none() {
            self.activation_hook.0 = Some(hook);
        }
    }

    /// Dispatch `event` at `target` per DOM §2.9: one capture pass from
    /// the root down, one bubble pass from the target up. The target
    /// takes part in both — its capture listeners fire in the capture
    /// pass and its non-capture listeners in the bubble pass, each
    /// reporting `EventPhase::AtTarget` — so registration order never
    /// interleaves them, and `stop_propagation()` in a target capture
    /// listener suppresses the target's bubble listeners. Returns `Err`
    /// on an invalid target.
    ///
    /// When dispatch ends, `phase`, `current_target`, and the two
    /// stop-propagation flags are reset (spec step 5.9), so the same
    /// `Event` value can be dispatched again; `default_prevented`
    /// persists.
    ///
    /// Handlers may mutate the Dom via `EventCtx::dom`. The ancestor path
    /// is computed up-front so mid-dispatch mutations don't destabilize
    /// iteration. Listeners added during dispatch fire on *subsequent*
    /// dispatches, not the current one.
    pub fn dispatch_event(&mut self, target: NodeId, event: &mut Event) -> Result<()> {
        self.node_or_err(target)?;
        if event.dispatching {
            // DOM §2.9 step 1: the dispatch flag is set → InvalidStateError.
            // Letting the inner dispatch run would reset the outer
            // dispatch's propagation flags when it finished.
            return Err(DomError::InvalidState("event is already being dispatched"));
        }
        // The flag is set for the passes and cleared when the guard
        // drops — on every return, early (`InvalidNode`) or not, and when
        // a listener panic unwinds (`P7G-DISPATCH-FLAG-1`).
        self.dispatch_passes(target, &mut DispatchFlag::set(event))?;

        // Activation behavior (DOM §2.9 step 11): after dispatch, once,
        // whether or not propagation was stopped; `canceled` tells the
        // hook to run the legacy-canceled-activation step instead.
        let canceled = event.default_prevented();
        self.run_activation_hook(target, event, ActivationPhase::Post { canceled });
        Ok(())
    }

    /// The part of [`Self::dispatch_event`] run with the dispatch flag
    /// set: the pre-activation step, the capture and bubble passes and
    /// the end-of-dispatch reset (DOM §2.9 steps 5.5–5.9).
    fn dispatch_passes(&mut self, target: NodeId, event: &mut Event) -> Result<()> {
        event.target = Some(target);

        // Legacy-pre-activation behavior (DOM §2.9 step 5.5): before any
        // listener sees the event.
        self.run_activation_hook(target, event, ActivationPhase::Pre);

        // Path from root → target (inclusive). Always non-empty if the
        // node is in the arena (the node itself is the last element).
        let path = self.ancestor_path(target);
        if path.is_empty() {
            return Err(DomError::InvalidNode(target));
        }

        // DOM §2.9 dispatch: one capture pass root → target, one bubble
        // pass target → root. The target participates in *both* passes
        // (its capture listeners in the first, its non-capture listeners
        // in the second) and reports `AtTarget` for each. This is what
        // every engine ships since 2019: a target capture listener runs
        // before a target bubble listener regardless of registration
        // order, and `stopPropagation()` in the former suppresses the
        // latter.

        // ── Capture pass ──────────────────────────────────────────
        event.phase = EventPhase::Capturing;
        for &node in path.iter().take(path.len() - 1) {
            if event.propagation_stopped {
                break;
            }
            event.current_target = Some(node);
            self.fire_at(node, event, PhaseFilter::Capture);
        }
        if !event.propagation_stopped {
            event.phase = EventPhase::AtTarget;
            event.current_target = Some(target);
            self.fire_at(target, event, PhaseFilter::Capture);
        }

        // ── Bubble pass ───────────────────────────────────────────
        if !event.propagation_stopped {
            event.phase = EventPhase::AtTarget;
            event.current_target = Some(target);
            self.fire_at(target, event, PhaseFilter::Bubble);
        }
        if event.bubbles && !event.propagation_stopped {
            event.phase = EventPhase::Bubbling;
            for &node in path.iter().rev().skip(1) {
                if event.propagation_stopped {
                    break;
                }
                event.current_target = Some(node);
                self.fire_at(node, event, PhaseFilter::Bubble);
            }
        }

        // DOM §2.9 step 5.9: clear the propagation flags so the same
        // `Event` can be dispatched again. `default_prevented` (the
        // canceled flag) deliberately persists.
        event.phase = EventPhase::None;
        event.current_target = None;
        event.propagation_stopped = false;
        event.immediate_propagation_stopped = false;
        Ok(())
    }

    /// Run matching listeners on `node`. Filter by `filter` (capture /
    /// bubble / all). Handlers get `&mut self` via `EventCtx::dom`.
    ///
    /// Implementation: snapshot the list of listener sequences to run,
    /// then for each one re-find it by seq, mem-replace its handler with
    /// a no-op while calling it, and restore afterwards. Handlers may add
    /// or remove listeners on this or any other node freely.
    fn fire_at(&mut self, node: NodeId, event: &mut Event, filter: PhaseFilter) {
        // Opportunistic sweep: drop any aborted listeners on this
        // node before snapshotting. Cheap (only runs when we're
        // about to dispatch) and keeps storage bounded across abort
        // cycles.
        if let Some(list) = self.listeners.by_node.get_mut(&node) {
            list.retain(|l| !l.signal.as_ref().is_some_and(|s| s.is_aborted()));
            if list.is_empty() {
                self.listeners.by_node.remove(&node);
            }
        }

        // Step 1: snapshot (seq, once) of listeners to run, in order.
        let to_fire: Vec<(u32, bool)> = match self.listeners.by_node.get(&node) {
            Some(list) => list
                .iter()
                .filter(|l| l.event_type == event.event_type && filter.matches(l.capture))
                .map(|l| (l.seq, l.once))
                .collect(),
            None => return,
        };

        // Step 2: fire each in order, re-locating by seq each time in case
        // handlers added/removed entries.
        for (seq, once) in to_fire {
            if event.immediate_propagation_stopped {
                break;
            }
            // Locate the listener.
            let Some(list) = self.listeners.by_node.get_mut(&node) else {
                return;
            };
            let Some(i) = list.iter().position(|l| l.seq == seq) else {
                continue; // removed by a previous handler
            };
            // Per-listener abort check — a prior handler in this
            // same dispatch may have aborted a signal governing
            // subsequent listeners. Drop + skip.
            if list[i].signal.as_ref().is_some_and(|s| s.is_aborted()) {
                list.remove(i);
                continue;
            }
            // Take the handler out so we can hand &mut self to it.
            let Some(mut handler) = list[i].handler.take() else {
                // Re-entrant call on the same listener — skip.
                continue;
            };

            // Run it. A panicking handler is caught so the listener can
            // be restored below — otherwise a host that catches the
            // panic is left with a listener that is counted but never
            // fires again. The payload is re-raised after restore.
            let outcome = {
                let mut ctx = EventCtx { event, dom: self };
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| handler(&mut ctx)))
            };

            // Restore (or expire, for `once`).
            if let Some(list) = self.listeners.by_node.get_mut(&node) {
                if let Some(i) = list.iter().position(|l| l.seq == seq) {
                    if once {
                        list.remove(i);
                    } else {
                        list[i].handler = Some(handler);
                    }
                }
                if list.is_empty() {
                    self.listeners.by_node.remove(&node);
                }
            }
            // If the node was removed from by_node mid-handler we simply
            // drop `handler`. A dropped listener stays dropped — matches
            // `remove_event_listener` semantics.

            if let Err(payload) = outcome {
                std::panic::resume_unwind(payload);
            }
        }
    }

    /// Internal hook: called from `free` to drop any listeners attached
    /// to a node that's being discarded.
    pub(crate) fn drop_listeners(&mut self, node: NodeId) {
        self.listeners.by_node.remove(&node);
    }
}

/// Which listeners to fire based on their `capture` flag.
#[derive(Debug, Clone, Copy)]
enum PhaseFilter {
    Capture,
    Bubble,
}

impl PhaseFilter {
    fn matches(self, listener_capture: bool) -> bool {
        match self {
            PhaseFilter::Capture => listener_capture,
            PhaseFilter::Bubble => !listener_capture,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::event::Event;
    use std::cell::Cell;
    use std::rc::Rc;

    /// Small helper to build a tree root → a → b → c and return ids.
    fn build_chain() -> (Dom, NodeId, NodeId, NodeId, NodeId) {
        let mut dom: Dom = Dom::new();
        let root = dom.root();
        let a = dom.create_element("a");
        let b = dom.create_element("b");
        let c = dom.create_element("c");
        dom.append_child(a, b).unwrap();
        dom.append_child(b, c).unwrap();
        dom.append_child(root, a).unwrap();
        (dom, a, b, c, root)
    }

    /// A panicking listener stays registered. Without this, a host that
    /// catches the panic ends up with a listener that is counted but
    /// never fires again — silent breakage of the consumer's wiring.
    #[test]
    fn panicking_listener_is_restored_after_the_panic() {
        let mut dom: Dom = Dom::new();
        let el = dom.create_element("div");
        let fired = Rc::new(Cell::new(0));
        let f2 = fired.clone();
        dom.add_event_listener(el, "click", ListenerOptions::default(), move |_| {
            f2.set(f2.get() + 1);
            if f2.get() == 1 {
                panic!("listener bomb");
            }
        })
        .unwrap();

        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let mut e = Event::new("click");
            dom.dispatch_event(el, &mut e).unwrap();
        }));
        assert!(result.is_err());
        assert_eq!(fired.get(), 1);
        assert_eq!(dom.listener_count(el), 1);

        // Second dispatch reaches the same listener again.
        let mut e = Event::new("click");
        dom.dispatch_event(el, &mut e).unwrap();
        assert_eq!(fired.get(), 2);
    }

    /// `P7G-DISPATCH-FLAG-1`: a pre-activation hook that drops the
    /// target makes `dispatch_event` return `InvalidNode` — and leaves
    /// the event undispatched, so the caller can retry it elsewhere
    /// instead of getting `InvalidState`.
    #[test]
    fn an_early_invalid_node_return_clears_the_dispatch_flag() {
        let (mut dom, a, _, c, _) = build_chain();
        dom.set_activation_hook(Some(Box::new(|dom, target, _, phase| {
            if phase == ActivationPhase::Pre && dom.contains(target) {
                let parent = dom.node(target).parent_node().unwrap().id();
                dom.remove_child_dropping(parent, target).unwrap();
            }
        })));
        let mut e = Event::new("click");
        assert!(matches!(
            dom.dispatch_event(c, &mut e),
            Err(DomError::InvalidNode(_))
        ));
        dom.set_activation_hook(None);
        assert_eq!(dom.dispatch_event(a, &mut e), Ok(()), "retry succeeds");
    }

    /// `P7G-DISPATCH-FLAG-1`: a listener panic that unwinds out of
    /// `dispatch_event` clears the dispatch flag on the way out, so the
    /// same `Event` value can be dispatched again.
    #[test]
    fn a_listener_panic_clears_the_dispatch_flag() {
        let mut dom: Dom = Dom::new();
        let el = dom.create_element("div");
        dom.add_event_listener(el, "boom", ListenerOptions::default(), |_| {
            panic!("listener bomb");
        })
        .unwrap();
        let mut e = Event::new("click");
        let mut boom = Event::new("boom");
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _ = dom.dispatch_event(el, &mut boom);
        }));
        assert!(result.is_err());
        boom.event_type = "click".into();
        assert_eq!(dom.dispatch_event(el, &mut boom), Ok(()));
        assert_eq!(dom.dispatch_event(el, &mut e), Ok(()));
    }

    fn cap() -> ListenerOptions {
        ListenerOptions {
            capture: true,
            ..ListenerOptions::default()
        }
    }

    fn log_listener(
        log: &Rc<std::cell::RefCell<Vec<&'static str>>>,
        tag: &'static str,
    ) -> impl FnMut(&mut EventCtx<'_, ()>) + 'static {
        let log = log.clone();
        move |_| log.borrow_mut().push(tag)
    }

    /// DOM §2.9 (2019+, shipped in every engine): at the target, capture
    /// listeners run in the capture pass and non-capture listeners run
    /// in the bubble pass — registration order does not interleave them.
    #[test]
    fn at_target_capture_listeners_fire_before_bubble_listeners() {
        let (mut dom, _, _, c, _) = build_chain();
        let log = Rc::new(std::cell::RefCell::new(Vec::new()));
        // Register bubble listeners first so registration order would
        // put them ahead of the capture listener.
        dom.add_event_listener(
            c,
            "click",
            ListenerOptions::default(),
            log_listener(&log, "b1"),
        )
        .unwrap();
        dom.add_event_listener(c, "click", cap(), log_listener(&log, "c1"))
            .unwrap();
        dom.add_event_listener(
            c,
            "click",
            ListenerOptions::default(),
            log_listener(&log, "b2"),
        )
        .unwrap();
        dom.add_event_listener(c, "click", cap(), log_listener(&log, "c2"))
            .unwrap();

        let mut e = Event::new("click");
        dom.dispatch_event(c, &mut e).unwrap();
        assert_eq!(*log.borrow(), vec!["c1", "c2", "b1", "b2"]);
    }

    /// `stopPropagation()` in a target capture listener suppresses the
    /// target's own bubble-side listeners (they belong to the next pass).
    #[test]
    fn stop_propagation_in_target_capture_listener_suppresses_target_bubble_listeners() {
        let (mut dom, _, _, c, _) = build_chain();
        let log = Rc::new(std::cell::RefCell::new(Vec::new()));
        dom.add_event_listener(
            c,
            "click",
            ListenerOptions::default(),
            log_listener(&log, "bubble"),
        )
        .unwrap();
        {
            let log = log.clone();
            dom.add_event_listener(c, "click", cap(), move |ctx| {
                log.borrow_mut().push("capture");
                ctx.event.stop_propagation();
            })
            .unwrap();
        }
        let mut e = Event::new("click");
        dom.dispatch_event(c, &mut e).unwrap();
        assert_eq!(*log.borrow(), vec!["capture"]);
    }

    /// Both listeners at the target report `AT_TARGET` as the phase.
    #[test]
    fn at_target_phase_is_reported_for_both_capture_and_bubble_listeners() {
        let (mut dom, _, _, c, _) = build_chain();
        let phases = Rc::new(std::cell::RefCell::new(Vec::new()));
        for opts in [cap(), ListenerOptions::default()] {
            let phases = phases.clone();
            dom.add_event_listener(c, "click", opts, move |ctx| {
                phases.borrow_mut().push(ctx.event.phase);
            })
            .unwrap();
        }
        let mut e = Event::new("click");
        dom.dispatch_event(c, &mut e).unwrap();
        assert_eq!(
            *phases.borrow(),
            vec![EventPhase::AtTarget, EventPhase::AtTarget]
        );
    }

    /// DOM §2.9 step 5.9: the stop-propagation flags are cleared when
    /// dispatch ends, so the same `Event` value can be dispatched again
    /// (only `canceled` persists).
    #[test]
    fn propagation_flags_reset_after_dispatch_so_event_can_be_redispatched() {
        let (mut dom, _, _, c, _) = build_chain();
        let fired = Rc::new(Cell::new(0));
        {
            let fired = fired.clone();
            dom.add_event_listener(c, "click", ListenerOptions::default(), move |ctx| {
                fired.set(fired.get() + 1);
                ctx.event.stop_immediate_propagation();
                ctx.event.prevent_default();
            })
            .unwrap();
        }
        let mut e = Event::new("click");
        dom.dispatch_event(c, &mut e).unwrap();
        assert!(!e.is_propagation_stopped());
        assert!(!e.is_immediate_propagation_stopped());
        assert!(e.default_prevented(), "canceled flag persists");

        dom.dispatch_event(c, &mut e).unwrap();
        assert_eq!(fired.get(), 2, "second dispatch reaches the listener again");
    }

    /// DOM §2.9 step 1: dispatching an event whose dispatch flag is set
    /// throws `InvalidStateError`. Without this, the inner dispatch's
    /// end-of-dispatch flag reset would clobber the outer dispatch's
    /// `stop_propagation()`.
    #[test]
    fn redispatching_an_in_flight_event_is_an_error_and_keeps_outer_flags() {
        let (mut dom, a, _, c, _) = build_chain();
        let inner_result = Rc::new(std::cell::RefCell::new(None));
        let target_fired = Rc::new(Cell::new(false));
        {
            let inner_result = inner_result.clone();
            dom.add_event_listener(a, "click", cap(), move |ctx| {
                ctx.event.stop_propagation();
                let r = ctx.dom.dispatch_event(a, ctx.event);
                *inner_result.borrow_mut() = Some(r);
            })
            .unwrap();
        }
        {
            let target_fired = target_fired.clone();
            dom.add_event_listener(c, "click", ListenerOptions::default(), move |_| {
                target_fired.set(true);
            })
            .unwrap();
        }
        let mut e = Event::new("click");
        dom.dispatch_event(c, &mut e).unwrap();
        assert!(matches!(
            inner_result.borrow().as_ref(),
            Some(Err(DomError::InvalidState(_)))
        ));
        assert!(
            !target_fired.get(),
            "outer stop_propagation survived the inner attempt"
        );
        // And the event is dispatchable again once the outer dispatch ends.
        dom.dispatch_event(c, &mut e).unwrap();
    }

    #[test]
    fn stale_id_is_rejected_by_dispatch_and_add_event_listener() {
        let mut dom: Dom = Dom::new();
        let root = dom.root();
        let el = dom.create_element("div");
        dom.append_child(root, el).unwrap();
        dom.remove_child_dropping(root, el).unwrap();
        let _reuses_slot = dom.create_element("span");
        let mut e = Event::new("click");
        assert!(matches!(
            dom.dispatch_event(el, &mut e).unwrap_err(),
            DomError::InvalidNode(_)
        ));
        assert!(matches!(
            dom.add_event_listener(el, "click", ListenerOptions::default(), |_| {})
                .unwrap_err(),
            DomError::InvalidNode(_)
        ));
    }

    /// DOM §2.9 activation behavior: the Dom's activation hook runs its
    /// pre-activation step before any listener sees the event and its
    /// post step after dispatch with the canceled flag — regardless of
    /// `stopPropagation()`, which only affects listeners.
    #[test]
    fn activation_hook_runs_pre_before_listeners_and_post_after_even_when_propagation_stops() {
        let (mut dom, _, _, c, _) = build_chain();
        let log = Rc::new(std::cell::RefCell::new(Vec::<String>::new()));
        {
            let log = log.clone();
            dom.set_activation_hook(Some(Box::new(move |_dom, target, event, phase| {
                log.borrow_mut()
                    .push(format!("{:?} {} {}", phase, event.event_type, target == c));
            })));
        }
        {
            let log = log.clone();
            dom.add_event_listener(c, "click", ListenerOptions::default(), move |ctx| {
                log.borrow_mut().push("listener".to_string());
                ctx.event.stop_propagation();
                ctx.event.prevent_default();
            })
            .unwrap();
        }
        let mut e = Event::new("click");
        e.cancelable = true;
        dom.dispatch_event(c, &mut e).unwrap();
        assert_eq!(
            *log.borrow(),
            vec![
                "Pre click true".to_string(),
                "listener".to_string(),
                "Post { canceled: true } click true".to_string(),
            ]
        );
        // The hook can be removed again.
        dom.set_activation_hook(None);
        dom.dispatch_event(c, &mut Event::new("click")).unwrap();
        assert_eq!(log.borrow().len(), 4, "only the listener ran");
    }

    #[test]
    fn add_and_remove_listener() {
        let mut dom: Dom = Dom::new();
        let el = dom.create_element("div");
        let fired = Rc::new(Cell::new(0));
        let f2 = fired.clone();
        let id = dom
            .add_event_listener(el, "click", ListenerOptions::default(), move |_| {
                f2.set(f2.get() + 1);
            })
            .unwrap();
        assert_eq!(dom.listener_count(el), 1);

        let mut e = Event::new("click");
        dom.dispatch_event(el, &mut e).unwrap();
        assert_eq!(fired.get(), 1);

        assert!(dom.remove_event_listener(id));
        assert_eq!(dom.listener_count(el), 0);

        let mut e2 = Event::new("click");
        dom.dispatch_event(el, &mut e2).unwrap();
        assert_eq!(fired.get(), 1); // unchanged
    }

    #[test]
    fn capture_target_bubble_ordering() {
        let (mut dom, a, b, c, _) = build_chain();
        let order = Rc::new(std::cell::RefCell::new(Vec::<&'static str>::new()));

        let o = order.clone();
        dom.add_event_listener(a, "click", ListenerOptions::capture(), move |_| {
            o.borrow_mut().push("a-capture");
        })
        .unwrap();
        let o = order.clone();
        dom.add_event_listener(b, "click", ListenerOptions::capture(), move |_| {
            o.borrow_mut().push("b-capture");
        })
        .unwrap();
        let o = order.clone();
        dom.add_event_listener(c, "click", ListenerOptions::default(), move |_| {
            o.borrow_mut().push("c-target");
        })
        .unwrap();
        let o = order.clone();
        dom.add_event_listener(b, "click", ListenerOptions::default(), move |_| {
            o.borrow_mut().push("b-bubble");
        })
        .unwrap();
        let o = order.clone();
        dom.add_event_listener(a, "click", ListenerOptions::default(), move |_| {
            o.borrow_mut().push("a-bubble");
        })
        .unwrap();

        let mut e = Event::new("click");
        dom.dispatch_event(c, &mut e).unwrap();

        assert_eq!(
            *order.borrow(),
            vec!["a-capture", "b-capture", "c-target", "b-bubble", "a-bubble"]
        );
    }

    #[test]
    fn stop_propagation_cuts_bubble() {
        let (mut dom, a, b, c, _) = build_chain();
        let a_fired = Rc::new(Cell::new(false));
        let af = a_fired.clone();
        dom.add_event_listener(a, "click", ListenerOptions::default(), move |_| {
            af.set(true);
        })
        .unwrap();
        dom.add_event_listener(b, "click", ListenerOptions::default(), move |ctx| {
            ctx.event.stop_propagation();
        })
        .unwrap();

        let mut e = Event::new("click");
        dom.dispatch_event(c, &mut e).unwrap();
        assert!(!a_fired.get());
    }

    #[test]
    fn stop_immediate_cuts_sibling_listener_on_same_node() {
        let mut dom: Dom = Dom::new();
        let el = dom.create_element("div");
        let hit_first = Rc::new(Cell::new(false));
        let hit_second = Rc::new(Cell::new(false));
        let h1 = hit_first.clone();
        let h2 = hit_second.clone();
        dom.add_event_listener(el, "x", ListenerOptions::default(), move |ctx| {
            h1.set(true);
            ctx.event.stop_immediate_propagation();
        })
        .unwrap();
        dom.add_event_listener(el, "x", ListenerOptions::default(), move |_| {
            h2.set(true);
        })
        .unwrap();

        let mut e = Event::new("x");
        dom.dispatch_event(el, &mut e).unwrap();
        assert!(hit_first.get());
        assert!(!hit_second.get());
    }

    #[test]
    fn non_bubbling_skips_bubble_phase() {
        let (mut dom, a, _, c, _) = build_chain();
        let a_fired = Rc::new(Cell::new(false));
        let af = a_fired.clone();
        dom.add_event_listener(a, "x", ListenerOptions::default(), move |_| {
            af.set(true);
        })
        .unwrap();

        let mut e = Event::new("x").with_bubbles(false);
        dom.dispatch_event(c, &mut e).unwrap();
        assert!(!a_fired.get());
    }

    #[test]
    fn prevent_default_sets_flag() {
        let mut dom: Dom = Dom::new();
        let el = dom.create_element("div");
        dom.add_event_listener(el, "click", ListenerOptions::default(), move |ctx| {
            ctx.event.prevent_default();
        })
        .unwrap();
        let mut e = Event::new("click");
        dom.dispatch_event(el, &mut e).unwrap();
        assert!(e.default_prevented());
    }

    #[test]
    fn once_removes_after_firing() {
        let mut dom: Dom = Dom::new();
        let el = dom.create_element("div");
        let fired = Rc::new(Cell::new(0));
        let f = fired.clone();
        dom.add_event_listener(el, "x", ListenerOptions::once(), move |_| {
            f.set(f.get() + 1);
        })
        .unwrap();

        let mut e1 = Event::new("x");
        dom.dispatch_event(el, &mut e1).unwrap();
        let mut e2 = Event::new("x");
        dom.dispatch_event(el, &mut e2).unwrap();
        assert_eq!(fired.get(), 1);
        assert_eq!(dom.listener_count(el), 0);
    }

    #[test]
    fn listener_type_is_filtered() {
        let mut dom: Dom = Dom::new();
        let el = dom.create_element("div");
        let click = Rc::new(Cell::new(0));
        let input = Rc::new(Cell::new(0));
        let cc = click.clone();
        let ii = input.clone();
        dom.add_event_listener(el, "click", ListenerOptions::default(), move |_| {
            cc.set(cc.get() + 1);
        })
        .unwrap();
        dom.add_event_listener(el, "input", ListenerOptions::default(), move |_| {
            ii.set(ii.get() + 1);
        })
        .unwrap();
        let mut e = Event::new("click");
        dom.dispatch_event(el, &mut e).unwrap();
        assert_eq!(click.get(), 1);
        assert_eq!(input.get(), 0);
    }

    #[test]
    fn handler_may_read_dom() {
        let mut dom: Dom = Dom::new();
        let root = dom.root();
        let a = dom.create_element("a");
        dom.set_attribute(a, "id", "target").unwrap();
        dom.append_child(root, a).unwrap();
        let seen = Rc::new(Cell::new(false));
        let s = seen.clone();
        dom.add_event_listener(a, "click", ListenerOptions::default(), move |ctx| {
            if ctx.dom.get_element_by_id("target").is_some() {
                s.set(true);
            }
        })
        .unwrap();

        let mut e = Event::new("click");
        dom.dispatch_event(a, &mut e).unwrap();
        assert!(seen.get());
    }

    #[test]
    fn handler_may_mutate_dom() {
        let mut dom: Dom = Dom::new();
        let el = dom.create_element("div");
        dom.add_event_listener(el, "click", ListenerOptions::default(), move |ctx| {
            let added = ctx.dom.create_element("added");
            ctx.dom.append_child(el, added).unwrap();
        })
        .unwrap();
        let mut e = Event::new("click");
        dom.dispatch_event(el, &mut e).unwrap();
        assert_eq!(dom.node(el).child_element_count(), 1);
    }

    #[test]
    fn dispatch_on_orphan_node_still_fires_target() {
        let mut dom: Dom = Dom::new();
        let el = dom.create_element("div");
        let fired = Rc::new(Cell::new(false));
        let f = fired.clone();
        dom.add_event_listener(el, "click", ListenerOptions::default(), move |_| {
            f.set(true);
        })
        .unwrap();
        let mut e = Event::new("click");
        dom.dispatch_event(el, &mut e).unwrap();
        assert!(fired.get());
    }

    #[test]
    fn current_target_reflects_node_during_dispatch() {
        let (mut dom, a, _b, c, _) = build_chain();
        let ct_at_a = Rc::new(Cell::new(None));
        let p = ct_at_a.clone();
        dom.add_event_listener(a, "click", ListenerOptions::default(), move |ctx| {
            p.set(ctx.event.current_target);
        })
        .unwrap();
        let mut e = Event::new("click");
        dom.dispatch_event(c, &mut e).unwrap();
        assert_eq!(ct_at_a.get(), Some(a));
        // After dispatch, current_target is reset.
        assert_eq!(e.current_target, None);
    }

    #[test]
    fn removing_node_unregisters_listeners_via_drop_subtree() {
        let mut dom: Dom = Dom::new();
        let el = dom.create_element("div");
        let _ = dom
            .add_event_listener(el, "click", ListenerOptions::default(), |_| {})
            .unwrap();
        let root = dom.root();
        dom.append_child(root, el).unwrap();
        dom.drop_subtree(el).unwrap();
        assert_eq!(dom.listener_count(el), 0);
    }

    // ── AbortSignal / AbortController ────────────────────────────────

    #[test]
    fn abort_signal_removes_listener_on_next_dispatch() {
        use crate::AbortController;

        let mut dom: Dom = Dom::new();
        let el = dom.create_element("div");
        let fired = Rc::new(Cell::new(0));
        let f = fired.clone();

        let ctrl = AbortController::new();
        let sig = ctrl.signal();
        dom.add_event_listener(
            el,
            "click",
            ListenerOptions::default().with_signal(sig),
            move |_| {
                f.set(f.get() + 1);
            },
        )
        .unwrap();

        // First dispatch: fires normally.
        dom.dispatch_event(el, &mut Event::new("click")).unwrap();
        assert_eq!(fired.get(), 1);

        // Abort, then dispatch again: listener is skipped + removed.
        ctrl.abort();
        dom.dispatch_event(el, &mut Event::new("click")).unwrap();
        assert_eq!(fired.get(), 1);
        assert_eq!(dom.listener_count(el), 0);
    }

    #[test]
    fn abort_signal_removes_multiple_listeners_at_once() {
        use crate::AbortController;

        let mut dom: Dom = Dom::new();
        let el = dom.create_element("div");
        let ctrl = AbortController::new();
        let sig = ctrl.signal();

        for _ in 0..5 {
            dom.add_event_listener(
                el,
                "click",
                ListenerOptions::default().with_signal(sig.clone()),
                |_| {},
            )
            .unwrap();
        }
        assert_eq!(dom.listener_count(el), 5);

        ctrl.abort();
        dom.dispatch_event(el, &mut Event::new("click")).unwrap();
        assert_eq!(dom.listener_count(el), 0);
    }

    #[test]
    fn abort_signal_independent_of_other_listeners() {
        use crate::AbortController;

        let mut dom: Dom = Dom::new();
        let el = dom.create_element("div");
        let ctrl = AbortController::new();
        let sig = ctrl.signal();

        let fired_aborted = Rc::new(Cell::new(0));
        let fa = fired_aborted.clone();
        dom.add_event_listener(
            el,
            "click",
            ListenerOptions::default().with_signal(sig),
            move |_| {
                fa.set(fa.get() + 1);
            },
        )
        .unwrap();

        let fired_normal = Rc::new(Cell::new(0));
        let fn_ = fired_normal.clone();
        dom.add_event_listener(el, "click", ListenerOptions::default(), move |_| {
            fn_.set(fn_.get() + 1);
        })
        .unwrap();

        ctrl.abort();
        dom.dispatch_event(el, &mut Event::new("click")).unwrap();
        assert_eq!(fired_aborted.get(), 0, "aborted listener must not fire");
        assert_eq!(fired_normal.get(), 1, "unrelated listener still fires");
    }

    #[test]
    fn adding_listener_with_already_aborted_signal_never_fires() {
        use crate::AbortController;

        let mut dom: Dom = Dom::new();
        let el = dom.create_element("div");
        let ctrl = AbortController::new();
        ctrl.abort();

        let fired = Rc::new(Cell::new(0));
        let f = fired.clone();
        dom.add_event_listener(
            el,
            "click",
            ListenerOptions::default().with_signal(ctrl.signal()),
            move |_| {
                f.set(f.get() + 1);
            },
        )
        .unwrap();

        dom.dispatch_event(el, &mut Event::new("click")).unwrap();
        assert_eq!(fired.get(), 0);
        assert_eq!(dom.listener_count(el), 0);
    }

    #[test]
    fn handler_aborting_mid_dispatch_skips_later_listeners_on_same_node() {
        use crate::AbortController;

        let mut dom: Dom = Dom::new();
        let el = dom.create_element("div");
        let ctrl = AbortController::new();

        let order = Rc::new(std::cell::RefCell::new(Vec::<&'static str>::new()));

        // Listener A: fires + aborts the controller. Shares the
        // controller via `.clone()` into the closure.
        let order_a = order.clone();
        let ctrl_a = ctrl.clone();
        dom.add_event_listener(el, "click", ListenerOptions::default(), move |_| {
            order_a.borrow_mut().push("a");
            ctrl_a.abort();
        })
        .unwrap();

        // Listener B: governed by the signal; should be skipped
        // after A aborts.
        let order_b = order.clone();
        dom.add_event_listener(
            el,
            "click",
            ListenerOptions::default().with_signal(ctrl.signal()),
            move |_| {
                order_b.borrow_mut().push("b");
            },
        )
        .unwrap();

        // Listener C: not governed by the signal; fires regardless.
        let order_c = order.clone();
        dom.add_event_listener(el, "click", ListenerOptions::default(), move |_| {
            order_c.borrow_mut().push("c");
        })
        .unwrap();

        dom.dispatch_event(el, &mut Event::new("click")).unwrap();
        assert_eq!(*order.borrow(), vec!["a", "c"]);
    }

    #[test]
    fn signal_clone_governs_same_listener() {
        use crate::AbortController;

        let mut dom: Dom = Dom::new();
        let el = dom.create_element("div");
        let ctrl = AbortController::new();
        let sig1 = ctrl.signal();
        let sig2 = sig1.clone();

        let fired = Rc::new(Cell::new(0));
        let f = fired.clone();
        dom.add_event_listener(
            el,
            "click",
            ListenerOptions::default().with_signal(sig2),
            move |_| {
                f.set(f.get() + 1);
            },
        )
        .unwrap();

        // Dispatch once: fires. Use sig1 to validate (not aborted).
        assert!(!sig1.is_aborted());
        dom.dispatch_event(el, &mut Event::new("click")).unwrap();
        assert_eq!(fired.get(), 1);

        // Abort via controller, dispatch again: skipped.
        ctrl.abort();
        assert!(sig1.is_aborted());
        dom.dispatch_event(el, &mut Event::new("click")).unwrap();
        assert_eq!(fired.get(), 1);
    }
}