Model

Struct Model 

Source
pub struct Model {
    pub columns: Vec<Column>,
    pub rows: Vec<Row>,
    pub selected: usize,
    pub width: i32,
    pub height: i32,
    pub keymap: TableKeyMap,
    pub styles: Styles,
    pub focus: bool,
    pub help: Model,
    /* private fields */
}
Expand description

Interactive table model containing data, styling, navigation state, and a viewport for efficient rendering and scrolling.

Fields§

§columns: Vec<Column>

Column definitions controlling headers and widths.

§rows: Vec<Row>

Row data; each row contains one string per column.

§selected: usize

Index of the currently selected row (0-based).

§width: i32

Rendered width of the table in characters.

§height: i32

Rendered height of the table in lines.

§keymap: TableKeyMap

Key bindings for navigation and movement.

§styles: Styles

Styles used when rendering the table.

§focus: bool

Whether this table currently has keyboard focus.

§help: Model

Help model used to render key binding help.

Implementations§

Source§

impl Model

Source

pub fn new(columns: Vec<Column>) -> Self

Creates a new table with the given columns and sensible defaults.

Defaults: height 20, focused, empty rows, and default styles/keymap.

Source

pub fn with_options(opts: Vec<TableOption>) -> Self

Creates a new table with configuration options (Go-compatible constructor).

This constructor provides a flexible, option-based approach to table creation that matches the Go version’s New(opts...) pattern. Each option is a function that configures a specific aspect of the table.

§Arguments
  • opts - Vector of configuration options to apply
§Returns

A configured table model with all options applied

§Examples
use bubbletea_widgets::table::{Model, with_columns, with_rows, with_height, Column, Row};

// Create a fully configured table
let table = Model::with_options(vec![
    with_columns(vec![
        Column::new("ID", 8),
        Column::new("Name", 20),
        Column::new("Status", 12),
    ]),
    with_rows(vec![
        Row::new(vec!["001".into(), "Alice".into(), "Active".into()]),
        Row::new(vec!["002".into(), "Bob".into(), "Inactive".into()]),
    ]),
    with_height(15),
]);

Creating an empty table (equivalent to Go’s New()):

use bubbletea_widgets::table::Model;

let table = Model::with_options(vec![]);
assert_eq!(table.columns.len(), 0);
assert_eq!(table.rows.len(), 0);
§Constructor Philosophy

This pattern provides the same flexibility as the Go version while maintaining Rust’s type safety and ownership semantics. Options are applied in the order provided, allowing later options to override earlier ones if they configure the same property.

Source

pub fn with_rows(self, rows: Vec<Row>) -> Self

Sets the table rows on construction and returns self for chaining.

Source

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

Sets the table width in characters and rebuilds the viewport content.

Source

pub fn set_height(&mut self, h: i32)

Sets the table height in lines and rebuilds the viewport content.

Source

pub fn add_row(&mut self, row: Row)

Appends a row to the table and refreshes the rendered content.

Source

pub fn selected_row(&self) -> Option<&Row>

Returns a reference to the currently selected row, if any.

Source

pub fn select_next(&mut self)

Moves the selection down by one row.

Source

pub fn select_prev(&mut self)

Moves the selection up by one row.

Source

pub fn move_up(&mut self, n: usize)

Moves the selection up by the specified number of rows (Go-compatible alias).

This method provides Go API compatibility by matching the MoveUp method signature and behavior from the original table implementation.

§Arguments
  • n - Number of rows to move up
§Examples
use bubbletea_widgets::table::{Model, Column, Row};

let mut table = Model::new(vec![Column::new("Data", 20)]);
table.rows = vec![
    Row::new(vec!["Row 1".into()]),
    Row::new(vec!["Row 2".into()]),
    Row::new(vec!["Row 3".into()]),
];
table.selected = 2;

table.move_up(1);
assert_eq!(table.selected, 1);
Source

pub fn move_down(&mut self, n: usize)

Moves the selection down by the specified number of rows (Go-compatible alias).

This method provides Go API compatibility by matching the MoveDown method signature and behavior from the original table implementation.

§Arguments
  • n - Number of rows to move down
§Examples
use bubbletea_widgets::table::{Model, Column, Row};

let mut table = Model::new(vec![Column::new("Data", 20)]);
table.rows = vec![
    Row::new(vec!["Row 1".into()]),
    Row::new(vec!["Row 2".into()]),
    Row::new(vec!["Row 3".into()]),
];
table.selected = 0;

table.move_down(2);
assert_eq!(table.selected, 2);
Source

