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 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);

Render a clickable hyperlink.

The link is interactive: clicking it (or pressing Enter/Space when focused) opens the URL in the system browser. OSC 8 is also emitted for terminals that support native hyperlinks.

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 help_from_keymap(&mut self, keymap: &KeyMap) -> Response

Render help bar from a KeyMap. Shows visible bindings as key-description pairs.

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 group_hover_fg(&mut self, color: Color) -> &mut Self

Source

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

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 image(&mut self, img: &HalfBlockImage) -> Response

Render a half-block image in the terminal.

Each terminal cell displays two vertical pixels using the character with foreground (upper pixel) and background (lower pixel) colors.

Create a HalfBlockImage from a file (requires image feature):

let img = image::open("photo.png").unwrap();
let half = HalfBlockImage::from_dynamic(&img, 40, 20);
ui.image(&half);

Or from raw RGB data (no feature needed):

let rgb = vec![255u8; 30 * 20 * 3];
let half = HalfBlockImage::from_rgb(&rgb, 30, 10);
ui.image(&half);
Source

pub fn streaming_text(&mut self, state: &mut StreamingTextState) -> Response

Render streaming text with a typing cursor indicator.

Displays the accumulated text content. While streaming is true, shows a blinking cursor () at the end.

let mut stream = StreamingTextState::new();
stream.start();
stream.push("Hello from ");
stream.push("the AI!");
ui.streaming_text(&mut stream);
Source

pub fn streaming_markdown( &mut self, state: &mut StreamingMarkdownState, ) -> Response

Render streaming markdown with a typing cursor indicator.

Parses accumulated markdown content line-by-line while streaming. Supports headings, lists, inline formatting, horizontal rules, and fenced code blocks with open/close tracking across stream chunks.

let mut stream = StreamingMarkdownState::new();
stream.start();
stream.push("# Hello\n");
stream.push("- **streaming** markdown\n");
stream.push("```rust\nlet x = 1;\n");
ui.streaming_markdown(&mut stream);
Source

pub fn tool_approval(&mut self, state: &mut ToolApprovalState) -> Response

Render a tool approval widget with approve/reject buttons.

Shows the tool name, description, and two action buttons. Returns the updated ApprovalAction each frame.

let mut tool = ToolApprovalState::new("read_file", "Read contents of config.toml");
ui.tool_approval(&mut tool);
if tool.action == ApprovalAction::Approved {
}
Source

pub fn context_bar(&mut self, items: &[ContextItem]) -> Response

Render a context bar showing active context items with token counts.

Displays a horizontal bar of context sources (files, URLs, etc.) with their token counts, useful for AI chat interfaces.

let items = vec![ContextItem::new("main.rs", 1200), ContextItem::new("lib.rs", 800)];
ui.context_bar(&items);
Source

pub fn alert(&mut self, message: &str, level: AlertLevel) -> Response

Source

pub fn confirm(&mut self, question: &str, result: &mut bool) -> Response

Yes/No confirmation dialog. Returns Response with .clicked=true when answered.

result is set to true for Yes, false for No.

§Examples
let mut answer = false;
let r = ui.confirm("Delete this file?", &mut answer);
if r.clicked && answer { /* user confirmed */ }
Source

pub fn breadcrumb(&mut self, segments: &[&str]) -> Option<usize>

Source

pub fn breadcrumb_with( &mut self, segments: &[&str], separator: &str, ) -> Option<usize>

Source

pub fn accordion( &mut self, title: &str, open: &mut bool, f: impl FnOnce(&mut Context), ) -> Response

Source

pub fn definition_list(&mut self, items: &[(&str, &str)]) -> Response

Source

pub fn divider_text(&mut self, label: &str) -> Response

Source

pub fn badge(&mut self, label: &str) -> Response

Source

pub fn badge_colored(&mut self, label: &str, color: Color) -> Response

Source

pub fn key_hint(&mut self, key: &str) -> Response

Source

pub fn stat(&mut self, label: &str, value: &str) -> Response

Source

pub fn stat_colored( &mut self, label: &str, value: &str, color: Color, ) -> Response

