Skip to main content

tui/tabs/
scripts.rs

1//! Scripts tab: the user's scripts, from `list-scripts`.
2
3use ratatui::layout::Constraint;
4use scripting::nomiscript::{Value, format_value};
5
6use crate::tabs::plist::{plist_flag, plist_text};
7use crate::tabs::select_list::{SelectList, SelectRow};
8
9/// One script as the server lists it.
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub 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.
19pub type ScriptsTab = SelectList<ScriptRow>;
20
21impl ScriptRow {
22    fn state(&self) -> String {
23        let state = if self.enabled { "enabled" } else { "disabled" };
24        match self.has_source {
25            true => state.to_string(),
26            false => format!("{state}, no source"),
27        }
28    }
29}
30
31impl SelectRow for ScriptRow {
32    const HEADERS: &'static [&'static str] = &["Name", "State"];
33    const WIDTHS: &'static [Constraint] = &[Constraint::Fill(1), Constraint::Length(24)];
34
35    fn parse(plist: &Value) -> Result<Self, String> {
36        let malformed = || format!("malformed script: {}", format_value(plist));
37        let name = plist_text(plist, ":name").ok_or_else(malformed)?;
38        Ok(Self {
39            id: plist_text(plist, ":id").ok_or_else(malformed)?,
40            name: if name.is_empty() {
41                "unnamed".to_string()
42            } else {
43                name
44            },
45            enabled: plist_flag(plist, ":enabled").ok_or_else(malformed)?,
46            has_source: plist_flag(plist, ":has-source").ok_or_else(malformed)?,
47        })
48    }
49
50    fn key(&self) -> &str {
51        &self.id
52    }
53
54    fn cells(&self) -> Vec<String> {
55        vec![self.name.clone(), self.state()]
56    }
57}
58
59#[cfg(test)]
60mod tests;