pub fn goto_top(&mut self)

Moves the selection to the first row (Go-compatible alias).

This method provides Go API compatibility by matching the GotoTop method from the original table implementation.

§Examples
use bubbletea_widgets::table::{Model, Column, Row};

let mut table = Model::new(vec![Column::new("Data", 20)]);
table.rows = vec![
    Row::new(vec!["Row 1".into()]),
    Row::new(vec!["Row 2".into()]),
    Row::new(vec!["Row 3".into()]),
];
table.selected = 2;

table.goto_top();
assert_eq!(table.selected, 0);
Source

pub fn goto_bottom(&mut self)

Moves the selection to the last row (Go-compatible alias).

This method provides Go API compatibility by matching the GotoBottom method from the original table implementation.

§Examples
use bubbletea_widgets::table::{Model, Column, Row};

let mut table = Model::new(vec![Column::new("Data", 20)]);
table.rows = vec![
    Row::new(vec!["Row 1".into()]),
    Row::new(vec!["Row 2".into()]),
    Row::new(vec!["Row 3".into()]),
];
table.selected = 0;

table.goto_bottom();
assert_eq!(table.selected, 2);
Source

pub fn set_styles(&mut self, s: Styles)

Sets table styles and rebuilds the viewport content.

This method matches the Go version’s SetStyles functionality by updating the table’s visual styling and ensuring the viewport content is rebuilt to reflect the new styles.

§Arguments
  • s - The new styling configuration to apply
§Examples
use bubbletea_widgets::table::{Model, Column, Styles};
use lipgloss_extras::prelude::*;

let mut table = Model::new(vec![Column::new("Data", 20)]);

let custom_styles = Styles {
    header: Style::new().bold(true).background(Color::from("blue")),
    cell: Style::new().padding(0, 1, 0, 1),
    selected: Style::new().background(Color::from("green")),
};

table.set_styles(custom_styles);
// Table now uses the new styles and viewport is updated
Source

pub fn update_viewport(&mut self)

Updates the viewport content based on current columns, rows, and styling.

This method matches the Go version’s UpdateViewport functionality by rebuilding the rendered table content and ensuring the selected row remains visible. It should be called after any changes to table structure, data, or styling.

§Examples
use bubbletea_widgets::table::{Model, Column, Row};

let mut table = Model::new(vec![Column::new("Name", 20)]);
table.rows.push(Row::new(vec!["Alice".into()]));

// After manual changes, update the viewport
table.update_viewport();
§When to Call

This method is automatically called by most table methods, but you may need to call it manually when:

  • Directly modifying the rows or columns fields
  • Changing dimensions or styling outside of provided methods
  • Ensuring content is current after external modifications
Source

pub fn help_view(&self) -> String

Renders help information for table navigation keys.

This method matches the Go version’s HelpView functionality by generating formatted help text that documents all available key bindings for table navigation.

§Returns

A formatted string containing help information for table navigation

§Examples
use bubbletea_widgets::table::{Model, Column};

let table = Model::new(vec![Column::new("Data", 20)]);
let help_text = table.help_view();

// Contains formatted help showing navigation keys
println!("Table Help:\n{}", help_text);
§Integration

This method is typically used to display help information separately from the main table view:

use bubbletea_widgets::table::{Model, Column};

struct App {
    table: Model,
    show_help: bool,
}

impl App {
    fn view(&self) -> String {
        let mut output = self.table.view();
        if self.show_help {
            output.push_str("\n\n");
            output.push_str(&self.table.help_view());
        }
        output
    }
}
Source

pub fn view(&self) -> String

Renders the table as a string.

Source

pub fn focus(&mut self)

Gives keyboard focus to the table.

Source

pub fn blur(&mut self)

Removes keyboard focus from the table.

Trait Implementations§

Source§

impl Clone for Model

Source§

fn clone(&self) -> Model

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Model

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl KeyMap for Model

Help system integration for displaying table navigation keys.

This implementation provides the help system with information about the table’s key bindings, enabling automatic generation of help text that documents the available navigation commands.

Source§

fn short_help(&self) -> Vec<&Binding>

Returns the most commonly used key bindings for short help display.

This method provides a concise list of the most essential navigation keys that users need to know for basic table operation. It’s used when displaying compact help information.

§Returns

A vector of key binding references for row and page navigation

§Examples
use bubbletea_widgets::table::{Model, Column};
use bubbletea_widgets::help::KeyMap;

let table = Model::new(vec![Column::new("Data", 20)]);
let short_bindings = table.short_help();

