Model

Struct Model 

Source
pub struct Model {
Show 14 fields pub err: Option<String>, pub prompt: String, pub prompt_style: Style, pub text_style: Style, pub placeholder: String, pub placeholder_style: Style, pub cursor: Model, pub cursor_mode: Mode, pub width: i32, pub key_map: KeyMap, pub char_limit: i32, pub echo_mode: EchoMode, pub echo_character: char, pub completion_style: Style, /* private fields */
}
Expand description

The main text input component model for Bubble Tea applications.

This struct represents a single-line text input field with support for:

  • Cursor movement and text editing
  • Input validation
  • Auto-completion suggestions
  • Different echo modes (normal, password, hidden)
  • Horizontal scrolling for long text
  • Customizable styling and key bindings

The model follows the Elm Architecture pattern used by Bubble Tea, with separate Init(), Update(), and View() methods for state management.

§Examples

use bubbletea_widgets::textinput::{new, EchoMode};
use bubbletea_rs::Model;

// Create and configure a text input
let mut input = new();
input.focus();
input.set_placeholder("Enter your name...");
input.set_width(30);
input.set_char_limit(50);

// For password input
input.set_echo_mode(EchoMode::EchoPassword);

// With validation
input.set_validate(Box::new(|s: &str| {
    if s.len() >= 3 {
        Ok(())
    } else {
        Err("Must be at least 3 characters".to_string())
    }
}));

§Note

This struct matches the Go Model struct exactly for 1-1 compatibility.

Fields§

§err: Option<String>

Err is an error that was not caught by a validator.

§prompt: String

Prompt is the prompt to display before the text input.

§prompt_style: Style

Style for the prompt prefix.

§text_style: Style

TextStyle is the style of the text as it’s being typed.

§placeholder: String

Placeholder is the placeholder text to display when the input is empty.

§placeholder_style: Style

Style for the placeholder text.

§cursor: Model

Cursor is the cursor model.

§cursor_mode: Mode

Cursor rendering mode (blink/static/hidden).

§width: i32

Width is the maximum number of characters that can be displayed at once.

§key_map: KeyMap

KeyMap encodes the keybindings.

§char_limit: i32

CharLimit is the maximum number of characters this input will accept. 0 means no limit.

§echo_mode: EchoMode

EchoMode is the echo mode of the input.

§echo_character: char

EchoCharacter is the character to use for password fields.

§completion_style: Style

CompletionStyle is the style of the completion suggestion.

Implementations§

Source§

impl Model

Source

pub fn set_value(&mut self, s: &str)

Sets the value of the text input.

This method replaces the entire content of the text input with the provided string. If a validation function is set, it will be applied to the new value.

§Arguments
  • s - The new string value to set
§Examples
use bubbletea_widgets::textinput::new;

let mut input = new();
input.set_value("Hello, world!");
assert_eq!(input.value(), "Hello, world!");
§Note

This method matches Go’s SetValue method exactly for compatibility.

Source

pub fn value(&self) -> String

Returns the current value of the text input.

§Returns

A String containing the current text value

§Examples
use bubbletea_widgets::textinput::new;

let mut input = new();
input.set_value("test");
assert_eq!(input.value(), "test");
§Note

This method matches Go’s Value method exactly for compatibility.

Source

pub fn position(&self) -> usize

Returns the current cursor position as a character index.

§Returns

The cursor position as a usize, where 0 is the beginning of the text

§Examples
use bubbletea_widgets::textinput::new;

let mut input = new();
input.set_value("hello");
input.set_cursor(2);
assert_eq!(input.position(), 2);
§Note

This method matches Go’s Position method exactly for compatibility.

Source

pub fn set_cursor(&mut self, pos: usize)

Moves the cursor to the specified position.

If the position is beyond the end of the text, the cursor will be placed at the end. This method also handles overflow for horizontal scrolling when the text is wider than the display width.

§Arguments
  • pos - The new cursor position as a character index
§Examples
use bubbletea_widgets::textinput::new;

let mut input = new();
input.set_value("hello world");
input.set_cursor(6); // Position after "hello "
assert_eq!(input.position(), 6);
§Note

This method matches Go’s SetCursor method exactly for compatibility.

Source

pub fn cursor_start(&mut self)

Moves the cursor to the beginning of the input field.

§Examples
use bubbletea_widgets::textinput::new;

let mut input = new();
input.set_value("hello");
input.cursor_end();
input.cursor_start();
assert_eq!(input.position(), 0);
§Note

This method matches Go’s CursorStart method exactly for compatibility.

Source

pub fn cursor_end(&mut self)

