slt/context/runtime.rs
1use super::*;
2
3impl Context {
4 pub(crate) fn new(
5 events: Vec<Event>,
6 width: u32,
7 height: u32,
8 state: &mut FrameState,
9 theme: Theme,
10 ) -> Self {
11 let hook_states = &mut state.hook_states;
12 let named_states = std::mem::take(&mut state.named_states);
13 // Issue #215: hand off the keyed-state map for this frame. Same
14 // lifetime as `named_states`: moved out at frame start, moved back
15 // at frame end (see `run_frame_kernel`).
16 let keyed_states = std::mem::take(&mut state.keyed_states);
17 // Issue #262: hand off the partial-chord buffer for this frame. Same
18 // lifetime as `keyed_states`: moved out at frame start, moved back at
19 // frame end (see `run_frame_kernel`).
20 let chord = std::mem::take(&mut state.chord_states);
21 // Issue #248: hand off the scheduler timer table for this frame. Same
22 // lifetime as `named_states`: moved out at frame start, moved back at
23 // frame end (where untouched slots are GC'd; see `run_frame_kernel`).
24 let scheduler = std::mem::take(&mut state.scheduler);
25 // Issue #234: hand off the async task registry for this frame. Same
26 // lifetime as `scheduler`: moved out at frame start, moved back at
27 // frame end (see `run_frame_kernel`).
28 #[cfg(feature = "async")]
29 let async_tasks = std::mem::take(&mut state.async_tasks);
30 let screen_hook_map = std::mem::take(&mut state.screen_hook_map);
31 let focus = &mut state.focus;
32 // Issue #217: name→index map from the previous frame, used to resolve
33 // `focus_by_name(name)` at frame start. We move it out so the
34 // `register_focusable_named` calls in this frame can rebuild a fresh
35 // `focus_name_map`. The fresh map is swapped back into
36 // `focus_name_map_prev` at frame end.
37 let focus_name_map_prev = std::mem::take(&mut focus.focus_name_map_prev);
38 let pending_focus_name = focus.pending_focus_name.take();
39 let prev_focus_index = focus.prev_focus_index;
40 let layout_feedback = &mut state.layout_feedback;
41 let diagnostics = &mut state.diagnostics;
42 let consumed = vec![false; events.len()];
43
44 // Single wall-clock sample for this frame, reused for double-click
45 // timing below and for `frame_instant` (the timer/scheduler clock).
46 let frame_now = std::time::Instant::now();
47 let mut mouse_pos = layout_feedback.last_mouse_pos;
48 let mut click_pos = None;
49 let mut right_click_pos = None;
50 let mut double_click_pos = None;
51 let mut scroll_pos = None;
52 let mut scroll_delta_frame: i32 = 0;
53 for event in &events {
54 if let Event::Mouse(mouse) = event {
55 mouse_pos = Some((mouse.x, mouse.y));
56 match mouse.kind {
57 MouseKind::Down(MouseButton::Left) => {
58 click_pos = Some((mouse.x, mouse.y));
59 // v0.21.1: a left click on the same cell as the previous
60 // click, within `DOUBLE_CLICK_WINDOW`, is a double-click.
61 // Clear the tracker after firing so a third click starts
62 // a fresh pair (no triple-counting).
63 let pos = (mouse.x, mouse.y);
64 let is_double = layout_feedback.last_click_pos == Some(pos)
65 && layout_feedback.last_click_at.is_some_and(|t| {
66 frame_now.duration_since(t) <= crate::DOUBLE_CLICK_WINDOW
67 });
68 if is_double {
69 double_click_pos = Some(pos);
70 layout_feedback.last_click_at = None;
71 layout_feedback.last_click_pos = None;
72 } else {
73 layout_feedback.last_click_at = Some(frame_now);
74 layout_feedback.last_click_pos = Some(pos);
75 }
76 }
77 MouseKind::Down(MouseButton::Right) => {
78 // Issue #208: capture last right-click position so
79 // `response_for` can hit-test against per-widget rects.
80 right_click_pos = Some((mouse.x, mouse.y));
81 }
82 // v0.21.1: accumulate net vertical wheel delta + the cursor
83 // position, hover-gated per-widget by `response_for`.
84 MouseKind::ScrollUp => {
85 scroll_pos = Some((mouse.x, mouse.y));
86 scroll_delta_frame = scroll_delta_frame.saturating_add(1);
87 }
88 MouseKind::ScrollDown => {
89 scroll_pos = Some((mouse.x, mouse.y));
90 scroll_delta_frame = scroll_delta_frame.saturating_sub(1);
91 }
92 _ => {}
93 }
94 }
95 }
96
97 let mut focus_index = focus.focus_index;
98 if let Some((mx, my)) = click_pos {
99 let mut best: Option<(usize, u64)> = None;
100 for &(fid, rect) in &layout_feedback.prev_focus_rects {
101 if mx >= rect.x && mx < rect.right() && my >= rect.y && my < rect.bottom() {
102 let area = rect.width as u64 * rect.height as u64;
103 if best.is_none_or(|(_, ba)| area < ba) {
104 best = Some((fid, area));
105 }
106 }
107 }
108 if let Some((fid, _)) = best {
109 focus_index = fid;
110 }
111 }
112
113 // Issue #217: resolve a pending `focus_by_name(...)` request against
114 // the previous frame's `name → index` map. If the name wasn't
115 // registered last frame, we keep the request pending for the next
116 // frame so a widget that registers later can still receive focus.
117 // If the request resolves, we consume it.
118 let mut still_pending: Option<String> = None;
119 if let Some(name) = pending_focus_name {
120 if let Some(&resolved) = focus_name_map_prev.get(&name) {
121 focus_index = resolved;
122 } else {
123 still_pending = Some(name);
124 }
125 }
126
127 // Reuse `commands_buf` capacity from the previous frame (issue #150).
128 // `mem::take` swaps an empty Vec into `state.commands_buf`; we then
129 // clear (no-op when reclaimed from a `build_tree` drain, defensive
130 // when reclaimed from the quit path that ran without `build_tree`)
131 // and reuse the allocation. After `build_tree(&mut ctx.commands)`
132 // drains the Vec in place, the empty (but capacity-bearing) Vec is
133 // moved back into `state.commands_buf` at frame end inside
134 // `run_frame_kernel`.
135 let mut commands = std::mem::take(&mut state.commands_buf);
136 commands.clear();
137
138 // Issue #204: reuse the six per-frame `Vec`/`HashSet` allocations
139 // (`context_stack`, `deferred_draws`, `rollback.group_stack`,
140 // `rollback.text_color_stack`, `pending_tooltips`, `hovered_groups`).
141 // Same `mem::take` pattern as `commands_buf` (#150). Each buffer is
142 // empty at frame end (asserted at `run_frame_kernel`) — `mem::take`
143 // hands a `Default::default()` empty back to the state, the Vec/HashSet
144 // we move into `Context` keeps its capacity from the prior frame, and
145 // `clear()` here is a no-op except as a defensive guard against future
146 // refactors that might leak items past the assertions.
147 let mut context_stack = std::mem::take(&mut state.context_stack_buf);
148 context_stack.clear();
149 let mut deferred_draws = std::mem::take(&mut state.deferred_draws_buf);
150 deferred_draws.clear();
151 let mut group_stack = std::mem::take(&mut state.group_stack_buf);
152 group_stack.clear();
153 let mut text_color_stack = std::mem::take(&mut state.text_color_stack_buf);
154 text_color_stack.clear();
155 let mut pending_tooltips = std::mem::take(&mut state.pending_tooltips_buf);
156 pending_tooltips.clear();
157 let hovered_groups = std::mem::take(&mut state.hovered_groups_buf);
158 // `hovered_groups` is `clear()`-ed inside `build_hovered_groups`
159 // immediately below, so we do not pre-clear here — capacity is
160 // preserved across frames.
161
162 // Issue #273: hand off the previous frame's `cached` region keys and a
163 // recycled (cleared) buffer to record this frame's keys into. Both
164 // round-trip back into `FrameState` at frame end. Empty (zero
165 // overhead) for apps that never call `cached`.
166 let region_versions_prev = std::mem::take(&mut state.region_versions);
167 let mut region_versions_cur = std::mem::take(&mut state.region_versions_buf);
168 region_versions_cur.clear();
169
170 let mut ctx = Self {
171 commands,
172 events,
173 consumed,
174 should_quit: false,
175 area_width: width,
176 area_height: height,
177 tick: diagnostics.tick,
178 focus_index,
179 hook_states: std::mem::take(hook_states),
180 named_states,
181 keyed_states,
182 chord,
183 context_stack,
184 prev_focus_count: focus.prev_focus_count,
185 prev_modal_focus_start: focus.prev_modal_focus_start,
186 prev_modal_focus_count: focus.prev_modal_focus_count,
187 prev_scroll_infos: std::mem::take(&mut layout_feedback.prev_scroll_infos),
188 prev_scroll_rects: std::mem::take(&mut layout_feedback.prev_scroll_rects),
189 prev_hit_map: std::mem::take(&mut layout_feedback.prev_hit_map),
190 prev_group_rects: std::mem::take(&mut layout_feedback.prev_group_rects),
191 prev_focus_groups: std::mem::take(&mut layout_feedback.prev_focus_groups),
192 mouse_pos,
193 click_pos,
194 right_click_pos,
195 double_click_pos,
196 scroll_pos,
197 scroll_delta_frame,
198 prev_modal_active: focus.prev_modal_active,
199 clipboard_text: None,
200 debug: diagnostics.debug_mode,
201 debug_layer: diagnostics.debug_layer,
202 inspector_mode: diagnostics.inspector_mode,
203 theme,
204 is_real_terminal: false,
205 // Issue #264: conservative default; overwritten by the probed
206 // snapshot in `run_frame_kernel` on a real terminal.
207 #[cfg(feature = "crossterm")]
208 capabilities: crate::terminal::Capabilities::default(),
209 deferred_draws,
210 rollback: ContextRollbackState {
211 last_text_idx: None,
212 focus_count: 0,
213 last_focusable_id: None,
214 pending_focusable_id: None,
215 interaction_count: 0,
216 scroll_count: 0,
217 group_count: 0,
218 group_stack,
219 overlay_depth: 0,
220 modal_active: false,
221 modal_focus_start: 0,
222 modal_focus_count: 0,
223 hook_cursor: 0,
224 dark_mode: theme.is_dark,
225 notification_queue: std::mem::take(&mut diagnostics.notification_queue),
226 text_color_stack,
227 },
228 pending_tooltips,
229 pending_screen_nav: Vec::new(),
230 hovered_groups,
231 region_versions_prev,
232 region_versions_cur,
233 region_cache_hits: 0,
234 region_cache_misses: 0,
235 scroll_lines_per_event: 1,
236 screen_hook_map,
237 widget_theme: WidgetTheme::new(),
238 prev_focus_index,
239 focus_name_map_prev,
240 focus_name_map: std::collections::HashMap::new(),
241 pending_focus_name: still_pending,
242 // Issue #248: sample a single wall-clock "now" for every timer
243 // method called this frame. v0.21.1: reuse the `frame_now` sampled
244 // above (also used for double-click timing) so the frame has one
245 // coherent clock reading.
246 frame_instant: frame_now,
247 scheduler,
248 // Issue #234: async task registry round-tripped like `scheduler`.
249 #[cfg(feature = "async")]
250 async_tasks,
251 };
252 ctx.build_hovered_groups();
253 ctx
254 }
255
256 fn build_hovered_groups(&mut self) {
257 self.hovered_groups.clear();
258 if let Some(pos) = self.mouse_pos {
259 for (name, rect) in &self.prev_group_rects {
260 if pos.0 >= rect.x
261 && pos.0 < rect.x + rect.width
262 && pos.1 >= rect.y
263 && pos.1 < rect.y + rect.height
264 {
265 self.hovered_groups.insert(std::sync::Arc::clone(name));
266 }
267 }
268 }
269 }
270
271 /// Set how many lines each scroll event moves. Default is 1.
272 pub fn set_scroll_speed(&mut self, lines: u32) {
273 self.scroll_lines_per_event = lines.max(1);
274 }
275
276 /// Get the current scroll speed (lines per scroll event).
277 pub fn scroll_speed(&self) -> u32 {
278 self.scroll_lines_per_event
279 }
280
281 /// Get the current focus index.
282 ///
283 /// Widget indices are assigned in the order [`register_focusable()`](Self::register_focusable) is called.
284 /// Indices are 0-based and wrap at [`focus_count()`](Self::focus_count).
285 pub fn focus_index(&self) -> usize {
286 self.focus_index
287 }
288
289 /// Set the focus index to a specific focusable widget.
290 ///
291 /// Widget indices are assigned in the order [`register_focusable()`](Self::register_focusable) is called
292 /// (0-based). If `index` exceeds the number of focusable widgets it will
293 /// be clamped by the modulo in [`register_focusable`](Self::register_focusable).
294 ///
295 /// # Example
296 ///
297 /// ```no_run
298 /// # slt::run(|ui: &mut slt::Context| {
299 /// // Focus the second focusable widget (index 1)
300 /// ui.set_focus_index(1);
301 /// # });
302 /// ```
303 pub fn set_focus_index(&mut self, index: usize) {
304 self.focus_index = index;
305 }
306
307 /// Get the number of focusable widgets registered in the previous frame.
308 ///
309 /// Returns 0 on the very first frame. Useful together with
310 /// [`set_focus_index()`](Self::set_focus_index) for programmatic focus control.
311 ///
312 /// Note: this intentionally reads `prev_focus_count` (the settled count
313 /// from the last completed frame) rather than `focus_count` (the
314 /// still-incrementing counter for the current frame).
315 #[allow(clippy::misnamed_getters)]
316 pub fn focus_count(&self) -> usize {
317 self.prev_focus_count
318 }
319
320 /// Advance keyboard focus one step, honoring an active modal's focus trap.
321 /// `forward` selects next vs previous; both wrap. Shared by
322 /// [`focus_next`](Self::focus_next) / [`focus_prev`](Self::focus_prev) and
323 /// the `Tab`/`Shift+Tab` handler in `process_focus_keys` (v0.21.1).
324 pub(crate) fn advance_focus(&mut self, forward: bool) {
325 if self.prev_modal_active && self.prev_modal_focus_count > 0 {
326 let mut modal_local = self.focus_index.saturating_sub(self.prev_modal_focus_start);
327 modal_local %= self.prev_modal_focus_count;
328 let next = if forward {
329 (modal_local + 1) % self.prev_modal_focus_count
330 } else if modal_local == 0 {
331 self.prev_modal_focus_count - 1
332 } else {
333 modal_local - 1
334 };
335 self.focus_index = self.prev_modal_focus_start + next;
336 } else if self.prev_focus_count > 0 {
337 self.focus_index = if forward {
338 (self.focus_index + 1) % self.prev_focus_count
339 } else if self.focus_index == 0 {
340 self.prev_focus_count - 1
341 } else {
342 self.focus_index - 1
343 };
344 }
345 }
346
347 /// Move keyboard focus to the next focusable widget (wrapping), exactly as
348 /// pressing `Tab` would. Honors an active modal's focus trap. Pairs with
349 /// [`set_focus_index`](Self::set_focus_index) / [`focus_count`](Self::focus_count)
350 /// for programmatic focus control (e.g. an app-level shortcut). Available
351 /// since v0.21.1.
352 ///
353 /// # Example
354 ///
355 /// ```no_run
356 /// # slt::run(|ui: &mut slt::Context| {
357 /// // Advance focus on a custom shortcut (e.g. a vim-style 'j').
358 /// if ui.key('j') {
359 /// ui.focus_next();
360 /// }
361 /// # });
362 /// ```
363 pub fn focus_next(&mut self) {
364 self.advance_focus(true);
365 }
366
367 /// Move keyboard focus to the previous focusable widget (wrapping), exactly
368 /// as `Shift+Tab` would. Honors an active modal's focus trap. Available
369 /// since v0.21.1.
370 pub fn focus_prev(&mut self) {
371 self.advance_focus(false);
372 }
373
374 /// Move focus to the next focusable widget belonging to the named focus
375 /// group, wrapping within the group. If focus is currently outside the
376 /// group it jumps to the group's first member. No-op if the group had no
377 /// focusable widgets on the previous frame.
378 ///
379 /// Focus groups are declared with [`group`](Self::group); this is the
380 /// scoped counterpart to [`focus_next`](Self::focus_next) for building a
381 /// focus trap around a panel or sub-form without a modal. Available since
382 /// v0.21.1.
383 pub fn focus_next_in_group(&mut self, group: &str) {
384 self.advance_focus_in_group(group, true);
385 }
386
387 /// Move focus to the previous focusable widget in the named group
388 /// (wrapping). See [`focus_next_in_group`](Self::focus_next_in_group).
389 /// Available since v0.21.1.
390 pub fn focus_prev_in_group(&mut self, group: &str) {
391 self.advance_focus_in_group(group, false);
392 }
393
394 fn advance_focus_in_group(&mut self, group: &str, forward: bool) {
395 // Membership comes from the previous frame's `index -> group` table,
396 // the same source `is_group_focused` consults. Indices are valid
397 // focus indices (0..prev_focus_count).
398 let members: Vec<usize> = self
399 .prev_focus_groups
400 .iter()
401 .enumerate()
402 .filter_map(|(idx, g)| match g.as_deref() {
403 Some(name) if name == group => Some(idx),
404 _ => None,
405 })
406 .collect();
407 if members.is_empty() {
408 return;
409 }
410 let new_pos = match members.iter().position(|&m| m == self.focus_index) {
411 Some(p) => {
412 if forward {
413 (p + 1) % members.len()
414 } else if p == 0 {
415 members.len() - 1
416 } else {
417 p - 1
418 }
419 }
420 // Focus is outside the group: jump to its first member.
421 None => 0,
422 };
423 self.focus_index = members[new_pos];
424 }
425
426 /// Read-only snapshot of the terminal's negotiated capabilities
427 /// (issue #264).
428 ///
429 /// Populated once at session enter via a DA1/DA2/XTGETTCAP probe. This is
430 /// **diagnostics-only**: image rendering already routes through the
431 /// automatic blitter ladder (Kitty > Sixel > sextant > half-block), so app
432 /// code is never required to branch on the returned value. On a headless
433 /// backend (e.g. [`TestBackend`](crate::TestBackend)) or piped stdout, the
434 /// probe is skipped and every field is a conservative default.
435 ///
436 /// Available since `0.21.0`.
437 ///
438 /// # Example
439 ///
440 /// ```no_run
441 /// # slt::run(|ui: &mut slt::Context| {
442 /// let caps = ui.capabilities();
443 /// // e.g. surface a "truecolor: on" line in a diagnostics panel.
444 /// let _ = caps.truecolor;
445 /// # });
446 /// ```
447 #[cfg(feature = "crossterm")]
448 #[cfg_attr(docsrs, doc(cfg(feature = "crossterm")))]
449 pub fn capabilities(&self) -> &crate::terminal::Capabilities {
450 &self.capabilities
451 }
452
453 pub(crate) fn process_focus_keys(&mut self) {
454 // Scan for Tab / Shift+Tab / BackTab, recording the direction of each
455 // and consuming the event. The mutation (`advance_focus`) is applied
456 // after the scan: it borrows `&mut self` wholesale, which cannot run
457 // while `self.events` is iterated by reference. Collecting first
458 // preserves the original "each Tab advances once" semantics.
459 let mut actions: Vec<bool> = Vec::new();
460 for (i, event) in self.events.iter().enumerate() {
461 if self.consumed[i] {
462 continue;
463 }
464 if let Event::Key(key) = event {
465 if key.kind != KeyEventKind::Press {
466 continue;
467 }
468 if key.code == KeyCode::Tab && !key.modifiers.contains(KeyModifiers::SHIFT) {
469 actions.push(true);
470 self.consumed[i] = true;
471 } else if (key.code == KeyCode::Tab && key.modifiers.contains(KeyModifiers::SHIFT))
472 || key.code == KeyCode::BackTab
473 {
474 actions.push(false);
475 self.consumed[i] = true;
476 }
477 }
478 }
479 for forward in actions {
480 self.advance_focus(forward);
481 }
482 }
483
484 /// Render a custom [`Widget`].
485 ///
486 /// Calls [`Widget::ui`] with this context and returns the widget's response.
487 pub fn widget<W: Widget>(&mut self, w: &mut W) -> W::Response {
488 w.ui(self)
489 }
490
491 /// Wrap child widgets in a panic boundary.
492 ///
493 /// If the closure panics, the panic is caught and an error message is
494 /// rendered in place of the children. The app continues running.
495 ///
496 /// # Example
497 ///
498 /// ```no_run
499 /// # slt::run(|ui: &mut slt::Context| {
500 /// ui.error_boundary(|ui| {
501 /// ui.text("risky widget");
502 /// });
503 /// # });
504 /// ```
505 pub fn error_boundary(&mut self, f: impl FnOnce(&mut Context)) {
506 self.error_boundary_with(f, |ui, msg| {
507 ui.styled(
508 format!("⚠ Error: {msg}"),
509 Style::new().fg(ui.theme.error).bold(),
510 );
511 });
512 }
513
514 /// Like [`error_boundary`](Self::error_boundary), but renders a custom
515 /// fallback instead of the default error message.
516 ///
517 /// The fallback closure receives the panic message as a [`String`].
518 ///
519 /// # Example
520 ///
521 /// ```no_run
522 /// # slt::run(|ui: &mut slt::Context| {
523 /// ui.error_boundary_with(
524 /// |ui| {
525 /// ui.text("risky widget");
526 /// },
527 /// |ui, msg| {
528 /// ui.text(format!("Recovered from panic: {msg}"));
529 /// },
530 /// );
531 /// # });
532 /// ```
533 pub fn error_boundary_with(
534 &mut self,
535 f: impl FnOnce(&mut Context),
536 fallback: impl FnOnce(&mut Context, String),
537 ) {
538 let snapshot = ContextCheckpoint::capture(self);
539
540 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
541 f(self);
542 }));
543
544 match result {
545 Ok(()) => {}
546 Err(panic_info) => {
547 if self.is_real_terminal {
548 #[cfg(feature = "crossterm")]
549 {
550 let _ = crossterm::terminal::enable_raw_mode();
551 let _ = crossterm::execute!(
552 std::io::stdout(),
553 crossterm::terminal::EnterAlternateScreen
554 );
555 }
556
557 #[cfg(not(feature = "crossterm"))]
558 {}
559 }
560
561 snapshot.restore(self);
562
563 let msg = if let Some(s) = panic_info.downcast_ref::<&str>() {
564 (*s).to_string()
565 } else if let Some(s) = panic_info.downcast_ref::<String>() {
566 s.clone()
567 } else {
568 "widget panicked".to_string()
569 };
570
571 fallback(self, msg);
572 }
573 }
574 }
575
576 /// Reserve the next interaction slot without emitting a marker command.
577 pub(crate) fn reserve_interaction_slot(&mut self) -> usize {
578 let id = self.rollback.interaction_count;
579 self.rollback.interaction_count += 1;
580 id
581 }
582
583 /// Advance the interaction counter for structural commands that still
584 /// participate in hit-map indexing.
585 pub(crate) fn skip_interaction_slot(&mut self) {
586 self.reserve_interaction_slot();
587 }
588
589 /// Issue #273: record a [`ContainerBuilder::cached`] region's version key
590 /// at its (declaration-ordered) call site and classify it as a hit or
591 /// miss versus the previous frame.
592 ///
593 /// Returns `true` if `version_key` matches the value this call site
594 /// recorded last frame (a hit), `false` on a key change, a brand-new slot,
595 /// the first frame, or after a resize (all misses).
596 ///
597 /// This is purely an *author-declared stability signal*: the caller still
598 /// re-runs its closure every frame, so output stays byte-identical and the
599 /// immediate-mode invariant is preserved exactly. The hit/miss result is
600 /// recorded for diagnostics ([`Context::region_cache_hits`] /
601 /// [`Context::region_cache_misses`]) and to give a future cell-level cache
602 /// a sound, principle-preserving gate. See the type-level docs on
603 /// [`ContainerBuilder::cached`] for the full design rationale.
604 pub(crate) fn record_cached_region(&mut self, version_key: u64) -> bool {
605 let idx = self.region_versions_cur.len();
606 let hit = self
607 .region_versions_prev
608 .get(idx)
609 .is_some_and(|&prev| prev == version_key);
610 self.region_versions_cur.push(version_key);
611 if hit {
612 self.region_cache_hits = self.region_cache_hits.saturating_add(1);
613 } else {
614 self.region_cache_misses = self.region_cache_misses.saturating_add(1);
615 }
616 hit
617 }
618
619 /// Number of [`ContainerBuilder::cached`] regions this frame whose version
620 /// key was unchanged from the previous frame (cache hits).
621 ///
622 /// Diagnostics for the opt-in streaming cache (issue #273). A region is a
623 /// hit when its author-supplied `version_key` matches the value the same
624 /// call site recorded last frame; it misses on a key change, a new call
625 /// site, the first frame, or after a terminal resize.
626 ///
627 /// Since 0.21.0.
628 ///
629 /// # Example
630 /// ```no_run
631 /// # slt::run(|ui: &mut slt::Context| {
632 /// ui.container().cached(42, |ui| {
633 /// ui.text("stable chrome");
634 /// });
635 /// let _hits = ui.region_cache_hits();
636 /// # });
637 /// ```
638 pub fn region_cache_hits(&self) -> u32 {
639 self.region_cache_hits
640 }
641
642 /// Number of [`ContainerBuilder::cached`] regions this frame whose version
643 /// key changed (or was new / first-frame / post-resize) — cache misses.
644 ///
645 /// The counterpart to [`Context::region_cache_hits`]. See issue #273.
646 ///
647 /// Since 0.21.0.
648 ///
649 /// # Example
650 /// ```no_run
651 /// # slt::run(|ui: &mut slt::Context| {
652 /// ui.container().cached(7, |ui| {
653 /// ui.text("chrome");
654 /// });
655 /// let _misses = ui.region_cache_misses();
656 /// # });
657 /// ```
658 pub fn region_cache_misses(&self) -> u32 {
659 self.region_cache_misses
660 }
661
662 /// Reserve the next interaction ID and emit a marker command.
663 pub(crate) fn next_interaction_id(&mut self) -> usize {
664 let id = self.reserve_interaction_slot();
665 self.commands.push(Command::InteractionMarker(id));
666 id
667 }
668
669 /// Allocate a click/hover interaction slot and return the [`Response`].
670 ///
671 /// Use this in custom widgets to detect mouse clicks and hovers without
672 /// wrapping content in a container. Call it immediately before the text,
673 /// rich text, link, or container that should own the interaction rect.
674 /// Each call reserves one slot in the hit-test map, so the call order
675 /// must be stable across frames.
676 pub fn interaction(&mut self) -> Response {
677 if (self.rollback.modal_active || self.prev_modal_active)
678 && self.rollback.overlay_depth == 0
679 {
680 return Response::none();
681 }
682 let id = self.next_interaction_id();
683 self.response_for(id)
684 }
685
686 /// Compute and consume the `(gained_focus, lost_focus)` edge flags for the
687 /// widget most recently registered via [`register_focusable`].
688 ///
689 /// If that focusable lined up with the previously-focused widget index from
690 /// the prior frame, the focus change since maps directly to gained/lost.
691 /// Takes (consumes) the `last_focusable_id` marker so a single
692 /// `register_focusable` powers exactly one transition computation.
693 ///
694 /// Shared by [`begin_widget_interaction`](Self::begin_widget_interaction)
695 /// and the widgets that assemble their `Response` by hand rather than
696 /// through it (`text_input`, `slider`, `number_input`) — issue #208 left
697 /// those three reporting `gained_focus`/`lost_focus` as always-false; this
698 /// closes that gap (v0.21.1).
699 pub(crate) fn focus_transitions(&mut self, focused: bool) -> (bool, bool) {
700 if let Some(this_id) = self.rollback.last_focusable_id.take() {
701 let was_focused = self
702 .prev_focus_index
703 .map(|prev| prev == this_id)
704 .unwrap_or(false);
705 (focused && !was_focused, !focused && was_focused)
706 } else {
707 (false, false)
708 }
709 }
710
711 pub(crate) fn begin_widget_interaction(&mut self, focused: bool) -> (usize, Response) {
712 let interaction_id = self.next_interaction_id();
713 let mut response = self.response_for(interaction_id);
714 response.focused = focused;
715 let (gained, lost) = self.focus_transitions(focused);
716 response.gained_focus = gained;
717 response.lost_focus = lost;
718 (interaction_id, response)
719 }
720
721 pub(crate) fn consume_indices<I>(&mut self, indices: I)
722 where
723 I: IntoIterator<Item = usize>,
724 {
725 for index in indices {
726 self.consumed[index] = true;
727 }
728 }
729
730 pub(crate) fn available_key_presses(
731 &self,
732 ) -> impl Iterator<Item = (usize, &crate::event::KeyEvent)> + '_ {
733 self.events.iter().enumerate().filter_map(|(i, event)| {
734 if self.consumed[i] {
735 return None;
736 }
737 match event {
738 Event::Key(key) if key.kind == KeyEventKind::Press => Some((i, key)),
739 _ => None,
740 }
741 })
742 }
743
744 pub(crate) fn available_pastes(&self) -> impl Iterator<Item = (usize, &str)> + '_ {
745 self.events.iter().enumerate().filter_map(|(i, event)| {
746 if self.consumed[i] {
747 return None;
748 }
749 match event {
750 Event::Paste(text) => Some((i, text.as_str())),
751 _ => None,
752 }
753 })
754 }
755
756 pub(crate) fn left_clicks_in_rect(
757 &self,
758 rect: Rect,
759 ) -> impl Iterator<Item = (usize, &crate::event::MouseEvent)> + '_ {
760 self.mouse_events_in_rect(rect).filter_map(|(i, mouse)| {
761 if matches!(mouse.kind, MouseKind::Down(MouseButton::Left)) {
762 Some((i, mouse))
763 } else {
764 None
765 }
766 })
767 }
768
769 pub(crate) fn mouse_events_in_rect(
770 &self,
771 rect: Rect,
772 ) -> impl Iterator<Item = (usize, &crate::event::MouseEvent)> + '_ {
773 self.events
774 .iter()
775 .enumerate()
776 .filter_map(move |(i, event)| {
777 if self.consumed[i] {
778 return None;
779 }
780
781 let Event::Mouse(mouse) = event else {
782 return None;
783 };
784
785 if mouse.x < rect.x
786 || mouse.x >= rect.right()
787 || mouse.y < rect.y
788 || mouse.y >= rect.bottom()
789 {
790 return None;
791 }
792
793 Some((i, mouse))
794 })
795 }
796
797 pub(crate) fn left_clicks_for_interaction(
798 &self,
799 interaction_id: usize,
800 ) -> Option<(Rect, Vec<(usize, &crate::event::MouseEvent)>)> {
801 let rect = self.prev_hit_map.get(interaction_id).copied()?;
802 let clicks = self.left_clicks_in_rect(rect).collect();
803 Some((rect, clicks))
804 }
805
806 pub(crate) fn consume_activation_keys(&mut self, focused: bool) -> bool {
807 if !focused {
808 return false;
809 }
810
811 // Activation keys (Enter / Space) are typically 0–1 per frame and
812 // bounded above by the simultaneous-keypress count from the input
813 // pipeline (well under 8 in practice). A `SmallVec` with an 8-slot
814 // inline capacity eliminates the per-focusable `Vec<usize>` heap
815 // allocation that showed up on every focused widget × every frame.
816 // Spillover beyond 8 falls back to the heap automatically. Closes #135.
817 let consumed: smallvec::SmallVec<[usize; 8]> = self
818 .available_key_presses()
819 .filter_map(|(i, key)| {
820 if matches!(key.code, KeyCode::Enter | KeyCode::Char(' ')) {
821 Some(i)
822 } else {
823 None
824 }
825 })
826 .collect();
827 let activated = !consumed.is_empty();
828 if activated {
829 // `consume_indices` takes `IntoIterator<Item = usize>` — `SmallVec`
830 // satisfies that bound directly, no signature change needed.
831 self.consume_indices(consumed);
832 }
833 activated
834 }
835
836 /// Register a widget as focusable and return whether it currently has focus.
837 ///
838 /// Call this in custom widgets that need keyboard focus. Each call increments
839 /// the internal focus counter, so the call order must be stable across frames.
840 ///
841 /// # Slot reservation by `register_focusable_named`
842 ///
843 /// If [`register_focusable_named`](Self::register_focusable_named) was
844 /// called immediately before this call, it has already allocated a
845 /// slot and bound a name to it; this call **reuses** that slot
846 /// instead of allocating a fresh one. That keeps the name binding
847 /// pointed at the widget the user sees rather than at a dummy slot.
848 pub fn register_focusable(&mut self) -> bool {
849 if (self.rollback.modal_active || self.prev_modal_active)
850 && self.rollback.overlay_depth == 0
851 {
852 self.rollback.last_focusable_id = None;
853 // Drop any pending reservation: the suppressed widget never
854 // attached, so reusing the reserved id from a later widget in
855 // the same frame would silently rebind the name to the wrong
856 // slot.
857 self.rollback.pending_focusable_id = None;
858 return false;
859 }
860 // Issue #217 follow-up: if `register_focusable_named` reserved a
861 // slot for us, reuse it (and skip the FocusMarker push — it was
862 // already emitted when the reservation was made). Otherwise,
863 // allocate a fresh slot the normal way.
864 let (id, freshly_allocated) =
865 if let Some(reserved) = self.rollback.pending_focusable_id.take() {
866 (reserved, false)
867 } else {
868 let id = self.rollback.focus_count;
869 self.rollback.focus_count += 1;
870 (id, true)
871 };
872 // Issue #208: remember this widget's focus id so the immediately
873 // following `begin_widget_interaction` call can compare against
874 // `prev_focus_index` and emit gained/lost focus signals.
875 self.rollback.last_focusable_id = Some(id);
876 if freshly_allocated {
877 self.commands.push(Command::FocusMarker(id));
878 }
879 if self.prev_modal_active
880 && self.prev_modal_focus_count > 0
881 && self.rollback.modal_active
882 && self.rollback.overlay_depth > 0
883 {
884 let mut modal_local_id = id.saturating_sub(self.rollback.modal_focus_start);
885 modal_local_id %= self.prev_modal_focus_count;
886 let mut modal_focus_idx = self.focus_index.saturating_sub(self.prev_modal_focus_start);
887 modal_focus_idx %= self.prev_modal_focus_count;
888 return modal_local_id == modal_focus_idx;
889 }
890 if self.prev_focus_count == 0 {
891 return true;
892 }
893 self.focus_index % self.prev_focus_count == id
894 }
895
896 /// Create persistent state that survives across frames.
897 ///
898 /// Returns a `State<T>` handle. Access with `state.get(ui)` / `state.get_mut(ui)`.
899 ///
900 /// # Rules
901 /// - Must be called in the same order every frame (like React hooks)
902 /// - Do NOT call inside if/else that changes between frames
903 ///
904 /// # Example
905 /// ```ignore
906 /// let count = ui.use_state(|| 0i32);
907 /// let val = count.get(ui);
908 /// ui.text(format!("Count: {val}"));
909 /// if ui.button("+1").clicked {
910 /// *count.get_mut(ui) += 1;
911 /// }
912 /// ```
913 pub fn use_state<T: 'static>(&mut self, init: impl FnOnce() -> T) -> State<T> {
914 let idx = self.rollback.hook_cursor;
915 self.rollback.hook_cursor += 1;
916
917 if idx >= self.hook_states.len() {
918 self.hook_states.push(Box::new(init()));
919 }
920
921 State::from_idx(idx)
922 }
923
924 /// Component-local persistent state keyed by a stable id.
925 ///
926 /// Unlike [`use_state`](Self::use_state), this is **not order-dependent** —
927 /// the value is looked up by `id` instead of call position. Safe to call
928 /// inside conditional branches or reusable component functions.
929 ///
930 /// Returns a `State<T>` handle. Access with `state.get(ui)` /
931 /// `state.get_mut(ui)`. Persists across frames.
932 ///
933 /// # Scoping
934 ///
935 /// Keys are `&'static str` and live in a single global namespace per
936 /// `Context` (no automatic per-component scoping). Two calls with the same
937 /// `id` in the same frame share the same value, regardless of where they
938 /// occur in the tree. Pick unique ids — for example, prefix with a
939 /// component name (`"counter::value"`).
940 ///
941 /// # Naming
942 ///
943 /// The no-suffix form takes an `init` closure, matching
944 /// [`use_state`](Self::use_state)`(init)` and
945 /// [`use_state_keyed`](Self::use_state_keyed)`(id, init)`. Use
946 /// [`use_state_named_default`](Self::use_state_named_default) for the
947 /// `T: Default` shorthand.
948 ///
949 /// # Example
950 ///
951 /// ```no_run
952 /// fn counter(ui: &mut slt::Context) {
953 /// let count = ui.use_state_named("counter::value", || 0i32);
954 /// ui.text(format!("Count: {}", count.get(ui)));
955 /// if ui.button("+1").clicked {
956 /// *count.get_mut(ui) += 1;
957 /// }
958 /// }
959 /// ```
960 pub fn use_state_named<T: 'static>(
961 &mut self,
962 id: &'static str,
963 init: impl FnOnce() -> T,
964 ) -> State<T> {
965 self.named_states
966 .entry(id)
967 .or_insert_with(|| Box::new(init()));
968 State::from_named(id)
969 }
970
971 /// Like [`use_state_named`](Self::use_state_named), but uses
972 /// [`Default::default()`] to initialize the value on first call.
973 ///
974 /// Mirrors [`use_state_keyed_default`](Self::use_state_keyed_default): the
975 /// `_default` suffix means "no init closure, `T: Default` required".
976 ///
977 /// # Example
978 ///
979 /// ```no_run
980 /// # slt::run(|ui: &mut slt::Context| {
981 /// let value = ui.use_state_named_default::<i32>("counter::value");
982 /// ui.text(format!("{}", value.get(ui)));
983 /// # });
984 /// ```
985 pub fn use_state_named_default<T: 'static + Default>(&mut self, id: &'static str) -> State<T> {
986 self.use_state_named(id, T::default)
987 }
988
989 /// Deprecated alias for [`use_state_named`](Self::use_state_named).
990 ///
991 /// **Deprecated since 0.21.0**: the `_named` family now follows the
992 /// "no-suffix = init closure" convention so it matches
993 /// [`use_state`](Self::use_state) and
994 /// [`use_state_keyed`](Self::use_state_keyed). The init-closure form is now
995 /// spelled `use_state_named(id, init)`; the `T: Default` shorthand is
996 /// [`use_state_named_default`](Self::use_state_named_default).
997 ///
998 /// # Example
999 ///
1000 /// ```no_run
1001 /// # slt::run(|ui: &mut slt::Context| {
1002 /// // Old: ui.use_state_named_with("counter::value", || 0i32)
1003 /// let count = ui.use_state_named("counter::value", || 0i32);
1004 /// ui.text(format!("{}", count.get(ui)));
1005 /// # });
1006 /// ```
1007 #[deprecated(
1008 since = "0.21.0",
1009 note = "Renamed to `use_state_named` — the no-suffix form now takes the init closure, matching `use_state` / `use_state_keyed`."
1010 )]
1011 pub fn use_state_named_with<T: 'static>(
1012 &mut self,
1013 id: &'static str,
1014 init: impl FnOnce() -> T,
1015 ) -> State<T> {
1016 self.use_state_named(id, init)
1017 }
1018
1019 /// Smoothly animate between `0.0` and `1.0` driven by a boolean.
1020 ///
1021 /// Returns the current interpolated value (0.0..=1.0). When `value` is
1022 /// `true` the result tweens toward `1.0`; when `false` it tweens back
1023 /// toward `0.0`. The transition duration defaults to
1024 /// [`DEFAULT_ANIMATE_TICKS`](crate::anim::DEFAULT_ANIMATE_TICKS) (12 ticks
1025 /// ≈ 200 ms at 60 Hz). Use [`Context::animate_value`] for custom duration
1026 /// or non-binary targets.
1027 ///
1028 /// State is stored in the per-context named-state map under `id`. The
1029 /// id is `&'static str` (single global namespace per context), matching
1030 /// [`Context::use_state_named`]. Pick a unique key per call site — two
1031 /// `animate_bool` calls with the same id share state.
1032 ///
1033 /// On the first call, the value snaps to the target with no visible
1034 /// transition (so widgets that mount in their final state don't pop).
1035 ///
1036 /// # Example
1037 /// ```ignore
1038 /// let opacity = ui.animate_bool("sidebar::visible", is_open);
1039 /// // 0.0 ≤ opacity ≤ 1.0; use as alpha or visibility threshold.
1040 /// ```
1041 ///
1042 /// # See also
1043 ///
1044 /// - [`animate_value`](Self::animate_value) — the underlying primitive this
1045 /// delegates to; use it for a custom duration or a non-binary target.
1046 /// - [`Tween`](crate::Tween) — full control over easing and lifecycle.
1047 pub fn animate_bool(&mut self, id: &'static str, value: bool) -> f64 {
1048 let target = if value { 1.0 } else { 0.0 };
1049 self.animate_value(id, target, crate::anim::DEFAULT_ANIMATE_TICKS)
1050 }
1051
1052 /// Smoothly animate a `f64` value toward `target` over `duration_ticks`.
1053 ///
1054 /// Uses a linear-easing [`crate::Tween`] stored implicitly in the
1055 /// per-context named-state map under `id`. Returns the current
1056 /// interpolated value. On the first call the value snaps to `target`
1057 /// with no visible transition; on subsequent calls when `target`
1058 /// changes the tween is rebuilt starting from the current interpolated
1059 /// value, so retargeting mid-flight does not produce a jump.
1060 ///
1061 /// `duration_ticks == 0` snaps immediately to the new target.
1062 ///
1063 /// # Panics
1064 ///
1065 /// Panics if `id` is already bound in the named-state map to a value of a
1066 /// different type (e.g. a [`use_state_named`](Self::use_state_named) call
1067 /// reused the same id), since the stored entry then fails to downcast to
1068 /// the internal animation state:
1069 ///
1070 /// ```text
1071 /// animate_value: id {id} is already used for a different state type
1072 /// ```
1073 ///
1074 /// Pick a unique id per call site to avoid the collision.
1075 ///
1076 /// # Example
1077 /// ```ignore
1078 /// let bar_height = ui.animate_value("loading::bar", target_height, 30);
1079 /// ui.bar(bar_height);
1080 /// ```
1081 ///
1082 /// # Comparison with `Tween`
1083 /// Use this shorthand when you want zero boilerplate and linear easing
1084 /// is acceptable. For custom easing, a non-static key, or
1085 /// non-tick-based control, construct a [`crate::Tween`] explicitly via
1086 /// [`Context::use_state_named`](Self::use_state_named).
1087 ///
1088 /// # See also
1089 ///
1090 /// - [`animate_bool`](Self::animate_bool) — boolean-driven shorthand that
1091 /// tweens between `0.0` and `1.0`.
1092 /// - [`Tween`](crate::Tween) — explicit easing and lifecycle control.
1093 pub fn animate_value(&mut self, id: &'static str, target: f64, duration_ticks: u64) -> f64 {
1094 let tick = self.tick;
1095 let entry = self
1096 .named_states
1097 .entry(id)
1098 .or_insert_with(|| Box::new(crate::anim::AnimState::new(target, tick)));
1099 let state = entry
1100 .downcast_mut::<crate::anim::AnimState>()
1101 .unwrap_or_else(|| {
1102 panic!("animate_value: id {id:?} is already used for a different state type")
1103 });
1104 state.sample(target, duration_ticks, tick)
1105 }
1106
1107 /// One-shot frame-clock timer (issue #248).
1108 ///
1109 /// Returns `true` exactly once — on the first frame at or after `dur` has
1110 /// elapsed since the first `schedule` call for `id` — and `false` on every
1111 /// other frame, both before and after. Re-arm by calling
1112 /// [`cancel`](Self::cancel) and then `schedule` again.
1113 ///
1114 /// Wall-clock based ([`std::time::Instant`] sampled once at frame start),
1115 /// so it works with the default feature set and without the `async`
1116 /// feature. Precision is bounded by the run loop's `tick_rate` (the
1117 /// deadline is observed on the next frame after it elapses), so durations
1118 /// well below the frame cadence are not meaningful.
1119 ///
1120 /// The id lives in the same per-context namespace as
1121 /// [`use_state_named`](Self::use_state_named): pick a unique key per call
1122 /// site.
1123 ///
1124 /// # Example
1125 /// ```no_run
1126 /// use std::time::Duration;
1127 ///
1128 /// slt::run(|ui: &mut slt::Context| {
1129 /// if ui.schedule("splash::dismiss", Duration::from_millis(800)) {
1130 /// // Runs once, ~800ms after the first frame that called this.
1131 /// ui.text("Splash dismissed.");
1132 /// }
1133 /// })?;
1134 /// # Ok::<_, std::io::Error>(())
1135 /// ```
1136 pub fn schedule(&mut self, id: &'static str, dur: std::time::Duration) -> bool {
1137 let now = self.frame_instant;
1138 let slot = self
1139 .scheduler
1140 .named
1141 .entry(id)
1142 .or_insert_with(|| SchedulerSlot {
1143 started: now,
1144 kind: SchedKind::Once { dur, fired: false },
1145 touched_this_frame: false,
1146 });
1147 slot.touched_this_frame = true;
1148 let elapsed = now.saturating_duration_since(slot.started);
1149 match &mut slot.kind {
1150 SchedKind::Once { dur, fired } if !*fired && elapsed >= *dur => {
1151 *fired = true;
1152 true
1153 }
1154 // Not yet due, already fired, or a re-used id bound to a different
1155 // timer kind: do not fire (a typo can't crash the app).
1156 _ => false,
1157 }
1158 }
1159
1160 /// Recurring frame-clock timer (issue #248).
1161 ///
1162 /// Returns the number of whole `dur` intervals that elapsed since the
1163 /// previous frame this `id` was sampled: `0` on most frames, `1` typically,
1164 /// and `> 1` if the frame loop stalled past several intervals — so no ticks
1165 /// are silently dropped. The internal clock advances by exactly the
1166 /// returned number of intervals each frame, so counts never drift.
1167 ///
1168 /// Wall-clock based and `async`-free, like [`schedule`](Self::schedule).
1169 ///
1170 /// # Example
1171 /// ```no_run
1172 /// use std::time::Duration;
1173 ///
1174 /// slt::run(|ui: &mut slt::Context| {
1175 /// let ticks = ui.every("clock::second", Duration::from_secs(1));
1176 /// if ticks > 0 {
1177 /// // Advance a once-per-second animation by `ticks` steps.
1178 /// }
1179 /// })?;
1180 /// # Ok::<_, std::io::Error>(())
1181 /// ```
1182 pub fn every(&mut self, id: &'static str, dur: std::time::Duration) -> u32 {
1183 let now = self.frame_instant;
1184 let interval = dur.max(std::time::Duration::from_nanos(1));
1185 let slot = self
1186 .scheduler
1187 .named
1188 .entry(id)
1189 .or_insert_with(|| SchedulerSlot {
1190 started: now,
1191 kind: SchedKind::Every {
1192 interval,
1193 last: now,
1194 },
1195 touched_this_frame: false,
1196 });
1197 slot.touched_this_frame = true;
1198 match &mut slot.kind {
1199 SchedKind::Every { interval, last } => {
1200 let elapsed = now.saturating_duration_since(*last);
1201 let fired = crate::widgets::intervals_elapsed(elapsed, *interval);
1202 if fired > 0 {
1203 // Advance by exactly the intervals reported so counts never
1204 // drift, even across stalled frames.
1205 let advance = interval.saturating_mul(fired);
1206 *last = last.checked_add(advance).unwrap_or(now);
1207 }
1208 fired
1209 }
1210 _ => 0,
1211 }
1212 }
1213
1214 /// Debounce timer — the typeahead / search-as-you-type primitive (#248).
1215 ///
1216 /// Each frame where `dirty == true` resets the quiet window to `dur`.
1217 /// Returns `true` exactly once on the first frame after `dur` of quiet (no
1218 /// `dirty`), then stays `false` until the next dirty frame re-arms it. This
1219 /// mirrors Textual's `@work(exclusive=True)` debounce: collapse a burst of
1220 /// keystrokes so only the final, settled query runs.
1221 ///
1222 /// Wall-clock based and `async`-free, like [`schedule`](Self::schedule).
1223 ///
1224 /// # Example
1225 /// ```no_run
1226 /// use std::time::Duration;
1227 /// use slt::TextInputState;
1228 ///
1229 /// let mut query = TextInputState::with_placeholder("Search...");
1230 /// slt::run(move |ui: &mut slt::Context| {
1231 /// // `resp.changed` is true on the keystroke frame -> the dirty signal.
1232 /// let resp = ui.text_input(&mut query);
1233 /// // Fire the search only after 250ms of no typing.
1234 /// if ui.debounce("search::run", Duration::from_millis(250), resp.changed) {
1235 /// // run_search(&query.value());
1236 /// }
1237 /// })?;
1238 /// # Ok::<_, std::io::Error>(())
1239 /// ```
1240 pub fn debounce(&mut self, id: &'static str, dur: std::time::Duration, dirty: bool) -> bool {
1241 let now = self.frame_instant;
1242 let slot = self
1243 .scheduler
1244 .named
1245 .entry(id)
1246 .or_insert_with(|| SchedulerSlot {
1247 started: now,
1248 kind: SchedKind::Debounce {
1249 dur,
1250 quiet_started: now,
1251 fired: false,
1252 },
1253 touched_this_frame: false,
1254 });
1255 slot.touched_this_frame = true;
1256 match &mut slot.kind {
1257 SchedKind::Debounce {
1258 dur: slot_dur,
1259 quiet_started,
1260 fired,
1261 } => {
1262 *slot_dur = dur;
1263 if dirty {
1264 // Re-arm the quiet window from this frame.
1265 *quiet_started = now;
1266 *fired = false;
1267 false
1268 } else if !*fired && now.saturating_duration_since(*quiet_started) >= *slot_dur {
1269 *fired = true;
1270 true
1271 } else {
1272 false
1273 }
1274 }
1275 _ => false,
1276 }
1277 }
1278
1279 /// Exclusive-group claim — cancel stale work on supersede (issue #248).
1280 ///
1281 /// Within a `group`, only the most-recently-claimed `id` returns `true`;
1282 /// once a newer `id` claims the group, every prior `id` returns `false`
1283 /// from then on. Use it to cancel an in-flight typeahead query when a newer
1284 /// query supersedes it: pair with [`debounce`](Self::debounce) to fire the
1285 /// settled query, then guard the work with `exclusive` so only the latest
1286 /// claim proceeds.
1287 ///
1288 /// # Example
1289 /// ```no_run
1290 /// use std::time::Duration;
1291 ///
1292 /// slt::run(|ui: &mut slt::Context| {
1293 /// let query_id = "q-42"; // e.g. a per-keystroke sequence id
1294 /// if ui.exclusive("search", query_id) {
1295 /// // Only the latest claimed query runs; older ones are cancelled.
1296 /// }
1297 /// })?;
1298 /// # Ok::<_, std::io::Error>(())
1299 /// ```
1300 pub fn exclusive(&mut self, group: &'static str, id: &str) -> bool {
1301 let entry = self
1302 .scheduler
1303 .exclusive
1304 .entry(group.to_string())
1305 .or_default();
1306 if entry.winner == id {
1307 // The reigning claim re-polls itself: still the winner.
1308 return true;
1309 }
1310 if entry.retired.contains(id) {
1311 // A previously-superseded id can never win again: stale work stays
1312 // cancelled even if re-polled.
1313 return false;
1314 }
1315 // A new id supersedes the group: retire the old winner (if any) and
1316 // become the active claim.
1317 if !entry.winner.is_empty() {
1318 let old = std::mem::take(&mut entry.winner);
1319 entry.retired.insert(old);
1320 }
1321 entry.winner = id.to_string();
1322 true
1323 }
1324
1325 /// Drop the scheduler slot for `id`, re-arming it on the next
1326 /// [`schedule`](Self::schedule) / [`every`](Self::every) /
1327 /// [`debounce`](Self::debounce) call (issue #248).
1328 ///
1329 /// Accepts both `&'static str` and runtime-`String` ids: clears the slot
1330 /// from the named map and the dynamic-id map.
1331 ///
1332 /// # Example
1333 /// ```no_run
1334 /// use std::time::Duration;
1335 ///
1336 /// slt::run(|ui: &mut slt::Context| {
1337 /// if ui.schedule("retry", Duration::from_secs(5)) {
1338 /// // ...
1339 /// }
1340 /// if ui.key('r') {
1341 /// ui.cancel("retry"); // next `schedule("retry", ..)` starts fresh
1342 /// }
1343 /// })?;
1344 /// # Ok::<_, std::io::Error>(())
1345 /// ```
1346 pub fn cancel(&mut self, id: &str) {
1347 self.scheduler.named.remove(id);
1348 self.scheduler.keyed.remove(id);
1349 }
1350
1351 /// Wall-clock time elapsed since `id` was first scheduled, or `None` if no
1352 /// live timer slot exists for `id` (issue #248).
1353 ///
1354 /// Useful for progress UIs ("retrying in 3s…") that want the raw elapsed
1355 /// duration rather than a fire/no-fire signal. Measured against the same
1356 /// frame instant the timer methods use.
1357 ///
1358 /// # Example
1359 /// ```no_run
1360 /// use std::time::Duration;
1361 ///
1362 /// slt::run(|ui: &mut slt::Context| {
1363 /// ui.schedule("upload", Duration::from_secs(30));
1364 /// if let Some(elapsed) = ui.elapsed("upload") {
1365 /// ui.text(format!("Uploading for {}s", elapsed.as_secs()));
1366 /// }
1367 /// })?;
1368 /// # Ok::<_, std::io::Error>(())
1369 /// ```
1370 pub fn elapsed(&self, id: &str) -> Option<std::time::Duration> {
1371 let started = self
1372 .scheduler
1373 .named
1374 .get(id)
1375 .or_else(|| self.scheduler.keyed.get(id))
1376 .map(|slot| slot.started)?;
1377 Some(self.frame_instant.saturating_duration_since(started))
1378 }
1379
1380 /// Remove dynamic keyed state created by
1381 /// [`use_state_keyed`](Self::use_state_keyed).
1382 ///
1383 /// Returns `true` when a slot existed. Any old [`State`] handle for the
1384 /// removed id becomes invalid and will panic if used before the state is
1385 /// recreated by `use_state_keyed`.
1386 pub fn remove_state_keyed(&mut self, id: &str) -> bool {
1387 self.keyed_states.remove(id).is_some()
1388 }
1389
1390 /// Retain only dynamic keyed-state entries accepted by `keep`.
1391 ///
1392 /// Returns the number of removed entries. This is intended for long-lived
1393 /// dynamic lists where ids come from data and removed items should release
1394 /// their per-row state.
1395 pub fn retain_state_keyed(&mut self, mut keep: impl FnMut(&str) -> bool) -> usize {
1396 let before = self.keyed_states.len();
1397 self.keyed_states.retain(|key, _| keep(key));
1398 before - self.keyed_states.len()
1399 }
1400
1401 /// Number of live dynamic keyed-state entries.
1402 ///
1403 /// Diagnostic helper for spotting churn when using runtime ids.
1404 pub fn keyed_state_count(&self) -> usize {
1405 self.keyed_states.len()
1406 }
1407
1408 /// Push a value onto the context stack for the duration of `body`.
1409 ///
1410 /// Inside `body`, child widgets can call
1411 /// [`use_context::<T>()`](Self::use_context) or
1412 /// [`try_use_context::<T>()`](Self::try_use_context) to look up the
1413 /// nearest provided value of type `T`. Provides cascade in LIFO order:
1414 /// nested calls with the same `T` shadow outer ones.
1415 ///
1416 /// The value is automatically popped when `body` returns — including on
1417 /// panic, so the context stack is always restored.
1418 ///
1419 /// # Example
1420 ///
1421 /// ```ignore
1422 /// struct Theme { accent: slt::Color }
1423 /// ui.provide(Theme { accent: slt::Color::Red }, |ui| {
1424 /// // Any widget here can `let theme = ui.use_context::<Theme>();`
1425 /// render_button(ui);
1426 /// });
1427 /// ```
1428 pub fn provide<T: 'static, R>(&mut self, value: T, body: impl FnOnce(&mut Context) -> R) -> R {
1429 self.context_stack
1430 .push(Box::new(value) as Box<dyn std::any::Any>);
1431
1432 // catch_unwind ensures the entry is popped even if `body` panics, so
1433 // the context stack is never left with leaked frames. We re-panic
1434 // afterwards so the panic propagates normally to outer scopes.
1435 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| body(self)));
1436
1437 // Pop in both success and panic paths.
1438 self.context_stack.pop();
1439
1440 match result {
1441 Ok(value) => value,
1442 Err(panic) => std::panic::resume_unwind(panic),
1443 }
1444 }
1445
1446 /// Spawn a fire-and-forget async task from inside the frame closure.
1447 ///
1448 /// Returns a [`TaskHandle<T>`](crate::TaskHandle) you store and pass to
1449 /// [`poll`](Self::poll) on later frames to retrieve the result. This closes
1450 /// the ergonomics gap of the channel pattern (`run_async` + an external
1451 /// `Sender`) for the common case: "click a button, kick off one async call,
1452 /// show its result next frame" — without wiring a channel yourself.
1453 ///
1454 /// **Dropping the returned handle cancels the in-flight task.** Keep it
1455 /// alive (e.g. in `use_state`) for as long as you care about the result.
1456 /// Each handle carries a unique id, so two `TaskHandle<String>` live at the
1457 /// same time never cross their results.
1458 ///
1459 /// Requires the `async` feature and an active Tokio runtime — call it
1460 /// inside [`run_async`](crate::run_async) /
1461 /// [`run_async_with`](crate::run_async_with), which inject the runtime
1462 /// handle.
1463 ///
1464 /// # Panics
1465 ///
1466 /// Panics if no Tokio runtime was injected (e.g. when called from the sync
1467 /// [`run`](crate::run) loop or `TestBackend` without a runtime).
1468 ///
1469 /// # Example
1470 ///
1471 /// ```no_run
1472 /// # #[cfg(feature = "async")]
1473 /// # async fn run() -> std::io::Result<()> {
1474 /// use slt::{Context, RunConfig, TaskHandle};
1475 ///
1476 /// async fn fetch() -> String {
1477 /// // e.g. an HTTP request
1478 /// "result".to_string()
1479 /// }
1480 ///
1481 /// slt::run_async_with(RunConfig::default(), |ui: &mut Context, _: &mut Vec<()>| {
1482 /// // One handle, stored across frames via `use_state`.
1483 /// let handle = ui.use_state(|| None::<TaskHandle<String>>);
1484 ///
1485 /// if ui.button("Fetch").clicked && handle.get(ui).is_none() {
1486 /// *handle.get_mut(ui) = Some(ui.spawn(async { fetch().await }));
1487 /// }
1488 ///
1489 /// // Take the handle out of state to poll it: `ui.poll` needs `&mut ui`,
1490 /// // which cannot coexist with a `&TaskHandle` borrowed from `ui`'s own
1491 /// // state. Put it back if the task is still pending.
1492 /// if let Some(h) = handle.get_mut(ui).take() {
1493 /// match ui.poll(&h) {
1494 /// Some(result) => {
1495 /// ui.text(format!("Got: {result}"));
1496 /// }
1497 /// None => {
1498 /// *handle.get_mut(ui) = Some(h);
1499 /// ui.text("Loading...");
1500 /// }
1501 /// }
1502 /// }
1503 /// })?;
1504 /// # Ok(())
1505 /// # }
1506 /// ```
1507 #[cfg(feature = "async")]
1508 #[cfg_attr(docsrs, doc(cfg(feature = "async")))]
1509 pub fn spawn<T: Send + 'static>(
1510 &mut self,
1511 fut: impl std::future::Future<Output = T> + Send + 'static,
1512 ) -> TaskHandle<T> {
1513 self.async_tasks.spawn(fut)
1514 }
1515
1516 /// Poll a [`TaskHandle`](crate::TaskHandle) for its result.
1517 ///
1518 /// Returns `Some(result)` exactly once — on the first frame after the task
1519 /// completes — then `None` on every subsequent call. Returns `None` while
1520 /// the task is still in flight.
1521 ///
1522 /// Pairs with [`spawn`](Self::spawn). Requires the `async` feature.
1523 ///
1524 /// # Example
1525 ///
1526 /// ```no_run
1527 /// # #[cfg(feature = "async")]
1528 /// # fn ex(ui: &mut slt::Context, handle: &slt::TaskHandle<u32>) {
1529 /// if let Some(value) = ui.poll(handle) {
1530 /// ui.text(format!("done: {value}"));
1531 /// }
1532 /// # }
1533 /// ```
1534 #[cfg(feature = "async")]
1535 #[cfg_attr(docsrs, doc(cfg(feature = "async")))]
1536 pub fn poll<T: 'static>(&mut self, handle: &TaskHandle<T>) -> Option<T> {
1537 self.async_tasks.poll::<T>(handle.id())
1538 }
1539
1540 /// Look up the nearest provided value of type `T` on the context stack.
1541 ///
1542 /// Searches from the top of the stack (most-recent
1543 /// [`provide`](Self::provide)) downward. Returns the first match.
1544 ///
1545 /// # Panics
1546 ///
1547 /// Panics if no value of type `T` is currently provided. Use
1548 /// [`try_use_context`](Self::try_use_context) for a non-panicking variant.
1549 pub fn use_context<T: 'static>(&self) -> &T {
1550 self.try_use_context::<T>().unwrap_or_else(|| {
1551 panic!(
1552 "no context of type {} was provided; use ui.provide(value, |ui| ...) in a parent scope",
1553 std::any::type_name::<T>()
1554 )
1555 })
1556 }
1557
1558 /// Like [`use_context`](Self::use_context), but returns `None` instead of
1559 /// panicking when no value of type `T` is on the stack.
1560 pub fn try_use_context<T: 'static>(&self) -> Option<&T> {
1561 self.context_stack
1562 .iter()
1563 .rev()
1564 .find_map(|entry| entry.downcast_ref::<T>())
1565 }
1566
1567 /// Memoize a computed value. Recomputes only when `deps` changes.
1568 ///
1569 /// Returns a [`Memo<T>`] *index handle*, mirroring [`use_state`]'s
1570 /// [`State<T>`]. The handle holds **no** borrow of `ui`, so it composes with
1571 /// later `ui.*` calls — read the value on demand with `.get(ui)` /
1572 /// `.copied(ui)`.
1573 ///
1574 /// Before v0.21.0 this returned `&T`, a live borrow of `&mut Context` that
1575 /// could not be held across subsequent `ui.*` mutations. That form is now
1576 /// [`use_memo_ref`](Self::use_memo_ref) (deprecated). Migrate
1577 /// `let x = *ui.use_memo(&d, f);` to `let x = ui.use_memo(&d, f).copied(ui);`.
1578 ///
1579 /// [`use_state`]: Self::use_state
1580 ///
1581 /// # Panics
1582 ///
1583 /// Panics if the hook slot at this call position was previously used for a
1584 /// different hook (a rules-of-hooks / call-order violation), since the
1585 /// type-erased slot then fails to downcast to `MemoSlot<T>`:
1586 ///
1587 /// ```text
1588 /// Hook type mismatch at index {idx}: expected {type}. Hooks must be called in the same order every frame.
1589 /// ```
1590 ///
1591 /// Keep hook calls in the same order every frame — do not call this inside
1592 /// an `if`/`else` whose branch changes between frames.
1593 ///
1594 /// # Example
1595 /// ```no_run
1596 /// # slt::run(|ui: &mut slt::Context| {
1597 /// let count = ui.use_state(|| 0i32);
1598 /// let count_val = *count.get(ui);
1599 /// let doubled = ui.use_memo(&count_val, |c| c * 2);
1600 /// // The handle survives an intervening `ui.*` call (this is the whole point).
1601 /// ui.text("doubled:");
1602 /// ui.text(format!("{}", doubled.copied(ui)));
1603 /// # });
1604 /// ```
1605 pub fn use_memo<T: 'static, D: PartialEq + Clone + 'static>(
1606 &mut self,
1607 deps: &D,
1608 compute: impl FnOnce(&D) -> T,
1609 ) -> Memo<T> {
1610 let idx = self.rollback.hook_cursor;
1611 self.rollback.hook_cursor += 1;
1612
1613 // First call at this slot: allocate fresh state. Deps are stored
1614 // type-erased so the read path (`Memo::get`) can downcast `MemoSlot<T>`
1615 // without restating `D`.
1616 if idx >= self.hook_states.len() {
1617 self.hook_states.push(Box::new(MemoSlot {
1618 deps: Box::new(deps.clone()),
1619 value: compute(deps),
1620 }));
1621 return Memo::from_idx(idx);
1622 }
1623
1624 // Slot already exists: it must be the same `MemoSlot<T>` shape we used
1625 // last frame, or the caller broke the rules-of-hooks contract.
1626 match self.hook_states[idx].downcast_mut::<MemoSlot<T>>() {
1627 Some(slot) => {
1628 // Compare against the previous (type-erased) deps. A failed
1629 // downcast of the stored deps to `&D` is treated as stale so the
1630 // value is recomputed rather than silently kept.
1631 let stale = slot
1632 .deps
1633 .downcast_ref::<D>()
1634 .map(|prev| *prev != *deps)
1635 .unwrap_or(true);
1636 if stale {
1637 slot.deps = Box::new(deps.clone());
1638 slot.value = compute(deps);
1639 }
1640 }
1641 None => panic!(
1642 "Hook type mismatch at index {}: expected {}. Hooks must be called in the same order every frame.",
1643 idx,
1644 std::any::type_name::<MemoSlot<T>>()
1645 ),
1646 }
1647 Memo::from_idx(idx)
1648 }
1649
1650 /// Deprecated `&T`-returning form of [`use_memo`](Self::use_memo).
1651 ///
1652 /// **Deprecated since 0.21.0**: [`use_memo`](Self::use_memo) now returns a
1653 /// [`Memo<T>`] handle that does not borrow `ui`, so it composes with later
1654 /// `ui.*` calls. This alias preserves the original behaviour (returning a
1655 /// `&T` borrow of `ui`) for callers that cannot migrate immediately; the
1656 /// borrow keeps `ui` immutably borrowed until the reference is dropped.
1657 ///
1658 /// Migrate `let x = *ui.use_memo_ref(&d, f);` to
1659 /// `let x = ui.use_memo(&d, f).copied(ui);` (or `.get(ui)` for a reference).
1660 ///
1661 /// # Panics
1662 ///
1663 /// Panics if the hook slot at this call position was previously used for a
1664 /// different hook (a rules-of-hooks / call-order violation), since the
1665 /// type-erased slot then fails to downcast to `(D, T)`:
1666 ///
1667 /// ```text
1668 /// Hook type mismatch at index {idx}: expected {type}. Hooks must be called in the same order every frame.
1669 /// ```
1670 ///
1671 /// # Example
1672 /// ```no_run
1673 /// # slt::run(|ui: &mut slt::Context| {
1674 /// # #[allow(deprecated)]
1675 /// let doubled = *ui.use_memo_ref(&21i32, |c| c * 2);
1676 /// ui.text(format!("{doubled}"));
1677 /// # });
1678 /// ```
1679 #[deprecated(
1680 since = "0.21.0",
1681 note = "use_memo now returns a Memo<T> handle; call `.get(ui)` / `.copied(ui)`"
1682 )]
1683 pub fn use_memo_ref<T: 'static, D: PartialEq + Clone + 'static>(
1684 &mut self,
1685 deps: &D,
1686 compute: impl FnOnce(&D) -> T,
1687 ) -> &T {
1688 let idx = self.rollback.hook_cursor;
1689 self.rollback.hook_cursor += 1;
1690
1691 // First call at this slot: allocate fresh state.
1692 if idx >= self.hook_states.len() {
1693 let value = compute(deps);
1694 self.hook_states.push(Box::new((deps.clone(), value)));
1695 return self.hook_states[idx]
1696 .downcast_ref::<(D, T)>()
1697 .map(|(_, v)| v)
1698 .expect("freshly inserted slot must downcast to its own type");
1699 }
1700
1701 // Slot already exists: it must be the same `(D, T)` shape we used last
1702 // frame, or the caller broke the rules-of-hooks contract.
1703 //
1704 // Single downcast on the cache-hit path (closes #133): use
1705 // `downcast_mut` to update deps/value in place when they change, and
1706 // return `&stored.1` directly — eliminating the redundant second
1707 // `downcast_ref` that ran on every call regardless of cache state.
1708 match self.hook_states[idx].downcast_mut::<(D, T)>() {
1709 Some(stored) => {
1710 if stored.0 != *deps {
1711 stored.0 = deps.clone();
1712 stored.1 = compute(deps);
1713 }
1714 &stored.1
1715 }
1716 None => panic!(
1717 "Hook type mismatch at index {}: expected {}. Hooks must be called in the same order every frame.",
1718 idx,
1719 std::any::type_name::<(D, T)>()
1720 ),
1721 }
1722 }
1723
1724 /// Returns `light` color if current theme is light mode, `dark` color if dark mode.
1725 pub fn light_dark(&self, light: Color, dark: Color) -> Color {
1726 if self.theme.is_dark { dark } else { light }
1727 }
1728
1729 /// Show a toast notification without managing ToastState.
1730 ///
1731 /// # Examples
1732 /// ```
1733 /// # use slt::*;
1734 /// # TestBackend::new(80, 24).render(|ui| {
1735 /// ui.notify("File saved!", ToastLevel::Success);
1736 /// # });
1737 /// ```
1738 pub fn notify(&mut self, message: &str, level: ToastLevel) {
1739 let tick = self.tick;
1740 self.rollback
1741 .notification_queue
1742 .push((message.to_string(), level, tick));
1743 }
1744
1745 pub(crate) fn render_notifications(&mut self) {
1746 let tick = self.tick;
1747 self.rollback
1748 .notification_queue
1749 .retain(|(_, _, created)| tick.saturating_sub(*created) < 180);
1750 if self.rollback.notification_queue.is_empty() {
1751 return;
1752 }
1753
1754 // The `overlay` closure captures `self` mutably, so we cannot keep an
1755 // immutable borrow of `self.rollback.notification_queue` alive across
1756 // the call. Move the queue out for the render, then move it back —
1757 // no `String::clone` per notification, no intermediate `Vec` alloc.
1758 // Closes the non-empty path of #138.
1759 let queue = std::mem::take(&mut self.rollback.notification_queue);
1760 let theme = self.theme;
1761
1762 let _ = self.overlay(|ui| {
1763 let _ = ui.row(|ui| {
1764 ui.spacer();
1765 let _ = ui.col(|ui| {
1766 for (message, level, _) in queue.iter().rev() {
1767 let color = match level {
1768 ToastLevel::Info => theme.primary,
1769 ToastLevel::Success => theme.success,
1770 ToastLevel::Warning => theme.warning,
1771 ToastLevel::Error => theme.error,
1772 };
1773 let mut line = String::with_capacity(2 + message.len());
1774 line.push_str("● ");
1775 line.push_str(message);
1776 ui.styled(line, Style::new().fg(color));
1777 }
1778 });
1779 });
1780 });
1781
1782 // Restore the queue so subsequent frames can re-render until each
1783 // entry's TTL expires above.
1784 self.rollback.notification_queue = queue;
1785 }
1786
1787 // ----------------------------------------------------------------
1788 // v0.20.0 hooks: keyed state, effects, named focus, key gating
1789 // ----------------------------------------------------------------
1790
1791 /// Component-local persistent state keyed by a runtime string.
1792 ///
1793 /// Unlike [`use_state_named`](Self::use_state_named), `id` can be a
1794 /// runtime value such as `format!("row-{i}")`. The key is converted to
1795 /// `String` once per call. The hot path (key already present) performs
1796 /// **zero string allocations beyond the [`Into<String>`] conversion at
1797 /// the call site** — first looking up by `&str`, only allocating a
1798 /// fresh map key on first insert. Together: at most **one allocation
1799 /// per call, regardless of cache state**.
1800 ///
1801 /// # When to use
1802 /// - Per-item state in a dynamic list where positional [`use_state`]
1803 /// would break if items are reordered or filtered.
1804 /// - Reusable component functions called with a runtime discriminator.
1805 ///
1806 /// # Namespace
1807 /// Keys live in a single global namespace per `Context`. Prefix them
1808 /// to avoid collisions: `format!("my_component::item-{i}")`.
1809 ///
1810 /// # Stale entries
1811 /// Removed items leak their state until the `Context` is dropped (or
1812 /// the program exits). For long-running sessions with churn, manage
1813 /// state externally via a single `Vec<T>` in [`use_state`].
1814 ///
1815 /// # Example
1816 ///
1817 /// ```ignore
1818 /// for (i, item) in items.iter().enumerate() {
1819 /// let row_state = ui.use_state_keyed(format!("row-{i}"), || ItemState::default());
1820 /// // ...
1821 /// }
1822 /// ```
1823 ///
1824 /// [`use_state`]: Self::use_state
1825 pub fn use_state_keyed<T: 'static>(
1826 &mut self,
1827 id: impl Into<String>,
1828 init: impl FnOnce() -> T,
1829 ) -> State<T> {
1830 let key: String = id.into();
1831 // Lookup by `&str` first to avoid cloning on the hot
1832 // (already-populated) path. Only on first insert do we clone the
1833 // key into the map; otherwise the original `key` String is the
1834 // sole allocation and is moved into `State::from_keyed`.
1835 if !self.keyed_states.contains_key(key.as_str()) {
1836 self.keyed_states.insert(key.clone(), Box::new(init()));
1837 }
1838 State::from_keyed(key)
1839 }
1840
1841 /// Like [`use_state_keyed`](Self::use_state_keyed), but uses
1842 /// [`Default::default()`] to initialize the value on first call.
1843 ///
1844 /// # Example
1845 ///
1846 /// ```ignore
1847 /// let counter = ui.use_state_keyed_default::<i32>(format!("c-{i}"));
1848 /// ```
1849 pub fn use_state_keyed_default<T: Default + 'static>(
1850 &mut self,
1851 id: impl Into<String>,
1852 ) -> State<T> {
1853 self.use_state_keyed(id, T::default)
1854 }
1855
1856 /// Run a side-effecting closure when `deps` changes.
1857 ///
1858 /// On the **first frame** the hook slot is encountered, `f` is called
1859 /// unconditionally. On **subsequent frames**, `f` is only called when
1860 /// `*deps != stored_deps`. The hook is **positional** (same ordering
1861 /// rules as [`use_state`](Self::use_state)).
1862 ///
1863 /// # Fire-and-forget semantics
1864 ///
1865 /// There is no cleanup callback. If setup resources need teardown,
1866 /// store a handle in [`use_state`](Self::use_state) and drop it on
1867 /// a later frame.
1868 ///
1869 /// # Caveat: `error_boundary` re-fire
1870 ///
1871 /// Effects placed inside an [`error_boundary`](Self::error_boundary)
1872 /// scope can re-fire when the boundary catches a panic and rolls back
1873 /// the hook slots. For non-idempotent side effects (network requests,
1874 /// payments) put the effect outside the boundary or guard with an
1875 /// idempotency key.
1876 ///
1877 /// # Panics
1878 ///
1879 /// Panics if the hook slot at this call position was previously used for a
1880 /// different hook (a rules-of-hooks / call-order violation), since the
1881 /// type-erased slot then fails to downcast to the deps type `D`:
1882 ///
1883 /// ```text
1884 /// Hook type mismatch at index {idx}: expected {type}. Hooks must be called in the same order every frame.
1885 /// ```
1886 ///
1887 /// # Common patterns
1888 ///
1889 /// ```ignore
1890 /// // Run once on first frame:
1891 /// ui.use_effect(|_| initialize_logger(), &());
1892 ///
1893 /// // Run when `selected_tab` changes:
1894 /// ui.use_effect(|tab| load_tab_data(*tab), &selected_tab);
1895 /// ```
1896 pub fn use_effect<D: PartialEq + Clone + 'static>(&mut self, f: impl FnOnce(&D), deps: &D) {
1897 let idx = self.rollback.hook_cursor;
1898 self.rollback.hook_cursor += 1;
1899
1900 if idx >= self.hook_states.len() {
1901 // First encounter: run the effect, then store the deps so we
1902 // can detect future changes.
1903 f(deps);
1904 self.hook_states.push(Box::new(deps.clone()));
1905 return;
1906 }
1907
1908 match self.hook_states[idx].downcast_mut::<D>() {
1909 Some(stored) => {
1910 if *stored != *deps {
1911 f(deps);
1912 *stored = deps.clone();
1913 }
1914 }
1915 None => panic!(
1916 "Hook type mismatch at index {idx}: expected {}. \
1917 Hooks must be called in the same order every frame.",
1918 std::any::type_name::<D>()
1919 ),
1920 }
1921 }
1922
1923 /// Register a focusable slot bound to a stable string name.
1924 ///
1925 /// Returns `true` if the registered slot currently has focus, exactly
1926 /// like [`register_focusable`](Self::register_focusable) — but also
1927 /// records the `name → slot` mapping so other code can later call
1928 /// [`focus_by_name`](Self::focus_by_name) and
1929 /// [`focused_name`](Self::focused_name).
1930 ///
1931 /// # How the slot is shared with the widget that follows
1932 ///
1933 /// Every SLT widget that takes focus (`button`, `text_input`,
1934 /// `tabs`, …) internally calls `register_focusable()` to claim its
1935 /// own slot. To keep the name pointed at the **widget the user
1936 /// sees**, this call:
1937 ///
1938 /// 1. allocates a slot eagerly (so the name binding works even when
1939 /// no widget follows — useful for tests and for custom focusable
1940 /// regions),
1941 /// 2. records the `name → slot` mapping into the frame's
1942 /// `focus_name_map` (first-write-wins on duplicate names within
1943 /// a frame),
1944 /// 3. **reserves** the slot id so the next `register_focusable()`
1945 /// on the same frame *reuses* it instead of allocating a fresh
1946 /// slot — that's how `text_input(&mut state)` placed right after
1947 /// inherits the name.
1948 ///
1949 /// Names are re-registered each frame; the previous frame's map is
1950 /// kept under `focus_name_map_prev` so [`focus_by_name`](Context::focus_by_name) can resolve
1951 /// a name that has already been registered.
1952 ///
1953 /// # Two valid usage shapes
1954 ///
1955 /// **Shape A — name a widget that follows immediately** (the common
1956 /// pattern; the widget reuses the reserved slot):
1957 ///
1958 /// ```ignore
1959 /// let _ = ui.register_focusable_named("search");
1960 /// let _ = ui.text_input(&mut search_state);
1961 /// // later: ui.focus_by_name("search") jumps to the text_input
1962 /// ```
1963 ///
1964 /// **Shape B — register a named focusable region with no inner
1965 /// widget** (e.g. a custom render area that handles its own keys
1966 /// when focused):
1967 ///
1968 /// ```ignore
1969 /// let focused = ui.register_focusable_named("canvas");
1970 /// if focused { /* react to keys via key_presses_when */ }
1971 /// ```
1972 pub fn register_focusable_named(&mut self, name: &str) -> bool {
1973 // Modal/overlay suppression: when a modal is active and we're not
1974 // inside it, focusables outside the modal must be invisible to
1975 // tab/click cycling. Drop the registration entirely (no slot
1976 // allocation, no name binding, no reservation leak).
1977 if (self.rollback.modal_active || self.prev_modal_active)
1978 && self.rollback.overlay_depth == 0
1979 {
1980 self.rollback.pending_focusable_id = None;
1981 return false;
1982 }
1983 // Eagerly allocate the slot — symmetric with `register_focusable`,
1984 // so the slot exists even when no widget follows.
1985 let id = self.rollback.focus_count;
1986 self.rollback.focus_count += 1;
1987 self.rollback.last_focusable_id = Some(id);
1988 self.commands.push(Command::FocusMarker(id));
1989 // First-write-wins on duplicate names within a single frame —
1990 // a second `register_focusable_named("dup")` keeps the first
1991 // slot bound to the name and orphans its own slot's name binding.
1992 self.focus_name_map.entry(name.to_string()).or_insert(id);
1993 // Reserve `id` for the very next `register_focusable()` call to
1994 // reuse, so widgets like `text_input` placed immediately after
1995 // share the named slot rather than allocating a fresh one.
1996 // Last-write-wins on the reservation: stacking two
1997 // `register_focusable_named` calls without an intervening widget
1998 // leaves the second slot reserved (the first slot stays bound to
1999 // its name in `focus_name_map`, just without a widget attached).
2000 self.rollback.pending_focusable_id = Some(id);
2001 // Same focus-index prediction as `register_focusable`.
2002 if self.prev_modal_active
2003 && self.prev_modal_focus_count > 0
2004 && self.rollback.modal_active
2005 && self.rollback.overlay_depth > 0
2006 {
2007 let mut modal_local_id = id.saturating_sub(self.rollback.modal_focus_start);
2008 modal_local_id %= self.prev_modal_focus_count;
2009 let mut modal_focus_idx = self.focus_index.saturating_sub(self.prev_modal_focus_start);
2010 modal_focus_idx %= self.prev_modal_focus_count;
2011 return modal_local_id == modal_focus_idx;
2012 }
2013 if self.prev_focus_count == 0 {
2014 return true;
2015 }
2016 self.focus_index % self.prev_focus_count == id
2017 }
2018
2019 /// Request focus on the named widget.
2020 ///
2021 /// If the named widget was registered last frame the focus change
2022 /// takes effect at the **start of the next frame** (one-frame delay
2023 /// is the deferred-command pattern used throughout SLT). If the name
2024 /// has never been registered, the request stays pending: the next
2025 /// frame to register that name receives focus.
2026 ///
2027 /// Returns `true` if the call **will** resolve — i.e. the name was
2028 /// either registered earlier in this frame (via
2029 /// [`register_focusable_named`](Self::register_focusable_named)) or in
2030 /// the previous frame. Returns `false` only when the name has not been
2031 /// seen by either frame, in which case the request stays pending until
2032 /// some future frame registers the name.
2033 ///
2034 /// # Example
2035 ///
2036 /// ```ignore
2037 /// if ui.button("Find").clicked {
2038 /// ui.focus_by_name("search");
2039 /// }
2040 /// ```
2041 pub fn focus_by_name(&mut self, name: &str) -> bool {
2042 // Resolve against either the previous frame's settled map or the
2043 // in-progress map being built right now. The latter handles the
2044 // common "register, then focus_by_name in the same frame" pattern
2045 // that callers naturally expect to return `true`.
2046 //
2047 // The actual focus change still lands at the start of the next
2048 // frame via `focus_name_map_prev` lookup in `Context::new`. The
2049 // return value is purely about resolvability: "true" means the name
2050 // is known and the focus shift will land next frame; "false" means
2051 // the request is pending a future registration.
2052 let resolved =
2053 self.focus_name_map_prev.contains_key(name) || self.focus_name_map.contains_key(name);
2054 // Always store the request — even if it resolved this frame, the
2055 // next-frame plumbing (`Context::new`) is what actually applies
2056 // the index. We use take/replace so the caller cannot stack two
2057 // pending names; the most recent wins.
2058 self.pending_focus_name = Some(name.to_string());
2059 resolved
2060 }
2061
2062 /// Return the name of the currently focused widget, if it was
2063 /// registered with
2064 /// [`register_focusable_named`](Self::register_focusable_named) this
2065 /// frame.
2066 ///
2067 /// Returns `None` if the focused widget used the unnamed
2068 /// [`register_focusable`](Self::register_focusable) API or if no widget
2069 /// has focus.
2070 pub fn focused_name(&self) -> Option<&str> {
2071 // Search this frame's map for the entry whose index equals
2072 // `focus_index`. The map is small (one entry per named focusable),
2073 // so a linear scan is fine — typical apps register <50 names.
2074 self.focus_name_map
2075 .iter()
2076 .find_map(|(name, &idx)| (idx == self.focus_index).then_some(name.as_str()))
2077 }
2078
2079 /// Iterate unconsumed key-press events, gated on `active`.
2080 ///
2081 /// When `active` is `false`, returns an empty iterator. When `active`
2082 /// is `true`, behaves identically to the internal
2083 /// `available_key_presses`. The returned indices are valid for
2084 /// [`consume_event`](Self::consume_event).
2085 ///
2086 /// This is the **preferred pattern** for focus-gated keyboard handling
2087 /// in custom widgets. Because the iterator borrows `self.events`
2088 /// immutably, collect the indices first and consume them after the
2089 /// loop:
2090 ///
2091 /// ```ignore
2092 /// let focused = ui.register_focusable();
2093 /// let mut hits: Vec<usize> = Vec::new();
2094 /// for (i, key) in ui.key_presses_when(focused) {
2095 /// if key.code == slt::KeyCode::Enter {
2096 /// hits.push(i);
2097 /// // ... handle Enter ...
2098 /// }
2099 /// }
2100 /// for i in hits { ui.consume_event(i); }
2101 /// ```
2102 pub fn key_presses_when(
2103 &self,
2104 active: bool,
2105 ) -> impl Iterator<Item = (usize, &crate::event::KeyEvent)> + '_ {
2106 // The `!active` short-circuit at the head of the predicate yields
2107 // an empty iterator at zero allocation cost when the widget isn't
2108 // focused. Indices are still drawn from `self.events` so callers
2109 // can pass them straight to `consume_event`.
2110 self.events
2111 .iter()
2112 .enumerate()
2113 .filter_map(move |(i, event)| {
2114 if !active {
2115 return None;
2116 }
2117 if self.consumed.get(i).copied().unwrap_or(true) {
2118 return None;
2119 }
2120 match event {
2121 Event::Key(key) if key.kind == KeyEventKind::Press => Some((i, key)),
2122 _ => None,
2123 }
2124 })
2125 }
2126
2127 /// Mark the event at `index` as consumed.
2128 ///
2129 /// Public counterpart to the crate-internal `consume_indices`. Use
2130 /// this in custom widgets after handling an event yielded by
2131 /// [`key_presses_when`](Self::key_presses_when) so subsequent widgets
2132 /// don't react to the same key. Out-of-range indices are silently
2133 /// ignored (matching the iterator-pair semantics).
2134 pub fn consume_event(&mut self, index: usize) {
2135 if let Some(slot) = self.consumed.get_mut(index) {
2136 *slot = true;
2137 }
2138 }
2139
2140 // ── Issue #233: in-frame static-log append ───────────────────────────
2141 //
2142 // The runtime holds the buffer inside `named_states` under a reserved
2143 // sentinel key. `Context::new` (owned by another agent) does not need to
2144 // initialise this field — `or_insert_with` handles first-call creation,
2145 // and `lib::run_frame_kernel` drains the buffer back into `FrameState`
2146 // for the run-loop to consume.
2147
2148 /// Append a line that will be flushed to terminal scrollback **before**
2149 /// the dynamic frame content (issue #233).
2150 ///
2151 /// Lines accumulated this frame are written via the active runtime — for
2152 /// [`crate::run_static`] / [`crate::run_static_with`], they are printed
2153 /// above the inline dynamic area as committed scrollback. For full-screen
2154 /// runtimes ([`crate::run`], [`crate::run_async`]) and inline mode
2155 /// ([`crate::run_inline`]), the buffer is silently dropped after a debug
2156 /// warning is emitted on the first call per frame, since those modes have
2157 /// no scrollback area to write to.
2158 ///
2159 /// The headless [`crate::TestBackend`] accumulates the lines into the
2160 /// frame state where they can be drained by tests via
2161 /// [`Context::take_static_log`] (or by inspecting the buffer when
2162 /// constructing a custom backend).
2163 ///
2164 /// # Order
2165 ///
2166 /// `static_log` may be called any number of times per frame. Lines are
2167 /// flushed in call order, all before the dynamic frame for the same
2168 /// tick.
2169 ///
2170 /// # Example
2171 ///
2172 /// ```
2173 /// # use slt::*;
2174 /// # TestBackend::new(40, 4).render(|ui| {
2175 /// ui.static_log("event 1");
2176 /// ui.static_log(format!("event {}", 2));
2177 /// ui.text("dynamic content");
2178 /// # });
2179 /// ```
2180 pub fn static_log(&mut self, line: impl Into<String>) {
2181 let entry = self
2182 .named_states
2183 .entry(STATIC_LOG_KEY)
2184 .or_insert_with(|| Box::new(Vec::<String>::new()) as Box<dyn std::any::Any>);
2185 if let Some(buf) = entry.downcast_mut::<Vec<String>>() {
2186 buf.push(line.into());
2187 }
2188 }
2189
2190 /// Drain and return the queued static-log lines for the current frame
2191 /// (issue #233). Used by tests / external backends to inspect what
2192 /// `ui.static_log(...)` emitted during a [`crate::TestBackend::render`]
2193 /// call.
2194 pub fn take_static_log(&mut self) -> Vec<String> {
2195 if let Some(boxed) = self.named_states.get_mut(STATIC_LOG_KEY)
2196 && let Some(buf) = boxed.downcast_mut::<Vec<String>>()
2197 {
2198 return std::mem::take(buf);
2199 }
2200 Vec::new()
2201 }
2202
2203 // ── Issue #236: widget keymap publishing ─────────────────────────────
2204
2205 /// Publish a widget's keymap so the framework can show it in the help
2206 /// overlay (issue #236).
2207 ///
2208 /// Each call registers `(name, bindings)` for the current frame. Widgets
2209 /// implementing [`crate::keymap::WidgetKeyHelp`] typically forward their
2210 /// `key_help()` slice here:
2211 ///
2212 /// ```
2213 /// # use slt::*;
2214 /// # use slt::keymap::WidgetKeyHelp;
2215 /// struct Counter;
2216 /// impl WidgetKeyHelp for Counter {
2217 /// fn key_help(&self) -> &'static [(&'static str, &'static str)] {
2218 /// const HELP: &[(&str, &str)] = &[("↑", "increment"), ("↓", "decrement")];
2219 /// HELP
2220 /// }
2221 /// }
2222 /// # TestBackend::new(40, 4).render(|ui| {
2223 /// let counter = Counter;
2224 /// ui.publish_keymap("counter", counter.key_help());
2225 /// # });
2226 /// ```
2227 ///
2228 /// The registry is reset at the start of every frame (the first call on a
2229 /// new tick clears stale entries). Both calls in the same frame
2230 /// accumulate; calls across frames do not leak.
2231 pub fn publish_keymap(
2232 &mut self,
2233 name: &'static str,
2234 bindings: &'static [(&'static str, &'static str)],
2235 ) {
2236 // The registry is cleared at frame start by `run_frame_kernel`
2237 // (issue #236) — see `clear_keymap_registry` in `lib.rs`. We just
2238 // need to insert/append here.
2239 let entry = self
2240 .named_states
2241 .entry(KEYMAP_REGISTRY_KEY)
2242 .or_insert_with(|| {
2243 Box::new(Vec::<crate::keymap::PublishedKeymap>::new()) as Box<dyn std::any::Any>
2244 });
2245 if let Some(vec) = entry.downcast_mut::<Vec<crate::keymap::PublishedKeymap>>() {
2246 vec.push(crate::keymap::PublishedKeymap::new(name, bindings));
2247 }
2248 }
2249
2250 /// Return all keymaps published this frame (issue #236).
2251 ///
2252 /// Empty if no widget called [`Context::publish_keymap`] yet on the
2253 /// current frame. The registry is reset at the start of every frame.
2254 pub fn published_keymaps(&self) -> &[crate::keymap::PublishedKeymap] {
2255 if let Some(boxed) = self.named_states.get(KEYMAP_REGISTRY_KEY)
2256 && let Some(vec) = boxed.downcast_ref::<Vec<crate::keymap::PublishedKeymap>>()
2257 {
2258 return vec;
2259 }
2260 &[]
2261 }
2262
2263 /// Render an automatic keymap-help overlay listing every widget keymap
2264 /// published this frame (issue #236).
2265 ///
2266 /// Pass `open = true` to render the overlay (typically gated on a
2267 /// `?` / `F1` keypress). When `open` is `false`, this method is a
2268 /// no-op. The overlay groups bindings by widget name and dismisses
2269 /// when the next frame is rendered with `open = false`.
2270 ///
2271 /// # Example
2272 ///
2273 /// ```
2274 /// # use slt::*;
2275 /// # TestBackend::new(40, 12).render(|ui| {
2276 /// const RICHLOG: &[(&str, &str)] = &[("↑/k", "scroll up"), ("↓/j", "scroll down")];
2277 /// ui.publish_keymap("rich_log", RICHLOG);
2278 /// // Show the help overlay when '?' is pressed
2279 /// let show = ui.key('?');
2280 /// ui.keymap_help_overlay(show);
2281 /// # });
2282 /// ```
2283 pub fn keymap_help_overlay(&mut self, open: bool) {
2284 if !open {
2285 return;
2286 }
2287
2288 let entries: Vec<crate::keymap::PublishedKeymap> = self.published_keymaps().to_vec();
2289 if entries.is_empty() {
2290 return;
2291 }
2292
2293 let theme = self.theme;
2294 let _ = self.modal(|ui| {
2295 ui.styled("Keyboard shortcuts", Style::new().bold().fg(theme.primary));
2296 ui.text("");
2297 for entry in &entries {
2298 ui.styled(entry.name, Style::new().bold().fg(theme.text));
2299 for (key, desc) in entry.bindings {
2300 let line = format!(" {key:<14} {desc}");
2301 ui.styled(line, Style::new().fg(theme.text_dim));
2302 }
2303 ui.text("");
2304 }
2305 ui.styled(
2306 "Press Esc / ? to close",
2307 Style::new().fg(theme.text_dim).italic(),
2308 );
2309 });
2310 }
2311}
2312
2313// Sentinel keys reused from `lib.rs` so the two reads/writes can never drift.
2314use crate::{
2315 KEYMAP_REGISTRY_NAMED_STATE_KEY as KEYMAP_REGISTRY_KEY,
2316 STATIC_LOG_NAMED_STATE_KEY as STATIC_LOG_KEY,
2317};