Skip to main content

FormBuilder

Struct FormBuilder 

Source
pub struct FormBuilder { /* private fields */ }
Expand description

Builder for creating forms.

Implementations§

Source§

impl FormBuilder

Source

pub fn new() -> Self

Creates a new form builder.

Source

pub fn title(self, title: impl Into<String>) -> Self

Sets the form title.

Examples found in repository?
examples/address_form.rs (line 28)
18fn main() -> io::Result<()> {
19    // Setup terminal
20    enable_raw_mode()?;
21    let mut stdout = io::stdout();
22    execute!(stdout, EnterAlternateScreen)?;
23    let backend = CrosstermBackend::new(stdout);
24    let mut terminal = Terminal::new(backend)?;
25
26    // Create the form
27    let mut form = Form::builder()
28        .title("Shipping Information")
29        .text("name", "Full Name")
30            .placeholder("John Doe")
31            .required()
32            .done()
33        .text("email", "Email")
34            .placeholder("john@example.com")
35            .required()
36            .validator(Box::new(ratatui_form::Email))
37            .done()
38        .text("phone", "Phone")
39            .placeholder("(555) 123-4567")
40            .done()
41        .block(AddressBlock::new("shipping").required())
42        .checkbox("newsletter", "Subscribe to newsletter")
43            .done()
44        .checkbox("terms", "I agree to the terms and conditions")
45            .required()
46            .done()
47        .build();
48
49    // Main loop
50    loop {
51        // Render
52        terminal.draw(|frame| {
53            let area = frame.area();
54            form.render(area, frame.buffer_mut());
55        })?;
56
57        // Handle input
58        if let Event::Key(key_event) = event::read()? {
59            // Quick exit with Ctrl+C
60            if key_event.code == KeyCode::Char('c')
61                && key_event.modifiers.contains(event::KeyModifiers::CONTROL)
62            {
63                break;
64            }
65
66            form.handle_input(key_event);
67
68            match form.result() {
69                FormResult::Submitted => {
70                    // Write JSON and exit
71                    form.write_json("shipping.json")?;
72                    break;
73                }
74                FormResult::Cancelled => {
75                    break;
76                }
77                FormResult::Active => {}
78            }
79        }
80    }
81
82    // Cleanup terminal
83    disable_raw_mode()?;
84    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
85
86    // Print result
87    match form.result() {
88        FormResult::Submitted => {
89            println!("Form submitted! Data saved to shipping.json");
90            println!("\nForm data:");
91            println!("{}", serde_json::to_string_pretty(&form.to_json()).unwrap());
92        }
93        FormResult::Cancelled => {
94            println!("Form cancelled.");
95        }
96        FormResult::Active => {
97            println!("Form exited.");
98        }
99    }
100
101    Ok(())
102}
Source

pub fn style(self, style: FormStyle) -> Self

Sets the form style.

Source

pub fn text( self, id: impl Into<String>, label: impl Into<String>, ) -> TextFieldBuilder

Starts building a text field.

Examples found in repository?
examples/address_form.rs (line 29)
18fn main() -> io::Result<()> {
19    // Setup terminal
20    enable_raw_mode()?;
21    let mut stdout = io::stdout();
22    execute!(stdout, EnterAlternateScreen)?;
23    let backend = CrosstermBackend::new(stdout);
24    let mut terminal = Terminal::new(backend)?;
25
26    // Create the form
27    let mut form = Form::builder()
28        .title("Shipping Information")
29        .text("name", "Full Name")
30            .placeholder("John Doe")
31            .required()
32            .done()
33        .text("email", "Email")
34            .placeholder("john@example.com")
35            .required()
36            .validator(Box::new(ratatui_form::Email))
37            .done()
38        .text("phone", "Phone")
39            .placeholder("(555) 123-4567")
40            .done()
41        .block(AddressBlock::new("shipping").required())
42        .checkbox("newsletter", "Subscribe to newsletter")
43            .done()
44        .checkbox("terms", "I agree to the terms and conditions")
45            .required()
46            .done()
47        .build();
48
49    // Main loop
50    loop {
51        // Render
52        terminal.draw(|frame| {
53            let area = frame.area();
54            form.render(area, frame.buffer_mut());
55        })?;
56
57        // Handle input
58        if let Event::Key(key_event) = event::read()? {
59            // Quick exit with Ctrl+C
60            if key_event.code == KeyCode::Char('c')
61                && key_event.modifiers.contains(event::KeyModifiers::CONTROL)
62            {
63                break;
64            }
65
66            form.handle_input(key_event);
67
68            match form.result() {
69                FormResult::Submitted => {
70                    // Write JSON and exit
71                    form.write_json("shipping.json")?;
72                    break;
73                }
74                FormResult::Cancelled => {
75                    break;
76                }
77                FormResult::Active => {}
78            }
79        }
80    }
81
82    // Cleanup terminal
83    disable_raw_mode()?;
84    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
85
86    // Print result
87    match form.result() {
88        FormResult::Submitted => {
89            println!("Form submitted! Data saved to shipping.json");
90            println!("\nForm data:");
91            println!("{}", serde_json::to_string_pretty(&form.to_json()).unwrap());
92        }
93        FormResult::Cancelled => {
94            println!("Form cancelled.");
95        }
96        FormResult::Active => {
97            println!("Form exited.");
98        }
99    }
100
101    Ok(())
102}
Source