Moves the cursor to the end of the input field.

§Examples
use bubbletea_widgets::textinput::new;

let mut input = new();
input.set_value("hello");
input.cursor_start();
input.cursor_end();
assert_eq!(input.position(), 5);
§Note

This method matches Go’s CursorEnd method exactly for compatibility.

Source

pub fn focused(&self) -> bool

Returns whether the text input currently has focus.

§Returns

true if the input is focused and will respond to key events, false otherwise

§Examples
use bubbletea_widgets::textinput::new;

let mut input = new();
assert!(!input.focused());
input.focus();
assert!(input.focused());
§Note

This method matches Go’s Focused method exactly for compatibility.

Source

pub fn focus(&mut self) -> Cmd

Sets focus on the text input, enabling it to receive key events.

When focused, the text input will display a cursor and respond to keyboard input. This method also focuses the cursor component which may return a command for cursor blinking.

§Returns

A Cmd that may be used to start cursor blinking animation

§Examples
use bubbletea_widgets::textinput::new;

let mut input = new();
let cmd = input.focus();
assert!(input.focused());
§Note

This method matches Go’s Focus method exactly for compatibility.

Source

pub fn blur(&mut self)

Removes focus from the text input, disabling key event handling.

When blurred, the text input will not respond to keyboard input and the cursor will not be visible.

§Examples
use bubbletea_widgets::textinput::new;

let mut input = new();
input.focus();
assert!(input.focused());
input.blur();
assert!(!input.focused());
§Note

This method matches Go’s Blur method exactly for compatibility.

Source

pub fn reset(&mut self)

Clears all text and resets the cursor to the beginning.

This method removes all text content and moves the cursor to position 0. It does not change other settings like placeholder text, validation, or styling.

§Examples
use bubbletea_widgets::textinput::new;

let mut input = new();
input.set_value("some text");
input.reset();
assert_eq!(input.value(), "");
assert_eq!(input.position(), 0);
§Note

This method matches Go’s Reset method exactly for compatibility.

Source

pub fn set_suggestions(&mut self, suggestions: Vec<String>)

Sets the list of available suggestions for auto-completion.

Suggestions will be filtered based on the current input and can be navigated using the configured key bindings (typically up/down arrows and tab to accept).

§Arguments
  • suggestions - A vector of strings that can be suggested to the user
§Examples
use bubbletea_widgets::textinput::new;

let mut input = new();
input.set_suggestions(vec![
    "apple".to_string(),
    "application".to_string(),
    "apply".to_string(),
]);
input.set_value("app");
// Now suggestions starting with "app" will be available
§Note

This method matches Go’s SetSuggestions method exactly for compatibility.

Source

pub fn set_placeholder(&mut self, placeholder: &str)

Sets the placeholder text displayed when the input is empty.

§Arguments
  • placeholder - The placeholder text to display
§Examples
use bubbletea_widgets::textinput::new;

let mut input = new();
input.set_placeholder("Enter your name...");
// Placeholder will be visible when input is empty and focused
Source

pub fn set_width(&mut self, width: i32)

Sets the display width of the input field in characters.

This controls how many characters are visible at once. If the text is longer than the width, it will scroll horizontally as the user types or moves the cursor.

§Arguments
  • width - The width in characters. Use 0 for no width limit.
§Examples
use bubbletea_widgets::textinput::new;

let mut input = new();
input.set_width(20); // Show up to 20 characters at once
Source

pub fn set_echo_mode(&mut self, mode: EchoMode)

Sets the echo mode for displaying typed characters.

§Arguments
  • mode - The echo mode to use:
    • EchoNormal: Display characters as typed (default)
    • EchoPassword: Display asterisks instead of actual characters
    • EchoNone: Don’t display any characters
§Examples
use bubbletea_widgets::textinput::{new, EchoMode};

let mut input = new();
input.set_echo_mode(EchoMode::EchoPassword);
input.set_value("secret");
// Text will appear as asterisks: ******
Source

pub fn set_char_limit(&mut self, limit: i32)

Sets the maximum number of characters allowed in the input.

§Arguments
  • limit - Maximum number of characters. Use 0 for no limit.
§Examples
use bubbletea_widgets::textinput::new;

let mut input = new();
input.set_char_limit(10); // Allow up to 10 characters
input.set_value("This is a very long string");
assert_eq!(input.value().len(), 10); // Truncated to 10 characters
Source

pub fn set_validate(&mut self, validate: ValidateFunc)

Sets a validation function that will be called whenever the input changes.

The validation function receives the current input value and should return Ok(()) if the input is valid, or Err(message) if invalid.

