tui-dispatch-core 0.7.0

Core traits and types for tui-dispatch
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
//! Event bus for dispatching events to registered handlers

use crate::event::{ComponentId, EventContext, EventKind, EventType, GlobalKeyPolicy};
use crate::keybindings::Keybindings;
use crate::{Action, BindingContext};
use crossterm::event::{self, KeyEventKind, MouseEventKind};
use std::collections::HashMap;
use std::time::Duration;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
#[cfg(feature = "tracing")]
use tracing::{debug, info};

/// Raw event from crossterm before processing
#[derive(Debug)]
pub enum RawEvent {
    Key(crossterm::event::KeyEvent),
    Mouse(crossterm::event::MouseEvent),
    Resize(u16, u16),
}

/// State accessors used by the event bus for routing decisions.
pub trait EventRoutingState<Id: ComponentId, Ctx: BindingContext> {
    fn focused(&self) -> Option<Id>;
    fn modal(&self) -> Option<Id>;
    fn binding_context(&self, id: Id) -> Ctx;
    fn default_context(&self) -> Ctx;
}

/// Where a handler is being routed in the current event flow.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RouteTarget<Id: ComponentId> {
    Modal(Id),
    Focused(Id),
    Hovered(Id),
    Subscriber(Id),
    Global,
}

/// Result of mapping an event into actions plus an optional render hint.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EventOutcome<A> {
    /// Actions to enqueue.
    pub actions: Vec<A>,
    /// Whether to force a re-render.
    pub needs_render: bool,
}

impl<A> EventOutcome<A> {
    /// No actions and no render.
    pub fn ignored() -> Self {
        Self {
            actions: Vec::new(),
            needs_render: false,
        }
    }

    /// No actions, but request a render.
    pub fn needs_render() -> Self {
        Self {
            actions: Vec::new(),
            needs_render: true,
        }
    }

    /// Wrap a single action.
    pub fn action(action: A) -> Self {
        Self {
            actions: vec![action],
            needs_render: false,
        }
    }

    /// Wrap multiple actions.
    pub fn actions<I>(actions: I) -> Self
    where
        I: IntoIterator<Item = A>,
    {
        Self {
            actions: actions.into_iter().collect(),
            needs_render: false,
        }
    }

    /// Mark that a render is needed.
    pub fn with_render(mut self) -> Self {
        self.needs_render = true;
        self
    }

    /// Create from any iterator of actions
    ///
    /// Useful for converting `Component::handle_event` results which return
    /// `impl IntoIterator<Item = A>`.
    pub fn from_actions(iter: impl IntoIterator<Item = A>) -> Self {
        Self {
            actions: iter.into_iter().collect(),
            needs_render: false,
        }
    }
}

impl<A> Default for EventOutcome<A> {
    fn default() -> Self {
        Self::ignored()
    }
}

impl<A> From<A> for EventOutcome<A> {
    fn from(action: A) -> Self {
        Self::action(action)
    }
}

impl<A> From<Vec<A>> for EventOutcome<A> {
    fn from(actions: Vec<A>) -> Self {
        Self {
            actions,
            needs_render: false,
        }
    }
}

impl<A> From<Option<A>> for EventOutcome<A> {
    fn from(action: Option<A>) -> Self {
        match action {
            Some(action) => Self::action(action),
            None => Self::ignored(),
        }
    }
}

/// Routing plan that determines the order components receive events.
///
/// Priority: Modal → Hovered → Focused → Subscribers → Global subscribers
struct RoutingPlan<Id: ComponentId> {
    targets: Vec<(RouteTarget<Id>, Id)>,
    modal_blocks: bool,
}

