Guide API
Skip to main content

tvision_rs/widgets/
list_box.rs

1//! `ListBox` and `SortedListBox` (documented on the types).
2
3use crate::data::FieldValue;
4use crate::event::Event;
5use crate::view::{Context, DrawCtx, Point, StateFlag, View, ViewId, ViewState};
6use crate::widgets::list_viewer::{self, ListViewer, ListViewerState};
7
8/// A concrete list viewer that owns a `Vec<String>` as its item source.
9///
10/// A concrete list box over a `Vec<String>`: the first concrete
11/// [`ListViewer`](crate::widgets::list_viewer::ListViewer). It holds the items
12/// and delegates all draw/event/nav logic to the shared list-viewer functions via
13/// the [`ListViewer`] trait. Only [`get_text`](ListViewer::get_text) is
14/// overridden; `is_selected` and `select_item` inherit the base behavior
15/// (`item == focused`, and the base broadcasts that an item was selected).
16///
17/// # Population wiring
18///
19/// The constructor sets fields only (empty items, range 0) — no [`Context`] is
20/// available at construction. After insertion into a group:
21///
22/// 1. Call [`new_list`](ListBox::new_list) to populate the items and publish the
23///    vertical-bar range + focus position.
24/// 2. Call [`list_viewer::update_steps`](crate::widgets::list_viewer::update_steps)
25///    to publish the page/arrow step sizes to the bars.
26///
27/// Missing step 1 leaves the list empty; missing step 2 leaves the scrollbar
28/// thumb unsized. Both require a `Context`, so they cannot run in the constructor.
29///
30/// # The focused item as a value
31///
32/// The list box's [`value`](View::value) is its focused item index. Scattering a
33/// value back (focusing an item) is done through
34/// [`set_value_ctx`](ListBox::set_value_ctx) rather than the plain
35/// [`set_value`](View::set_value), because focusing an item must republish the
36/// scroll-bar position and so needs a [`Context`].
37///
38/// `ListBox` is the standard list widget: embed it in a dialog or group,
39/// call [`new_list`](Self::new_list) after insertion to populate and wire
40/// the scroll bar, then read the user's selection back via
41/// [`value`](View::value). It reuses all shared draw/event/navigation logic
42/// from the [`ListViewer`] trait; only [`get_text`](ListViewer::get_text) is
43/// overridden — every other hook (selection highlight, keyboard scroll,
44/// mouse drag) is handled by the trait's default implementations.
45///
46/// # Turbo Vision heritage
47///
48/// Ports `TListBox` (`tlistbox.cpp`). The list-record get/set hooks become the
49/// typed value protocol (D10); mouse press-and-hold, auto-scroll, and resize
50/// handling all live in the shared list-viewer base.
51pub struct ListBox {
52    lv: ListViewerState,
53    /// The displayed rows (the source narrowed by the query in `Filter` mode).
54    items: Vec<String>,
55    /// The full host-supplied set; `items` is derived from this.
56    source: Vec<String>,
57}
58
59impl ListBox {
60    /// Create a new, empty list box wired to optional scroll bars.
61    ///
62    /// Pass the `ViewId` of a [`ScrollBar`](crate::widgets::ScrollBar) for `h`
63    /// and/or `v` to connect the horizontal and vertical bars; pass `None` if
64    /// no bar is needed.  The item list starts empty and the range is 0 —
65    /// nothing is drawn until you call [`new_list`](Self::new_list) after
66    /// inserting this widget into its parent group.
67    ///
68    /// # Example
69    /// ```rust,ignore
70    /// let lb = ListBox::new(bounds, 1, None, Some(vbar_id));
71    /// // insert lb into its group, then:
72    /// lb.new_list(vec!["Item A".into(), "Item B".into()], ctx);
73    /// ```
74    pub fn new(
75        bounds: crate::view::Rect,
76        num_cols: i32,
77        h: Option<ViewId>,
78        v: Option<ViewId>,
79    ) -> Self {
80        ListBox {
81            lv: ListViewerState::new(bounds, num_cols, h, v),
82            items: Vec::new(),
83            source: Vec::new(),
84        }
85    }
86
87    /// Enable find mode (default [`FindMode::Off`](crate::widgets::FindMode::Off) keeps the classic lookup).
88    /// `Filter` makes the list narrow its own source by the query; `Highlight`
89    /// only owns the query + highlight (the host supplies the rows).
90    pub fn with_find(mut self, mode: crate::widgets::list_viewer::FindMode) -> Self {
91        self.lv.find_mode = mode;
92        self
93    }
94
95    /// Replace the item collection, update the scroll-bar range, and focus item 0.
96    ///
97    /// This is the primary way to populate (or repopulate) a `ListBox`.  Call
98    /// it **after** the widget has been inserted into its parent group so that
99    /// the scroll-bar `ViewId`s are resolvable.  After this call, also invoke
100    /// [`list_viewer::update_steps`](list_viewer::update_steps) to publish the
101    /// page and arrow step sizes to the bars.
102    ///
103    /// On an empty `items` vec the range is set to 0 and focus stays at 0;
104    /// `focus_item(0)` is skipped.  On a non-empty vec focus always resets to
105    /// item 0 — to restore a prior selection scatter the index back afterwards
106    /// with [`set_value_ctx`](View::set_value_ctx).
107    pub fn new_list(&mut self, items: Vec<String>, ctx: &mut Context) {
108        self.source = items;
109        self.rebuild_view(ctx, true);
110    }
111
112    /// Re-derive `items` from `source` (narrowing by the query in `Filter`
113    /// mode), then republish the range and place focus via the shared helpers.
114    fn rebuild_view(&mut self, ctx: &mut Context, reset_focus: bool) {
115        self.items = list_viewer::filtered_view(&self.source, self.lv.find_mode, &self.lv.query);
116        let len = self.items.len() as i32;
117        list_viewer::apply_view_len(self, len, reset_focus, ctx);
118    }
119
120    /// The current item collection as a read-only slice.
121    ///
122    /// Use this to inspect or copy the items without modifying them.  To
123    /// replace the collection, call [`new_list`](Self::new_list) — that
124    /// method also republishes the scroll-bar range, which a direct
125    /// `Vec` write would miss.  In [`FindMode::Filter`](crate::widgets::list_viewer::FindMode)
126    /// with an active query, the returned slice is the query-narrowed view, not the full
127    /// set supplied via `new_list`; clearing the query restores the full set.
128    pub fn list(&self) -> &[String] {
129        &self.items
130    }
131}
132
133impl ListViewer for ListBox {
134    fn lv(&self) -> &ListViewerState {
135        &self.lv
136    }
137
138    fn lv_mut(&mut self) -> &mut ListViewerState {
139        &mut self.lv
140    }
141
142    /// Return the text for `item` from the owned Vec.
143    ///
144    /// An out-of-bounds index (including an empty list) returns an empty string.
145    fn get_text(&self, item: i32) -> String {
146        self.items.get(item as usize).cloned().unwrap_or_default()
147    }
148
149    fn on_query_changed(&mut self, ctx: &mut Context) {
150        if self.lv.find_mode == crate::widgets::list_viewer::FindMode::Filter {
151            self.rebuild_view(ctx, false);
152        }
153    }
154    // is_selected / select_item: inherit the base (item == focused, and the base
155    // broadcasts that an item was selected). Not overridden here.
156}
157
158impl View for ListBox {
159    fn state(&self) -> &ViewState {
160        &self.lv.state
161    }
162
163    fn state_mut(&mut self) -> &mut ViewState {
164        &mut self.lv.state
165    }
166
167    fn draw(&mut self, ctx: &mut DrawCtx) {
168        list_viewer::draw(self, ctx);
169    }
170
171    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
172        list_viewer::handle_event(self, ev, ctx);
173    }
174
175    fn set_state(&mut self, flag: StateFlag, enable: bool, ctx: &mut Context) {
176        list_viewer::set_state(self, flag, enable, ctx);
177    }
178
179    /// Republish the scroll-bar steps after a bounds change.
180    fn on_bounds_changed(&mut self, ctx: &mut Context) {
181        list_viewer::on_bounds_changed(self, ctx);
182    }
183
184    fn cursor_request(&self) -> Option<Point> {
185        list_viewer::focused_cursor(self)
186    }
187
188    fn apply_scroll_sync(&mut self, h: Option<i32>, v: Option<i32>, ctx: &mut Context) {
189        list_viewer::apply_scroll(self, h, v, ctx);
190    }
191
192    fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
193        Some(self)
194    }
195
196    /// The focused item's **index** as a `FieldValue::Int`.
197    ///
198    /// This is the dialog-gather value: it captures *which* item the user
199    /// chose, not the item text.  Call this after the user closes the dialog
200    /// (or at any point) to read the current selection.
201    ///
202    /// The item collection itself is **not** part of this value — it is
203    /// configuration set once via [`new_list`](Self::new_list) and does not
204    /// travel through the gather/scatter cycle.
205    fn value(&self) -> Option<FieldValue> {
206        Some(FieldValue::Int(self.lv.focused))
207    }
208
209    /// Focus the item at `index` and republish the vertical scroll bar.
210    ///
211    /// Use this to restore a previously gathered selection (dialog scatter):
212    /// pass back the `FieldValue::Int` that `value()` returned.  The item
213    /// list is **not** replaced — only the focused index changes.  If you also
214    /// need to repopulate the list, call [`new_list`](Self::new_list) first,
215    /// then scatter the index with this method.
216    ///
217    /// An out-of-range index is clamped to `0..range` (so scatter after a
218    /// shorter re-population is safe).  Non-`Int` variants are silently
219    /// ignored.
220    fn set_value_ctx(&mut self, v: FieldValue, ctx: &mut Context) {
221        if let FieldValue::Int(idx) = v {
222            list_viewer::focus_item_num(self, idx, ctx);
223        }
224    }
225}
226
227// ---------------------------------------------------------------------------
228// SortedListBox
229// ---------------------------------------------------------------------------
230
231/// Case-insensitive ordering (ASCII-fold; list items are filenames or labels).
232fn ci_cmp(a: &str, b: &str) -> core::cmp::Ordering {
233    a.chars()
234        .map(|c| c.to_ascii_lowercase())
235        .cmp(b.chars().map(|c| c.to_ascii_lowercase()))
236}
237
238/// A list viewer with incremental type-to-search over a case-insensitively
239/// sorted string list. A **direct `ListViewer` impl** (like [`ListBox`]); the
240/// search state machine lives as the
241/// [`sorted_handle_event`](crate::widgets::list_viewer::sorted_handle_event) /
242/// [`sorted_cursor`](crate::widgets::list_viewer::sorted_cursor) free functions
243/// over the [`SortedSearch`](crate::widgets::list_viewer::SortedSearch) sub-trait,
244/// which this widget implements.
245///
246/// ## Design notes
247/// * The list is an owned `Vec<String>`; `new_list` keeps it CASE-INSENSITIVELY
248///   SORTED so the binary search and the case-insensitive prefix-confirm cohere.
249///   File/dir subclasses can impose their own ordering.
250/// * The search key here is the typed prefix itself; a file/dir subclass
251///   overrides `search` to supply its own key derivation and ordering.
252/// * The shift bits are captured but UNUSED in this base — a file list reads them.
253///
254/// # Turbo Vision heritage
255///
256/// Ports `TSortedListBox` (`stddlg.cpp`); the injected sorted collection becomes
257/// the owned, case-insensitively sorted `Vec<String>`.
258pub struct SortedListBox {
259    lv: ListViewerState,
260    /// The displayed rows (the source narrowed by the query in `Filter` mode).
261    items: Vec<String>,
262    /// The full host-supplied set, kept sorted; `items` is derived from this.
263    source: Vec<String>,
264    /// The index of the last matched char in the focused item's text; -1 = no
265    /// active search.
266    search_pos: i32,
267    /// Captured shift bits; UNUSED in this base (a file list reads them).
268    shift_state: u8,
269}
270
271impl SortedListBox {
272    /// Create a new, empty sorted list box wired to optional scroll bars.
273    ///
274    /// Like [`ListBox::new`], but additionally enables the visible cursor and
275    /// positions it at column 1 — the cursor advances past the matched prefix
276    /// during type-to-search.  The item list starts empty; call
277    /// [`new_list`](Self::new_list) after insertion to populate it.
278    ///
279    /// Pass `None` for `h` or `v` when no horizontal or vertical scroll bar
280    /// is needed.
281    pub fn new(
282        bounds: crate::view::Rect,
283        num_cols: i32,
284        h: Option<ViewId>,
285        v: Option<ViewId>,
286    ) -> Self {
287        let mut lv = ListViewerState::new(bounds, num_cols, h, v);
288        lv.state.show_cursor();
289        lv.state.set_cursor(1, 0);
290        SortedListBox {
291            lv,
292            items: Vec::new(),
293            source: Vec::new(),
294            search_pos: -1,
295            shift_state: 0,
296        }
297    }
298
299    /// Enable find mode (default [`FindMode::Off`](crate::widgets::FindMode::Off) keeps the classic lookup).
300    /// `Filter` makes the list narrow its own (already-sorted) source by the
301    /// query, so the narrowed view stays in sorted order.
302    pub fn with_find(mut self, mode: crate::widgets::list_viewer::FindMode) -> Self {
303        self.lv.find_mode = mode;
304        self
305    }
306
307    /// Replace the item collection, sort it case-insensitively, and reset the search state.
308    ///
309    /// The items are sorted in-place (ASCII case-fold) so that the binary
310    /// search used by type-to-search produces correct results.  After sorting,
311    /// the scroll-bar range is republished and focus is reset to item 0.  Any
312    /// active type-to-search state (`search_pos`) is cleared.
313    ///
314    /// Call this **after** the widget has been inserted into its parent group
315    /// (same requirement as [`ListBox::new_list`]).  Pass items in any order —
316    /// `new_list` sorts them for you.
317    pub fn new_list(&mut self, mut items: Vec<String>, ctx: &mut Context) {
318        items.sort_by(|a, b| ci_cmp(a, b));
319        self.source = items;
320        self.search_pos = -1;
321        self.rebuild_view(ctx, true);
322    }
323
324    /// Re-derive `items` by narrowing the already-sorted `source` with the query
325    /// (in `Filter` mode); the narrowed view stays sorted because `source` is
326    /// sorted and `filtered_view` preserves order.
327    fn rebuild_view(&mut self, ctx: &mut Context, reset_focus: bool) {
328        self.items = list_viewer::filtered_view(&self.source, self.lv.find_mode, &self.lv.query);
329        let len = self.items.len() as i32;
330        list_viewer::apply_view_len(self, len, reset_focus, ctx);
331    }
332
333    /// The current item collection as a read-only, case-insensitively sorted slice.
334    ///
335    /// The slice is always in the order established by the last
336    /// [`new_list`](Self::new_list) call (ASCII case-folded lexicographic).
337    /// Use it to read the items; to replace them call `new_list`.  In
338    /// [`FindMode::Filter`](crate::widgets::list_viewer::FindMode) with an active query,
339    /// the returned slice is the query-narrowed view, not the full set supplied via
340    /// `new_list`; clearing the query restores the full set.
341    pub fn list(&self) -> &[String] {
342        &self.items
343    }
344
345    /// Test accessor for `search_pos` (used in tests only).
346    #[cfg(test)]
347    pub(crate) fn search_pos(&self) -> i32 {
348        self.search_pos
349    }
350}
351
352impl ListViewer for SortedListBox {
353    fn lv(&self) -> &ListViewerState {
354        &self.lv
355    }
356
357    fn lv_mut(&mut self) -> &mut ListViewerState {
358        &mut self.lv
359    }
360
361    /// Return the text for `item` from the owned Vec.
362    fn get_text(&self, item: i32) -> String {
363        self.items.get(item as usize).cloned().unwrap_or_default()
364    }
365
366    fn on_query_changed(&mut self, ctx: &mut Context) {
367        if self.lv.find_mode == crate::widgets::list_viewer::FindMode::Filter {
368            self.rebuild_view(ctx, false);
369        }
370    }
371    // is_selected / select_item: inherit the base (item == focused, and the base
372    // broadcasts that an item was selected). Not overridden here.
373}
374
375impl list_viewer::SortedSearch for SortedListBox {
376    fn search_pos(&self) -> i32 {
377        self.search_pos
378    }
379
380    fn set_search_pos(&mut self, pos: i32) {
381        self.search_pos = pos;
382    }
383
384    fn shift_state(&self) -> u8 {
385        self.shift_state
386    }
387
388    fn set_shift_state(&mut self, s: u8) {
389        self.shift_state = s;
390    }
391
392    /// Map the typed prefix to the best matching item index.
393    ///
394    /// The key IS the typed prefix itself: `cur` is joined into a string and
395    /// compared case-insensitively against the sorted items.  Returns the first
396    /// index `i` in `0..range` such that `items[i] >= key` (case-insensitive
397    /// insertion point), or `range` when every item sorts before the prefix.
398    ///
399    /// Subclasses (e.g. a file-list box) can override `search` to derive a
400    /// different key or use a different ordering; this base implementation
401    /// covers the generic string case.
402    fn search(&self, cur: &[char]) -> i32 {
403        let key: String = cur.iter().collect();
404        let range = self.lv.range;
405        let (mut lo, mut hi) = (0i32, range);
406        while lo < hi {
407            let mid = lo + (hi - lo) / 2;
408            if ci_cmp(&self.get_text(mid), &key) == core::cmp::Ordering::Less {
409                lo = mid + 1;
410            } else {
411                hi = mid;
412            }
413        }
414        lo
415    }
416}
417
418impl View for SortedListBox {
419    fn state(&self) -> &ViewState {
420        &self.lv.state
421    }
422
423    fn state_mut(&mut self) -> &mut ViewState {
424        &mut self.lv.state
425    }
426
427    fn draw(&mut self, ctx: &mut DrawCtx) {
428        list_viewer::draw(self, ctx);
429    }
430
431    /// The incremental type-to-search state machine, shared verbatim via the
432    /// [`sorted_handle_event`](list_viewer::sorted_handle_event) free function
433    /// over the `SortedSearch` sub-trait.
434    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
435        list_viewer::sorted_handle_event(self, ev, ctx);
436    }
437
438    fn set_state(&mut self, flag: StateFlag, enable: bool, ctx: &mut Context) {
439        list_viewer::set_state(self, flag, enable, ctx);
440    }
441
442    /// Republish the scroll-bar steps after a bounds change.
443    fn on_bounds_changed(&mut self, ctx: &mut Context) {
444        list_viewer::on_bounds_changed(self, ctx);
445    }
446
447    /// Cursor advanced past the matched prefix — shared via
448    /// [`sorted_cursor`](list_viewer::sorted_cursor).
449    fn cursor_request(&self) -> Option<Point> {
450        list_viewer::sorted_cursor(self)
451    }
452
453    fn apply_scroll_sync(&mut self, h: Option<i32>, v: Option<i32>, ctx: &mut Context) {
454        list_viewer::apply_scroll(self, h, v, ctx);
455    }
456
457    fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
458        Some(self)
459    }
460
461    /// The focused item's **index** in the (sorted) item Vec as a `FieldValue::Int`.
462    ///
463    /// Gather this value after the user closes the dialog to find out which
464    /// item was selected.  Because the list is sorted by `new_list`, the index
465    /// refers to the sorted position — use [`list`](Self::list) to map it back
466    /// to the item text if needed.  The item collection itself is not part of
467    /// this value (same contract as [`ListBox::value`]).
468    fn value(&self) -> Option<FieldValue> {
469        Some(FieldValue::Int(self.lv.focused))
470    }
471
472    /// Focus the item at `index` and republish the vertical scroll bar.
473    ///
474    /// Scatter a previously gathered `FieldValue::Int` back here to restore the
475    /// user's prior selection.  The index refers to the sorted position; an
476    /// out-of-range value is clamped.  Non-`Int` variants are silently ignored.
477    /// The item list is not replaced — call [`new_list`](Self::new_list) first
478    /// if you need to repopulate.
479    fn set_value_ctx(&mut self, v: FieldValue, ctx: &mut Context) {
480        if let FieldValue::Int(idx) = v {
481            list_viewer::focus_item_num(self, idx, ctx);
482        }
483    }
484}
485
486// ---------------------------------------------------------------------------
487// Tests
488// ---------------------------------------------------------------------------
489
490#[cfg(test)]
491mod tests {
492    use super::*;
493    use crate::backend::{HeadlessBackend, Renderer};
494    use crate::event::{Key, KeyEvent, KeyModifiers};
495    use crate::screen::Buffer;
496    use crate::theme::Theme;
497    use crate::view::{Deferred, Group, Rect};
498    use crate::widgets::list_viewer::{FindMode, ListViewer};
499    use std::collections::VecDeque;
500
501    fn make_ctx<'a>(
502        out: &'a mut VecDeque<Event>,
503        timers: &'a mut crate::timer::TimerQueue,
504        deferred: &'a mut Vec<Deferred>,
505    ) -> Context<'a> {
506        Context::new(out, timers, 0, deferred)
507    }
508
509    fn key_ev(k: Key) -> Event {
510        Event::KeyDown(KeyEvent::new(k, KeyModifiers::default()))
511    }
512
513    /// Render a ListBox into a snapshot string.
514    fn render(lb: &mut ListBox, w: u16, h: u16) -> String {
515        let theme = Theme::classic_blue();
516        let (backend, screen) = HeadlessBackend::new(w, h);
517        let mut r = Renderer::new(Box::new(backend));
518        r.render(|buf: &mut Buffer| {
519            let bounds = lb.state().get_bounds();
520            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
521            lb.draw(&mut dc);
522        });
523        screen.snapshot()
524    }
525
526    // -- 1. ctor ----------------------------------------------------------------
527
528    #[test]
529    fn ctor_empty_items_and_zeroed_fields() {
530        let lb = ListBox::new(Rect::new(0, 0, 20, 8), 1, None, None);
531        assert!(lb.lv.state.options.first_click, "ofFirstClick set");
532        assert!(lb.lv.state.options.selectable, "ofSelectable set");
533        assert_eq!(lb.lv.range, 0, "range starts at 0");
534        assert_eq!(lb.lv.focused, 0, "focused starts at 0");
535        assert_eq!(lb.lv.top_item, 0, "top_item starts at 0");
536        assert_eq!(lb.lv.indent, 0, "indent starts at 0");
537        assert_eq!(lb.lv.num_cols, 1, "num_cols == 1");
538        assert!(lb.items.is_empty(), "items starts empty");
539    }
540
541    // -- 2. new_list --------------------------------------------------------
542
543    #[test]
544    fn new_list_sets_range_and_queues_vbar_params() {
545        // Need a real ViewId for the v-bar.
546        let mut mint_group = Group::new(Rect::new(0, 0, 4, 4));
547        let sentinel =
548            mint_group.insert(Box::new(ListBox::new(Rect::new(0, 0, 1, 1), 1, None, None)));
549
550        let mut lb = ListBox::new(Rect::new(0, 0, 20, 8), 1, None, Some(sentinel));
551        let mut out = VecDeque::new();
552        let mut timers = crate::timer::TimerQueue::new();
553        let mut deferred: Vec<Deferred> = vec![];
554        {
555            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
556            lb.new_list(
557                vec!["alpha".into(), "beta".into(), "gamma".into()],
558                &mut ctx,
559            );
560        }
561        assert_eq!(lb.lv.range, 3, "range == N after new_list");
562        assert_eq!(lb.lv.focused, 0, "focus_item(0) called");
563        // set_range queues ScrollBarSetParams{value:0, min:0, max:2, pg:None, ar:None}
564        // focus_item queues ScrollBarSetParams{value:0, min:None, max:None, …}
565        assert_eq!(
566            deferred.len(),
567            2,
568            "set_range + focus_item each queue one op"
569        );
570        assert!(matches!(
571            deferred[0],
572            Deferred::ScrollBarSetParams {
573                id,
574                value: Some(0),
575                min: Some(0),
576                max: Some(2),
577                page_step: None,
578                arrow_step: None,
579            } if id == sentinel
580        ));
581        assert!(matches!(
582            deferred[1],
583            Deferred::ScrollBarSetParams {
584                id,
585                value: Some(0),
586                min: None,
587                max: None,
588                page_step: None,
589                arrow_step: None,
590            } if id == sentinel
591        ));
592    }
593
594    #[test]
595    fn new_list_empty_skips_focus_item() {
596        let mut lb = ListBox::new(Rect::new(0, 0, 20, 8), 1, None, None);
597        let mut out = VecDeque::new();
598        let mut timers = crate::timer::TimerQueue::new();
599        let mut deferred: Vec<Deferred> = vec![];
600        {
601            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
602            lb.new_list(vec![], &mut ctx);
603        }
604        assert_eq!(lb.lv.range, 0, "range == 0 for empty list");
605        // No v-bar, so set_range queues nothing; focus_item not called.
606        assert!(deferred.is_empty(), "empty list queues nothing");
607    }
608
609    #[test]
610    fn new_list_replaces_previous_items() {
611        let mut lb = ListBox::new(Rect::new(0, 0, 20, 8), 1, None, None);
612        let mut out = VecDeque::new();
613        let mut timers = crate::timer::TimerQueue::new();
614        let mut deferred: Vec<Deferred> = vec![];
615        {
616            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
617            lb.new_list(vec!["first".into()], &mut ctx);
618        }
619        deferred.clear();
620        {
621            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
622            lb.new_list(vec!["second".into(), "third".into()], &mut ctx);
623        }
624        assert_eq!(lb.items.len(), 2, "old items replaced");
625        assert_eq!(lb.items[0], "second");
626        assert_eq!(lb.items[1], "third");
627        assert!(
628            lb.items.iter().all(|s| s != "first"),
629            "old item 'first' is gone"
630        );
631    }
632
633    // -- 3. get_text --------------------------------------------------------
634
635    #[test]
636    fn get_text_returns_item_or_empty_for_oob() {
637        let mut lb = ListBox::new(Rect::new(0, 0, 20, 8), 1, None, None);
638        let mut out = VecDeque::new();
639        let mut timers = crate::timer::TimerQueue::new();
640        let mut deferred: Vec<Deferred> = vec![];
641        {
642            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
643            lb.new_list(vec!["alpha".into(), "beta".into()], &mut ctx);
644        }
645        // In-range: a real item differs from empty (bite check).
646        let text0 = lb.get_text(0);
647        assert_eq!(text0, "alpha");
648        assert_ne!(
649            text0, "",
650            "in-range item is not empty (bite: distinguishes from OOB)"
651        );
652
653        let text1 = lb.get_text(1);
654        assert_eq!(text1, "beta");
655
656        // Out-of-range returns empty string (faithful: C++ `*dest = EOS`).
657        assert_eq!(lb.get_text(2), "");
658        assert_eq!(lb.get_text(99), "");
659        assert_eq!(lb.get_text(-1_i32), "");
660    }
661
662    // -- 4. value() ---------------------------------------------------------
663
664    #[test]
665    fn value_reflects_focused_item() {
666        let mut lb = ListBox::new(Rect::new(0, 0, 20, 8), 1, None, None);
667        let mut out = VecDeque::new();
668        let mut timers = crate::timer::TimerQueue::new();
669        let mut deferred: Vec<Deferred> = vec![];
670        {
671            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
672            lb.new_list(
673                vec!["a".into(), "b".into(), "c".into(), "d".into(), "e".into()],
674                &mut ctx,
675            );
676        }
677        // Initial focused == 0.
678        assert_eq!(lb.value(), Some(FieldValue::Int(0)), "initial focused == 0");
679
680        // Drive focus to item 2 via KeyDown(Down) twice.
681        deferred.clear();
682        let mut ev = key_ev(Key::Down);
683        {
684            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
685            lb.handle_event(&mut ev, &mut ctx);
686        }
687        let mut ev = key_ev(Key::Down);
688        {
689            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
690            lb.handle_event(&mut ev, &mut ctx);
691        }
692        assert_eq!(lb.lv.focused, 2, "focus moved to 2");
693        // value() must reflect the new focus (bite: 0 vs 2).
694        assert_eq!(
695            lb.value(),
696            Some(FieldValue::Int(2)),
697            "value() reflects focused == 2 (not the initial 0)"
698        );
699    }
700
701    // -- 5. draw snapshot ---------------------------------------------------
702
703    #[test]
704    fn snapshot_active_focused_list_box() {
705        let mut lb = ListBox::new(Rect::new(0, 0, 14, 5), 1, None, None);
706        lb.lv.state.state.selected = true;
707        lb.lv.state.state.active = true;
708        lb.lv.state.state.focused = true;
709        // Set items directly (no Context needed for draw test; range set manually).
710        lb.items = vec![
711            "apple".into(),
712            "banana".into(),
713            "cherry".into(),
714            "date".into(),
715        ];
716        lb.lv.range = 4;
717        lb.lv.focused = 1;
718        insta::assert_snapshot!(render(&mut lb, 14, 5));
719    }
720
721    // -- 6. delegation smoke ------------------------------------------------
722
723    #[test]
724    fn handle_event_wired_down_moves_focused() {
725        let mut lb = ListBox::new(Rect::new(0, 0, 20, 8), 1, None, None);
726        lb.items = vec!["x".into(), "y".into(), "z".into()];
727        lb.lv.range = 3;
728        let mut out = VecDeque::new();
729        let mut timers = crate::timer::TimerQueue::new();
730        let mut deferred: Vec<Deferred> = vec![];
731
732        let mut ev = key_ev(Key::Down);
733        {
734            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
735            lb.handle_event(&mut ev, &mut ctx);
736        }
737        assert_eq!(lb.lv.focused, 1, "KeyDown(Down) wired: focused moves to 1");
738        assert!(ev.is_nothing(), "Down consumed");
739    }
740
741    #[test]
742    fn broadcast_from_own_vbar_queues_sync_list_viewer() {
743        // Insert the list box into a group so it has a ViewId.
744        let mut group = Group::new(Rect::new(0, 0, 30, 20));
745
746        // Mint a v-bar id.
747        let mut vbar_group = Group::new(Rect::new(0, 0, 4, 4));
748        let v_id = vbar_group.insert(Box::new(ListBox::new(Rect::new(0, 0, 1, 1), 1, None, None)));
749
750        let lb_id = group.insert(Box::new(ListBox::new(
751            Rect::new(0, 0, 20, 8),
752            1,
753            None,
754            Some(v_id),
755        )));
756
757        let mut out = VecDeque::new();
758        let mut timers = crate::timer::TimerQueue::new();
759        let mut deferred: Vec<Deferred> = vec![];
760
761        // cmScrollBarChanged from own v-bar → ScrollSync queued.
762        let mut ev = Event::Broadcast {
763            command: crate::command::Command::SCROLL_BAR_CHANGED,
764            source: Some(v_id),
765        };
766        {
767            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
768            group
769                .find_mut(lb_id)
770                .unwrap()
771                .handle_event(&mut ev, &mut ctx);
772        }
773        assert_eq!(deferred.len(), 1, "one ScrollSync op queued");
774        assert!(
775            matches!(
776                deferred[0],
777                Deferred::ScrollSync {
778                    target,
779                    h: None,
780                    v: Some(vid),
781                } if target == lb_id && vid == v_id
782            ),
783            "ScrollSync carries correct target and v-bar ids"
784        );
785    }
786
787    // =========================================================================
788    // SortedListBox tests
789    // =========================================================================
790
791    // Helper: build a SortedListBox populated with the given items (pre-sorted
792    // externally for readability, but new_list will sort them anyway).
793    fn make_sorted_lb(
794        items: Vec<&str>,
795    ) -> (
796        SortedListBox,
797        VecDeque<Event>,
798        crate::timer::TimerQueue,
799        Vec<Deferred>,
800    ) {
801        let mut slb = SortedListBox::new(Rect::new(0, 0, 20, 8), 1, None, None);
802        let mut out = VecDeque::new();
803        let mut timers = crate::timer::TimerQueue::new();
804        let mut deferred: Vec<Deferred> = vec![];
805        {
806            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
807            slb.new_list(items.into_iter().map(|s| s.into()).collect(), &mut ctx);
808        }
809        deferred.clear();
810        (slb, out, timers, deferred)
811    }
812
813    // -- SLB 1. type-to-jump ---------------------------------------------------
814
815    #[test]
816    fn sorted_lb_type_to_jump_b_then_br() {
817        use crate::widgets::list_viewer::ListViewer;
818        let (mut slb, mut out, mut timers, mut deferred) =
819            make_sorted_lb(vec!["alpha", "beta", "bravo", "charlie"]);
820        // After new_list sorts: ["alpha", "beta", "bravo", "charlie"].
821        // Focused starts at 0 ("alpha").
822
823        // Type 'b' → jump to first item starting with 'b' ("beta" at index 1).
824        let mut ev = key_ev(Key::Char('b'));
825        {
826            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
827            slb.handle_event(&mut ev, &mut ctx);
828        }
829        assert_eq!(slb.lv().focused, 1, "'b' -> focused == 1 (\"beta\")");
830        assert_eq!(slb.search_pos(), 0, "search_pos == 0 after first char");
831        assert!(ev.is_nothing(), "'b' consumed (alpha match found)");
832
833        deferred.clear();
834
835        // Type 'r' → advance to "bravo" (index 2).
836        let mut ev = key_ev(Key::Char('r'));
837        {
838            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
839            slb.handle_event(&mut ev, &mut ctx);
840        }
841        assert_eq!(slb.lv().focused, 2, "'br' -> focused == 2 (\"bravo\")");
842        assert_eq!(slb.search_pos(), 1, "search_pos == 1 after second char");
843        assert!(ev.is_nothing(), "'r' consumed");
844    }
845
846    // -- SLB 2. backspace shortens ---------------------------------------------
847
848    #[test]
849    fn sorted_lb_backspace_shortens_search() {
850        use crate::widgets::list_viewer::ListViewer;
851        let (mut slb, mut out, mut timers, mut deferred) =
852            make_sorted_lb(vec!["alpha", "beta", "bravo", "charlie"]);
853
854        // Type "br" to focus "bravo".
855        for ch in ['b', 'r'] {
856            let mut ev = key_ev(Key::Char(ch));
857            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
858            slb.handle_event(&mut ev, &mut ctx);
859            deferred.clear();
860        }
861        assert_eq!(slb.lv().focused, 2, "pre: focused == 2 (\"bravo\")");
862        assert_eq!(slb.search_pos(), 1, "pre: search_pos == 1");
863
864        // Backspace → search shortens to "b" and re-resolves.
865        // cur is re-seeded from "bravo" (the focused item), truncated to 1 char ("b").
866        // search("b") finds "beta" (index 1) or "bravo" (index 2) — the first
867        // item >= "b" case-insensitively.  "beta" < "bravo" alphabetically, so
868        // search returns index 1 ("beta").
869        let mut ev = key_ev(Key::Backspace);
870        {
871            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
872            slb.handle_event(&mut ev, &mut ctx);
873        }
874        assert_eq!(slb.search_pos(), 0, "search_pos decremented to 0");
875        // Focus should be on the first item matching "b" prefix ("beta").
876        assert_eq!(slb.lv().focused, 1, "backspace re-focuses to \"beta\"");
877    }
878
879    // -- SLB 3. dot jumps to the extension separator ---------------------------
880
881    #[test]
882    fn sorted_lb_dot_jumps_to_extension() {
883        use crate::widgets::list_viewer::ListViewer;
884        // Same-basename sibling: after case-insensitive sort the order is
885        // ["file.bak", "file.txt", "zebra"]. The dot branch must search for the
886        // FULL focused text ("file.txt"), NOT the truncated prefix ("file."):
887        // searching "file." would binary-resolve to "file.bak" (index 0) and,
888        // since ci_prefix_eq("file.txt","file.bak",5) is true, wrongly jump there.
889        // Searching the full "file.txt" lands on index 1 (the same item) → no jump.
890        let (mut slb, mut out, mut timers, mut deferred) =
891            make_sorted_lb(vec!["file.txt", "file.bak", "zebra"]);
892        // After sort: index 0 = "file.bak", 1 = "file.txt", 2 = "zebra".
893        assert_eq!(slb.get_text(0), "file.bak");
894        assert_eq!(slb.get_text(1), "file.txt");
895        assert_eq!(slb.lv().focused, 0, "starts at 0 (\"file.bak\")");
896
897        // Type "file.t" up to (but not including) the dot, then the dot, then a
898        // final char, navigating focus onto "file.txt" first.
899        // Type 'f' → first item >= "f" is "file.bak" (index 0).
900        for (ch, want_focus) in [('f', 0), ('i', 0), ('l', 0), ('e', 0)] {
901            let mut ev = key_ev(Key::Char(ch));
902            {
903                let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
904                slb.handle_event(&mut ev, &mut ctx);
905            }
906            assert_eq!(
907                slb.lv().focused,
908                want_focus,
909                "typing '{ch}' keeps focus on \"file.bak\" (shared prefix)"
910            );
911            deferred.clear();
912        }
913        assert_eq!(slb.search_pos(), 3, "search_pos == 3 after \"file\"");
914
915        // Now move focus onto "file.txt" via Down (arrow nav resets search_pos).
916        let mut ev = key_ev(Key::Down);
917        {
918            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
919            slb.handle_event(&mut ev, &mut ctx);
920        }
921        assert_eq!(slb.lv().focused, 1, "Down -> focus \"file.txt\"");
922        assert_eq!(slb.search_pos(), -1, "arrow nav reset search_pos");
923        deferred.clear();
924
925        // Press '.' → cur is re-seeded from the FOCUSED item "file.txt"; the dot
926        // branch finds '.' at index 4, so search_pos = 4. The search key MUST be
927        // the full "file.txt", landing on index 1 (same item) → focus must NOT
928        // mis-jump to "file.bak".
929        let mut ev = key_ev(Key::Char('.'));
930        {
931            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
932            slb.handle_event(&mut ev, &mut ctx);
933        }
934        assert_eq!(
935            slb.search_pos(),
936            4,
937            "dot sets search_pos to the '.' position"
938        );
939        assert_eq!(
940            slb.lv().focused,
941            1,
942            "dot must NOT mis-jump to \"file.bak\"; stays on \"file.txt\""
943        );
944    }
945
946    // -- SLB 4. no-match reverts but alpha still consumes ----------------------
947
948    #[test]
949    fn sorted_lb_no_match_alpha_consumes_but_reverts() {
950        use crate::widgets::list_viewer::ListViewer;
951        let (mut slb, mut out, mut timers, mut deferred) =
952            make_sorted_lb(vec!["alpha", "beta", "bravo", "charlie"]);
953
954        // Type 'z' — no item starts with 'z'. Focused stays at 0.
955        // search_pos reverts to -1 (the old_pos before the attempt).
956        // Event is CONSUMED because 'z' is alpha.
957        let mut ev = key_ev(Key::Char('z'));
958        {
959            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
960            slb.handle_event(&mut ev, &mut ctx);
961        }
962        assert_eq!(slb.lv().focused, 0, "no match: focus unchanged");
963        assert_eq!(slb.search_pos(), -1, "no match: search_pos reverted to -1");
964        assert!(ev.is_nothing(), "alpha key consumed even on no-match");
965    }
966
967    // -- SLB 5. no-match punctuation passes through ----------------------------
968
969    #[test]
970    fn sorted_lb_no_match_punctuation_passes_through() {
971        use crate::widgets::list_viewer::ListViewer;
972        // Items have no '.' so the dot branch sets search_pos = -1 (no dot found).
973        // After revert the event should NOT be cleared (not alpha, search_pos unchanged).
974        let (mut slb, mut out, mut timers, mut deferred) =
975            make_sorted_lb(vec!["alpha", "beta", "bravo", "charlie"]);
976
977        // search_pos is -1. Type '.' — dot branch finds no '.' in "alpha"
978        // (the focused item), so search_pos = -1 (same as old_pos).
979        // is_alpha is false for '.'; search_pos == old_pos (-1 == -1) → NOT consumed.
980        let mut ev = key_ev(Key::Char('.'));
981        {
982            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
983            slb.handle_event(&mut ev, &mut ctx);
984        }
985        assert_eq!(slb.lv().focused, 0, "focus unchanged");
986        assert_eq!(slb.search_pos(), -1, "search_pos stays -1");
987        assert!(!ev.is_nothing(), "non-alpha no-match: event NOT consumed");
988    }
989
990    // -- SLB 6. arrow nav resets search ----------------------------------------
991
992    #[test]
993    fn sorted_lb_arrow_nav_resets_search_pos() {
994        let (mut slb, mut out, mut timers, mut deferred) =
995            make_sorted_lb(vec!["alpha", "beta", "bravo", "charlie"]);
996
997        // Type 'b' to start a search.
998        let mut ev = key_ev(Key::Char('b'));
999        {
1000            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1001            slb.handle_event(&mut ev, &mut ctx);
1002        }
1003        assert_eq!(slb.search_pos(), 0, "pre: search_pos == 0");
1004        deferred.clear();
1005
1006        // Send Down — the base handle_event moves focused (1→2 or further),
1007        // which triggers the `old_value != focused` reset.
1008        let mut ev = key_ev(Key::Down);
1009        {
1010            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1011            slb.handle_event(&mut ev, &mut ctx);
1012        }
1013        assert_eq!(slb.search_pos(), -1, "arrow nav resets search_pos to -1");
1014    }
1015
1016    // -- SLB 7. cmReleasedFocus resets search ----------------------------------
1017
1018    #[test]
1019    fn sorted_lb_released_focus_resets_search_pos() {
1020        let (mut slb, mut out, mut timers, mut deferred) =
1021            make_sorted_lb(vec!["alpha", "beta", "bravo", "charlie"]);
1022
1023        // Type 'b' to start a search.
1024        let mut ev = key_ev(Key::Char('b'));
1025        {
1026            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1027            slb.handle_event(&mut ev, &mut ctx);
1028        }
1029        assert_eq!(slb.search_pos(), 0, "pre: search_pos == 0");
1030        deferred.clear();
1031
1032        // Send cmReleasedFocus broadcast.
1033        let mut ev = Event::Broadcast {
1034            command: crate::command::Command::RELEASED_FOCUS,
1035            source: None,
1036        };
1037        {
1038            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1039            slb.handle_event(&mut ev, &mut ctx);
1040        }
1041        assert_eq!(slb.search_pos(), -1, "cmReleasedFocus resets search_pos");
1042    }
1043
1044    // -- SLB 0. set_value_ctx scatter ------------------------------------------
1045
1046    #[test]
1047    fn sorted_lb_set_value_ctx_focuses_the_item() {
1048        // Build a SortedListBox with a v-bar sentinel so scroll-bar deferrals
1049        // land correctly (mirrors the ListBox harness in new_list_sets_range…).
1050        let mut mint_group = Group::new(Rect::new(0, 0, 4, 4));
1051        let sentinel =
1052            mint_group.insert(Box::new(ListBox::new(Rect::new(0, 0, 1, 1), 1, None, None)));
1053
1054        let mut slb = SortedListBox::new(Rect::new(0, 0, 20, 8), 1, None, Some(sentinel));
1055        let mut out = VecDeque::new();
1056        let mut timers = crate::timer::TimerQueue::new();
1057        let mut deferred: Vec<Deferred> = vec![];
1058        {
1059            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1060            // "alpha","beta","charlie" are already in case-insensitive order.
1061            slb.new_list(
1062                vec!["alpha".into(), "beta".into(), "charlie".into()],
1063                &mut ctx,
1064            );
1065        }
1066        // Gather: initial focus is 0.
1067        assert_eq!(slb.value(), Some(FieldValue::Int(0)), "initial gather == 0");
1068
1069        deferred.clear();
1070
1071        // Scatter index 2 ("charlie").
1072        {
1073            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1074            slb.set_value_ctx(FieldValue::Int(2), &mut ctx);
1075        }
1076
1077        // Round-trip: gather must return the scattered index.
1078        assert_eq!(
1079            slb.value(),
1080            Some(FieldValue::Int(2)),
1081            "after scatter(2) gather returns 2"
1082        );
1083
1084        // A scroll-bar param deferral for the v-bar must have been queued.
1085        assert!(
1086            deferred.iter().any(|d| matches!(
1087                d,
1088                Deferred::ScrollBarSetParams { id, value: Some(_), .. } if *id == sentinel
1089            )),
1090            "scatter queued a ScrollBarSetParams deferral for the v-bar"
1091        );
1092    }
1093
1094    // -- SLB 8. new_list sorts case-insensitively and resets search ------------
1095
1096    #[test]
1097    fn sorted_lb_new_list_sorts_and_resets() {
1098        use crate::widgets::list_viewer::ListViewer;
1099        let mut slb = SortedListBox::new(Rect::new(0, 0, 20, 8), 1, None, None);
1100        let mut out = VecDeque::new();
1101        let mut timers = crate::timer::TimerQueue::new();
1102        let mut deferred: Vec<Deferred> = vec![];
1103        // Provide items deliberately out of order; new_list should sort them.
1104        {
1105            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1106            slb.new_list(
1107                vec!["Zebra".into(), "apple".into(), "Banana".into()],
1108                &mut ctx,
1109            );
1110        }
1111        // Case-insensitive sort: "apple" < "Banana" < "Zebra".
1112        assert_eq!(slb.get_text(0), "apple", "sorted: apple first");
1113        assert_eq!(slb.get_text(1), "Banana", "sorted: Banana second");
1114        assert_eq!(slb.get_text(2), "Zebra", "sorted: Zebra third");
1115        assert_eq!(slb.search_pos(), -1, "new_list resets search_pos");
1116    }
1117
1118    // -- set_value_ctx -------------------------------------------------------
1119
1120    #[test]
1121    fn set_value_ctx_focuses_the_item() {
1122        let mut out = VecDeque::new();
1123        let mut timers = crate::timer::TimerQueue::new();
1124        let mut deferred = Vec::new();
1125        let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1126
1127        let mut lb = ListBox::new(Rect::new(0, 0, 10, 5), 1, None, None);
1128        lb.new_list(
1129            vec!["a".to_string(), "b".to_string(), "c".to_string()],
1130            &mut ctx,
1131        );
1132
1133        // Focus item 2 via set_value_ctx.
1134        lb.set_value_ctx(FieldValue::Int(2), &mut ctx);
1135
1136        // value() returns the focused index.
1137        assert_eq!(lb.value(), Some(FieldValue::Int(2)));
1138    }
1139
1140    #[test]
1141    fn set_value_ctx_ignores_non_int_variant() {
1142        let mut out = VecDeque::new();
1143        let mut timers = crate::timer::TimerQueue::new();
1144        let mut deferred = Vec::new();
1145        let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1146
1147        let mut lb = ListBox::new(Rect::new(0, 0, 10, 5), 1, None, None);
1148        lb.new_list(vec!["a".to_string(), "b".to_string()], &mut ctx);
1149        // Focus item 1 first.
1150        lb.set_value_ctx(FieldValue::Int(1), &mut ctx);
1151        assert_eq!(lb.value(), Some(FieldValue::Int(1)));
1152
1153        // Passing a Text variant should be ignored (no panic, focus unchanged).
1154        lb.set_value_ctx(FieldValue::Text("ignored".to_string()), &mut ctx);
1155        assert_eq!(
1156            lb.value(),
1157            Some(FieldValue::Int(1)),
1158            "focus unchanged after Text variant"
1159        );
1160    }
1161
1162    // -- find / self-filter ---------------------------------------------------
1163
1164    #[test]
1165    fn list_box_self_filter_narrows_and_restores() {
1166        let mut out = VecDeque::new();
1167        let mut timers = crate::timer::TimerQueue::new();
1168        let mut deferred = vec![];
1169        let mut lb =
1170            ListBox::new(Rect::new(0, 0, 14, 5), 1, None, None).with_find(FindMode::Filter);
1171        {
1172            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1173            lb.new_list(
1174                vec![
1175                    "apple".into(),
1176                    "banana".into(),
1177                    "grape".into(),
1178                    "orange".into(),
1179                ],
1180                &mut ctx,
1181            );
1182        }
1183        assert_eq!(lb.lv.range, 4, "empty query shows the full source");
1184
1185        lb.lv.query = "an".into();
1186        {
1187            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1188            lb.on_query_changed(&mut ctx);
1189        }
1190        assert_eq!(lb.lv.range, 2, "only rows containing 'an' survive");
1191        assert_eq!(lb.get_text(0), "banana");
1192        assert_eq!(lb.get_text(1), "orange", "insertion order preserved");
1193
1194        lb.lv.query.clear();
1195        {
1196            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1197            lb.on_query_changed(&mut ctx);
1198        }
1199        assert_eq!(
1200            lb.lv.range, 4,
1201            "clearing the query restores the full source"
1202        );
1203        assert_eq!(lb.get_text(0), "apple");
1204    }
1205
1206    #[test]
1207    fn sorted_list_box_self_filter_keeps_sorted_order() {
1208        let mut out = VecDeque::new();
1209        let mut timers = crate::timer::TimerQueue::new();
1210        let mut deferred = vec![];
1211        let mut slb =
1212            SortedListBox::new(Rect::new(0, 0, 14, 5), 1, None, None).with_find(FindMode::Filter);
1213        {
1214            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1215            slb.new_list(
1216                vec![
1217                    "orange".into(),
1218                    "apple".into(),
1219                    "banana".into(),
1220                    "grape".into(),
1221                ],
1222                &mut ctx,
1223            );
1224        }
1225        // Sorted: apple, banana, grape, orange.
1226        assert_eq!(slb.get_text(0), "apple");
1227        assert_eq!(slb.lv.range, 4);
1228
1229        slb.lv.query = "an".into();
1230        {
1231            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1232            slb.on_query_changed(&mut ctx);
1233        }
1234        // Containing "an", in sorted order: banana, orange.
1235        assert_eq!(slb.lv.range, 2);
1236        assert_eq!(slb.get_text(0), "banana");
1237        assert_eq!(slb.get_text(1), "orange");
1238
1239        slb.lv.query.clear();
1240        {
1241            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1242            slb.on_query_changed(&mut ctx);
1243        }
1244        assert_eq!(slb.lv.range, 4, "clearing restores the full sorted source");
1245    }
1246
1247    #[test]
1248    fn list_box_self_filter_clamps_focus() {
1249        let mut out = VecDeque::new();
1250        let mut timers = crate::timer::TimerQueue::new();
1251        let mut deferred = vec![];
1252        let mut lb =
1253            ListBox::new(Rect::new(0, 0, 14, 5), 1, None, None).with_find(FindMode::Filter);
1254        {
1255            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1256            lb.new_list(
1257                vec![
1258                    "apple".into(),
1259                    "banana".into(),
1260                    "grape".into(),
1261                    "orange".into(),
1262                ],
1263                &mut ctx,
1264            );
1265        }
1266        lb.lv.focused = 3;
1267        lb.lv.query = "an".into();
1268        {
1269            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1270            lb.on_query_changed(&mut ctx);
1271        }
1272        assert!(lb.lv.focused <= 1, "focus clamped into the narrowed range");
1273    }
1274
1275    #[test]
1276    fn set_find_query_narrows_like_typed_query() {
1277        let mut out = VecDeque::new();
1278        let mut timers = crate::timer::TimerQueue::new();
1279        let mut deferred = vec![];
1280        let mut lb =
1281            ListBox::new(Rect::new(0, 0, 14, 5), 1, None, None).with_find(FindMode::Filter);
1282        {
1283            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1284            lb.new_list(
1285                vec![
1286                    "apple".into(),
1287                    "banana".into(),
1288                    "grape".into(),
1289                    "orange".into(),
1290                ],
1291                &mut ctx,
1292            );
1293        }
1294        {
1295            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1296            lb.set_find_query("an", &mut ctx);
1297        }
1298        assert_eq!(
1299            lb.lv.range, 2,
1300            "set_find_query narrows via on_query_changed"
1301        );
1302        assert_eq!(lb.get_text(0), "banana");
1303        assert_eq!(lb.get_text(1), "orange", "insertion order preserved");
1304
1305        {
1306            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1307            lb.set_find_query("", &mut ctx);
1308        }
1309        assert_eq!(
1310            lb.lv.range, 4,
1311            "empty set_find_query restores the full source"
1312        );
1313        assert_eq!(lb.get_text(0), "apple");
1314    }
1315
1316    #[test]
1317    fn typed_and_set_find_query_reach_identical_state() {
1318        let src: Vec<String> = vec![
1319            "apple".into(),
1320            "banana".into(),
1321            "grape".into(),
1322            "orange".into(),
1323        ];
1324
1325        // Path A: reach "an" by keystrokes.
1326        let mut out_a = VecDeque::new();
1327        let mut timers_a = crate::timer::TimerQueue::new();
1328        let mut deferred_a = vec![];
1329        let mut lb_a =
1330            ListBox::new(Rect::new(0, 0, 14, 5), 1, None, None).with_find(FindMode::Filter);
1331        {
1332            let mut ctx = make_ctx(&mut out_a, &mut timers_a, &mut deferred_a);
1333            lb_a.new_list(src.clone(), &mut ctx);
1334        }
1335        for c in ['a', 'n'] {
1336            let mut ev = key_ev(Key::Char(c));
1337            let mut ctx = make_ctx(&mut out_a, &mut timers_a, &mut deferred_a);
1338            lb_a.handle_event(&mut ev, &mut ctx);
1339        }
1340
1341        // Path B: reach "an" by set_find_query.
1342        let mut out_b = VecDeque::new();
1343        let mut timers_b = crate::timer::TimerQueue::new();
1344        let mut deferred_b = vec![];
1345        let mut lb_b =
1346            ListBox::new(Rect::new(0, 0, 14, 5), 1, None, None).with_find(FindMode::Filter);
1347        {
1348            let mut ctx = make_ctx(&mut out_b, &mut timers_b, &mut deferred_b);
1349            lb_b.new_list(src.clone(), &mut ctx);
1350        }
1351        {
1352            let mut ctx = make_ctx(&mut out_b, &mut timers_b, &mut deferred_b);
1353            lb_b.set_find_query("an", &mut ctx);
1354        }
1355
1356        // Identical query, find_query(), and narrowed view.
1357        assert_eq!(lb_a.find_query(), lb_b.find_query(), "same find_query()");
1358        assert_eq!(lb_a.lv.query, lb_b.lv.query, "same raw query");
1359        assert_eq!(lb_a.lv.range, lb_b.lv.range, "same narrowed range");
1360        let rows_a: Vec<String> = (0..lb_a.lv.range).map(|i| lb_a.get_text(i)).collect();
1361        let rows_b: Vec<String> = (0..lb_b.lv.range).map(|i| lb_b.get_text(i)).collect();
1362        assert_eq!(rows_a, rows_b, "same visible rows");
1363    }
1364}