Source

pub fn stat_trend(&mut self, label: &str, value: &str, trend: Trend) -> Response

Source

pub fn empty_state(&mut self, title: &str, description: &str) -> Response

Source

pub fn empty_state_action( &mut self, title: &str, description: &str, action_label: &str, ) -> Response

Source

pub fn code_block(&mut self, code: &str) -> Response

Source

pub fn code_block_numbered(&mut self, code: &str) -> Response

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 line(&mut self, f: impl FnOnce(&mut Context)) -> &mut Self

Render inline text with mixed styles on a single line.

Unlike row, line() is designed for rich text — children are rendered as continuous inline text without gaps.

§Example
ui.line(|ui| {
    ui.text("Status: ");
    ui.text("Online").bold().fg(Color::Green);
});
Source

pub fn line_wrap(&mut self, f: impl FnOnce(&mut Context)) -> &mut Self

Render inline text with mixed styles, wrapping at word boundaries.

Like line, but when the combined text exceeds the container width it wraps across multiple lines while preserving per-segment styles.

§Example
ui.line_wrap(|ui| {
    ui.text("This is a long ");
    ui.text("important").bold().fg(Color::Red);
    ui.text(" message that wraps across lines");
});
Source

pub fn modal(&mut self, f: impl FnOnce(&mut Context))

Render content in a modal overlay with dimmed background.

ui.modal(|ui| {
    ui.text("Are you sure?");
    if ui.button("OK") { show = false; }
});
Source

pub fn overlay(&mut self, f: impl FnOnce(&mut Context))

Render floating content without dimming the background.

Source

pub fn group(&mut self, name: &str) -> ContainerBuilder<'_>

Create a named group container for shared hover/focus styling.

ui.group("card").border(Border::Rounded)
    .group_hover_bg(Color::Indexed(238))
    .col(|ui| { ui.text("Hover anywhere"); });
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 scrollbar(&mut self, state: &ScrollState)

Render a scrollbar track for a ScrollState.

Displays a track () with a proportional thumb (). The thumb size and position are calculated from the scroll state’s content height, viewport height, and current offset.

Typically placed beside a scrollable() container in a row():

let mut scroll = ScrollState::new();
ui.row(|ui| {
    ui.scrollable(&mut scroll).grow(1).col(|ui| {
        for i in 0..100 { ui.text(format!("Line {i}")); }
    });
    ui.scrollbar(&scroll);
});
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 is_group_hovered(&self, name: &str) -> bool

Returns true if the named group is currently hovered by the mouse.

Source

pub fn is_group_focused(&self, name: &str) -> bool

Returns true if the named group contains the currently focused widget.

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 form( &mut self, state: &mut FormState, f: impl FnOnce(&mut Context, &mut FormState), ) -> &mut Self

Render a form that groups input fields vertically.

Use Context::form_field inside the closure to render each field.

Source

pub fn form_field(&mut self, field: &mut FormField) -> &mut Self

Render a single form field with label and input.

Shows a validation error below the input when present.

Source

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

Render a submit button.

Returns true when the button is clicked or activated.

Source§

impl Context

Source

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

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 slider( &mut self, label: &str, value: &mut f64, range: RangeInclusive<f64>, ) -> Response

Horizontal slider for numeric values.

§Examples
let mut volume = 75.0_f64;
let r = ui.slider("Volume", &mut volume, 0.0..=100.0);
if r.changed { /* volume was adjusted */ }
Source

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

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.

Set TextareaState::word_wrap to enable soft-wrapping at a given display-column width. Up/Down then navigate visual lines.

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§

impl Context

Source

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

Render children in a fixed grid with the given number of columns.

Children are placed left-to-right, top-to-bottom. Each cell has equal width (area_width / cols). Rows wrap automatically.

§Example
ui.grid(3, |ui| {
    for i in 0..9 {
        ui.text(format!("Cell {i}"));
    }
});
Source

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

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 file_picker(&mut self, state: &mut FilePickerState) -> Response

Source

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

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) -> Response

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>) -> Response

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 button_with( &mut self, label: impl Into<String>, variant: ButtonVariant, ) -> Response

