1
//! Scripts tab: the user's scripts, from `list-scripts`.
2

            
3
use ratatui::layout::Constraint;
4
use scripting::nomiscript::{Value, format_value};
5

            
6
use crate::tabs::plist::{plist_flag, plist_text};
7
use crate::tabs::select_list::{SelectList, SelectRow};
8

            
9
/// One script as the server lists it.
10
#[derive(Debug, Clone, PartialEq, Eq)]
11
pub struct ScriptRow {
12
    pub id: String,
13
    pub name: String,
14
    pub enabled: bool,
15
    pub has_source: bool,
16
}
17

            
18
/// The scripts view: exactly the scripts the user holds.
19
pub type ScriptsTab = SelectList<ScriptRow>;
20

            
21
impl ScriptRow {
22
125
    fn state(&self) -> String {
23
125
        let state = if self.enabled { "enabled" } else { "disabled" };
24
125
        match self.has_source {
25
123
            true => state.to_string(),
26
2
            false => format!("{state}, no source"),
27
        }
28
125
    }
29
}
30

            
31
impl SelectRow for ScriptRow {
32
    const HEADERS: &'static [&'static str] = &["Name", "State"];
33
    const WIDTHS: &'static [Constraint] = &[Constraint::Fill(1), Constraint::Length(24)];
34

            
35
169
    fn parse(plist: &Value) -> Result<Self, String> {
36
1
        let malformed = || format!("malformed script: {}", format_value(plist));
37
169
        let name = plist_text(plist, ":name").ok_or_else(malformed)?;
38
        Ok(Self {
39
169
            id: plist_text(plist, ":id").ok_or_else(malformed)?,
40
169
            name: if name.is_empty() {
41
1
                "unnamed".to_string()
42
            } else {
43
168
                name
44
            },
45
169
            enabled: plist_flag(plist, ":enabled").ok_or_else(malformed)?,
46
169
            has_source: plist_flag(plist, ":has-source").ok_or_else(malformed)?,
47
        })
48
169
    }
49

            
50
8
    fn key(&self) -> &str {
51
8
        &self.id
52
8
    }
53

            
54
125
    fn cells(&self) -> Vec<String> {
55
125
        vec![self.name.clone(), self.state()]
56
125
    }
57
}
58

            
59
#[cfg(test)]
60
mod tests;