1pub mod client;
17pub mod keys;
18pub mod state;
19pub mod view;
20
21#[cfg(test)]
22mod page_tests;
23#[cfg(test)]
24mod screens;
25
26use std::io::IsTerminal;
27use std::sync::Arc;
28use std::sync::mpsc::{self, Receiver, Sender};
29use std::time::Duration;
30
31use ratatui::Terminal;
32use ratatui::backend::Backend;
33use ratatui::crossterm::event::{self, Event as Input, KeyEventKind};
34use time::OffsetDateTime;
35
36use crate::mcp::stdio::ClientConfig;
37use client::{Api, HttpApi};
38use state::{Effect, Event, State};
39use view::Theme;
40
41const TICK: Duration = Duration::from_millis(100);
43
44#[must_use]
48pub fn translate(input: &Input) -> Option<Event> {
49 match input {
50 Input::Key(key) if key.kind != KeyEventKind::Release => {
51 keys::action(key.code, key.modifiers).map(Event::Action)
52 }
53 Input::Resize(columns, lines) => Some(Event::Resize(*columns, *lines)),
54 _ => None,
55 }
56}
57
58pub fn run(config: &ClientConfig) -> Result<(), String> {
68 require_terminal(
70 std::io::stdin().is_terminal(),
71 std::io::stdout().is_terminal(),
72 )?;
73 let api: Arc<dyn Api> = Arc::new(HttpApi::new(config)?);
74 let theme = view::theme(
75 std::env::var("NO_COLOR").ok().as_deref(),
76 std::env::var("TERM").ok().as_deref(),
77 );
78 with_terminal(|terminal| {
79 let (answers, inbox) = mpsc::channel();
80 let mut dispatch = |effects: Vec<Effect>| send(&api, effects, &answers);
81 drive(
82 terminal,
83 &client::base(&config.url),
84 theme,
85 &mut Keyboard,
86 &inbox,
87 &mut dispatch,
88 &OffsetDateTime::now_utc,
89 )
90 .map(|_| ())
91 })?
92}
93
94pub fn with_terminal<T>(
109 body: impl FnOnce(&mut ratatui::DefaultTerminal) -> T,
110) -> Result<T, String> {
111 let mut terminal = ratatui::try_init().map_err(|e| format!("the terminal: {e}"))?;
112 let value = body(&mut terminal);
113 ratatui::restore();
114 Ok(value)
115}
116
117pub fn require_terminal(input: bool, output: bool) -> Result<(), String> {
126 let what = match (input, output) {
127 (true, true) => return Ok(()),
128 (false, true) => "standard input is not one",
129 (true, false) => "standard output is not one",
130 (false, false) => "standard input and standard output are not one",
131 };
132 Err(format!(
133 "a terminal is required: {what}; run it in a terminal, not through a pipe, a redirect or a job without one"
134 ))
135}
136
137pub trait Inputs {
140 fn next(&mut self, wait: Duration) -> std::io::Result<Option<Input>>;
146}
147
148struct Keyboard;
150
151impl Inputs for Keyboard {
152 fn next(&mut self, wait: Duration) -> std::io::Result<Option<Input>> {
153 if event::poll(wait)? {
154 event::read().map(Some)
155 } else {
156 Ok(None)
157 }
158 }
159}
160
161pub fn drive<B: Backend>(
170 terminal: &mut Terminal<B>,
171 server: &str,
172 theme: Theme,
173 inputs: &mut dyn Inputs,
174 inbox: &Receiver<Event>,
175 dispatch: &mut dyn FnMut(Vec<Effect>),
176 now: &dyn Fn() -> OffsetDateTime,
177) -> Result<State, String> {
178 let size = terminal.size().map_err(|e| format!("the terminal: {e}"))?;
179 let (mut state, first) = State::new(server, (size.width, size.height));
180 dispatch(first);
181 while !state.quit {
182 while let Ok(event) = inbox.try_recv() {
183 dispatch(state.step(event, now()));
184 }
185 terminal
186 .draw(|frame| view::draw(frame, &state, theme))
187 .map_err(|e| format!("the terminal: {e}"))?;
188 let input = inputs
189 .next(TICK)
190 .map_err(|e| format!("the terminal: {e}"))?;
191 if let Some(event) = input.as_ref().and_then(translate) {
192 dispatch(state.step(event, now()));
193 }
194 }
195 Ok(state)
196}
197
198fn send(api: &Arc<dyn Api>, effects: Vec<Effect>, answers: &Sender<Event>) {
200 for effect in effects {
201 let api = Arc::clone(api);
202 let answers = answers.clone();
203 std::thread::spawn(move || {
204 drop(answers.send(client::perform(api.as_ref(), &effect)));
207 });
208 }
209}
210
211#[cfg(test)]
212mod tests {
213 use ratatui::crossterm::event::{
214 Event as Input, KeyCode, KeyEvent, KeyEventKind, KeyModifiers,
215 };
216
217 use std::collections::VecDeque;
218 use std::sync::mpsc;
219 use std::time::Duration;
220
221 use ratatui::Terminal;
222 use ratatui::backend::TestBackend;
223 use time::OffsetDateTime;
224 use time::macros::datetime;
225
226 use super::client::{self, Api};
227 use super::state::{Action, ApiError, Effect, Event, KeyInfo, Page, Row, State, View};
228 use super::view::Theme;
229 use super::{Inputs, drive, translate};
230
231 const NOW: OffsetDateTime = datetime!(2026-11-10 01:20:00 UTC);
232
233 fn row(n: u8) -> Row {
234 Row {
235 uuid: format!("01a07da8-c2bb-83e5-b9a2-279e0d16bc{n:02}"),
236 stored_at: "2026-10-25T12:00:00Z".to_owned(),
237 updated_at: "2026-10-25T12:30:00Z".to_owned(),
238 version: format!("4f0c4b0a1d2e3f405162738495a6b7{n:02}"),
239 }
240 }
241
242 struct TwoVcons;
244
245 impl Api for TwoVcons {
246 fn key(&self) -> Result<KeyInfo, ApiError> {
247 Ok(KeyInfo {
248 id: "0123456789abcdef".to_owned(),
249 tenant: Some("t_example".to_owned()),
250 scopes: vec!["read".to_owned()],
251 })
252 }
253
254 fn page(&self, _cursor: Option<&str>) -> Result<Page, ApiError> {
255 Ok(Page {
256 vcons: vec![row(0), row(1)],
257 next: None,
258 })
259 }
260
261 fn masked(&self, _uuid: &str) -> Result<Vec<String>, ApiError> {
262 Ok(vec!["Masked view".to_owned()])
263 }
264
265 fn reveal(&self, _uuid: &str, _part: crate::reveal::Part) -> Result<String, ApiError> {
266 Ok("{}".to_owned())
267 }
268 }
269
270 struct Script(VecDeque<KeyCode>);
273
274 impl Inputs for Script {
275 fn next(&mut self, _wait: Duration) -> std::io::Result<Option<Input>> {
276 let code = self
277 .0
278 .pop_front()
279 .ok_or_else(|| std::io::Error::other("the script ended"))?;
280 Ok(Some(key(code, KeyEventKind::Press)))
281 }
282 }
283
284 fn driven(keys: &[KeyCode]) -> (Result<State, String>, String) {
287 let mut terminal = Terminal::new(TestBackend::new(80, 24)).expect("a terminal");
288 let (answers, inbox) = mpsc::channel();
289 let mut dispatch = |effects: Vec<Effect>| {
290 for effect in effects {
291 answers
292 .send(client::perform(&TwoVcons, &effect))
293 .expect("the loop holds the receiver");
294 }
295 };
296 let result = drive(
297 &mut terminal,
298 "https://vcon.example.com:8443",
299 Theme { color: false },
300 &mut Script(keys.iter().copied().collect()),
301 &inbox,
302 &mut dispatch,
303 &|| NOW,
304 );
305 let buffer = terminal.backend().buffer();
306 let frame = buffer
307 .content()
308 .iter()
309 .map(ratatui::buffer::Cell::symbol)
310 .collect();
311 (result, frame)
312 }
313
314 #[test]
315 fn the_loop_applies_answers_and_keys_in_order_and_ends_on_quit() {
316 let (result, frame) = driven(&[KeyCode::Down, KeyCode::Enter, KeyCode::Char('q')]);
317 let state = result.expect("the loop ends on q");
318 assert_eq!(state.view, View::Detail, "Enter opened the detail view");
319 assert_eq!(
320 state.detail,
321 Some(row(1).uuid),
322 "both answers were applied before Down, so Down moved to the second vCon"
323 );
324 assert!(
325 frame.contains(&format!("vCon {}", row(1).uuid)),
326 "the last frame drawn is the detail view: {frame}"
327 );
328 }
329
330 fn key(code: KeyCode, kind: KeyEventKind) -> Input {
331 Input::Key(KeyEvent::new_with_kind(code, KeyModifiers::NONE, kind))
332 }
333
334 #[test]
335 fn the_loop_stops_with_the_terminals_error_when_input_fails() {
336 let (result, _) = driven(&[KeyCode::Down]);
337 assert_eq!(
338 result,
339 Err("the terminal: the script ended".to_owned()),
340 "the error is returned, with what it is about"
341 );
342 }
343
344 #[test]
345 fn the_loop_stamps_answers_with_the_clock_it_is_given() {
346 let (result, _) = driven(&[KeyCode::Char('q')]);
347 assert_eq!(
348 result.expect("the loop ends on q").as_of,
349 Some(NOW),
350 "the list was read at the time the clock said"
351 );
352 }
353
354 #[test]
355 fn a_bound_key_going_down_is_its_action() {
356 assert_eq!(
357 translate(&key(KeyCode::Char('q'), KeyEventKind::Press)),
358 Some(Event::Action(Action::Quit)),
359 "q quits"
360 );
361 }
362
363 #[test]
364 fn a_held_key_repeats_its_action() {
365 assert_eq!(
366 translate(&key(KeyCode::Down, KeyEventKind::Repeat)),
367 Some(Event::Action(Action::Down)),
368 "holding Down keeps moving"
369 );
370 }
371
372 #[test]
373 fn a_key_coming_up_is_nothing() {
374 assert_eq!(
375 translate(&key(KeyCode::Char('q'), KeyEventKind::Release)),
376 None,
377 "a terminal that reports releases must not act twice"
378 );
379 }
380
381 #[test]
382 fn an_unbound_key_is_nothing() {
383 assert_eq!(
384 translate(&key(KeyCode::Char('x'), KeyEventKind::Press)),
385 None,
386 "x is not bound"
387 );
388 }
389
390 #[test]
391 fn a_resize_carries_the_new_size() {
392 assert_eq!(
393 translate(&Input::Resize(132, 43)),
394 Some(Event::Resize(132, 43)),
395 "columns, then lines"
396 );
397 }
398
399 #[test]
400 fn focus_and_paste_are_nothing() {
401 assert_eq!(
402 translate(&Input::FocusGained),
403 None,
404 "focus changes nothing"
405 );
406 assert_eq!(
407 translate(&Input::Paste("q".to_owned())),
408 None,
409 "pasted text is not typed keys"
410 );
411 }
412}