Render a styled button variant. Returns true when activated.

Use ButtonVariant::Primary for call-to-action, ButtonVariant::Danger for destructive actions, or ButtonVariant::Outline for secondary actions.

Source

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

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) -> Response

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 select(&mut self, state: &mut SelectState) -> Response

Render a dropdown select. Shows the selected item; expands on activation.

Returns true when the selection changed this frame.

Source

pub fn radio(&mut self, state: &mut RadioState) -> Response

Render a radio button group. Returns true when selection changed.

Source

pub fn multi_select(&mut self, state: &mut MultiSelectState) -> Response

Render a multi-select list. Space toggles, Up/Down navigates.

Source

pub fn tree(&mut self, state: &mut TreeState) -> Response

Render a tree view. Left/Right to collapse/expand, Up/Down to navigate.

Source

pub fn virtual_list( &mut self, state: &mut ListState, visible_height: usize, f: impl Fn(&mut Context, usize), ) -> &mut Self

Render a virtual list that only renders visible items.

total is the number of items. visible_height limits how many rows are rendered. The closure f is called only for visible indices.

Source

pub fn command_palette( &mut self, state: &mut CommandPaletteState, ) -> Option<usize>

Render a command palette overlay. Returns Some(index) when a command is selected.

Source

pub fn markdown(&mut self, text: &str) -> Response

Render a markdown string with basic formatting.

Supports headers (#), bold (**), italic (*), inline code (`), unordered lists (-/*), ordered lists (1.), and horizontal rules (---).

Source

pub fn key_seq(&self, seq: &str) -> bool

Check if a sequence of character keys was pressed across recent frames.

Matches when each character in seq appears in consecutive unconsumed key events within this frame. For single-frame sequences only (e.g., “gg”).

Source

pub fn separator(&mut self) -> Response

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)]) -> Response

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_release(&self, c: char) -> bool

Check if a character key was released this frame.

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

Source

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

Check if a specific key code was released this frame.

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

Source

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

Check for a character key press and consume the event, preventing other handlers from seeing it.

Returns true if the key was found unconsumed and is now consumed. Unlike key() which peeks without consuming, this claims exclusive ownership of the event.

Call after widgets if you want widgets to have priority over your handler, or before widgets to intercept first.

Source

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

Check for a special key press and consume the event, preventing other handlers from seeing it.

Returns true if the key was found unconsumed and is now consumed. Unlike key_code() which peeks without consuming, this claims exclusive ownership of the event.

Call after widgets if you want widgets to have priority over your handler, or before widgets to intercept first.

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 paste(&self) -> Option<&str>

Return the first unconsumed paste event text, if any.

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 copy_to_clipboard(&mut self, text: impl Into<String>)

Copy text to the system clipboard via OSC 52.

Works transparently over SSH connections. The text is queued and written to the terminal after the current frame renders.

Requires a terminal that supports OSC 52 (most modern terminals: Ghostty, kitty, WezTerm, iTerm2, Windows Terminal).

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 is_dark_mode(&self) -> bool

Check if dark mode is active.

Source

pub fn set_dark_mode(&mut self, dark: bool)

Set dark mode. When true, dark_* style variants are applied.

Source

pub fn width(&self) -> u32

Get the terminal width in cells.

Source

pub fn breakpoint(&self) -> Breakpoint

Get the current terminal width breakpoint.

Returns a Breakpoint based on the terminal width:

  • Xs: < 40 columns
  • Sm: 40-79 columns
  • Md: 80-119 columns
  • Lg: 120-159 columns
  • Xl: >= 160 columns

Use this for responsive layouts that adapt to terminal size:

match ui.breakpoint() {
    Breakpoint::Xs | Breakpoint::Sm => {
        ui.col(|ui| { ui.text("Stacked layout"); });
    }
    _ => {
        ui.row(|ui| { ui.text("Side-by-side layout"); });
    }
}
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.

Source§

impl Context

Source

pub fn bar_chart(&mut self, data: &[(&str, f64)], max_width: u32) -> Response

