edtui_papier/state/
command.rs

1use jagged::Index2;
2
3#[derive(Default, Clone, Debug)]
4/// Represents the state of the command mode.
5pub struct CommandState<I> {
6    pub(crate) start_cursor: Index2,
7    pub(crate) input: String,
8    pub available_commands: Vec<Command<I>>,
9}
10
11#[derive(Clone, Debug)]
12/// Represents a command that can be executed in command mode.
13pub struct Command<I> {
14    pub name: String,
15    pub aliases: Vec<String>,
16    pub description: String,
17    pub action: fn(String) -> I,
18}
19
20impl<I: Default> Default for Command<I> {
21    fn default() -> Self {
22        Self { name: String::new(), description: String::new(), aliases: Vec::new(), action: |_| I::default() }
23    }
24}
25
26impl<I> Command<I> {
27    pub fn new(name: String, description: String, aliases: Vec<String>, action: fn(String) -> I) -> Self {
28        Self { name, description, aliases, action }
29    }
30
31    pub fn name(&mut self, name: String) -> &mut Self {
32        self.name = name;
33        self
34    }
35
36    pub fn description(&mut self, description: String) -> &mut Self {
37        self.description = description;
38        self
39    }
40
41    pub fn aliases(&mut self, aliases: Vec<String>) -> &mut Self {
42        self.aliases = aliases;
43        self
44    }
45}
46
47impl<I> CommandState<I> {
48    /// Returns the length of the current search pattern.
49    pub(crate) fn command_len(&self) -> usize {
50        self.input.len()
51    }
52
53    /// Clears both the search pattern and matched indices.
54    pub(crate) fn clear(&mut self) {
55        self.input.clear();
56    }
57
58    /// Appends a character to the command.
59    pub(crate) fn push_char(&mut self, ch: char) {
60        self.input.push(ch);
61    }
62
63    /// Removes the last character from the command.
64    pub(crate) fn remove_char(&mut self) {
65        self.input.pop();
66    }
67
68    pub fn add_command(&mut self, name: String, description: String, aliases: Vec<String>, action: fn(String) -> I) {
69        self.available_commands.push(Command { name, description, aliases, action });
70    }
71}