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
impl Context
Sourcepub fn text(&mut self, s: impl Into<String>) -> &mut Self
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);Sourcepub fn link(
&mut self,
text: impl Into<String>,
url: impl Into<String>,
) -> &mut Self
pub fn link( &mut self, text: impl Into<String>, url: impl Into<String>, ) -> &mut Self
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.
Sourcepub fn text_wrap(&mut self, s: impl Into<String>) -> &mut Self
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.
Sourcepub fn help_from_keymap(&mut self, keymap: &KeyMap) -> Response
pub fn help_from_keymap(&mut self, keymap: &KeyMap) -> Response
Render help bar from a KeyMap. Shows visible bindings as key-description pairs.
Sourcepub fn dim(&mut self) -> &mut Self
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.
Sourcepub fn strikethrough(&mut self) -> &mut Self
pub fn strikethrough(&mut self) -> &mut Self
Apply strikethrough to the last rendered text element.
Sourcepub fn fg(&mut self, color: Color) -> &mut Self
pub fn fg(&mut self, color: Color) -> &mut Self
Set the foreground color of the last rendered text element.
Sourcepub fn bg(&mut self, color: Color) -> &mut Self
pub fn bg(&mut self, color: Color) -> &mut Self
Set the background color of the last rendered text element.
pub fn group_hover_fg(&mut self, color: Color) -> &mut Self
pub fn group_hover_bg(&mut self, color: Color) -> &mut Self
Sourcepub fn styled(&mut self, s: impl Into<String>, style: Style) -> &mut Self
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.
Sourcepub fn image(&mut self, img: &HalfBlockImage) -> Response
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);Sourcepub fn streaming_text(&mut self, state: &mut StreamingTextState) -> Response
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);Sourcepub fn streaming_markdown(
&mut self,
state: &mut StreamingMarkdownState,
) -> Response
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);Sourcepub fn tool_approval(&mut self, state: &mut ToolApprovalState) -> Response
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 {
}Sourcepub fn context_bar(&mut self, items: &[ContextItem]) -> Response
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);pub fn alert(&mut self, message: &str, level: AlertLevel) -> Response
Sourcepub fn confirm(&mut self, question: &str, result: &mut bool) -> Response
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 */ }pub fn accordion( &mut self, title: &str, open: &mut bool, f: impl FnOnce(&mut Context), ) -> Response
pub fn definition_list(&mut self, items: &[(&str, &str)]) -> Response
pub fn divider_text(&mut self, label: &str) -> Response
pub fn badge(&mut self, label: &str) -> Response
pub fn badge_colored(&mut self, label: &str, color: Color) -> Response
pub fn key_hint(&mut self, key: &str) -> Response
pub fn stat(&mut self, label: &str, value: &str) -> Response
pub fn stat_colored( &mut self, label: &str, value: &str, color: Color, ) -> Response
pub fn stat_trend(&mut self, label: &str, value: &str, trend: Trend) -> Response
pub fn empty_state(&mut self, title: &str, description: &str) -> Response
pub fn empty_state_action( &mut self, title: &str, description: &str, action_label: &str, ) -> Response
pub fn code_block(&mut self, code: &str) -> Response
pub fn code_block_numbered(&mut self, code: &str) -> Response
Sourcepub fn wrap(&mut self) -> &mut Self
pub fn wrap(&mut self) -> &mut Self
Enable word-boundary wrapping on the last rendered text element.
Sourcepub fn col_gap(&mut self, gap: u32, f: impl FnOnce(&mut Context)) -> Response
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.
Sourcepub fn row_gap(&mut self, gap: u32, f: impl FnOnce(&mut Context)) -> Response
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.
Sourcepub fn line_wrap(&mut self, f: impl FnOnce(&mut Context)) -> &mut Self
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");
});Sourcepub fn modal(&mut self, f: impl FnOnce(&mut Context))
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; }
});Sourcepub fn overlay(&mut self, f: impl FnOnce(&mut Context))
pub fn overlay(&mut self, f: impl FnOnce(&mut Context))
Render floating content without dimming the background.
Sourcepub fn group(&mut self, name: &str) -> ContainerBuilder<'_>
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"); });Sourcepub fn container(&mut self) -> ContainerBuilder<'_>
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");
});Sourcepub fn scrollable(&mut self, state: &mut ScrollState) -> ContainerBuilder<'_>
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}"));
}
});Sourcepub fn scrollbar(&mut self, state: &ScrollState)
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);
});Sourcepub fn bordered(&mut self, border: Border) -> ContainerBuilder<'_>
pub fn bordered(&mut self, border: Border) -> ContainerBuilder<'_>
Shortcut for container().border(border).
Returns a ContainerBuilder pre-configured with the given border style.
Sourcepub fn is_group_hovered(&self, name: &str) -> bool
pub fn is_group_hovered(&self, name: &str) -> bool
Returns true if the named group is currently hovered by the mouse.
Sourcepub fn is_group_focused(&self, name: &str) -> bool
pub fn is_group_focused(&self, name: &str) -> bool
Returns true if the named group contains the currently focused widget.
Sourcepub fn grow(&mut self, value: u16) -> &mut Self
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.
Sourcepub fn align(&mut self, align: Align) -> &mut Self
pub fn align(&mut self, align: Align) -> &mut Self
Set the text alignment of the last rendered text element.
Sourcepub fn spacer(&mut self) -> &mut Self
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.
Sourcepub fn form(
&mut self,
state: &mut FormState,
f: impl FnOnce(&mut Context, &mut FormState),
) -> &mut Self
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.
Sourcepub fn form_field(&mut self, field: &mut FormField) -> &mut Self
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.
Sourcepub fn form_submit(&mut self, label: impl Into<String>) -> Response
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
impl Context
Sourcepub fn text_input(&mut self, state: &mut TextInputState) -> Response
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 textSourcepub fn spinner(&mut self, state: &SpinnerState) -> &mut Self
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.
Sourcepub fn toast(&mut self, state: &mut ToastState) -> &mut Self
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.
Sourcepub fn slider(
&mut self,
label: &str,
value: &mut f64,
range: RangeInclusive<f64>,
) -> Response
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 */ }Sourcepub fn textarea(
&mut self,
state: &mut TextareaState,
visible_rows: u32,
) -> Response
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.
Sourcepub fn progress(&mut self, ratio: f64) -> &mut Self
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.
Sourcepub fn progress_bar(&mut self, ratio: f64, width: u32) -> &mut Self
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
impl Context
Sourcepub fn grid(&mut self, cols: u32, f: impl FnOnce(&mut Context)) -> Response
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}"));
}
});Sourcepub fn list(&mut self, state: &mut ListState) -> Response
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.
pub fn file_picker(&mut self, state: &mut FilePickerState) -> Response
Sourcepub fn table(&mut self, state: &mut TableState) -> Response
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.
Sourcepub fn tabs(&mut self, state: &mut TabsState) -> Response
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.
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.
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.
Sourcepub fn checkbox(
&mut self,
label: impl Into<String>,
checked: &mut bool,
) -> Response
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.
Sourcepub fn toggle(&mut self, label: impl Into<String>, on: &mut bool) -> Response
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.
Sourcepub fn select(&mut self, state: &mut SelectState) -> Response
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.
Sourcepub fn radio(&mut self, state: &mut RadioState) -> Response
pub fn radio(&mut self, state: &mut RadioState) -> Response
Render a radio button group. Returns true when selection changed.
Sourcepub fn multi_select(&mut self, state: &mut MultiSelectState) -> Response
pub fn multi_select(&mut self, state: &mut MultiSelectState) -> Response
Render a multi-select list. Space toggles, Up/Down navigates.
Sourcepub fn tree(&mut self, state: &mut TreeState) -> Response
pub fn tree(&mut self, state: &mut TreeState) -> Response
Render a tree view. Left/Right to collapse/expand, Up/Down to navigate.
Sourcepub fn virtual_list(
&mut self,
state: &mut ListState,
visible_height: usize,
f: impl Fn(&mut Context, usize),
) -> &mut Self
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.
Sourcepub fn command_palette(
&mut self,
state: &mut CommandPaletteState,
) -> Option<usize>
pub fn command_palette( &mut self, state: &mut CommandPaletteState, ) -> Option<usize>
Render a command palette overlay. Returns Some(index) when a command is selected.
Sourcepub fn markdown(&mut self, text: &str) -> Response
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 (---).
Sourcepub fn key_seq(&self, seq: &str) -> bool
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”).
Sourcepub fn separator(&mut self) -> Response
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.
Sourcepub fn help(&mut self, bindings: &[(&str, &str)]) -> Response
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.
Sourcepub fn key(&self, c: char) -> bool
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.
Sourcepub fn key_code(&self, code: KeyCode) -> bool
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.
Sourcepub fn key_release(&self, c: char) -> bool
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.
Sourcepub fn key_code_release(&self, code: KeyCode) -> bool
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.
Sourcepub fn consume_key(&mut self, c: char) -> bool
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.
Sourcepub fn consume_key_code(&mut self, code: KeyCode) -> bool
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.
Sourcepub fn key_mod(&self, c: char, modifiers: KeyModifiers) -> bool
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.
Sourcepub fn mouse_down(&self) -> Option<(u32, u32)>
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.
Sourcepub fn mouse_pos(&self) -> Option<(u32, u32)>
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.
Sourcepub fn scroll_down(&self) -> bool
pub fn scroll_down(&self) -> bool
Check if an unconsumed scroll-down event occurred this frame.
Sourcepub fn copy_to_clipboard(&mut self, text: impl Into<String>)
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).
Sourcepub fn set_theme(&mut self, theme: Theme)
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.
Sourcepub fn is_dark_mode(&self) -> bool
pub fn is_dark_mode(&self) -> bool
Check if dark mode is active.
Sourcepub fn set_dark_mode(&mut self, dark: bool)
pub fn set_dark_mode(&mut self, dark: bool)
Set dark mode. When true, dark_* style variants are applied.
Sourcepub fn breakpoint(&self) -> Breakpoint
pub fn breakpoint(&self) -> Breakpoint
Get the current terminal width breakpoint.
Returns a Breakpoint based on the terminal width:
Xs: < 40 columnsSm: 40-79 columnsMd: 80-119 columnsLg: 120-159 columnsXl: >= 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"); });
}
}Sourcepub fn tick(&self) -> u64
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.
Sourcepub fn debug_enabled(&self) -> bool
pub fn debug_enabled(&self) -> bool
Return whether the layout debugger is enabled.
The debugger is toggled with F12 at runtime.
Source§impl Context
impl Context
Sourcepub fn bar_chart(&mut self, data: &[(&str, f64)], max_width: u32) -> Response
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`].Sourcepub fn bar_chart_styled(
&mut self,
bars: &[Bar],
max_width: u32,
direction: BarDirection,
) -> Response
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);Sourcepub fn bar_chart_grouped(
&mut self,
groups: &[BarGroup],
max_width: u32,
) -> Response
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);Sourcepub fn sparkline(&mut self, data: &[f64], width: u32) -> Response
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`].Sourcepub fn sparkline_styled(
&mut self,
data: &[(f64, Option<Color>)],
width: u32,
) -> Response
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);Sourcepub fn canvas(
&mut self,
width: u32,
height: u32,
draw: impl FnOnce(&mut CanvasContext),
) -> Response
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);
});Sourcepub fn chart(
&mut self,
configure: impl FnOnce(&mut ChartBuilder),
width: u32,
height: u32,
) -> Response
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.
Sourcepub fn scatter(
&mut self,
data: &[(f64, f64)],
width: u32,
height: u32,
) -> Response
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.
Sourcepub fn histogram(&mut self, data: &[f64], width: u32, height: u32) -> Response
pub fn histogram(&mut self, data: &[f64], width: u32, height: u32) -> Response
Render a histogram from raw data with auto-binning.
Sourcepub fn histogram_with(
&mut self,
data: &[f64],
configure: impl FnOnce(&mut HistogramBuilder),
width: u32,
height: u32,
) -> Response
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
impl Context
Sourcepub fn widget<W: Widget>(&mut self, w: &mut W) -> W::Response
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.
Sourcepub fn error_boundary(&mut self, f: impl FnOnce(&mut Context))
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");
});Sourcepub fn error_boundary_with(
&mut self,
f: impl FnOnce(&mut Context),
fallback: impl FnOnce(&mut Context, String),
)
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}"));
},
);Sourcepub fn interaction(&mut self) -> Response
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.
Sourcepub fn register_focusable(&mut self) -> bool
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.
Sourcepub fn use_state<T: 'static>(&mut self, init: impl FnOnce() -> T) -> State<T>
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;
}Sourcepub fn use_memo<T: 'static, D: PartialEq + Clone + 'static>(
&mut self,
deps: &D,
compute: impl FnOnce(&D) -> T,
) -> &T
pub fn use_memo<T: 'static, D: PartialEq + Clone + 'static>( &mut self, deps: &D, compute: impl FnOnce(&D) -> T, ) -> &T
Sourcepub fn light_dark(&self, light: Color, dark: Color) -> Color
pub fn light_dark(&self, light: Color, dark: Color) -> Color
Returns light color if current theme is light mode, dark color if dark mode.
Sourcepub fn notify(&mut self, message: &str, level: ToastLevel)
pub fn notify(&mut self, message: &str, level: ToastLevel)
Show a toast notification without managing ToastState.
§Examples
ui.notify("File saved!", ToastLevel::Success);