§Arguments
  • validate - A function that takes a &str and returns Result<(), String>
§Examples
use bubbletea_widgets::textinput::new;

let mut input = new();
input.set_validate(Box::new(|s: &str| {
    if s.contains('@') {
        Ok(())
    } else {
        Err("Must contain @ symbol".to_string())
    }
}));
Source

pub fn update(&mut self, msg: Msg) -> Option<Cmd>

Processes a message and updates the text input state.

This method handles keyboard input, cursor movement, text editing operations, and clipboard operations. It should be called from your application’s update loop.

§Arguments
  • msg - The message to process (typically a key press or paste event)
§Returns

An optional Cmd that may need to be executed (e.g., for cursor blinking)

§Examples
use bubbletea_widgets::textinput::new;
use bubbletea_rs::{KeyMsg, Model};
use crossterm::event::{KeyCode, KeyModifiers};

let mut input = new();
input.focus();

// Simulate typing 'h'
let key_msg = KeyMsg {
    key: KeyCode::Char('h'),
    modifiers: KeyModifiers::NONE,
};
input.update(Box::new(key_msg));
assert_eq!(input.value(), "h");
Source§

impl Model

Source

pub fn available_suggestions(&self) -> Vec<String>

Returns the complete list of available suggestions.

This returns all suggestions that were set via set_suggestions(), regardless of the current input or filtering.

§Returns

A vector of all available suggestion strings

§Examples
use bubbletea_widgets::textinput::new;

let mut input = new();
input.set_suggestions(vec!["apple".to_string(), "banana".to_string()]);
let suggestions = input.available_suggestions();
assert_eq!(suggestions.len(), 2);
§Note

This method matches Go’s AvailableSuggestions method exactly.

Source

pub fn matched_suggestions(&self) -> Vec<String>

Returns the list of suggestions that match the current input.

This returns only the suggestions that start with the current input value (case-insensitive matching). The list is updated automatically as the user types.

§Returns

A vector of suggestion strings that match the current input

§Examples
use bubbletea_widgets::textinput::new;

let mut input = new();
input.set_suggestions(vec![
    "apple".to_string(),
    "application".to_string(),
    "banana".to_string(),
]);
input.set_value("app");
let matched = input.matched_suggestions();
assert_eq!(matched.len(), 2); // "apple" and "application"
§Note

This method matches Go’s MatchedSuggestions method exactly.

Source

pub fn current_suggestion_index(&self) -> usize

Returns the index of the currently selected suggestion.

This index refers to the position in the matched suggestions list (not the complete available suggestions list). Use up/down arrow keys or configured navigation bindings to change the selection.

§Returns

The zero-based index of the currently selected suggestion

§Examples
use bubbletea_widgets::textinput::new;

let mut input = new();
input.set_suggestions(vec!["apple".to_string(), "application".to_string()]);
input.set_value("app");
assert_eq!(input.current_suggestion_index(), 0); // First suggestion selected
§Note

This method matches Go’s CurrentSuggestionIndex method exactly.

Source

pub fn current_suggestion(&self) -> String

Returns the text of the currently selected suggestion.

If no suggestions are available or the index is out of bounds, this returns an empty string.

§Returns

The currently selected suggestion as a String, or empty string if none

§Examples
use bubbletea_widgets::textinput::new;

let mut input = new();
input.set_suggestions(vec!["apple".to_string(), "application".to_string()]);
input.set_value("app");
assert_eq!(input.current_suggestion(), "apple");
§Note

This method matches Go’s CurrentSuggestion method exactly.

Source§

impl Model

Source

pub fn view(&self) -> String

View renders the textinput in its current state. Matches Go’s View method exactly.

Trait Implementations§

Source§

impl Component for Model

Source§

fn focus(&mut self) -> Option<Cmd>

Sets the component to focused state.

This implementation wraps the existing focus() method to match the Component trait’s expected signature of returning Option<Cmd> instead of Cmd.

§Returns

Some(Cmd) containing a cursor blink command, or None if no command is needed.

Source§

fn blur(&mut self)

Sets the component to blurred (unfocused) state.

This directly delegates to the existing blur() method which already matches the Component trait signature.

Source§

fn focused(&self) -> bool

Returns the current focus state of the component.

This directly delegates to the existing focused() method which already matches the Component trait signature.

Source§

impl Default for Model

Source§

fn default() -> Self

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

impl Model for Model

Source§

fn init() -> (Self, Option<Cmd>)

Initialize the model with its initial state and optional startup command. Read more
Source§

fn update(&mut self, msg: Msg) -> Option<Cmd>