impl<Id: ComponentId> RoutingPlan<Id> {
    /// Build a routing plan for an event.
    fn build<S, Ctx>(
        event: &EventKind,
        is_global: bool,
        state: &S,
        subscribers: &[Id],
        global_subscribers: &[Id],
        hovered: Option<Id>,
    ) -> Self
    where
        S: EventRoutingState<Id, Ctx>,
        Ctx: BindingContext,
    {
        let is_broadcast = event.is_broadcast();
        let modal = state.modal();
        let focused = state.focused();

        let mut targets = Vec::with_capacity(
            subscribers.len()
                + if is_global {
                    global_subscribers.len()
                } else {
                    0
                }
                + if modal.is_some() { 1 } else { 0 }
                + if hovered.is_some() { 1 } else { 0 }
                + if focused.is_some() { 1 } else { 0 },
        );

        // Modal gets first priority
        if let Some(id) = modal {
            targets.push((RouteTarget::Modal(id), id));
        }

        // Modal blocks non-broadcast events from reaching other components
        let modal_blocks = modal.is_some() && !is_broadcast;

        if !modal_blocks {
            // Hovered component (mouse events only)
            if let Some(id) = hovered {
                targets.push((RouteTarget::Hovered(id), id));
            }

            // Focused component
            if let Some(id) = focused {
                targets.push((RouteTarget::Focused(id), id));
            }

            // Type-specific subscribers
            for &id in subscribers {
                targets.push((RouteTarget::Subscriber(id), id));
            }
        }

        // Global subscribers (for global events, even when modal is active)
        if is_global {
            for &id in global_subscribers {
                targets.push((RouteTarget::Subscriber(id), id));
            }
        }

        Self {
            targets,
            modal_blocks,
        }
    }

    fn iter(&self) -> impl Iterator<Item = (RouteTarget<Id>, Id)> + '_ {
        self.targets.iter().copied()
    }
}

/// Routed event passed to handlers.
#[derive(Debug, Clone)]
pub struct RoutedEvent<'a, Id: ComponentId, Ctx: BindingContext> {
    pub kind: EventKind,
    pub command: Option<&'a str>,
    pub binding_ctx: Ctx,
    pub target: RouteTarget<Id>,
    pub context: &'a EventContext<Id>,
}

/// Response returned by an event handler.
#[derive(Debug, Clone)]
pub struct HandlerResponse<A> {
    pub actions: Vec<A>,
    pub consumed: bool,
    pub needs_render: bool,
}

impl<A> HandlerResponse<A> {
    pub fn ignored() -> Self {
        Self {
            actions: Vec::new(),
            consumed: false,
            needs_render: false,
        }
    }

    pub fn action(action: A) -> Self {
        Self {
            actions: vec![action],
            consumed: true,
            needs_render: false,
        }
    }

    /// Multiple actions, event consumed.
    pub fn actions<I>(actions: I) -> Self
    where
        I: IntoIterator<Item = A>,
    {
        Self {
            actions: actions.into_iter().collect(),
            consumed: true,
            needs_render: false,
        }
    }

    /// Multiple actions, event NOT consumed (passthrough to other handlers).
    pub fn actions_passthrough<I>(actions: I) -> Self
    where
        I: IntoIterator<Item = A>,
    {
        Self {
            actions: actions.into_iter().collect(),
            consumed: false,
            needs_render: false,
        }
    }

    pub fn with_render(mut self) -> Self {
        self.needs_render = true;
        self
    }

    pub fn with_consumed(mut self, consumed: bool) -> Self {
        self.consumed = consumed;
        self
    }
}

/// Trait for event handlers registered with the bus.
pub trait EventHandler<S, A, Id: ComponentId, Ctx: BindingContext>: 'static {
    fn handle(&mut self, event: RoutedEvent<'_, Id, Ctx>, state: &S) -> HandlerResponse<A>;
}

impl<S, A, Id, Ctx, F> EventHandler<S, A, Id, Ctx> for F
where
    Id: ComponentId,
    Ctx: BindingContext,
    F: for<'a> FnMut(RoutedEvent<'a, Id, Ctx>, &S) -> HandlerResponse<A> + 'static,
{
    fn handle(&mut self, event: RoutedEvent<'_, Id, Ctx>, state: &S) -> HandlerResponse<A> {
        (self)(event, state)
    }
}

type HandlerFn<S, A, Id, Ctx> =
    dyn for<'a, 'ctx> FnMut(RoutedEvent<'ctx, Id, Ctx>, &'a S) -> HandlerResponse<A>;

/// Event bus that manages subscriptions and dispatches events.
pub struct EventBus<S, A: Action, Id: ComponentId, Ctx: BindingContext> {
    handlers: HashMap<Id, Box<HandlerFn<S, A, Id, Ctx>>>,
    global_handlers: Vec<Box<HandlerFn<S, A, Id, Ctx>>>,
    subscriptions: HashMap<EventType, Vec<Id>>,
    global_subscribers: Vec<Id>,
    registration_order: Vec<Id>,
    context: EventContext<Id>,
    global_key_policy: GlobalKeyPolicy,
}

/// Default binding context for apps that don't need custom contexts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct DefaultBindingContext;

