Skip to content

Commit

Permalink
feat(component): add ExecuteCommand action & logic to demonstrate spa…
Browse files Browse the repository at this point in the history
…wning external command

Signed-off-by: Deep Panchal <[email protected]>
  • Loading branch information
deepanchal committed Jul 13, 2024
1 parent 5e823ef commit 69d2d7d
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
4 changes: 4 additions & 0 deletions component/template/src/action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ use serde::{
};
use strum::Display;

type Command = String;
type CommandArgs = Vec<String>;

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Display, Deserialize)]
pub enum Action {
Tick,
Expand All @@ -17,4 +20,5 @@ pub enum Action {
ClearScreen,
Error(String),
Help,
ExecuteCommand(Command, CommandArgs),
}
16 changes: 16 additions & 0 deletions component/template/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,14 @@ impl App {
}
})?;
},
Action::ExecuteCommand(ref command, ref args) => {
tui.exit()?;
let cmd = command.to_string();
let cmd_args = args.iter().map(|s| s.as_str()).collect::<Vec<&str>>();
self.spawn_process(&cmd, &cmd_args)?;
tui.enter()?;
action_tx.send(Action::ClearScreen)?;
}
_ => {},
}
for component in self.components.iter_mut() {
Expand All @@ -149,4 +157,12 @@ impl App {
tui.exit()?;
Ok(())
}

fn spawn_process(&self, command: &str, args: &[&str]) -> Result<()> {
let status = std::process::Command::new(command).args(args).status()?;
if !status.success() {
eprintln!("\nCommand failed with status: {}", status);
}
Ok(())
}
}
14 changes: 13 additions & 1 deletion component/template/src/components/home.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,18 @@ impl Component for Home {
Ok(())
}

fn handle_key_events(&mut self, key: KeyEvent) -> Result<Option<Action>> {
match key.code {
KeyCode::Char('e') => {
let cmd = String::from("vim");
let cmd_args = vec!["/tmp/a.txt".into()];
let action = Action::ExecuteCommand(cmd, cmd_args);
Ok(Some(action))
}
_ => Ok(None)
}
}

fn update(&mut self, action: Action) -> Result<Option<Action>> {
match action {
Action::Tick => {
Expand All @@ -45,7 +57,7 @@ impl Component for Home {
}

fn draw(&mut self, f: &mut Frame<'_>, area: Rect) -> Result<()> {
f.render_widget(Paragraph::new("hello world"), area);
f.render_widget(Paragraph::new("Hello world, press 'e' to edit /tmp/a.txt with vim"), area);
Ok(())
}
}
Expand Down

0 comments on commit 69d2d7d

Please sign in to comment.