Skip to content

Latest commit

 

History

History
186 lines (126 loc) · 10.1 KB

ai-guide.md

File metadata and controls

186 lines (126 loc) · 10.1 KB

AI and Agent Guide

Quick-start for AI coding agents working with SLT.

Core mental model

  • SLT is immediate mode: the closure is the app.
  • Application state usually lives in normal Rust variables or structs.
  • Widget-local persistent state uses use_state() / use_memo().
  • Interactive widgets usually return Response.
  • Layout is mostly row(), col(), container(), scrollable().

Reading order

  1. README.md
  2. docs/guide/01-quick-start.md
  3. docs/reference/widgets.md
  4. docs/guide/03-patterns.md
  5. docs/reference/examples.md
  6. docs/internals/architecture.md for internals

Questions agents get wrong

"What's the difference between text().bold() and styled()?"

text() returns a Text builder, so .bold() styles exactly that element. styled() applies a pre-built Style in one call and returns the same builder. Use styled() when reusing styles across widgets.

"I called ui.bg() but the container background didn't change"

ui.bg() is a deprecated (v0.26) modifier of the LAST TEXT element, not the container. Chain on the text instead (ui.text("x").bg(color)); for a container background, use container().bg(color).col(...).

"How do I animate something?"

Animation types (Tween, Spring, Keyframes, Sequence, Stagger) are standalone structs, not Context methods. Compute values with tick() and pass them to style/layout methods. See docs/guide/07-animation.md.

"Where are the color palettes?"

Use palette::tailwind::{BLUE, RED, ...}.c500 for Tailwind-style colors. See docs/guide/06-theming.md.

"What's the difference between line() and row()?"

Both are horizontal. row() is a full layout container returning Response. line() is for inline rich text returning &mut Self with zero gap between children.

"How do I use _colored variants?"

Stateful widgets (list_colored, table_colored, text_input_colored, ...) take WidgetColors::new().fg(color).bg(color) as the last argument. Builder widgets take colors as a chained method: ui.button("Save").colors(&c), ui.badge("ok").color(c), ui.stat(l, v).color(c). Bind theme colors before the call (let c = ui.theme().success;), because a builder argument cannot borrow ui again. See docs/guide/06-theming.md.

"Why does my hook panic?"

use_state() and use_memo() must be called in the same order every frame. Never put them inside conditionals.

