Skip to main content

Context

Struct Context 

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

The main rendering context passed to your closure each frame.

Provides all methods for building UI: text, containers, widgets, and event handling. You receive a &mut Context on every frame and describe what to render by calling its methods. SLT collects those calls, lays them out with flexbox, diffs against the previous frame, and flushes only changed cells.

§Example

slt::run(|ui: &mut slt::Context| {
    if ui.key('q') { ui.quit(); }
    ui.text("Hello, world!").bold();
});

Implementations§

Source§

impl Context

Source

pub fn widget<W: Widget>(&mut self, w: &mut W) -> W::Response

Render a custom Widget.

Calls Widget::ui with this context and returns the widget’s response.

Source

pub fn interaction(&mut self) -> Response

Allocate a click/hover interaction slot and return the Response.

Use this in custom widgets to detect mouse clicks and hovers without wrapping content in a container. Each call reserves one slot in the hit-test map, so the call order must be stable across frames.

Source

pub fn register_focusable(&mut self) -> bool

Register a widget as focusable and return whether it currently has focus.

Call this in custom widgets that need keyboard focus. Each call increments the internal focus counter, so the call order must be stable across frames.

Source

pub fn text(&mut self, s: impl Into<String>) -> &mut Self

Render a text element. Returns &mut Self for style chaining.

§Example
use slt::Color;
ui.text("hello").bold().fg(Color::Cyan);
Source

pub fn text_wrap(&mut self, s: impl Into<String>) -> &mut Self

Render a text element with word-boundary wrapping.

Long lines are broken at word boundaries to fit the container width. Style chaining works the same as Context::text.

Source

pub fn bold(&mut self) -> &mut Self

Apply bold to the last rendered text element.

Source

pub fn dim(&mut self) -> &mut Self

Apply dim styling to the last rendered text element.

Also sets the foreground color to the theme’s text_dim color if no explicit foreground has been set.

Source

pub fn italic(&mut self) -> &mut Self

Apply italic to the last rendered text element.

Source

pub fn underline(&mut self) -> &mut Self

Apply underline to the last rendered text element.

Source

pub fn reversed(&mut self) -> &mut Self

Apply reverse-video to the last rendered text element.

Source

pub fn strikethrough(&mut self) -> &mut Self

Apply strikethrough to the last rendered text element.

Source

pub fn fg(&mut self, color: Color) -> &mut Self

Set the foreground color of the last rendered text element.

Source

pub fn bg(&mut self, color: Color) -> &mut Self

Set the background color of the last rendered text element.

Source

pub fn styled(&mut self, s: impl Into<String>, style: Style) -> &mut Self

Render a text element with an explicit Style applied immediately.

Equivalent to calling text(s) followed by style-chain methods, but more concise when you already have a Style value.

Source

pub fn wrap(&mut self) -> &mut Self

Enable word-boundary wrapping on the last rendered text element.

Source

pub fn col(&mut self, f: impl FnOnce(&mut Context)) -> Response

Create a vertical (column) container.

Children are stacked top-to-bottom. Returns a Response with click/hover state for the container area.

§Example
ui.col(|ui| {
    ui.text("line one");
    ui.text("line two");
});
Source

pub fn col_gap(&mut self, gap: u32, f: impl FnOnce(&mut Context)) -> Response

Create a vertical (column) container with a gap between children.

gap is the number of blank rows inserted between each child.

Source

pub fn row(&mut self, f: impl FnOnce(&mut Context)) -> Response

Create a horizontal (row) container.

Children are placed left-to-right. Returns a Response with click/hover state for the container area.

§Example
ui.row(|ui| {
    ui.text("left");
    ui.spacer();
    ui.text("right");
});
Source

pub fn row_gap(&mut self, gap: u32, f: impl FnOnce(&mut Context)) -> Response

Create a horizontal (row) container with a gap between children.

gap is the number of blank columns inserted between each child.

Source

pub fn container(&mut self) -> ContainerBuilder<'_>

Create a container with a fluent builder.

Use this for borders, padding, grow, constraints, and titles. Chain configuration methods on the returned ContainerBuilder, then call .col() or .row() to finalize.

§Example
use slt::Border;
ui.container()
    .border(Border::Rounded)
    .pad(1)
    .title("My Panel")
    .col(|ui| {
        ui.text("content");
    });
Source

pub fn scrollable(&mut self, state: &mut ScrollState) -> ContainerBuilder<'_>

Create a scrollable container. Handles wheel scroll and drag-to-scroll automatically.

Pass a ScrollState to persist scroll position across frames. The state is updated in-place with the current scroll offset and bounds.

§Example
let mut scroll = ScrollState::new();
ui.scrollable(&mut scroll).col(|ui| {
    for i in 0..100 {
        ui.text(format!("Line {i}"));
    }
});
Source

pub fn bordered(&mut self, border: Border) -> ContainerBuilder<'_>

Shortcut for container().border(border).

Returns a ContainerBuilder pre-configured with the given border style.

Source

pub fn grow(&mut self, value: u16) -> &mut Self

Set the flex-grow factor of the last rendered text element.

A value of 1 causes the element to expand and fill remaining space along the main axis.

Source

pub fn align(&mut self, align: Align) -> &mut Self

Set the text alignment of the last rendered text element.

Source

pub fn spacer(&mut self) -> &mut Self

Render an invisible spacer that expands to fill available space.

Useful for pushing siblings to opposite ends of a row or column.

