Guide API
Skip to main content

tvision_rs/status/
status_line.rs

1//! The bottom [`StatusLine`] — a one-row [`View`] at the bottom of the screen
2//! showing the items of the help-context-selected [`StatusDef`].
3//!
4//! It draws the items, hit-tests mouse clicks, runs the mouse press-and-hold
5//! drag-highlight, handles the [`Command::COMMAND_SET_CHANGED`](crate::command::Command::COMMAND_SET_CHANGED)
6//! broadcast (regraying its disabled items), and matches keyboard accelerators
7//! against **all** items (including the hidden, text-less ones).
8//!
9//! ## Mouse press-and-hold drag-highlight
10//!
11//! Pressing the mouse over the status line highlights the item under the cursor
12//! and follows it as the cursor moves, firing the item's command on release
13//! only if the cursor is still over an enabled item:
14//! * **`MouseDown`**: hit-test → set `pressed_item`, start tracking with
15//!   [`TrackMask`]`{ mouse_move: true }`. Do NOT post yet.
16//! * **`MouseMove`** (while tracking): re-derive the item under the cursor;
17//!   update `pressed_item` (→ `None` when off all items). The next redraw shows
18//!   the new highlight.
19//! * **`MouseUp`** (while tracking): if `pressed_item` is `Some(idx)` and its
20//!   command is enabled, post the command. Clear `pressed_item` / `tracking`.
21//!
22//! The `abs_origin` field caches the view-local `(0, 0)` in absolute screen
23//! coords from the last `draw`, used by the capture to localize events.
24//!
25//! ## Help-context updates and keyboard accelerators
26//!
27//! [`Program`](crate::app::Program) pre-routes key and status-line mouse events
28//! to the status line before normal dispatch, and on idle refreshes its help
29//! context from the topmost view (via [`set_help_ctx`](StatusLine::set_help_ctx))
30//! so the shown def follows the focused view. A key matching an item's
31//! accelerator is transformed in place into a command event so it propagates to
32//! the rest of the UI.
33//!
34//! ## Themes only — no palettes
35//!
36//! Colors resolve directly from the [`Theme`](crate::theme::Theme) via the
37//! `Status*` [`Role`]s ([`StatusColors`]), like
38//! [`MenuColors`](crate::menu::MenuColors).
39//!
40//! # Turbo Vision heritage
41//!
42//! Ports `TStatusLine` (`tstatusl.cpp`). The palette-index color indirection
43//! becomes direct theme-role lookups (deviation D7), and the streaming machinery
44//! is dropped (deviation D12). Structurally it embeds a [`ViewState`] with
45//! hand-written `View` methods rather than delegating, like
46//! [`MenuBar`](crate::menu::MenuBar).
47
48use crate::capture::TrackMask;
49use crate::color::Style;
50use crate::command::CommandSet;
51use crate::event::Event;
52use crate::help::HelpCtx;
53use crate::status::StatusDef;
54use crate::theme::Role;
55use crate::view::{Context, DrawCtx, Point, Rect, View, ViewState};
56
57use crate::text::cstrlen;
58
59/// The hint separator drawn before the hint text: a vertical bar `│` (U+2502)
60/// followed by a space. Drawn as plain text, not a `~`-marked control string.
61const HINT_SEPARATOR: &str = "\u{2502} ";
62
63/// The four `(lo, hi)` style pairs a status item is drawn in — normal, selected,
64/// normal-disabled, and selected-disabled — resolved once per draw from the
65/// [`Theme`](crate::theme::Theme) via the `Status*` [`Role`]s. Each pair is
66/// `(label style, shortcut-highlight style)`.
67///
68/// Analogous to [`MenuColors`](crate::menu::MenuColors) but reads the distinct
69/// `Status*` roles — deliberately a separate type (different roles), not a reuse.
70///
71/// All four pairs are resolved as a unit. The `select` / `sel_disabled` pairs are
72/// used by the hover/press highlight for the item under the cursor.
73#[derive(Clone, Copy)]
74pub struct StatusColors {
75    /// Normal: `(StatusNormal, StatusShortcut)`.
76    pub normal: (Style, Style),
77    /// Selected/highlighted: `(StatusSelect, StatusShortcutSelect)`.
78    pub select: (Style, Style),
79    /// Normal but disabled: `StatusDisabled` for both lo and hi.
80    pub norm_disabled: (Style, Style),
81    /// Selected but disabled: `StatusSelDisabled` for both lo and hi.
82    pub sel_disabled: (Style, Style),
83}
84
85impl StatusColors {
86    /// Build a `StatusColors` by reading all four `Status*` role pairs from the
87    /// draw context's theme in one pass.
88    ///
89    /// Call this once at the top of a `draw` implementation and pass the result to
90    /// `item` for each status item. This is how [`StatusLine::draw`]
91    /// uses it — the C++ equivalent resolved palette indices for each item
92    /// individually; this batches them all up front.
93    pub fn resolve(ctx: &DrawCtx) -> Self {
94        let d = ctx.style(Role::StatusDisabled);
95        let sd = ctx.style(Role::StatusSelDisabled);
96        StatusColors {
97            normal: (
98                ctx.style(Role::StatusNormal),
99                ctx.style(Role::StatusShortcut),
100            ),
101            select: (
102                ctx.style(Role::StatusSelect),
103                ctx.style(Role::StatusShortcutSelect),
104            ),
105            // Disabled rows: a single style for both lo and hi (no shortcut
106            // highlight when greyed).
107            norm_disabled: (d, d),
108            sel_disabled: (sd, sd),
109        }
110    }
111
112    /// The `(lo, hi)` pair for an item given its `enabled`/`selected` state: a
113    /// 2×2 matrix picking between the normal/select/disabled pairs.
114    fn item(&self, enabled: bool, selected: bool) -> (Style, Style) {
115        match (enabled, selected) {
116            (true, true) => self.select,
117            (true, false) => self.normal,
118            (false, true) => self.sel_disabled,
119            (false, false) => self.norm_disabled,
120        }
121    }
122}
123
124/// The bottom status line. Owns its `defs`, caches the selected def index and a
125/// command-set snapshot for graying.
126///
127/// # Turbo Vision heritage
128///
129/// Ports `TStatusLine` (`tstatusl.cpp`).
130pub struct StatusLine {
131    /// The embedded view state (geometry, flags, state bits).
132    state: ViewState,
133    /// The status-line definitions, owned.
134    defs: Vec<StatusDef>,
135    /// Index into [`defs`](Self::defs) of the currently-selected def, or `None` if
136    /// none match the current help context. Resolved by
137    /// [`find_items`](Self::find_items).
138    items_def: Option<usize>,
139    /// The view's current help context.
140    help_ctx: HelpCtx,
141    /// The hint provider; the default returns `None` (no hint). Overridable via
142    /// [`set_hint`](Self::set_hint).
143    hint: Box<dyn Fn(HelpCtx) -> Option<String>>,
144    /// Cached **disabled**-command snapshot for graying (a denylist; refreshed
145    /// by the [`update_menu_commands`](View::update_menu_commands) broker hook,
146    /// whose contract passes the program's disabled set). `None` before the
147    /// first refresh means **treat all as enabled** (the same startup gap menus
148    /// have — and consistent with the denylist default, where an empty set also
149    /// means all-enabled). A status item carries no per-item disabled flag, so
150    /// enablement is resolved against this snapshot at draw time.
151    disabled_cmds: Option<CommandSet>,
152    /// The item index currently being highlighted during a press-and-hold drag.
153    /// `None` when the cursor is over no item. Reset to `None` on `MouseUp`.
154    pressed_item: Option<usize>,
155    /// Whether a mouse hold-track is in flight (between the arming `MouseDown`
156    /// and the terminating `MouseUp`). Guards the `MouseMove`/`MouseUp` tracking
157    /// arms against stray (untracked) events — `MouseUp` is not mask-gated in
158    /// `Group::wants`.
159    tracking: bool,
160    /// Absolute screen position of view-local `(0, 0)`, cached each `draw` for
161    /// the mouse-tracking capture.
162    abs_origin: Point,
163}
164
165impl StatusLine {
166    /// Construct a status line over `bounds` presenting `defs`.
167    ///
168    /// The grow mode sticks the line to the bottom and stretches it with the
169    /// screen, and the view pre-processes accelerators before the focused view
170    /// sees the event. Broadcasts reach it because the group fans them to every
171    /// child unconditionally (see the identical note in
172    /// [`menu_view::handle_event`](crate::menu::menu_view)); no event-mask opt-in
173    /// is needed.
174    pub fn new(bounds: Rect, defs: Vec<StatusDef>) -> Self {
175        let mut state = ViewState::new(bounds);
176        state.grow_mode.lo_y = true; // stick to the bottom edge
177        state.grow_mode.hi_x = true; // stretch with screen width
178        state.grow_mode.hi_y = true; // stretch with screen height
179        state.options.pre_process = true; // see events before the focused view
180        let mut sl = StatusLine {
181            state,
182            defs,
183            items_def: None,
184            help_ctx: HelpCtx::NO_CONTEXT, // no context by default
185            hint: Box::new(|_| None),      // no hint by default
186            disabled_cmds: None,
187            pressed_item: None,
188            tracking: false,
189            abs_origin: Point::new(0, 0),
190        };
191        sl.find_items();
192        sl
193    }
194
195    /// Override the hint provider. The closure maps the current help context to an
196    /// optional hint string.
197    pub fn set_hint(&mut self, hint: impl Fn(HelpCtx) -> Option<String> + 'static) {
198        self.hint = Box::new(hint);
199    }
200
201    /// Builder-style [`set_hint`](Self::set_hint).
202    pub fn with_hint(mut self, hint: impl Fn(HelpCtx) -> Option<String> + 'static) -> Self {
203        self.set_hint(hint);
204        self
205    }
206
207    /// Scan `defs` and cache the index of the first def whose range matches the
208    /// current help context, or `None` if no def matches.
209    ///
210    /// Called automatically by [`new`](Self::new) and by
211    /// [`set_help_ctx`](Self::set_help_ctx) whenever the context changes.
212    /// You only need to call it directly if you modify [`defs`](StatusLine) in
213    /// place after construction.
214    pub fn find_items(&mut self) {
215        self.items_def = self
216            .defs
217            .iter()
218            .position(|d| d.range.matches(self.help_ctx));
219    }
220
221    /// Update the active help context and refresh the selected def.
222    ///
223    /// [`Program`](crate::app::Program) calls this on idle with the topmost
224    /// view's help context so the displayed items follow the focused view.
225    /// Idempotent: if `ctx` equals the current context the rescan is skipped.
226    ///
227    /// # Turbo Vision heritage
228    ///
229    /// Replaces `TStatusLine::update()`, which walked the view tree itself
230    /// (`TopView()`) to obtain the help context and then called `findItems` +
231    /// `drawView`. Here the `Program` idle loop resolves the context and passes
232    /// it in; the draw is handled by the framework's whole-tree redraw cycle.
233    pub fn set_help_ctx(&mut self, ctx: HelpCtx) {
234        if self.help_ctx == ctx {
235            return;
236        }
237        self.help_ctx = ctx;
238        self.find_items();
239    }
240
241    /// The items of the currently-selected def, or an empty slice if none is
242    /// selected.
243    fn items(&self) -> &[crate::status::StatusItem] {
244        match self.items_def {
245            Some(i) => &self.defs[i].items,
246            None => &[],
247        }
248    }
249
250    /// Whether `command` is enabled, per the cached disabled-set snapshot
251    /// (denylist: enabled iff NOT in the set). `None` (before the first broker
252    /// refresh) means **treat all as enabled** (the startup gap).
253    fn command_enabled(&self, command: crate::command::Command) -> bool {
254        !self
255            .disabled_cmds
256            .as_ref()
257            .is_some_and(|cs| cs.has(command))
258    }
259
260    /// The index of the item whose drawn span `[i, k)` contains the
261    /// **view-local** `mouse`, or `None`.
262    ///
263    /// A `mouse.y != 0` returns `None`; otherwise walk the selected def's items
264    /// accumulating the start `i` and end `k = i + width + 2` over the visible
265    /// items (a text-less item is **skipped** in the accumulator — it consumes no
266    /// width), and return the item whose `[i, k)` contains `mouse.x`.
267    fn item_mouse_is_in(&self, mouse: Point) -> Option<usize> {
268        if mouse.y != 0 {
269            return None;
270        }
271        let mut i = 0i32;
272        for (idx, item) in self.items().iter().enumerate() {
273            if let Some(text) = &item.text {
274                let k = i + cstrlen(text) + 2;
275                if mouse.x >= i && mouse.x < k {
276                    return Some(idx);
277                }
278                i = k;
279            }
280        }
281        None
282    }
283}
284
285impl View for StatusLine {
286    fn state(&self) -> &ViewState {
287        &self.state
288    }
289
290    fn state_mut(&mut self) -> &mut ViewState {
291        &mut self.state
292    }
293
294    /// Fill the row, then lay the selected def's visible items out left-to-right,
295    /// each with a leading + trailing space in the per-item style, then the hint
296    /// tail.
297    ///
298    /// The highlighted item is `pressed_item` — `None`
299    /// when no press-and-hold is in flight, or `Some(idx)` when the item at `idx`
300    /// is currently under the held button. The `(enabled, selected)` pair feeds
301    /// `StatusColors::item`, which selects the highlight styles for that item and
302    /// the normal styles for all others.
303    ///
304    /// `abs_origin` is cached here for the mouse-tracking capture.
305    fn draw(&mut self, ctx: &mut DrawCtx) {
306        // Cache the absolute origin for the mouse-tracking capture: the
307        // MouseTrackCapture converts abs mouse coords to view-local via this
308        // value.
309        self.abs_origin = ctx.origin();
310
311        let colors = StatusColors::resolve(ctx);
312        let size = self.state.size;
313
314        // Fill the whole row with the normal label style.
315        ctx.fill(Rect::new(0, 0, size.x, 1), ' ', colors.normal.0);
316
317        let mut i = 0i32;
318        for (idx, item) in self.items().iter().enumerate() {
319            // The `i += l + 2` advance is INSIDE the `Some(text)` arm, so a
320            // text-less item draws nothing AND consumes no width.
321            if let Some(text) = &item.text {
322                let l = cstrlen(text);
323                if i + l < size.x {
324                    let enabled = self.command_enabled(item.command);
325                    // selected = true iff this item is the one being held.
326                    let selected = self.pressed_item == Some(idx);
327                    let (lo, hi) = colors.item(enabled, selected);
328                    ctx.put_char(i, 0, ' ', lo);
329                    ctx.put_cstr(i + 1, 0, text, lo, hi);
330                    ctx.put_char(i + l + 1, 0, ' ', lo);
331                }
332                i += l + 2;
333            }
334        }
335
336        // Hint tail: if there is room (at least 2 columns left) and the hint
337        // provider returns a non-empty string, draw the separator then the
338        // clipped hint.
339        if i < size.x - 2
340            && let Some(text) = (self.hint)(self.help_ctx)
341            && !text.is_empty()
342        {
343            // Plain separator, in the normal label style.
344            ctx.put_str(i, 0, HINT_SEPARATOR, colors.normal.0);
345            i += 2;
346            // The hint text, clipped to the row: put_str already truncates at the
347            // clip right edge, so no explicit width arg is needed.
348            ctx.put_str(i, 0, &text, colors.normal.0);
349        }
350    }
351
352    /// Handle the status line's events.
353    ///
354    /// Branches:
355    ///
356    /// - **command-set-changed broadcast** → request the regray broker by the
357    ///   view's own id ([`Context::request_update_menu`] — the same menu pattern;
358    ///   reuses [`Deferred::UpdateMenu`](crate::view::Deferred::UpdateMenu) + the
359    ///   [`update_menu_commands`](View::update_menu_commands) hook). The whole-tree
360    ///   redraw makes any explicit repaint redundant.
361    /// - **mouse down** — the first step of the press-and-hold drag: hit-test the
362    ///   item, store as `pressed_item`, set
363    ///   `tracking = true`, arm [`TrackMask`]`{ mouse_move: true }`. Do NOT post
364    ///   yet.
365    /// - **mouse move** (guarded by `tracking`) — re-derive the item; update
366    ///   `pressed_item`. The next whole-tree redraw renders the new highlight.
367    /// - **mouse up** (guarded by `tracking`) — if `pressed_item` is Some and the
368    ///   command is enabled, post it. Clear `pressed_item` / `tracking`.
369    /// - **key down** — match the key against every item's accelerator (incl. the
370    ///   hidden text-less ones) and, if its command is enabled, transform the event
371    ///   into a command event in place so it propagates (see the module docs).
372    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
373        match ev {
374            // Command-set-changed broadcast: the regray runs through the broker — a
375            // child cannot read the command set inline, so request UpdateMenu by
376            // our own id; the pump calls back through View::update_menu_commands
377            // at apply time. No explicit repaint is needed (whole-tree redraw).
378            //
379            // The group fans broadcasts to EVERY child unconditionally, so no
380            // event-mask opt-in is needed (same as menu_view).
381            Event::Broadcast {
382                command: crate::command::Command::COMMAND_SET_CHANGED,
383                ..
384            } => {
385                if let Some(id) = self.state.id() {
386                    ctx.request_update_menu(id);
387                }
388            }
389
390            // Mouse down: the first step of the press-and-hold drag. Hit-test the
391            // item under the view-local mouse position, record it as
392            // `pressed_item`, and arm mouse-move tracking via the A3 seam. The
393            // command is NOT posted here — post waits until MouseUp.
394            Event::MouseDown(m) => {
395                self.pressed_item = self.item_mouse_is_in(m.position);
396                if let Some(id) = self.state.id() {
397                    self.tracking = true;
398                    ctx.start_mouse_track(
399                        id,
400                        self.abs_origin,
401                        TrackMask {
402                            mouse_move: true,
403                            ..Default::default()
404                        },
405                    );
406                } else {
407                    // Degenerate fallback: no ViewId — ids are stamped at
408                    // Group::insert, so this is test-only (an uninserted status
409                    // line). Posts ON DOWN, diverging from the release-confirm
410                    // semantics (the act-on-down fallback shared by
411                    // button/cluster/frame in B2 wave 1).
412                    if let Some(idx) = self.pressed_item {
413                        let cmd = self.items()[idx].command;
414                        if self.command_enabled(cmd) {
415                            ctx.post(cmd);
416                        }
417                    }
418                    self.pressed_item = None;
419                }
420                // The clear is load-bearing in BOTH branches: an uncleared
421                // MouseDown would fall through to normal positional routing and
422                // reach the status line a SECOND time via the root group,
423                // double-arming the capture.
424                ev.clear();
425            }
426
427            // Mouse move: re-derive the item under the view-local mouse (already
428            // localized by the capture) and update `pressed_item`. The next
429            // whole-tree redraw renders the highlight. Guarded by `tracking` —
430            // MouseMove is not mask-gated in Group::wants for untracked events.
431            Event::MouseMove(m) if self.tracking => {
432                self.pressed_item = self.item_mouse_is_in(m.position);
433                ev.clear();
434            }
435
436            // Mouse up: if the final item is present and its command is enabled,
437            // post the command; then clear. Guarded by `tracking` — MouseUp is not
438            // mask-gated in Group::wants.
439            Event::MouseUp(_) if self.tracking => {
440                self.tracking = false;
441                if let Some(idx) = self.pressed_item.take() {
442                    let cmd = self.items()[idx].command;
443                    if self.command_enabled(cmd) {
444                        ctx.post(cmd);
445                    }
446                }
447                ev.clear();
448            }
449
450            // Key down: match the key against EVERY item (incl. text-less hidden
451            // global hotkeys) and, if its command is enabled, TRANSFORM the event
452            // into a command event IN PLACE — no clear, no post. The program's
453            // pre-routing then lets the transformed command propagate to normal
454            // dispatch (posting + clearing here would double-handle). These
455            // transform-in-place-and-propagate semantics only make sense inside the
456            // pre-routing stage, which is why this arm landed with the program
457            // wiring step.
458            Event::KeyDown(k) => {
459                // Copy the key out so the `&mut ev` write below does not alias the
460                // `k: &mut KeyEvent` borrow.
461                let key = *k;
462                for item in self.items() {
463                    if item.key_code == Some(key) && self.command_enabled(item.command) {
464                        *ev = Event::Command(item.command);
465                        break;
466                    }
467                }
468            }
469            _ => {}
470        }
471    }
472
473    /// The command-graying broker hook (the same mechanism the menus use). The
474    /// pump calls this at apply time with the live **disabled-command set** (a
475    /// denylist) in hand; we snapshot it into
476    /// [`disabled_cmds`](StatusLine::disabled_cmds) so `draw` can gray disabled
477    /// items. (A status item has no per-item disabled flag, so enablement is
478    /// resolved against this cached snapshot rather than stored on the item.)
479    fn update_menu_commands(&mut self, disabled_cmds: &CommandSet) {
480        self.disabled_cmds = Some(disabled_cmds.clone());
481    }
482
483    /// Expose the concrete line so the pump / tests can introspect it (the cached
484    /// command-set snapshot the broker drives).
485    fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
486        Some(self)
487    }
488}
489
490impl StatusLine {
491    /// Read the cached **disabled**-command snapshot (test/inspection hook for
492    /// the broker-driven graying cache; a denylist).
493    pub fn disabled_cmds(&self) -> Option<&CommandSet> {
494        self.disabled_cmds.as_ref()
495    }
496
497    /// Read the currently-selected def index (test hook for `find_items`).
498    pub fn selected_def(&self) -> Option<usize> {
499        self.items_def
500    }
501}
502
503#[cfg(test)]
504mod tests {
505    use super::*;
506    use crate::backend::{HeadlessBackend, Renderer};
507    use crate::command::{Command, CommandSet};
508    use crate::event::{Event, Key, KeyEvent, MouseButtons, MouseEvent};
509    use crate::menu::alt;
510    use crate::screen::Buffer;
511    use crate::status::StatusDef;
512    use crate::theme::Theme;
513
514    fn f1() -> KeyEvent {
515        KeyEvent::from(Key::F(1))
516    }
517
518    /// A canonical default status line: Help, Exit, and a hidden Cut binding.
519    fn sample_defs() -> Vec<StatusDef> {
520        StatusDef::list()
521            .def_all(|d| {
522                d.item("~F1~ Help", f1(), Command::HELP)
523                    .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
524                    .key_item(KeyEvent::from(Key::F(10)), Command::MENU)
525            })
526            .build()
527    }
528
529    fn render(line: &mut StatusLine, w: u16, h: u16) -> String {
530        let theme = Theme::classic_blue();
531        let (backend, screen) = HeadlessBackend::new(w, h);
532        let mut r = Renderer::new(Box::new(backend));
533        r.render(|buf: &mut Buffer| {
534            let bounds = line.state().get_bounds();
535            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
536            line.draw(&mut dc);
537        });
538        screen.snapshot()
539    }
540
541    // -- ctor ---------------------------------------------------------------
542
543    #[test]
544    fn ctor_sets_grow_and_preprocess() {
545        let line = StatusLine::new(Rect::new(0, 24, 40, 25), sample_defs());
546        assert!(line.state.grow_mode.lo_y, "gfGrowLoY set");
547        assert!(line.state.grow_mode.hi_x, "gfGrowHiX set");
548        assert!(line.state.grow_mode.hi_y, "gfGrowHiY set");
549        assert!(line.state.options.pre_process, "ofPreProcess set");
550        // find_items ran in the ctor: the All def is selected.
551        assert_eq!(line.selected_def(), Some(0));
552        assert_eq!(line.help_ctx, HelpCtx::NO_CONTEXT);
553        assert!(line.disabled_cmds.is_none(), "no command set snapshot yet");
554    }
555
556    // -- find_items ---------------------------------------------------------
557
558    #[test]
559    fn find_items_all_matches_any_ctx() {
560        let mut line = StatusLine::new(Rect::new(0, 0, 40, 1), sample_defs());
561        assert_eq!(line.selected_def(), Some(0));
562        line.set_help_ctx(HelpCtx::custom("whatever.context"));
563        assert_eq!(line.selected_def(), Some(0), "All matches any context");
564    }
565
566    #[test]
567    fn find_items_first_match_wins_with_one_of_then_all() {
568        // [OneOf([a]), All]: ctx a -> def 0; ctx b -> def 1 (the All fallback).
569        let a = HelpCtx::custom("app.editor");
570        let b = HelpCtx::custom("app.browser");
571        let defs = StatusDef::list()
572            .def_one_of([a], |d| d.item("~F2~ Save", None, Command::SAVE))
573            .def_all(|d| d.item("~F1~ Help", f1(), Command::HELP))
574            .build();
575        let mut line = StatusLine::new(Rect::new(0, 0, 40, 1), defs);
576
577        line.set_help_ctx(a);
578        assert_eq!(line.selected_def(), Some(0), "ctx a selects the OneOf def");
579        line.set_help_ctx(b);
580        assert_eq!(
581            line.selected_def(),
582            Some(1),
583            "ctx b falls through to the All def"
584        );
585    }
586
587    #[test]
588    fn find_items_bite_all_first_captures_everything() {
589        // BITE: reorder so All is FIRST -> everything selects def 0 (the OneOf def
590        // is never reached). Proves first_match_wins is order-sensitive.
591        let a = HelpCtx::custom("app.editor");
592        let defs = StatusDef::list()
593            .def_all(|d| d.item("~F1~ Help", f1(), Command::HELP))
594            .def_one_of([a], |d| d.item("~F2~ Save", None, Command::SAVE))
595            .build();
596        let mut line = StatusLine::new(Rect::new(0, 0, 40, 1), defs);
597        line.set_help_ctx(a);
598        assert_eq!(
599            line.selected_def(),
600            Some(0),
601            "All first captures even ctx a"
602        );
603    }
604
605    #[test]
606    fn find_items_no_match_leaves_none() {
607        // A line with only a OneOf def and a non-member ctx -> no selection.
608        let a = HelpCtx::custom("app.editor");
609        let b = HelpCtx::custom("app.browser");
610        let defs = StatusDef::list()
611            .def_one_of([a], |d| d.item("~F2~ Save", None, Command::SAVE))
612            .build();
613        let mut line = StatusLine::new(Rect::new(0, 0, 40, 1), defs);
614        line.set_help_ctx(b);
615        assert_eq!(line.selected_def(), None, "no def matches -> items == 0");
616        // items() is then empty.
617        assert!(line.items().is_empty());
618    }
619
620    // -- item_mouse_is_in ---------------------------------------------------
621
622    #[test]
623    fn item_mouse_is_in_off_row_is_none() {
624        let line = StatusLine::new(Rect::new(0, 0, 40, 1), sample_defs());
625        // mouse.y != 0 -> None (off-row guard).
626        assert_eq!(line.item_mouse_is_in(Point::new(2, 1)), None);
627    }
628
629    #[test]
630    fn item_mouse_is_in_hits_correct_item_and_skips_textless() {
631        // Layout (cstrlen ignores ~):
632        //   "F1 Help"  cstrlen 7 -> [0, 9)   (idx 0)
633        //   "Alt-X Exit" cstrlen 10 -> [9, 21) (idx 1)
634        //   hidden Cut (text None) -> consumes NOTHING, span untouched (idx 2)
635        let line = StatusLine::new(Rect::new(0, 0, 40, 1), sample_defs());
636
637        assert_eq!(line.item_mouse_is_in(Point::new(0, 0)), Some(0));
638        assert_eq!(
639            line.item_mouse_is_in(Point::new(8, 0)),
640            Some(0),
641            "last col of item 0"
642        );
643        assert_eq!(
644            line.item_mouse_is_in(Point::new(9, 0)),
645            Some(1),
646            "first col of item 1"
647        );
648        assert_eq!(
649            line.item_mouse_is_in(Point::new(20, 0)),
650            Some(1),
651            "last col of item 1"
652        );
653        // BITE: the trailing space col of item 1 (col 20) maps to item 1, and a
654        // click past it (col 21) is in no item's span -> None (the hidden Cut
655        // binding does NOT occupy columns).
656        assert_eq!(
657            line.item_mouse_is_in(Point::new(21, 0)),
658            None,
659            "past last visible item"
660        );
661    }
662
663    #[test]
664    fn item_mouse_is_in_textless_neighbour_unaffected() {
665        // A textless item BETWEEN two visible items must not shift the second's
666        // span (its columns are unaffected — it consumes no width).
667        let defs = StatusDef::list()
668            .def_all(|d| {
669                d.item("AB", None, Command::HELP) // cstrlen 2 -> [0, 4)
670                    .key_item(f1(), Command::CUT) // hidden -> no width
671                    .item("CD", None, Command::QUIT) // cstrlen 2 -> [4, 8)
672            })
673            .build();
674        let line = StatusLine::new(Rect::new(0, 0, 40, 1), defs);
675        assert_eq!(line.item_mouse_is_in(Point::new(0, 0)), Some(0));
676        // Index 1 is the hidden item; the click at col 4 lands on the visible
677        // "CD" item (index 2), NOT the hidden index 1.
678        assert_eq!(line.item_mouse_is_in(Point::new(4, 0)), Some(2));
679        assert_eq!(line.item_mouse_is_in(Point::new(7, 0)), Some(2));
680    }
681
682    // -- command graying (broker hook) --------------------------------------
683
684    #[test]
685    fn update_menu_commands_snapshots_set() {
686        // The broker hook caches the live DISABLED set; command_enabled reads it.
687        let mut line = StatusLine::new(Rect::new(0, 0, 40, 1), sample_defs());
688        // Before any refresh, disabled_cmds is None -> everything is enabled.
689        assert!(line.disabled_cmds().is_none());
690        assert!(
691            line.command_enabled(Command::QUIT),
692            "None set -> all enabled"
693        );
694
695        // Snapshot a disabled set holding QUIT (HELP stays enabled).
696        let mut disabled = CommandSet::new();
697        disabled.insert(Command::QUIT);
698        line.update_menu_commands(&disabled);
699
700        assert!(line.disabled_cmds().is_some(), "broker hook cached the set");
701        assert!(
702            line.command_enabled(Command::HELP),
703            "HELP not in the disabled set -> enabled"
704        );
705        assert!(
706            !line.command_enabled(Command::QUIT),
707            "QUIT in the disabled set -> grayed"
708        );
709    }
710
711    #[test]
712    fn command_enabled_bite_without_refresh_stays_all_enabled() {
713        // BITE for the broker: without update_menu_commands the snapshot stays
714        // None and every command reads enabled (the startup gap menus share).
715        let line = StatusLine::new(Rect::new(0, 0, 40, 1), sample_defs());
716        assert!(line.disabled_cmds().is_none());
717        assert!(line.command_enabled(Command::QUIT));
718        assert!(line.command_enabled(Command::HELP));
719    }
720
721    // -- handle_event: broadcast arm ----------------------------------------
722
723    #[test]
724    fn broadcast_command_set_changed_requests_update_menu() {
725        use crate::view::{Context, Deferred};
726        use std::collections::VecDeque;
727
728        let mut line = StatusLine::new(Rect::new(0, 0, 40, 1), sample_defs());
729        // The view needs an id for request_update_menu to fire; stamp one as the
730        // group would.
731        let id = crate::view::ViewId::next();
732        line.state.id = Some(id);
733
734        let mut out = VecDeque::new();
735        let mut timers = crate::timer::TimerQueue::new();
736        let mut deferred = Vec::new();
737        let mut ev = Event::Broadcast {
738            command: Command::COMMAND_SET_CHANGED,
739            source: None,
740        };
741        {
742            let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
743            line.handle_event(&mut ev, &mut ctx);
744        }
745
746        assert!(
747            deferred
748                .iter()
749                .any(|d| matches!(d, Deferred::UpdateMenu(uid) if *uid == id)),
750            "cmCommandSetChanged requests UpdateMenu by the view's own id"
751        );
752    }
753
754    // -- handle_event: mouse arm --------------------------------------------
755    //
756    // The tracking arms (MouseMove, MouseUp) are driven directly with
757    // view-local positions — exactly as the pump's Deferred::MouseTrack apply
758    // arm does after the capture localizes them. The PushCapture path (the
759    // Deferred::PushCapture that start_mouse_track queues) is tested via the
760    // with_ctx_d helper and the integration test in program.rs wiring.
761
762    use crate::timer::TimerQueue;
763    use crate::view::{Context, Deferred};
764    use std::collections::VecDeque;
765
766    /// Run f with a fresh Context; return (out_events, deferred, return_value).
767    fn with_ctx_d<R>(
768        line: &mut StatusLine,
769        ev: &mut Event,
770        timers: &mut TimerQueue,
771        f: impl FnOnce(&mut StatusLine, &mut Event, &mut Context) -> R,
772    ) -> (Vec<Event>, Vec<Deferred>, R) {
773        let mut out = VecDeque::new();
774        let mut deferred: Vec<Deferred> = Vec::new();
775        let r = {
776            let mut ctx = Context::new(&mut out, timers, 0, &mut deferred);
777            f(line, ev, &mut ctx)
778        };
779        (out.into_iter().collect(), deferred, r)
780    }
781
782    fn mouse_down(x: i32, y: i32) -> Event {
783        Event::MouseDown(MouseEvent {
784            position: Point::new(x, y),
785            buttons: MouseButtons {
786                left: true,
787                ..Default::default()
788            },
789            ..Default::default()
790        })
791    }
792
793    fn mouse_move(x: i32, y: i32) -> Event {
794        Event::MouseMove(MouseEvent {
795            position: Point::new(x, y),
796            buttons: MouseButtons {
797                left: true,
798                ..Default::default()
799            },
800            ..Default::default()
801        })
802    }
803
804    fn mouse_up(x: i32, y: i32) -> Event {
805        Event::MouseUp(MouseEvent {
806            position: Point::new(x, y),
807            ..Default::default()
808        })
809    }
810
811    /// Stamp the view with a fresh id (like Group::insert would).
812    fn stamp_id(line: &mut StatusLine) -> crate::view::ViewId {
813        let id = crate::view::ViewId::next();
814        line.state.id = Some(id);
815        id
816    }
817
818    // Existing single-shot tests remain as coverage for the no-id degenerate
819    // fallback path (an uninserted status line, no ViewId -> immediate post).
820    // This path exists to preserve backward compatibility for unit tests that
821    // create a StatusLine without inserting it into a Group.
822
823    #[test]
824    fn mouse_down_on_enabled_item_posts_command_and_clears() {
825        // No id -> degenerate single-shot fallback: post immediately on MouseDown.
826        // Adapted from the old single-shot behavior; kept as coverage for the
827        // no-id path.  The real tracking path is tested in the `_with_id` tests
828        // below (post-on-release, sanctioned correction — same as cluster/button
829        // in wave 1).
830        let mut line = StatusLine::new(Rect::new(0, 0, 40, 1), sample_defs());
831        let mut timers = TimerQueue::new();
832        // Click inside "Alt-X Exit" (item 1, span [9, 21)) -> post QUIT immediately.
833        let mut ev = mouse_down(10, 0);
834        let (out, _deferred, ()) = with_ctx_d(&mut line, &mut ev, &mut timers, |l, e, ctx| {
835            l.handle_event(e, ctx)
836        });
837
838        assert!(ev.is_nothing(), "mouse-down is always cleared");
839        assert!(
840            out.iter()
841                .any(|e| matches!(e, Event::Command(Command::QUIT))),
842            "no-id path: enabled item posts immediately on MouseDown"
843        );
844    }
845
846    #[test]
847    fn mouse_down_on_disabled_item_clears_but_posts_nothing() {
848        let mut line = StatusLine::new(Rect::new(0, 0, 40, 1), sample_defs());
849        // Disable QUIT via the broker snapshot (the DISABLED set).
850        let mut disabled = CommandSet::new();
851        disabled.insert(Command::QUIT);
852        line.update_menu_commands(&disabled);
853
854        let mut timers = TimerQueue::new();
855        let mut ev = mouse_down(10, 0); // on the (disabled) Exit item
856        let (out, _deferred, ()) = with_ctx_d(&mut line, &mut ev, &mut timers, |l, e, ctx| {
857            l.handle_event(e, ctx)
858        });
859
860        assert!(ev.is_nothing(), "mouse-down is cleared even when disabled");
861        assert!(
862            !out.iter().any(|e| matches!(e, Event::Command(_))),
863            "a disabled item posts nothing (C++ commandEnabled guard)"
864        );
865    }
866
867    #[test]
868    fn mouse_down_off_row_clears_but_posts_nothing() {
869        let mut line = StatusLine::new(Rect::new(0, 0, 40, 1), sample_defs());
870        let mut timers = TimerQueue::new();
871        let mut ev = mouse_down(2, 1); // y != 0 -> no item hit
872        let (out, _deferred, ()) = with_ctx_d(&mut line, &mut ev, &mut timers, |l, e, ctx| {
873            l.handle_event(e, ctx)
874        });
875
876        assert!(ev.is_nothing());
877        assert!(!out.iter().any(|e| matches!(e, Event::Command(_))));
878    }
879
880    // -- mouse hold-tracking arm tests (the A3 seam — the real path) ----------
881    //
882    // These tests use a stamped id (as Group::insert would supply) so the
883    // MouseDown arm takes the real tracking path instead of the no-id fallback.
884    // Positions are view-local (as the capture localizes them).
885
886    /// Helper: a 40×1 status line with a stamped id, armed by a MouseDown on
887    /// "Alt-X Exit" (local col 10, span [9, 21)).  Returns the line + the
888    /// PushCapture deferred entry.
889    fn tracked_status_line() -> (StatusLine, crate::view::ViewId) {
890        let mut line = StatusLine::new(Rect::new(0, 0, 40, 1), sample_defs());
891        let id = stamp_id(&mut line);
892        let mut timers = TimerQueue::new();
893        let mut ev = mouse_down(10, 0); // inside "Alt-X Exit"
894        with_ctx_d(&mut line, &mut ev, &mut timers, |l, e, ctx| {
895            l.handle_event(e, ctx)
896        });
897        assert!(line.tracking, "MouseDown on an item arms tracking");
898        assert_eq!(
899            line.pressed_item,
900            Some(1),
901            "pressed_item = Alt-X Exit (idx 1)"
902        );
903        (line, id)
904    }
905
906    /// MouseDown on an item WITH an id: arms tracking (PushCapture deferred),
907    /// records pressed_item, does NOT post the command yet.
908    #[test]
909    fn mouse_down_with_id_arms_tracking_no_command() {
910        let mut line = StatusLine::new(Rect::new(0, 0, 40, 1), sample_defs());
911        let id = stamp_id(&mut line);
912        let mut timers = TimerQueue::new();
913        // Click inside "Alt-X Exit" (item 1, span [9, 21)).
914        let mut ev = mouse_down(10, 0);
915        let (out, deferred, ()) = with_ctx_d(&mut line, &mut ev, &mut timers, |l, e, ctx| {
916            l.handle_event(e, ctx)
917        });
918
919        assert!(ev.is_nothing(), "MouseDown is always cleared");
920        assert!(line.tracking, "tracking armed");
921        assert_eq!(
922            line.pressed_item,
923            Some(1),
924            "pressed_item set to the hit item index"
925        );
926        assert!(
927            out.is_empty(),
928            "command NOT posted at down time (post-on-release)"
929        );
930        // A PushCapture must have been deferred.
931        assert_eq!(deferred.len(), 1, "one PushCapture deferred");
932        assert!(
933            matches!(deferred[0], Deferred::PushCapture(_)),
934            "deferred[0] is PushCapture"
935        );
936        // The pushed capture's view() must return the status line's id.
937        if let Deferred::PushCapture(ref h) = deferred[0] {
938            assert_eq!(h.view(), Some(id), "capture tracks the status line's id");
939        }
940    }
941
942    /// MouseDown on NO item: tracking is armed (capture deferred), pressed_item
943    /// = None, no command posted.
944    #[test]
945    fn mouse_down_with_id_off_item_arms_tracking_no_pressed_item() {
946        let mut line = StatusLine::new(Rect::new(0, 0, 40, 1), sample_defs());
947        let _id = stamp_id(&mut line);
948        let mut timers = TimerQueue::new();
949        // Click past the last visible item (col 30) -> no hit.
950        let mut ev = mouse_down(30, 0);
951        let (out, deferred, ()) = with_ctx_d(&mut line, &mut ev, &mut timers, |l, e, ctx| {
952            l.handle_event(e, ctx)
953        });
954
955        assert!(ev.is_nothing());
956        assert!(
957            line.tracking,
958            "tracking armed even off items (mirrors C++ loop start)"
959        );
960        assert_eq!(line.pressed_item, None, "no item under the cursor");
961        assert!(out.is_empty(), "no command");
962        assert_eq!(deferred.len(), 1, "PushCapture still deferred");
963    }
964
965    /// MouseMove while tracking re-derives the item: move off item → pressed_item
966    /// becomes None; move back on → Some again.
967    #[test]
968    fn track_move_updates_pressed_item() {
969        let (mut line, _id) = tracked_status_line();
970        let mut timers = TimerQueue::new();
971
972        // Move off all items (col 30, past "Alt-X Exit" span [9, 21)).
973        let mut ev = mouse_move(30, 0);
974        let (out, deferred, ()) = with_ctx_d(&mut line, &mut ev, &mut timers, |l, e, ctx| {
975            l.handle_event(e, ctx)
976        });
977        assert!(ev.is_nothing(), "tracked move is consumed");
978        assert!(deferred.is_empty());
979        assert!(out.is_empty());
980        assert_eq!(
981            line.pressed_item, None,
982            "off items -> pressed_item = None (C++ drawSelect(0))"
983        );
984
985        // Move back onto "F1 Help" (item 0, span [0, 9)).
986        let mut ev = mouse_move(4, 0);
987        let (_, _, ()) = with_ctx_d(&mut line, &mut ev, &mut timers, |l, e, ctx| {
988            l.handle_event(e, ctx)
989        });
990        assert_eq!(
991            line.pressed_item,
992            Some(0),
993            "moved to item 0 -> pressed_item updated"
994        );
995        assert!(line.tracking, "still tracking");
996    }
997
998    /// Untracked MouseMove (tracking == false) falls through without updating
999    /// pressed_item.
1000    #[test]
1001    fn untracked_move_falls_through() {
1002        let mut line = StatusLine::new(Rect::new(0, 0, 40, 1), sample_defs());
1003        let mut timers = TimerQueue::new();
1004        let mut ev = mouse_move(4, 0);
1005        let (out, _, ()) = with_ctx_d(&mut line, &mut ev, &mut timers, |l, e, ctx| {
1006            l.handle_event(e, ctx)
1007        });
1008        // Event is not consumed (falls through to the _ arm).
1009        assert!(!ev.is_nothing(), "untracked move is not consumed");
1010        assert!(out.is_empty());
1011    }
1012
1013    /// MouseUp while tracking with a valid pressed_item fires the command.
1014    #[test]
1015    fn track_release_on_item_fires_command() {
1016        let (mut line, _id) = tracked_status_line();
1017        let mut timers = TimerQueue::new();
1018
1019        let mut ev = mouse_up(10, 0); // still on "Alt-X Exit"
1020        let (out, deferred, ()) = with_ctx_d(&mut line, &mut ev, &mut timers, |l, e, ctx| {
1021            l.handle_event(e, ctx)
1022        });
1023
1024        assert!(ev.is_nothing(), "tracked MouseUp is consumed");
1025        assert!(!line.tracking, "tracking cleared on MouseUp");
1026        assert_eq!(line.pressed_item, None, "pressed_item cleared on MouseUp");
1027        assert!(deferred.is_empty());
1028        assert!(
1029            out.iter()
1030                .any(|e| matches!(e, Event::Command(Command::QUIT))),
1031            "enabled item fires its command on release"
1032        );
1033    }
1034
1035    /// MouseUp while tracking with pressed_item = None (cursor was off all items
1036    /// when released) does NOT fire any command.
1037    #[test]
1038    fn track_release_off_item_fires_nothing() {
1039        let (mut line, _id) = tracked_status_line();
1040        let mut timers = TimerQueue::new();
1041
1042        // First move off items so pressed_item = None.
1043        let mut ev = mouse_move(30, 0);
1044        with_ctx_d(&mut line, &mut ev, &mut timers, |l, e, ctx| {
1045            l.handle_event(e, ctx)
1046        });
1047        assert_eq!(line.pressed_item, None);
1048
1049        // Release while off items.
1050        let mut ev = mouse_up(30, 0);
1051        let (out, _, ()) = with_ctx_d(&mut line, &mut ev, &mut timers, |l, e, ctx| {
1052            l.handle_event(e, ctx)
1053        });
1054
1055        assert!(ev.is_nothing(), "tracked up is consumed even with no item");
1056        assert!(!line.tracking);
1057        assert!(out.is_empty(), "no command when off items");
1058    }
1059
1060    /// MouseUp while tracking with a DISABLED pressed_item does NOT fire the
1061    /// command (the release path checks command enablement first).
1062    #[test]
1063    fn track_release_on_disabled_item_fires_nothing() {
1064        let (mut line, _id) = tracked_status_line();
1065        // Disable QUIT (the pressed item's command).
1066        let mut disabled = CommandSet::new();
1067        disabled.insert(Command::QUIT);
1068        line.update_menu_commands(&disabled);
1069
1070        let mut timers = TimerQueue::new();
1071        let mut ev = mouse_up(10, 0);
1072        let (out, _, ()) = with_ctx_d(&mut line, &mut ev, &mut timers, |l, e, ctx| {
1073            l.handle_event(e, ctx)
1074        });
1075
1076        assert!(ev.is_nothing(), "tracked up is consumed");
1077        assert!(!line.tracking);
1078        assert!(
1079            out.is_empty(),
1080            "disabled item fires nothing on release (commandEnabled guard)"
1081        );
1082    }
1083
1084    /// A stray MouseUp with no tracking in flight falls through untouched.
1085    #[test]
1086    fn stray_mouse_up_without_tracking_is_ignored() {
1087        let mut line = StatusLine::new(Rect::new(0, 0, 40, 1), sample_defs());
1088        let mut timers = TimerQueue::new();
1089        let mut ev = mouse_up(10, 0);
1090        let (out, _, ()) = with_ctx_d(&mut line, &mut ev, &mut timers, |l, e, ctx| {
1091            l.handle_event(e, ctx)
1092        });
1093
1094        assert!(!ev.is_nothing(), "stray up is not consumed");
1095        assert!(out.is_empty());
1096        assert!(!line.tracking);
1097    }
1098
1099    // -- draw snapshots -----------------------------------------------------
1100
1101    #[test]
1102    fn snapshot_normal_with_disabled_item() {
1103        // Two visible items + a hidden Cut binding; QUIT disabled (grayed) via the
1104        // broker snapshot. Proves the color matrix and the `i += l + 2` layout
1105        // (the hidden item adds nothing).
1106        let mut line = StatusLine::new(Rect::new(0, 0, 40, 1), sample_defs());
1107        let mut disabled = CommandSet::new();
1108        disabled.insert(Command::QUIT);
1109        line.update_menu_commands(&disabled);
1110        insta::assert_snapshot!(render(&mut line, 40, 1));
1111    }
1112
1113    #[test]
1114    fn snapshot_with_hint_tail() {
1115        // A hint closure returning text -> proves the hint tail (separator +
1116        // clipped hint), with `i < size.x - 2` true.
1117        let defs = StatusDef::list()
1118            .def_all(|d| d.item("~F1~ Help", f1(), Command::HELP))
1119            .build();
1120        let mut line = StatusLine::new(Rect::new(0, 0, 40, 1), defs)
1121            .with_hint(|_| Some("Press F1 for help".to_string()));
1122        insta::assert_snapshot!(render(&mut line, 40, 1));
1123    }
1124
1125    #[test]
1126    fn empty_hint_string_draws_no_separator() {
1127        // A hint closure returning Some("") must render NOTHING extra — an empty
1128        // hint is skipped, so no separator is drawn.
1129        // BITE: deleting the `!text.is_empty()` guard in `draw` would draw the
1130        // `│ ` separator for the empty hint, making this render differ from the
1131        // None-hint render. We assert they are byte-identical.
1132        let defs = StatusDef::list()
1133            .def_all(|d| d.item("~F1~ Help", f1(), Command::HELP))
1134            .build();
1135        let mut empty_hint = StatusLine::new(Rect::new(0, 0, 40, 1), defs.clone())
1136            .with_hint(|_| Some(String::new()));
1137        let mut none_hint = StatusLine::new(Rect::new(0, 0, 40, 1), defs).with_hint(|_| None);
1138        assert_eq!(
1139            render(&mut empty_hint, 40, 1),
1140            render(&mut none_hint, 40, 1),
1141            "an empty hint string draws no separator (C++ if(hintText.size()))"
1142        );
1143    }
1144
1145    #[test]
1146    fn snapshot_narrow_drops_overflowing_item() {
1147        // Width 8: "F1 Help" cstrlen 7, i=0 -> 0+7 < 8 true (drawn). i becomes 9;
1148        // "Alt-X Exit" -> 9+10 < 8 FALSE, not drawn (the clip-skip branch), and
1149        // there is no room for a hint (i=9, size.x-2=6). Exercises the clipped
1150        // path the wide line never hits.
1151        let mut line = StatusLine::new(Rect::new(0, 0, 8, 1), sample_defs());
1152        insta::assert_snapshot!(render(&mut line, 8, 1));
1153    }
1154
1155    #[test]
1156    fn snapshot_textless_item_draws_nothing() {
1157        // A line whose only items are a hidden binding then a visible one: the
1158        // hidden item must add no width, so the visible item starts at column 0.
1159        let defs = StatusDef::list()
1160            .def_all(|d| {
1161                d.key_item(f1(), Command::CUT) // hidden
1162                    .item("Visible", None, Command::HELP)
1163            })
1164            .build();
1165        let mut line = StatusLine::new(Rect::new(0, 0, 40, 1), defs);
1166        insta::assert_snapshot!(render(&mut line, 40, 1));
1167    }
1168
1169    /// Drag-highlight snapshot: with `pressed_item = Some(1)` (the "Alt-X Exit"
1170    /// item held), `draw` renders that item with the select/sel-disabled pair and
1171    /// all others with the normal/norm-disabled pair.
1172    ///
1173    /// Item 1 is drawn with `colors.select` (the "held" look), item 0 with
1174    /// `colors.normal`. The snapshot freezes the selected style for regression
1175    /// protection; hand-verify that item 1 appears visually distinct from item 0.
1176    #[test]
1177    fn snapshot_drag_highlight_held_item() {
1178        let mut line = StatusLine::new(Rect::new(0, 0, 40, 1), sample_defs());
1179        // Simulate a hold on "Alt-X Exit" (item 1) as if MouseDown was processed
1180        // and pressed_item was set. No actual event dispatch needed — draw reads
1181        // pressed_item directly.
1182        line.pressed_item = Some(1);
1183        insta::assert_snapshot!(render(&mut line, 40, 1));
1184    }
1185
1186    /// Drag-highlight with a DISABLED held item: when the pressed item's command
1187    /// is disabled, `draw` uses the selected-disabled pair for that item, not the
1188    /// plain select pair.
1189    #[test]
1190    fn snapshot_drag_highlight_held_disabled_item() {
1191        let mut line = StatusLine::new(Rect::new(0, 0, 40, 1), sample_defs());
1192        // Disable QUIT (item 1's command) so colors.item(false, true) = sel_disabled.
1193        let mut disabled = CommandSet::new();
1194        disabled.insert(Command::QUIT);
1195        line.update_menu_commands(&disabled);
1196        line.pressed_item = Some(1);
1197        insta::assert_snapshot!(render(&mut line, 40, 1));
1198    }
1199}