// Returns bindings for: up, down, page up, page down
assert_eq!(short_bindings.len(), 4);
§Help Content

The short help includes:

  • Row Up: Move selection up one row
  • Row Down: Move selection down one row
  • Page Up: Move up one page of rows
  • Page Down: Move down one page of rows
Source§

fn full_help(&self) -> Vec<Vec<&Binding>>

Returns all key bindings organized by category for full help display.

This method provides a comprehensive list of all available navigation keys, organized into logical groups for clear presentation in detailed help displays. Each group contains related navigation commands.

§Returns

A vector of groups, where each group is a vector of related key bindings

§Examples
use bubbletea_widgets::table::{Model, Column};
use bubbletea_widgets::help::KeyMap;

let table = Model::new(vec![Column::new("Data", 20)]);
let full_bindings = table.full_help();

// Returns 4 groups of key bindings
assert_eq!(full_bindings.len(), 4);

// First group: row navigation (up/down)
assert_eq!(full_bindings[0].len(), 2);
§Help Organization

The full help is organized into these groups:

  1. Row Navigation: Single row up/down movement
  2. Page Navigation: Full page up/down scrolling
  3. Half Page Navigation: Half page up/down movement
  4. Jump Navigation: Go to start/end positions
§Display Integration

This grouped format allows help displays to show related commands together with appropriate spacing and categorization for better user comprehension.

Source§

impl Model for Model

Source§

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

Creates a new empty table model for Bubble Tea applications.

This initialization method creates a table with no columns or data, suitable for applications that will configure the table structure after initialization. The table starts focused and ready to receive keyboard input.

§Returns

A tuple containing the new table model and no initial command

§Examples
use bubbletea_widgets::table::Model;
use bubbletea_rs::Model as BubbleTeaModel;

// This is typically called by the Bubble Tea framework
let (mut table, cmd) = Model::init();
assert_eq!(table.columns.len(), 0);
assert_eq!(table.rows.len(), 0);
assert!(cmd.is_none());
§Note

Most applications will want to use Model::new(columns) directly instead of this init method, as it allows specifying the table structure immediately.

Source§

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

Processes messages and updates table state with keyboard navigation.

This method handles all keyboard navigation for the table, including row selection, page scrolling, and jumping to start/end positions. It only processes messages when the table is focused, ensuring proper behavior in multi-component applications.

§Arguments
  • msg - The message to process, typically a KeyMsg for keyboard input
§Returns

An optional Cmd that may need to be executed (currently always None)

§Key Handling

The following keys are processed based on the table’s key map configuration:

  • Row Navigation: Up/Down arrows, k/j keys
  • Page Navigation: Page Up/Down, b/f keys
  • Half Page: u/d keys for half-page scrolling
  • Jump Navigation: Home/End, g/G keys for start/end
§Examples
use bubbletea_widgets::table::{Model, Column};
use bubbletea_rs::{KeyMsg, Model as BubbleTeaModel};
use crossterm::event::{KeyCode, KeyModifiers};

let mut table = Model::new(vec![Column::new("Data", 20)]);

// Simulate down arrow key press
let key_msg = Box::new(KeyMsg {
    key: KeyCode::Down,
    modifiers: KeyModifiers::NONE,
});
let cmd = table.update(key_msg);
// Table selection moves down (if there are rows)
§Focus Handling

If the table is not focused (self.focus == false), this method returns immediately without processing the message. This allows multiple components to coexist without interference.

§Performance Optimization

After any navigation that changes the selection, the viewport content is automatically rebuilt to ensure the selected row remains visible and the display is updated correctly.

Source§

fn view(&self) -> String

Renders the table for display in a Bubble Tea application.

This method delegates to the table’s own view() method to generate the formatted string representation. It’s called by the Bubble Tea framework during the render cycle.

§Returns

A multi-line string containing the formatted table with headers, data rows, selection highlighting, and applied styling

§Examples
use bubbletea_widgets::table::{Model, Column, Row};
use bubbletea_rs::Model as BubbleTeaModel;

let mut table = Model::new(vec![Column::new("Name", 15)]);
table.add_row(Row::new(vec!["Alice".into()]));

let output = table.view();
// Contains formatted table ready for terminal display
§Integration Pattern

This method is typically called from your application’s main view() method:

use bubbletea_widgets::table::Model as TableModel;
use bubbletea_rs::Model as BubbleTeaModel;

struct App {
    table: TableModel,
}

impl BubbleTeaModel for App {
     
    fn view(&self) -> String {
        format!("My Application\n\n{}", self.table.view())
    }
}

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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.