Render a horizontal bar chart from (label, value) pairs.

Bars are normalized against the largest value and rendered with up to max_width characters.

§Example
let data = [
    ("Sales", 160.0),
    ("Revenue", 120.0),
    ("Users", 220.0),
    ("Costs", 60.0),
];
ui.bar_chart(&data, 24);

For styled bars with per-bar colors, see [`bar_chart_styled`].
Source

pub fn bar_chart_styled( &mut self, bars: &[Bar], max_width: u32, direction: BarDirection, ) -> Response

Render a styled bar chart with per-bar colors, grouping, and direction control.

§Example
use slt::{Bar, Color};
let bars = vec![
    Bar::new("Q1", 32.0).color(Color::Cyan),
    Bar::new("Q2", 46.0).color(Color::Green),
    Bar::new("Q3", 28.0).color(Color::Yellow),
    Bar::new("Q4", 54.0).color(Color::Red),
];
ui.bar_chart_styled(&bars, 30, slt::BarDirection::Horizontal);
Source

pub fn bar_chart_with( &mut self, bars: &[Bar], configure: impl FnOnce(&mut BarChartConfig), max_size: u32, ) -> Response

Source

pub fn bar_chart_grouped( &mut self, groups: &[BarGroup], max_width: u32, ) -> Response

Render a grouped bar chart.

Each group contains multiple bars rendered side by side. Useful for comparing categories across groups (e.g., quarterly revenue by product).

§Example
use slt::{Bar, BarGroup, Color};
let groups = vec![
    BarGroup::new("2023", vec![Bar::new("Rev", 100.0).color(Color::Cyan), Bar::new("Cost", 60.0).color(Color::Red)]),
    BarGroup::new("2024", vec![Bar::new("Rev", 140.0).color(Color::Cyan), Bar::new("Cost", 80.0).color(Color::Red)]),
];
ui.bar_chart_grouped(&groups, 40);
Source

pub fn bar_chart_grouped_with( &mut self, groups: &[BarGroup], configure: impl FnOnce(&mut BarChartConfig), max_size: u32, ) -> Response

Source

pub fn sparkline(&mut self, data: &[f64], width: u32) -> Response

Render a single-line sparkline from numeric data.

Uses the last width points (or fewer if the data is shorter) and maps each point to one of ▁▂▃▄▅▆▇█.

§Example
let samples = [12.0, 9.0, 14.0, 18.0, 16.0, 21.0, 20.0, 24.0];
ui.sparkline(&samples, 16);

For per-point colors and missing values, see [`sparkline_styled`].
Source

pub fn sparkline_styled( &mut self, data: &[(f64, Option<Color>)], width: u32, ) -> Response

Render a sparkline with per-point colors.

Each point can have its own color via (f64, Option<Color>) tuples. Use f64::NAN for absent values (rendered as spaces).

§Example
use slt::Color;
let data: Vec<(f64, Option<Color>)> = vec![
    (12.0, Some(Color::Green)),
    (9.0, Some(Color::Red)),
    (14.0, Some(Color::Green)),
    (f64::NAN, None),
    (18.0, Some(Color::Cyan)),
];
ui.sparkline_styled(&data, 16);
Source

pub fn line_chart(&mut self, data: &[f64], width: u32, height: u32) -> Response

Render a multi-row line chart using braille characters.

width and height are terminal cell dimensions. Internally this uses braille dot resolution (width*2 x height*4) for smoother plotting.

§Example
let data = [1.0, 3.0, 2.0, 5.0, 4.0, 6.0, 3.0, 7.0];
ui.line_chart(&data, 40, 8);
Source

pub fn line_chart_colored( &mut self, data: &[f64], width: u32, height: u32, color: Color, ) -> Response

Render a multi-row line chart using a custom color.

Source

pub fn area_chart(&mut self, data: &[f64], width: u32, height: u32) -> Response

Render a multi-row area chart using the primary theme color.

Source

pub fn area_chart_colored( &mut self, data: &[f64], width: u32, height: u32, color: Color, ) -> Response

Render a multi-row area chart using a custom color.