Source

pub fn text_input(&mut self, state: &mut TextInputState) -> &mut Self

Render a single-line text input. Auto-handles cursor, typing, and backspace.

The widget claims focus via Context::register_focusable. When focused, it consumes character, backspace, arrow, Home, and End key events.

§Example
let mut input = TextInputState::with_placeholder("Search...");
ui.text_input(&mut input);
// input.value holds the current text
Source

pub fn spinner(&mut self, state: &SpinnerState) -> &mut Self

Render an animated spinner.

The spinner advances one frame per tick. Use SpinnerState::dots or SpinnerState::line to create the state, then chain style methods to color it.

Source

pub fn toast(&mut self, state: &mut ToastState) -> &mut Self

Render toast notifications. Calls state.cleanup(tick) automatically.

Expired messages are removed before rendering. If there are no active messages, nothing is rendered and self is returned unchanged.

Source

pub fn textarea( &mut self, state: &mut TextareaState, visible_rows: u32, ) -> &mut Self

Render a multi-line text area with the given number of visible rows.

When focused, handles character input, Enter (new line), Backspace, arrow keys, Home, and End. The cursor is rendered as a block character.

Source

pub fn progress(&mut self, ratio: f64) -> &mut Self

Render a progress bar (20 chars wide). ratio is clamped to 0.0..=1.0.

Uses block characters ( filled, empty). For a custom width use Context::progress_bar.

Source

pub fn progress_bar(&mut self, ratio: f64, width: u32) -> &mut Self

Render a progress bar with a custom character width.

ratio is clamped to 0.0..=1.0. width is the total number of characters rendered.

Source

pub fn list(&mut self, state: &mut ListState) -> &mut Self

Render a selectable list. Handles Up/Down (and k/j) navigation when focused.

The selected item is highlighted with the theme’s primary color. If the list is empty, nothing is rendered.

Source

pub fn table(&mut self, state: &mut TableState) -> &mut Self

Render a data table with column headers. Handles Up/Down selection when focused.

Column widths are computed automatically from header and cell content. The selected row is highlighted with the theme’s selection colors.

Source

pub fn tabs(&mut self, state: &mut TabsState) -> &mut Self

Render a tab bar. Handles Left/Right navigation when focused.

The active tab is rendered in the theme’s primary color. If the labels list is empty, nothing is rendered.

Source

pub fn button(&mut self, label: impl Into<String>) -> bool

Render a clickable button. Returns true when activated via Enter, Space, or mouse click.

The button is styled with the theme’s primary color when focused and the accent color when hovered.

Source

pub fn checkbox( &mut self, label: impl Into<String>, checked: &mut bool, ) -> &mut Self

Render a checkbox. Toggles the bool on Enter, Space, or click.

The checked state is shown with the theme’s success color. When focused, a prefix is added.

Source

pub fn toggle(&mut self, label: impl Into<String>, on: &mut bool) -> &mut Self

Render an on/off toggle switch.

Toggles on when activated via Enter, Space, or click. The switch renders as ●━━ ON or ━━● OFF colored with the theme’s success or dim color respectively.

Source

pub fn separator(&mut self) -> &mut Self

Render a horizontal divider line.

The line is drawn with the theme’s border color and expands to fill the container width.

Source

pub fn help(&mut self, bindings: &[(&str, &str)]) -> &mut Self

Render a help bar showing keybinding hints.

bindings is a slice of (key, action) pairs. Keys are rendered in the theme’s primary color; actions in the dim text color. Pairs are separated by a · character.

Source

pub fn key(&self, c: char) -> bool

Check if a character key was pressed this frame.

Returns true if the key event has not been consumed by another widget.

Source

pub fn key_code(&self, code: KeyCode) -> bool

Check if a specific key code was pressed this frame.

Returns true if the key event has not been consumed by another widget.

Source

pub fn key_mod(&self, c: char, modifiers: KeyModifiers) -> bool

Check if a character key with specific modifiers was pressed this frame.

Returns true if the key event has not been consumed by another widget.

Source

pub fn mouse_down(&self) -> Option<(u32, u32)>

Return the position of a left mouse button down event this frame, if any.

Returns None if no unconsumed mouse-down event occurred.

Source

pub fn mouse_pos(&self) -> Option<(u32, u32)>

Return the current mouse cursor position, if known.

The position is updated on every mouse move or click event. Returns None until the first mouse event is received.

Source

pub fn scroll_up(&self) -> bool

Check if an unconsumed scroll-up event occurred this frame.

Source

pub fn scroll_down(&self) -> bool

Check if an unconsumed scroll-down event occurred this frame.

Source

pub fn quit(&mut self)

Signal the run loop to exit after this frame.

Source

pub fn theme(&self) -> &Theme

Get the current theme.

Source

pub fn set_theme(&mut self, theme: Theme)

Change the theme for subsequent rendering.

All widgets rendered after this call will use the new theme’s colors.

Source

pub fn width(&self) -> u32

Get the terminal width in cells.

Source

pub fn height(&self) -> u32

Get the terminal height in cells.

Source

pub fn tick(&self) -> u64

Get the current tick count (increments each frame).

Useful for animations and time-based logic. The tick starts at 0 and increases by 1 on every rendered frame.

Source

pub fn debug_enabled(&self) -> bool

Return whether the layout debugger is enabled.

The debugger is toggled with F12 at runtime.

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, 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.