pub fn select( self, id: impl Into<String>, label: impl Into<String>, ) -> SelectFieldBuilder

Starts building a select field.

Source

pub fn checkbox( self, id: impl Into<String>, label: impl Into<String>, ) -> CheckboxFieldBuilder

Starts building a checkbox field.

Examples found in repository?
examples/address_form.rs (line 42)
18fn main() -> io::Result<()> {
19    // Setup terminal
20    enable_raw_mode()?;
21    let mut stdout = io::stdout();
22    execute!(stdout, EnterAlternateScreen)?;
23    let backend = CrosstermBackend::new(stdout);
24    let mut terminal = Terminal::new(backend)?;
25
26    // Create the form
27    let mut form = Form::builder()
28        .title("Shipping Information")
29        .text("name", "Full Name")
30            .placeholder("John Doe")
31            .required()
32            .done()
33        .text("email", "Email")
34            .placeholder("john@example.com")
35            .required()
36            .validator(Box::new(ratatui_form::Email))
37            .done()
38        .text("phone", "Phone")
39            .placeholder("(555) 123-4567")
40            .done()
41        .block(AddressBlock::new("shipping").required())
42        .checkbox("newsletter", "Subscribe to newsletter")
43            .done()
44        .checkbox("terms", "I agree to the terms and conditions")
45            .required()
46            .done()
47        .build();
48
49    // Main loop
50    loop {
51        // Render
52        terminal.draw(|frame| {
53            let area = frame.area();
54            form.render(area, frame.buffer_mut());
55        })?;
56
57        // Handle input
58        if let Event::Key(key_event) = event::read()? {
59            // Quick exit with Ctrl+C
60            if key_event.code == KeyCode::Char('c')
61                && key_event.modifiers.contains(event::KeyModifiers::CONTROL)
62            {
63                break;
64            }
65
66            form.handle_input(key_event);
67
68            match form.result() {
69                FormResult::Submitted => {
70                    // Write JSON and exit
71                    form.write_json("shipping.json")?;
72                    break;
73                }
74                FormResult::Cancelled => {
75                    break;
76                }
77                FormResult::Active => {}
78            }
79        }
80    }
81
82    // Cleanup terminal
83    disable_raw_mode()?;
84    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
85
86    // Print result
87    match form.result() {
88        FormResult::Submitted => {
89            println!("Form submitted! Data saved to shipping.json");
90            println!("\nForm data:");
91            println!("{}", serde_json::to_string_pretty(&form.to_json()).unwrap());
92        }
93        FormResult::Cancelled => {
94            println!("Form cancelled.");
95        }
96        FormResult::Active => {
97            println!("Form exited.");
98        }
99    }
100
101    Ok(())
102}
Source

pub fn field(self, field: Box<dyn Field>) -> Self

Adds a pre-built field.

Source

pub fn block(self, block: impl FormBlock) -> Self

Adds all fields from a block.