Source

pub fn candlestick( &mut self, candles: &[Candle], width: u32, height: u32, up_color: Color, down_color: Color, ) -> Response

Render an OHLC candlestick chart.

Source

pub fn heatmap( &mut self, data: &[Vec<f64>], width: u32, height: u32, low_color: Color, high_color: Color, ) -> Response

Render a heatmap from a 2D data grid.

Each cell maps to a block character with color intensity: low values -> dim/dark, high values -> bright/saturated.

§Arguments
  • data - Row-major 2D grid (outer = rows, inner = columns)
  • width - Widget width in terminal cells
  • height - Widget height in terminal cells
  • low_color - Color for minimum values
  • high_color - Color for maximum values
Source

pub fn canvas( &mut self, width: u32, height: u32, draw: impl FnOnce(&mut CanvasContext), ) -> Response

Render a braille drawing canvas.

The closure receives a CanvasContext for pixel-level drawing. Each terminal cell maps to a 2x4 braille dot matrix, giving width*2 x height*4 pixel resolution.

§Example
ui.canvas(40, 10, |cv| {
    cv.line(0, 0, cv.width() - 1, cv.height() - 1);
    cv.circle(40, 20, 15);
});
Source

pub fn chart( &mut self, configure: impl FnOnce(&mut ChartBuilder), width: u32, height: u32, ) -> Response

Render a multi-series chart with axes, legend, and auto-scaling.

width and height must be non-zero. For dynamic sizing, read terminal dimensions first (for example via ui.width() / ui.height()) and pass the computed values to this method.

Source

pub fn scatter( &mut self, data: &[(f64, f64)], width: u32, height: u32, ) -> Response

Renders a scatter plot.

Each point is a (x, y) tuple. Uses braille markers.

Source

pub fn histogram(&mut self, data: &[f64], width: u32, height: u32) -> Response

Render a histogram from raw data with auto-binning.

Source

pub fn histogram_with( &mut self, data: &[f64], configure: impl FnOnce(&mut HistogramBuilder), width: u32, height: u32, ) -> Response

Render a histogram with configuration options.

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 error_boundary(&mut self, f: impl FnOnce(&mut Context))

Wrap child widgets in a panic boundary.

If the closure panics, the panic is caught and an error message is rendered in place of the children. The app continues running.

§Example
ui.error_boundary(|ui| {
    ui.text("risky widget");
});
Source

pub fn error_boundary_with( &mut self, f: impl FnOnce(&mut Context), fallback: impl FnOnce(&mut Context, String), )

Like error_boundary, but renders a custom fallback instead of the default error message.

The fallback closure receives the panic message as a String.

§Example
ui.error_boundary_with(
    |ui| {
        ui.text("risky widget");
    },
    |ui, msg| {
        ui.text(format!("Recovered from panic: {msg}"));
    },
);
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 use_state<T: 'static>(&mut self, init: impl FnOnce() -> T) -> State<T>

Create persistent state that survives across frames.

Returns a State<T> handle. Access with state.get(ui) / state.get_mut(ui).

§Rules
  • Must be called in the same order every frame (like React hooks)
  • Do NOT call inside if/else that changes between frames
§Example
let count = ui.use_state(|| 0i32);
let val = count.get(ui);
ui.text(format!("Count: {val}"));
if ui.button("+1").clicked {
    *count.get_mut(ui) += 1;
}
Source

pub fn use_memo<T: 'static, D: PartialEq + Clone + 'static>( &mut self, deps: &D, compute: impl FnOnce(&D) -> T, ) -> &T

Memoize a computed value. Recomputes only when deps changes.

§Example
let doubled = ui.use_memo(&count, |c| c * 2);
ui.text(format!("Doubled: {doubled}"));
Source

pub fn light_dark(&self, light: Color, dark: Color) -> Color

Returns light color if current theme is light mode, dark color if dark mode.

Source

pub fn notify(&mut self, message: &str, level: ToastLevel)

Show a toast notification without managing ToastState.

§Examples
ui.notify("File saved!", ToastLevel::Success);

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.