tui-dialog 0.3.0

A widget for entering a single line of text in a dialog for Ratatui.
Documentation

A widget for entering a single line of text in a dialog for Ratatui. It also includes a function for creating a centered Rect to place the dialog in.

Based on https://github.com/ratatui/ratatui/blob/v0.26.1/examples/user_input.rs.

NOTE: The widget only works with the crossterm backend. Adding others is not a priority at this time.

Examples

For a full (but minimal) app demonstrating use, clone the repository and run cargo run --example basic.

You can also check out my app taskfinder for more extensive use.

use tui_dialog::{Dialog, centered_rect};

pub struct App {
    dialog: Dialog
    text: String,
    exit: bool,
}

// Initialize the app.
let mut app = App {
    dialog: Dialog::default(),
    text: "Hello world!".to_string(),
    exit: false,
};

// Then in main loop of app...
while !app.exit {
    terminal.draw(|frame| render(frame, app))?;

    // Handle user input.
    match event::read()? {
        Event::Key(key_event) if key_event.kind == KeyEventKind::Press => {
            // Pass all `key_event.code`s to a dialog if open.
            // (The dialog handles closing itself, when the user presses `Enter` or `Esc`.)
            if app.dialog.open {
                app.dialog.key_action(&key_event.code);
                if app.dialog.submitted {
                    // Here is where you'd do something more significant.
                    app.text = app.dialog.submitted_input.clone();
                }
            // Otherwise handle them here.
            } else {
                match key_event.code {
                    KeyCode::Char('q') => app.exit = true,
                    // Your app needs to open the dialog.
                    KeyCode::Char('d') => app.dialog.open = true,
                    _ => (),
                }
            }
        }
        _ => (),
    };
}

// Rendering the dialog...
fn render(frame: &mut Frame, app: &mut App) {
  // ...
  let dialog_area = centered_rect(frame.area(), 45, 5, 0, 0);
  // There is no need to clear the area first - the widget handles that itself. Just render it.
  // (See <https://ratatui.rs/recipes/layout/center-a-widget/#popups>.)
  frame.render_widget(app.dialog, dialog_area);
}