covey_plugin/
action.rs

1use crate::{Input, proto};
2
3/// An action for Covey to perform.
4///
5/// There are associated constructor functions which are easier to use
6/// than constructing from the enum variants.
7///
8/// Note that actions don't close Covey automatically. Add [`Action::Close`] to
9/// close the application. This should usually be first to feel more responsive
10/// and avoid waiting for other commands to run before closing.
11#[derive(Debug, Clone)]
12pub enum Action {
13    Close,
14    Copy(String),
15    SetInput(Input),
16    DisplayError(String),
17}
18
19impl Action {
20    pub(crate) fn into_proto(self) -> proto::Action {
21        use proto::action::Action as PrAction;
22
23        let inner_action = match self {
24            Self::Close => PrAction::Close(()),
25            Self::Copy(str) => PrAction::Copy(str),
26            Self::SetInput(input) => PrAction::SetInput(input.into_proto()),
27            Self::DisplayError(err) => PrAction::DisplayError(err),
28        };
29
30        proto::Action {
31            action: Some(inner_action),
32        }
33    }
34}
35
36/// Helper constructors for action variants
37impl Action {
38    pub fn close() -> Self {
39        Self::Close
40    }
41
42    pub fn copy(str: impl Into<String>) -> Self {
43        Self::Copy(str.into())
44    }
45
46    pub fn set_input(input: impl Into<Input>) -> Self {
47        Self::SetInput(input.into())
48    }
49
50    pub fn display_error(err: impl std::fmt::Display) -> Self {
51        Self::DisplayError(err.to_string())
52    }
53}
54
55/// Wrapper for a [`Vec<Action>`] with convenient conversion trait implementations.
56///
57/// [`From`] Implementations:
58/// - [`IntoIterator<Item = Action>`] -> `Vec<Action>`
59/// - [`Action`] -> `vec![Action]`
60/// - [`Input`] -> `vec![Action::SetInput(Input)]`
61///
62/// While each action will be run in sequence, they will not wait for previous
63/// actions to complete. If you need to run something more complex,
64/// you can write your desired code in the command callback.
65pub struct Actions {
66    pub list: Vec<Action>,
67    _priv: (),
68}
69
70impl<T: IntoIterator<Item = Action>> From<T> for Actions {
71    fn from(value: T) -> Self {
72        Self {
73            list: value.into_iter().collect(),
74            _priv: (),
75        }
76    }
77}
78
79impl From<Action> for Actions {
80    fn from(value: Action) -> Self {
81        Self::from(std::iter::once(value))
82    }
83}
84
85impl From<Input> for Actions {
86    fn from(value: Input) -> Self {
87        Self::from(Action::SetInput(value))
88    }
89}