use crate::event::{Event, KeyEvent};
use crate::runtime::{App, Command, Harness};
use crate::widget::View;
use crate::widgets::{Button, TextInput};
#[derive(Default)]
struct NewWorkspace {
name: String,
created: Vec<String>,
}
#[derive(Clone)]
enum Msg {
Name(String),
Create,
}
impl App for NewWorkspace {
type Msg = Msg;
fn update(&mut self, msg: Msg) -> Command<Msg> {
match msg {
Msg::Name(name) => self.name = name,
Msg::Create => self.created.push(std::mem::take(&mut self.name)),
}
Command::none()
}
fn view(&self, ui: &mut View<'_, Msg>) {
ui.add(
TextInput::new(&self.name).placeholder("Workspace name").on_change(Msg::Name).on_submit(|_| Msg::Create),
)
.fill_width()
.id("name");
ui.add(Button::new("Create").on_press(Msg::Create));
}
}
fn burst(text: &str) -> Vec<Event> {
text.chars()
.map(|c| match c {
'\n' => "enter".to_owned(),
c => c.to_string(),
})
.map(|chord| Event::Key(KeyEvent::press(&chord)))
.collect()
}
fn form() -> Harness<NewWorkspace> {
let mut h = Harness::new(NewWorkspace::default(), 40, 4);
let (x, y) = h.find("Workspace name").expect("the field shows its placeholder");
h.click(x, y);
h
}
#[test]
fn every_key_of_a_burst_reaches_a_controlled_field() {
let mut h = form();
h.events(&burst("demo"));
assert_eq!(h.app().name, "demo");
assert!(h.screen().contains("demo"), "{}", h.screen());
h.events(&burst("-api"));
assert_eq!(h.app().name, "demo-api", "a second burst continues where the first ended");
}
#[test]
fn enter_in_the_same_burst_submits_everything_typed_before_it() {
let mut h = form();
h.events(&burst("demo\n"));
assert_eq!(h.app().created, ["demo"]);
}