impl BindingContext for DefaultBindingContext {
    fn name(&self) -> &'static str {
        "default"
    }

    fn from_name(name: &str) -> Option<Self> {
        (name == "default").then_some(Self)
    }

    fn all() -> &'static [Self] {
        &[Self]
    }
}

/// Simplified EventBus for apps that don't need custom binding contexts.
///
/// Use this when you don't need context-specific keybindings:
/// ```ignore
/// let bus: SimpleEventBus<AppState, AppAction, ComponentId> = SimpleEventBus::new();
/// ```
pub type SimpleEventBus<S, A, Id> = EventBus<S, A, Id, DefaultBindingContext>;

impl<S: 'static, A, Id, Ctx> Default for EventBus<S, A, Id, Ctx>
where
    A: Action,
    Id: ComponentId + 'static,
    Ctx: BindingContext + 'static,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<S: 'static, A, Id, Ctx> EventBus<S, A, Id, Ctx>
where
    A: Action,
    Id: ComponentId + 'static,
    Ctx: BindingContext + 'static,
{
    /// Create a new event bus.
    pub fn new() -> Self {
        Self {
            handlers: HashMap::new(),
            global_handlers: Vec::new(),
            subscriptions: HashMap::new(),
            global_subscribers: Vec::new(),
            registration_order: Vec::new(),
            context: EventContext::default(),
            global_key_policy: GlobalKeyPolicy::Default,
        }
    }

    /// Set the global key policy.
    ///
    /// Controls which key events are treated as "global" — global events
    /// bypass modal blocking and are delivered to global subscribers.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Don't treat Esc as global (useful for modal-heavy apps)
    /// let bus = EventBus::new()
    ///     .with_global_key_policy(GlobalKeyPolicy::without_esc());
    /// ```
    pub fn with_global_key_policy(mut self, policy: GlobalKeyPolicy) -> Self {
        self.global_key_policy = policy;
        self
    }

    /// Register a handler for a component ID.
    pub fn register<F>(&mut self, component: Id, handler: F)
    where
        F: for<'a, 'ctx> FnMut(RoutedEvent<'ctx, Id, Ctx>, &'a S) -> HandlerResponse<A> + 'static,
    {
        if !self.handlers.contains_key(&component) {
            self.registration_order.push(component);
        }
        self.handlers.insert(component, Box::new(handler));
    }

    /// Register a component handler that implements [`EventHandler`].
    pub fn register_handler<H>(&mut self, component: Id, mut handler: H)
    where
        H: EventHandler<S, A, Id, Ctx> + 'static,
    {
        self.register(component, move |event, state| handler.handle(event, state));
    }

    /// Register a global handler (not tied to a component).
    pub fn register_global<F>(&mut self, handler: F)
    where
        F: for<'a, 'ctx> FnMut(RoutedEvent<'ctx, Id, Ctx>, &'a S) -> HandlerResponse<A> + 'static,
    {
        self.global_handlers.push(Box::new(handler));
    }

    /// Register a global handler that implements [`EventHandler`].
    pub fn register_global_handler<H>(&mut self, mut handler: H)
    where
        H: EventHandler<S, A, Id, Ctx> + 'static,
    {
        self.register_global(move |event, state| handler.handle(event, state));
    }

    /// Unregister a component handler.
    pub fn unregister(&mut self, component: Id) -> Option<Box<HandlerFn<S, A, Id, Ctx>>> {
        self.registration_order.retain(|id| *id != component);
        self.unsubscribe_all(component);
        self.handlers.remove(&component)
    }

    /// Subscribe a component to an event type.
    pub fn subscribe(&mut self, component: Id, event_type: EventType) {
        if event_type == EventType::Global {
            if !self.global_subscribers.contains(&component) {
                self.global_subscribers.push(component);
            }
            return;
        }

        let entry = self.subscriptions.entry(event_type).or_default();
        if !entry.contains(&component) {
            entry.push(component);
        }
    }

    /// Subscribe a component to multiple event types.
    pub fn subscribe_many(&mut self, component: Id, event_types: &[EventType]) {
        for &event_type in event_types {
            self.subscribe(component, event_type);
        }
    }

    /// Unsubscribe a component from an event type.
    pub fn unsubscribe(&mut self, component: Id, event_type: EventType) {
        if event_type == EventType::Global {
            self.global_subscribers.retain(|id| *id != component);
            return;
        }

        if let Some(subscribers) = self.subscriptions.get_mut(&event_type) {
            subscribers.retain(|id| *id != component);
        }
    }

    /// Unsubscribe a component from all event types.
    pub fn unsubscribe_all(&mut self, component: Id) {
        self.global_subscribers.retain(|id| *id != component);
        for subscribers in self.subscriptions.values_mut() {
            subscribers.retain(|id| *id != component);
        }
    }

    /// Get subscribers for an event type.
    pub fn get_subscribers(&self, event_type: EventType) -> Vec<Id> {
        if event_type == EventType::Global {
            return self.global_subscribers.clone();
        }

        self.subscriptions
            .get(&event_type)
            .cloned()
            .unwrap_or_default()
    }

    /// Get mutable reference to context.
    pub fn context_mut(&mut self) -> &mut EventContext<Id> {
        &mut self.context
    }

    /// Get reference to context.
    pub fn context(&self) -> &EventContext<Id> {
        &self.context
    }

    /// Route an event through the bus and collect actions.
    ///
    /// Routing priority: Modal → Hovered → Focused → Subscribers → Global handlers.
    /// Modal blocks non-broadcast events from reaching other components.
    pub fn handle_event(
        &mut self,
        event: &EventKind,
        state: &S,
        keybindings: &Keybindings<Ctx>,
    ) -> EventOutcome<A>
    where
        S: EventRoutingState<Id, Ctx>,
    {
        self.update_context(event);

        let is_broadcast = event.is_broadcast();
        let is_mouse_event = matches!(event, EventKind::Mouse(_) | EventKind::Scroll { .. });
        let key_event = match event {
            EventKind::Key(key)
                if matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat) =>
            {
                Some(key)
            }
            _ => None,
        };

        // Gather routing inputs
        let subscribers = self
            .subscriptions
            .get(&event.event_type())
            .map(|v| v.as_slice())
            .unwrap_or(&[]);
        let global_subscribers = self.global_subscribers.as_slice();
        let hovered = if is_mouse_event {
            self.mouse_position_from_event(event)
                .and_then(|(col, row)| self.hit_test(col, row))
        } else {
            None
        };

        // Resolve global status using the configured policy
        let is_global = self.global_key_policy.is_global(event);

        // Build routing plan
        let plan = RoutingPlan::build(
            event,
            is_global,
            state,
            subscribers,
            global_subscribers,
            hovered,
        );

        // Prepare binding context for global handlers
        let default_binding_ctx = state.default_context();
        let global_binding_ctx = state
            .modal()
            .or_else(|| state.focused())
            .map(|id| state.binding_context(id))
            .unwrap_or(default_binding_ctx);
        // Dispatch state
        let mut command_cache: HashMap<Ctx, Option<&str>> = HashMap::new();
        let mut actions = Vec::new();
        let mut needs_render = false;
        let mut consumed = false;
        let mut called: Vec<Id> = Vec::with_capacity(plan.targets.len());

        // Route to components
        for (target, id) in plan.iter() {
            if called.contains(&id) {
                continue;
            }
            called.push(id);

            if let Some(handler) = self.handlers.get_mut(&id) {
                let binding_ctx = state.binding_context(id);
                let command = if let Some(key) = key_event {
                    *command_cache
                        .entry(binding_ctx)
                        .or_insert_with(|| keybindings.get_command_ref(key, binding_ctx))
                } else {
                    None
                };
                let response = Self::call_handler(
                    handler.as_mut(),
                    target,
                    event,
                    command,
                    binding_ctx,
                    &self.context,
                    state,
                );

                actions.extend(response.actions);
                needs_render |= response.needs_render;
                consumed |= response.consumed;

                if consumed && !is_broadcast {
                    return EventOutcome {
                        actions,
                        needs_render,
                    };
                }
            }
        }

        // Global handlers (always run last, skip if modal blocks and not global event)
        let should_run_global = !plan.modal_blocks || is_global;
        if should_run_global {
            let global_command = if let Some(key) = key_event {
                *command_cache
                    .entry(global_binding_ctx)
                    .or_insert_with(|| keybindings.get_command_ref(key, global_binding_ctx))
            } else {
                None
            };
            for handler in self.global_handlers.iter_mut() {
                let response = Self::call_handler(
                    handler.as_mut(),
                    RouteTarget::Global,
                    event,
                    global_command,
                    global_binding_ctx,
                    &self.context,
                    state,
                );

                actions.extend(response.actions);
                needs_render |= response.needs_render;
                consumed |= response.consumed;

                if consumed && !is_broadcast {
                    break;
                }
            }
        }

        EventOutcome {
            actions,
            needs_render,
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn call_handler(
        handler: &mut HandlerFn<S, A, Id, Ctx>,
        target: RouteTarget<Id>,
        event: &EventKind,
        command: Option<&str>,
        binding_ctx: Ctx,
        context: &EventContext<Id>,
        state: &S,
    ) -> HandlerResponse<A> {
        let routed = RoutedEvent {
            kind: event.clone(),
            command,
            binding_ctx,
            target,
            context,
        };
        handler(routed, state)
    }

    fn update_context(&mut self, event: &EventKind) {
        match event {
            EventKind::Key(key) => {
                self.context.modifiers = key.modifiers;
            }
            EventKind::Mouse(mouse) => {
                self.context.mouse_position = Some((mouse.column, mouse.row));
                self.context.modifiers = mouse.modifiers;
            }
            EventKind::Scroll {
                column,
                row,
                modifiers,
                ..
            } => {
                self.context.mouse_position = Some((*column, *row));
                self.context.modifiers = *modifiers;
            }
            EventKind::Resize(width, height) => {
                if let Some((column, row)) = self.context.mouse_position {
                    if column >= *width || row >= *height {
                        self.context.mouse_position = None;
                    }
                }
            }
            EventKind::Tick => {}
        }
    }

    fn mouse_position_from_event(&self, event: &EventKind) -> Option<(u16, u16)> {
        match event {
            EventKind::Mouse(mouse) => Some((mouse.column, mouse.row)),
            EventKind::Scroll { column, row, .. } => Some((*column, *row)),
            _ => None,
        }
    }

    fn hit_test(&self, column: u16, row: u16) -> Option<Id> {
        self.registration_order
            .iter()
            .rev()
            .copied()
            .find(|&id| self.context.point_in_component(id, column, row))
    }
}

/// Spawn the event polling task with cancellation support.
///
/// This spawns an async task that polls for crossterm events and sends them
/// through the provided channel. The task can be cancelled using the token.
///
/// # Arguments
/// * `tx` - Channel to send raw events
/// * `poll_timeout` - Timeout for each poll operation
/// * `loop_sleep` - Sleep duration between poll cycles
/// * `cancel_token` - Token to cancel the polling task
pub fn spawn_event_poller(
    tx: mpsc::UnboundedSender<RawEvent>,
    poll_timeout: Duration,
    loop_sleep: Duration,
    cancel_token: CancellationToken,
) -> tokio::task::JoinHandle<()> {
    tokio::spawn(async move {
        const MAX_EVENTS_PER_BATCH: usize = 20;

        loop {
            tokio::select! {
                _ = cancel_token.cancelled() => {
                    #[cfg(feature = "tracing")]
                    info!("Event poller cancelled, draining buffer");
                    // Drain any remaining events from crossterm buffer before exiting
                    while event::poll(Duration::ZERO).unwrap_or(false) {
                        let _ = event::read();
                    }
                    break;
                }
                _ = tokio::time::sleep(loop_sleep) => {
                    // Process up to MAX_EVENTS_PER_BATCH events per iteration
                    let mut events_processed = 0;
                    while events_processed < MAX_EVENTS_PER_BATCH
                        && event::poll(poll_timeout).unwrap_or(false)
                    {
                        events_processed += 1;
                        if let Ok(evt) = event::read() {
                            let raw = match evt {
                                event::Event::Key(key) => Some(RawEvent::Key(key)),
                                event::Event::Mouse(mouse) => Some(RawEvent::Mouse(mouse)),
                                event::Event::Resize(w, h) => Some(RawEvent::Resize(w, h)),
                                _ => None,
                            };
                            if let Some(raw) = raw {
                                if tx.send(raw).is_err() {
                                    #[cfg(feature = "tracing")]
                                    debug!("Event channel closed, stopping poller");
                                    return;
                                }
                            }
                        }
                    }
                }
            }
        }
    })
}

/// Process a raw event into an EventKind.
pub fn process_raw_event(raw: RawEvent) -> EventKind {
    match raw {
        RawEvent::Key(key) => EventKind::Key(key),
        RawEvent::Mouse(mouse) => match mouse.kind {
            MouseEventKind::ScrollDown => EventKind::Scroll {
                column: mouse.column,
                row: mouse.row,
                delta: 1,
                modifiers: mouse.modifiers,
            },
            MouseEventKind::ScrollUp => EventKind::Scroll {
                column: mouse.column,
                row: mouse.row,
                delta: -1,
                modifiers: mouse.modifiers,
            },
            _ => EventKind::Mouse(mouse),
        },
        RawEvent::Resize(w, h) => EventKind::Resize(w, h),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::event::NumericComponentId;
    use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers};

    #[derive(Clone, Debug, PartialEq, Eq)]
    enum TestAction {
        Log(&'static str),
    }

    impl Action for TestAction {
        fn name(&self) -> &'static str {
            "Log"
        }
    }

    #[derive(Clone, Copy, PartialEq, Eq, Hash)]
    enum TestContext {
        Default,
    }

    impl BindingContext for TestContext {
        fn name(&self) -> &'static str {
            "default"
        }

        fn from_name(name: &str) -> Option<Self> {
            match name {
                "default" => Some(Self::Default),
                _ => None,
            }
        }

        fn all() -> &'static [Self] {
            &[Self::Default]
        }
    }

    #[derive(Default)]
    struct TestState {
        focused: Option<NumericComponentId>,
        modal: Option<NumericComponentId>,
    }

    impl EventRoutingState<NumericComponentId, TestContext> for TestState {
        fn focused(&self) -> Option<NumericComponentId> {
            self.focused
        }

        fn modal(&self) -> Option<NumericComponentId> {
            self.modal
        }

        fn binding_context(&self, _id: NumericComponentId) -> TestContext {
            TestContext::Default
        }

        fn default_context(&self) -> TestContext {
            TestContext::Default
        }
    }

    #[test]
    fn test_subscribe_unsubscribe() {
        let mut bus: EventBus<TestState, TestAction, NumericComponentId, TestContext> =
            EventBus::new();

        let component = NumericComponentId(1);
        bus.subscribe(component, EventType::Key);

        assert_eq!(bus.get_subscribers(EventType::Key), vec![component]);

        bus.unsubscribe(component, EventType::Key);
        assert!(bus.get_subscribers(EventType::Key).is_empty());
    }

    #[test]
    fn test_subscribe_many() {
        let mut bus: EventBus<TestState, TestAction, NumericComponentId, TestContext> =
            EventBus::new();

        let component = NumericComponentId(1);
        bus.subscribe_many(component, &[EventType::Key, EventType::Mouse]);

        assert_eq!(bus.get_subscribers(EventType::Key), vec![component]);
        assert_eq!(bus.get_subscribers(EventType::Mouse), vec![component]);
    }

    #[test]
    fn test_unsubscribe_all() {
        let mut bus: EventBus<TestState, TestAction, NumericComponentId, TestContext> =
            EventBus::new();

        let component = NumericComponentId(1);
        bus.subscribe_many(
            component,
            &[EventType::Key, EventType::Mouse, EventType::Scroll],
        );

        bus.unsubscribe_all(component);

        assert!(bus.get_subscribers(EventType::Key).is_empty());
        assert!(bus.get_subscribers(EventType::Mouse).is_empty());
        assert!(bus.get_subscribers(EventType::Scroll).is_empty());
    }

    #[test]
    fn test_handle_event_routes_modal_only() {
        let mut bus: EventBus<TestState, TestAction, NumericComponentId, TestContext> =
            EventBus::new();

        let focused = NumericComponentId(1);
        let modal = NumericComponentId(2);
        let subscriber = NumericComponentId(3);

        bus.register(focused, |_, _| HandlerResponse {
            actions: vec![TestAction::Log("focused")],
            consumed: false,
            needs_render: false,
        });
        bus.register(modal, |_, _| HandlerResponse {
            actions: vec![TestAction::Log("modal")],
            consumed: false,
            needs_render: false,
        });
        bus.register(subscriber, |_, _| HandlerResponse {
            actions: vec![TestAction::Log("subscriber")],
            consumed: false,
            needs_render: false,
        });
        bus.register_global(|_, _| HandlerResponse {
            actions: vec![TestAction::Log("global")],
            consumed: false,
            needs_render: false,
        });
        bus.subscribe(subscriber, EventType::Key);

        let state = TestState {
            focused: Some(focused),
            modal: Some(modal),
        };
        let keybindings = Keybindings::new();

        let key_event = KeyEvent {
            code: KeyCode::Char('a'),
            modifiers: KeyModifiers::NONE,
            kind: KeyEventKind::Press,
            state: KeyEventState::empty(),
        };

        let outcome = bus.handle_event(&EventKind::Key(key_event), &state, &keybindings);
        assert_eq!(outcome.actions, vec![TestAction::Log("modal")]);
    }

    #[test]
    fn test_global_subscribers_only_for_global_events() {
        let mut bus: EventBus<TestState, TestAction, NumericComponentId, TestContext> =
            EventBus::new();

        let global_subscriber = NumericComponentId(1);
        let key_subscriber = NumericComponentId(2);

        bus.register(global_subscriber, |_, _| HandlerResponse {
            actions: vec![TestAction::Log("global")],
            consumed: false,
            needs_render: false,
        });
        bus.register(key_subscriber, |_, _| HandlerResponse {
            actions: vec![TestAction::Log("key")],
            consumed: false,
            needs_render: false,
        });
        bus.subscribe(global_subscriber, EventType::Global);
        bus.subscribe(key_subscriber, EventType::Key);

        let state = TestState::default();
        let keybindings = Keybindings::new();

        let key_event = KeyEvent {
            code: KeyCode::Char('a'),
            modifiers: KeyModifiers::NONE,
            kind: KeyEventKind::Press,
            state: KeyEventState::empty(),
        };

        let outcome = bus.handle_event(&EventKind::Key(key_event), &state, &keybindings);
        assert_eq!(outcome.actions, vec![TestAction::Log("key")]);

        let esc_event = KeyEvent {
            code: KeyCode::Esc,
            modifiers: KeyModifiers::NONE,
            kind: KeyEventKind::Press,
            state: KeyEventState::empty(),
        };

        let outcome = bus.handle_event(&EventKind::Key(esc_event), &state, &keybindings);
        assert_eq!(
            outcome.actions,
            vec![TestAction::Log("key"), TestAction::Log("global")]
        );
    }

    #[test]
    fn test_handle_event_consumes() {
        let mut bus: EventBus<TestState, TestAction, NumericComponentId, TestContext> =
            EventBus::new();

        let focused = NumericComponentId(1);
        let modal = NumericComponentId(2);

        bus.register(focused, |_, _| {
            HandlerResponse::action(TestAction::Log("focused"))
        });
        bus.register(modal, |_, _| {
            HandlerResponse::action(TestAction::Log("modal"))
        });

        let state = TestState {
            focused: Some(focused),
            modal: Some(modal),
        };
        let keybindings = Keybindings::new();

        let key_event = KeyEvent {
            code: KeyCode::Char('a'),
            modifiers: KeyModifiers::NONE,
            kind: KeyEventKind::Press,
            state: KeyEventState::empty(),
        };

        let outcome = bus.handle_event(&EventKind::Key(key_event), &state, &keybindings);
        assert_eq!(outcome.actions, vec![TestAction::Log("modal")]);
    }

    #[test]
    fn test_process_raw_event_key() {
        use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers};

        let key_event = KeyEvent {
            code: KeyCode::Char('a'),
            modifiers: KeyModifiers::NONE,
            kind: KeyEventKind::Press,
            state: KeyEventState::empty(),
        };

        let kind = process_raw_event(RawEvent::Key(key_event));
        assert!(matches!(kind, EventKind::Key(_)));
    }

    #[test]
    fn test_process_raw_event_scroll() {
        use crossterm::event::{MouseEvent, MouseEventKind};

        let scroll_down = MouseEvent {
            kind: MouseEventKind::ScrollDown,
            column: 10,
            row: 20,
            modifiers: KeyModifiers::NONE,
        };

        let kind = process_raw_event(RawEvent::Mouse(scroll_down));
        match kind {
            EventKind::Scroll {
                column,
                row,
                delta,
                modifiers,
            } => {
                assert_eq!(column, 10);
                assert_eq!(row, 20);
                assert_eq!(delta, 1);
                assert_eq!(modifiers, KeyModifiers::NONE);
            }
            _ => panic!("Expected Scroll event"),
        }
    }

    #[test]
    fn test_process_raw_event_resize() {
        let kind = process_raw_event(RawEvent::Resize(80, 24));
        assert!(matches!(kind, EventKind::Resize(80, 24)));
    }
}