Examples found in repository?
examples/address_form.rs (line 41)
18fn main() -> io::Result<()> {
19    // Setup terminal
20    enable_raw_mode()?;
21    let mut stdout = io::stdout();
22    execute!(stdout, EnterAlternateScreen)?;
23    let backend = CrosstermBackend::new(stdout);
24    let mut terminal = Terminal::new(backend)?;
25
26    // Create the form
27    let mut form = Form::builder()
28        .title("Shipping Information")
29        .text("name", "Full Name")
30            .placeholder("John Doe")
31            .required()
32            .done()
33        .text("email", "Email")
34            .placeholder("john@example.com")
35            .required()
36            .validator(Box::new(ratatui_form::Email))
37            .done()
38        .text("phone", "Phone")
39            .placeholder("(555) 123-4567")
40            .done()
41        .block(AddressBlock::new("shipping").required())
42        .checkbox("newsletter", "Subscribe to newsletter")
43            .done()
44        .checkbox("terms", "I agree to the terms and conditions")
45            .required()
46            .done()
47        .build();
48
49    // Main loop
50    loop {
51        // Render
52        terminal.draw(|frame| {
53            let area = frame.area();
54            form.render(area, frame.buffer_mut());
55        })?;
56
57        // Handle input
58        if let Event::Key(key_event) = event::read()? {
59            // Quick exit with Ctrl+C
60            if key_event.code == KeyCode::Char('c')
61                && key_event.modifiers.contains(event::KeyModifiers::CONTROL)
62            {
63                break;
64            }
65
66            form.handle_input(key_event);
67
68            match form.result() {
69                FormResult::Submitted => {
70                    // Write JSON and exit
71                    form.write_json("shipping.json")?;
72                    break;
73                }
74                FormResult::Cancelled => {
75                    break;
76                }
77                FormResult::Active => {}
78            }
79        }
80    }
81
82    // Cleanup terminal
83    disable_raw_mode()?;
84    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
85
86    // Print result
87    match form.result() {
88        FormResult::Submitted => {
89            println!("Form submitted! Data saved to shipping.json");
90            println!("\nForm data:");
91            println!("{}", serde_json::to_string_pretty(&form.to_json()).unwrap());
92        }
93        FormResult::Cancelled => {
94            println!("Form cancelled.");
95        }
96        FormResult::Active => {
97            println!("Form exited.");
98        }
99    }
100
101    Ok(())
102}
Source

pub fn build(self) -> Form

Builds the form.

Examples found in repository?
examples/address_form.rs (line 47)
18fn main() -> io::Result<()> {
19    // Setup terminal
20    enable_raw_mode()?;
21    let mut stdout = io::stdout();
22    execute!(stdout, EnterAlternateScreen)?;
23    let backend = CrosstermBackend::new(stdout);
24    let mut terminal = Terminal::new(backend)?;
25
26    // Create the form
27    let mut form = Form::builder()
28        .title("Shipping Information")
29        .text("name", "Full Name")
30            .placeholder("John Doe")
31            .required()
32            .done()
33        .text("email", "Email")
34            .placeholder("john@example.com")
35            .required()
36            .validator(Box::new(ratatui_form::Email))
37            .done()
38        .text("phone", "Phone")
39            .placeholder("(555) 123-4567")
40            .done()
41        .block(AddressBlock::new("shipping").required())
42        .checkbox("newsletter", "Subscribe to newsletter")
43            .done()
44        .checkbox("terms", "I agree to the terms and conditions")
45            .required()
46            .done()
47        .build();
48
49    // Main loop
50    loop {
51        // Render
52        terminal.draw(|frame| {
53            let area = frame.area();
54            form.render(area, frame.buffer_mut());
55        })?;
56
57        // Handle input
58        if let Event::Key(key_event) = event::read()? {
59            // Quick exit with Ctrl+C
60            if key_event.code == KeyCode::Char('c')
61                && key_event.modifiers.contains(event::KeyModifiers::CONTROL)
62            {
63                break;
64            }
65
66            form.handle_input(key_event);
67
68            match form.result() {
69                FormResult::Submitted => {
70                    // Write JSON and exit
71                    form.write_json("shipping.json")?;
72                    break;
73                }
74                FormResult::Cancelled => {
75                    break;
76                }
77                FormResult::Active => {}
78            }
79        }
80    }
81
82    // Cleanup terminal
83    disable_raw_mode()?;
84    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
85
86    // Print result
87    match form.result() {
88        FormResult::Submitted => {
89            println!("Form submitted! Data saved to shipping.json");
90            println!("\nForm data:");
91            println!("{}", serde_json::to_string_pretty(&form.to_json()).unwrap());
92        }
93        FormResult::Cancelled => {
94            println!("Form cancelled.");
95        }
96        FormResult::Active => {
97            println!("Form exited.");
98        }
99    }
100
101    Ok(())
102}

Trait Implementations§

Source§

impl Default for FormBuilder

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.