1
//! The Scripts tab through the real key dispatch: list, delete and the tab key.
2

            
3
use crate::app::App;
4
use crate::modal::Modal;
5
use crate::route::{RouteCtx, ScriptRoute};
6
use crate::tabs::fetch::Fetch;
7
use crate::tabs::nms_eval::double::Sent;
8
use crate::tabs::select_list::SelectRow;
9
use crate::test_support::{key, press};
10
use crate::view::Tab;
11
use ratatui::crossterm::event::KeyCode;
12

            
13
pub(super) const SYNC: &str = "aaaaaaaa-0000-0000-0000-000000000001";
14
pub(super) const OLD: &str = "bbbbbbbb-0000-0000-0000-000000000002";
15

            
16
18
pub(super) fn scripts_app() -> (App, Sent) {
17
18
    let mut app = crate::test_support::app();
18
18
    let sent = app.attach_echo();
19
18
    app.switch_tab(Tab::Scripts);
20
18
    (app, sent)
21
18
}
22

            
23
17
fn loading_id(app: &App) -> anyhow::Result<i64> {
24
17
    match app.scripts().state {
25
17
        Fetch::Loading { id } => Ok(id),
26
        ref other => anyhow::bail!("not loading: {other:?}"),
27
    }
28
17
}
29

            
30
/// A `list-scripts` reply with a row of `(id, name, enabled, has_source)` each.
31
16
pub(super) fn load_states(
32
16
    app: &mut App,
33
16
    scripts: &[(&str, &str, bool, bool)],
34
16
) -> anyhow::Result<()> {
35
16
    let id = loading_id(app)?;
36
38
    let flag = |on: bool| if on { "t" } else { "nil" };
37
16
    let rows: Vec<String> = scripts
38
16
        .iter()
39
19
        .map(|(id, name, enabled, has_source)| {
40
19
            format!(
41
19
                r#"(:id \"{id}\" :name \"{name}\" :enabled {} :has-source {})"#,
42
19
                flag(*enabled),
43
19
                flag(*has_source)
44
            )
45
19
        })
46
        .collect();
47
16
    let wire = format!(r#"(:id {id} :value "({})")"#, rows.join(" "));
48
16
    app.route_reply(id, &wire);
49
16
    Ok(())
50
16
}
51

            
52
13
pub(super) fn load(app: &mut App, scripts: &[(&str, &str)]) -> anyhow::Result<()> {
53
13
    let rows: Vec<_> = scripts
54
13
        .iter()
55
15
        .map(|(id, name)| (*id, *name, true, true))
56
        .collect();
57
13
    load_states(app, &rows)
58
13
}
59

            
60
14
pub(super) fn pending(app: &App, wanted: fn(&ScriptRoute) -> bool) -> Option<i64> {
61
14
    app.pending_routes
62
14
        .iter()
63
12
        .find_map(|(id, route)| match &route.ctx {
64
12
            RouteCtx::Script(route) if wanted(route) => Some(*id),
65
            _ => None,
66
12
        })
67
14
}
68

            
69
2
fn shown(app: &App) -> Vec<String> {
70
2
    app.scripts()
71
2
        .rows()
72
2
        .iter()
73
3
        .map(|row| row.cells().join(" | "))
74
        .collect()
75
2
}
76

            
77
#[tokio::test]
78
1
async fn opening_the_tab_lists_the_scripts_with_their_states() -> anyhow::Result<()> {
79
1
    let (mut app, sent) = scripts_app();
80
1
    load_states(
81
1
        &mut app,
82
1
        &[(SYNC, "sync", true, true), (OLD, "old", false, false)],
83
1
    )?;
84
1
    assert_eq!(shown(&app), ["sync | enabled", "old | disabled, no source"]);
85
1
    tokio::task::yield_now().await;
86
1
    app.drain_eval();
87
1
    let echoed = sent.frames().join("\n");
88
1
    assert!(echoed.contains(r#"(list-scripts)"#), "{echoed}");
89
2
    Ok(())
90
1
}
91

            
92
#[tokio::test]
93
1
async fn zero_opens_the_tab_and_console_stays_on_nine() {
94
1
    let mut app = crate::test_support::app();
95
1
    press(&mut app, key(KeyCode::Char('0')));
96
1
    assert_eq!(app.front_kind(), Some(Tab::Scripts));
97
1
    press(&mut app, key(KeyCode::Char('9')));
98
1
    assert_eq!(app.front_kind(), Some(Tab::Console));
99
1
}
100

            
101
#[tokio::test]
102
1
async fn a_list_error_shows_in_the_tab() -> anyhow::Result<()> {
103
1
    let (mut app, _) = scripts_app();
104
1
    let id = loading_id(&app)?;
105
1
    app.route_reply(
106
1
        id,
107
1
        &format!(r#"(:id {id} :error (:code db :message "connection refused"))"#),
108
1
    );
109
1
    assert!(matches!(&app.scripts().state, Fetch::Error(m) if m.contains("connection refused")));
110
2
    Ok(())
111
1
}
112

            
113
#[tokio::test]
114
1
async fn keys_without_a_selection_say_so() {
115
1
    let (mut app, _) = scripts_app();
116
1
    for letter in ['d', 'e', 't'] {
117
3
        app.status.clear();
118
3
        press(&mut app, key(KeyCode::Char(letter)));
119
3
        assert_eq!(app.status, "no script selected", "{letter}");
120
1
    }
121
1
    assert!(app.overlays.is_empty());
122
1
}
123

            
124
#[tokio::test]
125
1
async fn d_asks_naming_the_script_and_n_cancels() -> anyhow::Result<()> {
126
1
    let (mut app, _) = scripts_app();
127
1
    load(&mut app, &[(SYNC, "sync"), (OLD, "old")])?;
128
1
    press(&mut app, key(KeyCode::Char('j')));
129

            
130
1
    press(&mut app, key(KeyCode::Char('d')));
131
1
    let Some(Modal::Confirm { prompt, .. }) = app.overlays.top() else {
132
        anyhow::bail!("no confirm");
133
    };
134
1
    assert_eq!(prompt, "Delete script old?");
135

            
136
1
    press(&mut app, key(KeyCode::Char('n')));
137
1
    assert!(app.overlays.is_empty());
138
1
    assert!(pending(&app, |r| matches!(r, ScriptRoute::Delete { .. })).is_none());
139
2
    Ok(())
140
1
}
141

            
142
#[tokio::test]
143
1
async fn enter_confirms_the_delete_over_delete_script_and_refreshes() -> anyhow::Result<()> {
144
1
    let (mut app, sent) = scripts_app();
145
1
    load(&mut app, &[(SYNC, "sync"), (OLD, "old")])?;
146
1
    press(&mut app, key(KeyCode::Char('d')));
147

            
148
1
    press(&mut app, key(KeyCode::Enter));
149
1
    let id = pending(&app, |r| matches!(r, ScriptRoute::Delete { .. }))
150
        .ok_or_else(|| anyhow::anyhow!("delete not sent"))?;
151
1
    tokio::task::yield_now().await;
152
1
    app.drain_eval();
153
1
    let echoed = sent.frames().join("\n");
154
1
    assert!(
155
1
        echoed.contains(&format!(r#"(delete-script "{SYNC}")"#)),
156
        "{echoed}"
157
    );
158

            
159
1
    app.route_reply(id, &format!("(:id {id} :value t)"));
160
1
    assert_eq!(app.status, "deleted sync");
161
1
    load(&mut app, &[(OLD, "old")])?;
162
1
    assert_eq!(shown(&app), ["old | enabled"]);
163
2
    Ok(())
164
1
}
165

            
166
#[tokio::test]
167
1
async fn a_failed_delete_shows_the_servers_message_and_does_not_refetch() -> anyhow::Result<()> {
168
1
    let (mut app, _) = scripts_app();
169
1
    load(&mut app, &[(SYNC, "sync")])?;
170
1
    press(&mut app, key(KeyCode::Char('d')));
171
1
    press(&mut app, key(KeyCode::Char('y')));
172
1
    let id = pending(&app, |r| matches!(r, ScriptRoute::Delete { .. }))
173
        .ok_or_else(|| anyhow::anyhow!("delete not sent"))?;
174

            
175
1
    app.route_reply(
176
1
        id,
177
1
        &format!(r#"(:id {id} :error (:code not-found :message "no such script"))"#),
178
1
    );
179

            
180
1
    assert!(app.status.contains("no such script"), "{}", app.status);
181
1
    assert!(!app.scripts().any_loading());
182
2
    Ok(())
183
1
}