p2p_chat/ui/runner/actions/context.rs
1//! This module defines the `CommandContext`, which provides access to the
2//! application's state and UI for command handlers.
3use std::sync::Arc;
4
5use tokio::sync::mpsc;
6
7use crate::cli::commands::Node;
8use crate::ui::UIEvent;
9
10/// Provides context and utilities to command handlers.
11///
12/// This struct allows command handlers to interact with the core application
13/// `Node` and send events back to the user interface.
14#[derive(Clone)]
15pub struct CommandContext {
16 /// A reference to the application's core `Node`.
17 node: Arc<Node>,
18 /// The sender for dispatching `UIEvent`s to the UI.
19 ui_sender: mpsc::UnboundedSender<UIEvent>,
20}
21
22impl CommandContext {
23 /// Creates a new `CommandContext`.
24 ///
25 /// # Arguments
26 ///
27 /// * `node` - An `Arc` to the application's core `Node`.
28 /// * `ui_sender` - An `mpsc::UnboundedSender` for `UIEvent`s.
29 pub fn new(node: Arc<Node>, ui_sender: mpsc::UnboundedSender<UIEvent>) -> Self {
30 Self { node, ui_sender }
31 }
32
33 /// Returns a reference to the application's core `Node`.
34 pub fn node(&self) -> &Arc<Node> {
35 &self.node
36 }
37
38 /// Emits a generic `UIEvent` to the user interface.
39 ///
40 /// # Arguments
41 ///
42 /// * `event` - The `UIEvent` to emit.
43 pub fn emit(&self, event: UIEvent) {
44 let _ = self.ui_sender.send(event);
45 }
46
47 /// Emits a chat message to be displayed in the UI.
48 ///
49 /// # Arguments
50 ///
51 /// * `message` - The message content.
52 pub fn emit_chat<S: Into<String>>(&self, message: S) {
53 self.emit(UIEvent::ChatMessage(message.into()));
54 }
55
56 /// Emits a history output block to be displayed in the UI.
57 ///
58 /// This is typically used for multi-line outputs from commands like `history`.
59 ///
60 /// # Arguments
61 ///
62 /// * `message` - The history output content.
63 pub fn emit_history<S: Into<String>>(&self, message: S) {
64 self.emit(UIEvent::HistoryOutput(message.into()));
65 }
66}