Exception: ui.use_state_keyed(id, init) and ui.use_state_keyed_default::<T>(id) are id-keyed variants and are safe inside if/match branches and loops (id is a &'static str or a runtime String). use_state_named is a deprecated alias that now shares the same slot.

// Wrong: order-based hook inside a conditional drifts the call order.
if expanded {
    let count = ui.use_state(|| 0); // BAD — frame N has it, frame N+1 may not.
}

// Right: id-keyed variant is safe inside conditionals.
if expanded {
    let count = ui.use_state_keyed_default::<i32>("sidebar.count"); // OK
}

The original use_state / use_memo order rule still holds — only the id-keyed use_state_keyed* variants opt out of it.

"How do I handle keyboard shortcuts?"

Use key(c), key_code(code), or key_mod(c, mods). For modal-aware shortcuts use the regular versions. For global shortcuts that bypass modals, use raw_key_code() or raw_key_mod(). Check global shortcuts after rendering widgets: key* only sees events no widget has consumed yet, so a ui.key('q') check placed before a focused text_input fires even while the user types q into the field. For multi-key chords that span frames (vi gg, leader keys like <space>ff) use key_chord("gg") — it buffers partial input across frames and times out on inactivity.

"Why doesn't hover (or a tooltip) do anything?"

The mouse is on by default since v0.26: RunConfig::default() resolves to MouseMode::Drag locally (MouseMode::Click over SSH/mosh), so .clicked, wheel scrolling, scrollbar and split-pane drags, and text selection work with plain slt::run. Pointer moves without a button held are only reported in MouseMode::Hover, so generate slt::run_with(slt::RunConfig::default().mouse_mode(slt::MouseMode::Hover), |ui| { ... }) for any app that relies on .hovered, group_hover_*, on_hover, or ui.tooltip. If clicks do nothing either, look for .mouse(false) / MouseMode::Off. Buttons always activate from the keyboard (focus + Enter/Space).

"How do I make a custom widget?"

Implement the Widget trait with type Response and fn ui(&mut self, ui: &mut Context) -> Self::Response. Use register_focusable() for keyboard support and interaction() for click/hover.

"Can I use SLT without crossterm?"

Yes, for custom backends with Backend, AppState, and frame().

"Should I create an app struct?"

Only if it helps. SLT does not require one.

"Should every widget return Response?"

No. Built-in interactive widgets usually do. Custom widgets can return (), bool, or Response.

"Why is hover/focus data weird on the first frame?"

Because hit-testing and Response.rect use the last layout; see the previous-frame rule.

"Token streaming re-renders the whole frame every token — how do I speed it up?"

That is the immediate-mode contract: stream.push(delta) then the whole closure runs again. Use ui.container().cached(version_key, f) to wrap the static chrome (chat history, sidebar, status bar) keyed off a value you already own — e.g. a hash of the non-streaming inputs, or StreamingTextState::version() of the other panes. Leave the stream itself uncached; it changes every token. Note the current semantics are honest: f still runs every frame (output is byte-identical to .col(f)), and cached records a hit/miss stability signal (Context::region_cache_hits() / region_cache_misses()) rather than skipping the body — this is an author-controlled cache, not reactive binding. See Performance — Pattern 7 for the full rationale and the Phase-0 streaming benchmark.

Implementation rules for agents

  • Prefer ui.container().p(1).col(...) over inventing new layout patterns.
  • Prefer existing *State types over custom ad-hoc input structs.
  • Use Response.changed / .clicked instead of inventing parallel booleans.
  • Use register_focusable() and interaction() in custom widgets.
  • Respect hook ordering rules.
  • Animation types are standalone structs, not Context methods — compute values separately.
  • Use palette::tailwind colors instead of hardcoding RGB values.
  • Check docs/reference/features.md before using feature-gated APIs.

Context injection: stop threading shared state through every render fn

When a value is read by many nested render functions (theme, current tick, current user, toast bus), do not thread &theme, &tick, &mut toasts parameters through every signature. Use ui.provide(value, |ui| ...) once near the root, then have nested code read it back with ui.use_context::<T>() (panics if missing) or ui.try_use_context::<T>() (returns Option<&T>). Added in v0.19.0.

// `provide` boxes the value as `dyn Any`, so the type must satisfy `T: 'static`.
// `Theme` is `Copy`, so deref-copy from `ui.theme()`. Use `&'static str` for
// string literals; switch to `String` if the value comes from runtime input.
#[derive(Clone, Copy)]
struct AppCtx {
    theme: slt::Theme,
    tick: u64,
    user: &'static str,
}

fn main() -> std::io::Result<()> {
    slt::run(|ui: &mut slt::Context| {
        let ctx = AppCtx { theme: *ui.theme(), tick: ui.tick(), user: "subin" };
        ui.provide(ctx, |ui| {
            render_card(ui);
        });
    })
}

fn render_card(ui: &mut slt::Context) {
    // End the immutable borrow before the next `&mut ui` widget call.
    let ctx = *ui.use_context::<AppCtx>();
    ui.text(format!("hi {} (tick {})", ctx.user, ctx.tick));
}

use_context and try_use_context return references tied to ui. Never keep one across a widget call: copy or clone the whole value (or just the fields the component needs) first.

Reserve explicit parameters for writes (e.g. &mut MyDocState) — those should still be passed in, not read out of the context bag. See Patterns guide for the full pattern.

Conditional styling without re-chaining

with_if(cond, modifier) and with(modifier) (v0.19.0) let you fold conditional styling into a single fluent chain on text and ContainerBuilder. Replace if cond { t.bold(); t.fg(Color::Red); } style branching with ui.text(...).with_if(is_error, |t| { t.bold().fg(Color::Red); }) — the text closure receives a Text builder for the same element and returns (), so wrap the chain in a block. On ContainerBuilder the builder is by value and the closure must return it: .with_if(focused, |c| c.title("(focused)").p(2)). Cleaner diffs, no broken chains.

Internal widget rules for agents

When editing SLT built-in widgets inside src/context/*, prefer the internal interaction helpers instead of hand-rolling event scans again. These are internal pub(crate) helpers, not stable public API for external widgets.

  • Use begin_widget_interaction(focused) for marker + Response setup.
  • Use available_key_presses() / available_pastes() to iterate unconsumed inputs.
  • Use left_clicks_for_interaction() or mouse_events_in_rect() for hit-tested mouse handling.
  • Finish by calling consume_indices(...) instead of mutating self.consumed[...] across the widget body.

Public custom widgets should still use the stable public surface (register_focusable(), interaction(), Response).

Keep docs and implementation aligned

When an agent changes a public API, it should update:

  • crate rustdoc in src/lib.rs or the defining file
  • the most relevant guide in docs/
  • example coverage if the new API needs a runnable reference

If the behavior is hard to explain cleanly, the API may still need refinement.