bubbletea-rs

repository·main·Indexed 43 days ago

https://github.com/whit3rabbit/bubbletea-rs

A Rust implementation of the Bubble Tea TUI framework, inspired by Charmbracelet's Go project. It enables the creation of interactive, styled, and async-capable terminal user interfaces using the Model-View-Update (MVU) pattern. Version 0.0.9 includes support for alternate screen buffers, signal handling for suspend/resume, cell-based mouse motion, and a suite of widgets for building complex interfaces like chat apps and autocomplete systems.

Tokens
61.2K
Snippets
204
Records
283
Agent score
52%

What's inside bubbletea-rs

  1. Explore the bubbletea-rs Examples Gallery

    main

    The bubbletea-rs repository contains a wide variety of examples demonstrating different TUI (Terminal User Interface) patterns, components, and behaviors. Developers can use these examples as templates or reference implementations for common tasks such as input handling, layout management, and asynchronous updates.

    Key categories of examples include:

    • Input & Forms: Autocomplete, Credit Card Form, Textinput, Textarea, File Picker.
    • Layout & Views: Composable Views, Split Editors, Tabs, Views, Fullscreen, Altscreen Toggle.
    • Lists & Data: List Simple, List Default, List Fancy, Table, Paginator, Pager.
    • Feedback & Progress: Spinner, Spinners, Progress Animated, Progress Static, Progress Download, Result.
    • Concurrency & Async: Debounce, Exec, Http, Realtime, Timer, Timer Advanced, Send Msg.
    • System & Environment: Window Size, Set Window Title, Mouse, Focus Blur, Prevent Quit.
  2. How the MVU (Model-View-Update) pattern works in bubbletea-rs

    main

    Bubbletea uses the Model-View-Update pattern to manage TUI application state and lifecycle:

    1. Model: Represents your application's state (data).
    2. View: A function that renders the current state to the terminal as a String.
    3. Update: A function that processes incoming Messages (Msg) (like keypresses or timers) and returns an updated model and an optional Command (Cmd) (asynchronous operations).

    The lifecycle follows a continuous loop: The app receives a message $\rightarrow$ update() processes it and modifies the model $\rightarrow$ view() renders the new state $\rightarrow$ the terminal is updated.

  3. Auto-formatting and validation rules in the Credit Card Form

    main

    The credit card form demonstrates real-time input validation and auto-formatting for three specific fields:

    • Credit Card Number: Automatically adds spaces every 4 digits (e.g., 4505123456789012 becomes 4505 1234 5678 9012).
    • Expiry Date: Automatically inserts a slash after the first 2 digits (e.g., 1225 becomes 12/25).
    • CVV: Restricted to 3 digits only.
  4. How the Timer example works

    main

    The Timer example demonstrates a state-driven UI using several bubbletea-widgets components:

    • bubbletea-widgets::timer: Manages the countdown and high-precision ticks.
    • bubbletea-widgets::key: Manages key bindings (like s for start/stop, r for reset, and q for quit).
    • bubbletea-widgets::help: Automatically generates help text. It only displays key bindings that are currently enabled.

    State Management Pattern: When a StartStopMsg is received, the application updates the timer and then synchronizes the key bindings. For example, if the timer is running, the 'stop' binding is enabled and the 'start' binding is disabled. This ensures the help menu always reflects valid user actions.

  5. Choose the right input widget for your use case

    main

    Depending on your requirements, you should select the appropriate widget from the bubbletea-widgets ecosystem:

    • Single Field: Use the standard textinput for simple, single-line inputs.
    • Multi-line Input: Use bubbletea-widgets::textarea for text areas.
    • Selection Forms: Use bubbletea-widgets::list when the user needs to select from a list of options.
    • Data Entry Grids: Use bubbletea-widgets::table for structured data entry in a grid format.
  6. How Model-View-Update (MVU) Architecture works in bubbletea-rs

    main

    All bubbletea-rs applications follow the Model-View-Update (MVU) pattern, which consists of three core components:

    1. Model: Represents the application state (e.g., a struct holding a countdown number or complex application data).
    2. View: A method that renders the UI by returning a String representation of the current state.
    3. Update: A method that handles incoming Msg events (like keyboard input or timer ticks), modifies the Model state, and optionally returns a Cmd (asynchronous command).

    The Data Flow:

    • User Input/Events $\rightarrow$ Update (processes message and changes state)
    • Update $\rightarrow$ Model (state is updated)
    • Model $\rightarrow$ View (renders new UI string)
    • View $\rightarrow$ Terminal (displays the string)
    • Update $\rightarrow$ Runtime (if an asynchronous Cmd is returned, the runtime executes it and sends a new Msg back to the Update loop).
  7. Terminal compatibility for focus reporting

    main

    Focus reporting relies on the terminal emulator sending specific escape sequences.

    • Supported Terminals: Modern graphical terminals like iTerm2, Alacritty, Windows Terminal, and GNOME Terminal.
    • Unsupported/Limited: Basic terminal emulators and some SSH sessions.

    Best Practice: Always implement graceful degradation. Ensure your application remains functional even if the terminal does not support focus events.

  8. How to implement quit prevention in bubbletea-rs

    main

    Unlike the original Go implementation which uses message filtering (tea.WithFilter()), the bubbletea-rs implementation achieves quit prevention through explicit model state management.

    To implement this pattern:

    1. Track an unsaved changes flag (e.g., has_changes: bool) in your model.
    2. Track a quitting state (e.g., quitting: bool) to manage the transition to a confirmation dialog.
    3. In your update logic, intercept quit attempts (like Esc or Ctrl+C). Instead of returning a Quit command immediately, transition the model to the confirmation state if has_changes is true.
    4. Only issue the actual Quit command once the user confirms the action (e.g., by pressing Y) while in the confirmation state.
  9. Use the Viewport component for scrollable content

    main

    The Pager example demonstrates how to use bubbletea-widgets::viewport to create a scrollable text display. Key patterns include:

    • Scrollable Content: Implementing text display that supports scrolling.
    • Dynamic Content Loading: Reading content (such as markdown files) from disk to populate the viewport.
    • Responsive Layout: Calculating and adjusting the viewport size dynamically based on the height of other UI elements like headers and footers.
    • Navigation: Providing both mouse (wheel) and keyboard support for scrolling.
  10. How the Model-View-Update (MVU) architecture works

    main

    The bubbletea-rs framework is built on the Model-View-Update pattern, which separates application state, logic, and rendering into three distinct parts:

    1. Model (State): Holds your application state, business logic, and handles updates.
    2. View (Rendering): Responsible for rendering the UI. It uses lipgloss for styling, layouts, and components to transform the state into a visual representation.
    3. Commands (Async Ops): Handles side effects such as timers, HTTP requests, File I/O, or custom async operations. These are processed by the bubbletea-rs event loop.

    The event loop orchestrates the flow: updates change the Model, which triggers a View re-render, and Commands are executed asynchronously to feed new messages back into the loop.

  11. Implementation details of the Table Example

    main

    The table example is built using several key patterns and components:

    • Rendering: Uses lipgloss-extras::table for the core table rendering logic.
    • Viewport: Implements a fixed-height scrollable viewport (set to 7 rows).
    • State Management: Manages focus states to change the visual appearance of selection highlighting.
    • Styling: Uses custom styling to replicate the behavior and aesthetics of the original Go Bubble Tea table example.