Update the model in response to a received message. Read more
Source§

fn view(&self) -> String

Render the current model state as a string for terminal display. Read more

Auto Trait Implementations§

§

impl Freeze for Model

§

impl !RefUnwindSafe for Model

§

impl Send for Model

§

impl !Sync for Model

§

impl Unpin for Model

§

impl !UnwindSafe for Model

Blanket Implementations§

Source§

impl<S, D, Swp, Dwp, T> AdaptInto<D, Swp, Dwp, T> for S
where T: Real + Zero + Arithmetics + Clone, Swp: WhitePoint<T>, Dwp: WhitePoint<T>, D: AdaptFrom<S, Swp, Dwp, T>,

Source§

fn adapt_into_using<M>(self, method: M) -> D
where M: TransformMatrix<T>,

Convert the source color to the destination color using the specified method.
Source§

fn adapt_into(self) -> D

Convert the source color to the destination color using the bradford method by default.
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, C> ArraysFrom<C> for T
where C: IntoArrays<T>,

Source§

fn arrays_from(colors: C) -> T

Cast a collection of colors into a collection of arrays.
Source§

impl<T, C> ArraysInto<C> for T
where C: FromArrays<T>,

Source§

fn arrays_into(self) -> C

Cast this collection of arrays into a collection of colors.
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<WpParam, T, U> Cam16IntoUnclamped<WpParam, T> for U
where T: FromCam16Unclamped<WpParam, U>,

Source§

type Scalar = <T as FromCam16Unclamped<WpParam, U>>::Scalar

The number type that’s used in parameters when converting.
Source§

fn cam16_into_unclamped( self, parameters: BakedParameters<WpParam, <U as Cam16IntoUnclamped<WpParam, T>>::Scalar>, ) -> T

Converts self into C, using the provided parameters.
Source§

impl<T, C> ComponentsFrom<C> for T
where C: IntoComponents<T>,

Source§

fn components_from(colors: C) -> T

Cast a collection of colors into a collection of color components.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromAngle<T> for T

Source§

fn from_angle(angle: T) -> T

Performs a conversion from angle.
Source§

impl<T, U> FromStimulus<U> for T
where U: IntoStimulus<T>,

Source§

fn from_stimulus(other: U) -> T

Converts other into Self, while performing the appropriate scaling, rounding and clamping.
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, U> IntoAngle<U> for T
where U: FromAngle<T>,

Source§

fn into_angle(self) -> U

Performs a conversion into T.
Source§

impl<WpParam, T, U> IntoCam16Unclamped<WpParam, T> for U
where T: Cam16FromUnclamped<WpParam, U>,

Source§

type Scalar = <T as Cam16FromUnclamped<WpParam, U>>::Scalar

The number type that’s used in parameters when converting.
Source§

fn into_cam16_unclamped( self, parameters: BakedParameters<WpParam, <U as IntoCam16Unclamped<WpParam, T>>::Scalar>, ) -> T

Converts self into C, using the provided parameters.
Source§

impl<T, U> IntoColor<U> for T
where U: FromColor<T>,

Source§

fn into_color(self) -> U

Convert into T with values clamped to the color defined bounds Read more
Source§

impl<T, U> IntoColorUnclamped<U> for T
where U: FromColorUnclamped<T>,

Source§

fn into_color_unclamped(self) -> U

Convert into T. The resulting color might be invalid in its color space Read more
Source§

impl<T> IntoStimulus<T> for T

Source§

fn into_stimulus(self) -> T

Converts self into T, while performing the appropriate scaling, rounding and clamping.
Source§

impl<T, C> TryComponentsInto<C> for T
where C: TryFromComponents<T>,

Source§

type Error = <C as TryFromComponents<T>>::Error

The error for when try_into_colors fails to cast.
Source§

fn try_components_into(self) -> Result<C, <T as TryComponentsInto<C>>::Error>

Try to cast this collection of color components into a collection of colors. 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.
Source§

impl<T, U> TryIntoColor<U> for T
where U: TryFromColor<T>,

Source§

fn try_into_color(self) -> Result<U, OutOfBounds<U>>

Convert into T, returning ok if the color is inside of its defined range, otherwise an OutOfBounds error is returned which contains the unclamped color. Read more
Source§

impl<C, U> UintsFrom<C> for U
where C: IntoUints<U>,

Source§

fn uints_from(colors: C) -> U

Cast a collection of colors into a collection of unsigned integers.
Source§

impl<C, U> UintsInto<C> for U
where C: FromUints<U>,

Source§

fn uints_into(self) -> C

Cast this collection of unsigned integers into a collection of colors.