Skip to main content

ftui_widgets/
help.rs

1//! Help widget for displaying keybinding lists.
2//!
3//! Renders a styled list of key/description pairs for showing available
4//! keyboard shortcuts in a TUI application.
5//!
6//! # Example
7//!
8//! ```
9//! use ftui_widgets::help::{Help, HelpEntry};
10//!
11//! let help = Help::new()
12//!     .entry("q", "quit")
13//!     .entry("^s", "save")
14//!     .entry("?", "toggle help");
15//!
16//! assert_eq!(help.entries().len(), 3);
17//! ```
18
19use crate::hint_ranker::{HintContext, HintRanker, RankingEvidence};
20use crate::{StatefulWidget, Widget, clear_text_area, draw_text_span};
21use ftui_core::geometry::Rect;
22use ftui_core::keybinding::{ContextId, KeyMap};
23use ftui_render::budget::DegradationLevel;
24use ftui_render::buffer::Buffer;
25use ftui_render::cell::{Cell, PackedRgba};
26use ftui_render::frame::Frame;
27use ftui_style::Style;
28use ftui_style::StyleFlags;
29use ftui_text::wrap::display_width;
30use std::hash::{Hash, Hasher};
31
32/// Category for organizing help entries into logical groups.
33#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
34pub enum HelpCategory {
35    /// General/uncategorized keybinding.
36    #[default]
37    General,
38    /// Navigation keys (arrows, page up/down, home/end, etc.).
39    Navigation,
40    /// Editing actions (cut, copy, paste, undo, redo, etc.).
41    Editing,
42    /// File operations (save, open, close, new, etc.).
43    File,
44    /// View/display controls (zoom, scroll, toggle panels, etc.).
45    View,
46    /// Application-level shortcuts (quit, settings, help, etc.).
47    Global,
48    /// Custom category with a user-defined label.
49    Custom(String),
50}
51
52impl HelpCategory {
53    /// Return a display label for this category.
54    #[must_use]
55    pub fn label(&self) -> &str {
56        match self {
57            Self::General => "General",
58            Self::Navigation => "Navigation",
59            Self::Editing => "Editing",
60            Self::File => "File",
61            Self::View => "View",
62            Self::Global => "Global",
63            Self::Custom(s) => s,
64        }
65    }
66}
67
68/// A single keybinding entry in the help view.
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct HelpEntry {
71    /// The key or key combination (e.g. "^C", "↑/k").
72    pub key: String,
73    /// Description of what the key does.
74    pub desc: String,
75    /// Whether this entry is enabled (disabled entries are hidden).
76    pub enabled: bool,
77    /// Category for grouping related entries.
78    pub category: HelpCategory,
79}
80
81impl HelpEntry {
82    /// Create a new enabled help entry.
83    #[must_use]
84    pub fn new(key: impl Into<String>, desc: impl Into<String>) -> Self {
85        Self {
86            key: key.into(),
87            desc: desc.into(),
88            enabled: true,
89            category: HelpCategory::default(),
90        }
91    }
92
93    /// Set whether this entry is enabled.
94    #[must_use]
95    pub fn with_enabled(mut self, enabled: bool) -> Self {
96        self.enabled = enabled;
97        self
98    }
99
100    /// Set the category for this entry.
101    #[must_use]
102    pub fn with_category(mut self, category: HelpCategory) -> Self {
103        self.category = category;
104        self
105    }
106}
107
108/// Display mode for the help widget.
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
110pub enum HelpMode {
111    /// Short inline mode: entries separated by a bullet on one line.
112    #[default]
113    Short,
114    /// Full mode: entries stacked vertically with aligned columns.
115    Full,
116}
117
118/// Help widget that renders keybinding entries.
119///
120/// In [`HelpMode::Short`] mode, entries are shown inline separated by a bullet
121/// character, truncated with an ellipsis if they exceed the available width.
122///
123/// In [`HelpMode::Full`] mode, entries are rendered in a vertical list with
124/// keys and descriptions in aligned columns.
125#[derive(Debug, Clone)]
126pub struct Help {
127    entries: Vec<HelpEntry>,
128    mode: HelpMode,
129    /// Separator between entries in short mode.
130    separator: String,
131    /// Ellipsis shown when truncated.
132    ellipsis: String,
133    /// Style for key text.
134    key_style: Style,
135    /// Style for description text.
136    desc_style: Style,
137    /// Style for separator/ellipsis.
138    separator_style: Style,
139    /// Hint ids assigned by [`Help::register_with_ranker`], parallel to
140    /// `entries`; empty until a ranker has been attached.
141    hint_ids: Vec<usize>,
142}
143
144/// Cached render state for [`Help`], enabling incremental layout reuse and
145/// dirty-rect updates for keybinding hint panels.
146///
147/// # Invariants
148/// - Layout is reused only when entry count and slot widths remain compatible.
149/// - Dirty rects always cover the full prior slot width for changed entries.
150/// - Layout rebuilds on any change that could cause reflow.
151///
152/// # Failure Modes
153/// - If a changed entry exceeds its cached slot width, we rebuild the layout.
154/// - If enabled entry count changes, we rebuild the layout.
155#[derive(Debug, Default)]
156pub struct HelpRenderState {
157    cache: Option<HelpCache>,
158    enabled_indices: Vec<usize>,
159    dirty_indices: Vec<usize>,
160    dirty_rects: Vec<Rect>,
161    stats: HelpCacheStats,
162}
163
164/// Cache hit/miss statistics for [`HelpRenderState`].
165#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
166pub struct HelpCacheStats {
167    pub hits: u64,
168    pub misses: u64,
169    pub dirty_updates: u64,
170    pub layout_rebuilds: u64,
171}
172
173impl HelpRenderState {
174    /// Return cache statistics.
175    #[must_use]
176    pub fn stats(&self) -> HelpCacheStats {
177        self.stats
178    }
179
180    /// Clear recorded dirty rects.
181    pub fn clear_dirty_rects(&mut self) {
182        self.dirty_rects.clear();
183    }
184
185    /// Take dirty rects for logging/inspection.
186    #[must_use]
187    pub fn take_dirty_rects(&mut self) -> Vec<Rect> {
188        std::mem::take(&mut self.dirty_rects)
189    }
190
191    /// Read dirty rects without clearing.
192    #[must_use]
193    pub fn dirty_rects(&self) -> &[Rect] {
194        &self.dirty_rects
195    }
196
197    /// Reset cache stats (useful for perf logging).
198    pub fn reset_stats(&mut self) {
199        self.stats = HelpCacheStats::default();
200    }
201}
202
203#[derive(Debug)]
204struct HelpCache {
205    buffer: Buffer,
206    layout: HelpLayout,
207    key: LayoutKey,
208    entry_hashes: Vec<u64>,
209    enabled_count: usize,
210}
211
212#[derive(Debug, Clone)]
213struct HelpLayout {
214    mode: HelpMode,
215    width: u16,
216    entries: Vec<EntrySlot>,
217    ellipsis: Option<EllipsisSlot>,
218    max_key_width: usize,
219    separator_width: usize,
220}
221
222#[derive(Debug, Clone)]
223struct EntrySlot {
224    x: u16,
225    y: u16,
226    width: u16,
227    key_width: usize,
228}
229
230#[derive(Debug, Clone)]
231struct EllipsisSlot {
232    x: u16,
233    width: u16,
234    prefix_space: bool,
235}
236
237#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
238struct StyleKey {
239    fg: Option<PackedRgba>,
240    bg: Option<PackedRgba>,
241    attrs: Option<StyleFlags>,
242}
243
244impl From<Style> for StyleKey {
245    fn from(style: Style) -> Self {
246        Self {
247            fg: style.fg,
248            bg: style.bg,
249            attrs: style.attrs,
250        }
251    }
252}
253
254#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
255struct LayoutKey {
256    mode: HelpMode,
257    width: u16,
258    height: u16,
259    separator_hash: u64,
260    ellipsis_hash: u64,
261    key_style: StyleKey,
262    desc_style: StyleKey,
263    separator_style: StyleKey,
264    degradation: DegradationLevel,
265}
266
267impl Default for Help {
268    fn default() -> Self {
269        Self::new()
270    }
271}
272
273impl Help {
274    /// Create a new help widget with no entries.
275    #[must_use]
276    pub fn new() -> Self {
277        Self {
278            entries: Vec::new(),
279            mode: HelpMode::Short,
280            separator: " • ".to_string(),
281            ellipsis: "…".to_string(),
282            key_style: Style::new().bold(),
283            desc_style: Style::default(),
284            separator_style: Style::default(),
285            hint_ids: Vec::new(),
286        }
287    }
288
289    /// Build a help bar from a [`KeyMap`]: one entry per labelled binding
290    /// that wins under `active` contexts (shadowed bindings are left out),
291    /// with the chord's display text as the key and the label as the
292    /// description. Unlabelled bindings have nothing to say and are skipped.
293    ///
294    /// Entries keep bind order; attach a ranker with
295    /// [`Help::register_with_ranker`] and feed dispatched chords back through
296    /// [`Help::record_used`] with `chord.to_string()` to reorder by use.
297    #[must_use]
298    pub fn from_keymap<A>(map: &KeyMap<A>, active: &[ContextId]) -> Self {
299        let mut help = Self::new();
300        for binding in map.bindings() {
301            let Some(label) = binding.label.as_deref() else {
302                continue;
303            };
304            let wins = map
305                .lookup(&binding.chord, active)
306                .exact
307                .is_some_and(|winner| winner.id == binding.id);
308            if wins {
309                help.entries
310                    .push(HelpEntry::new(binding.chord.to_string(), label));
311            }
312        }
313        help
314    }
315
316    /// Register every entry with a [`HintRanker`] so the widget can be
317    /// reordered by learned utility (see [`Help::apply_ranking`]).
318    ///
319    /// Each entry becomes one ranker hint whose display cost is the width of
320    /// `"key desc"` in columns; the returned ids are in entry order, so callers
321    /// can feed usage back with [`HintRanker::record_usage`] when a shortcut is
322    /// pressed. Call this once after the entries are final; adding entries
323    /// afterwards requires registering again.
324    pub fn register_with_ranker(
325        &mut self,
326        ranker: &mut HintRanker,
327        context: HintContext,
328    ) -> Vec<usize> {
329        self.hint_ids = self
330            .entries
331            .iter()
332            .map(|entry| {
333                let cost = (display_width(&entry.key) + 1 + display_width(&entry.desc)) as f64;
334                ranker.register(
335                    format!("{} {}", entry.key, entry.desc),
336                    cost,
337                    context.clone(),
338                    0,
339                )
340            })
341            .collect();
342        self.hint_ids.clone()
343    }
344
345    /// Hint id of the entry at `index`, once registered with a ranker.
346    #[must_use]
347    pub fn hint_id(&self, index: usize) -> Option<usize> {
348        self.hint_ids.get(index).copied()
349    }
350
351    /// Reorder the entries by the ranker's current utility ordering.
352    ///
353    /// The ranker decides (expected utility, a value-of-information
354    /// exploration bonus, display cost, and a hysteresis margin that stops
355    /// near-ties from flickering); this method only applies the order. Entries
356    /// the ranker did not rank (for example filtered out by `context_key`)
357    /// keep their relative order after the ranked ones. Returns the ranker's
358    /// evidence ledger so callers can log why the hints are ordered this way.
359    /// Does nothing if the entries were never registered or changed since.
360    pub fn apply_ranking(
361        &mut self,
362        ranker: &mut HintRanker,
363        context_key: Option<&str>,
364    ) -> Vec<RankingEvidence> {
365        if self.hint_ids.len() != self.entries.len() || self.entries.is_empty() {
366            return Vec::new();
367        }
368        let (order, ledger) = ranker.rank(context_key);
369        let position = |hint_id: usize| order.iter().position(|id| *id == hint_id);
370        let mut indexed: Vec<(usize, usize)> = (0..self.entries.len())
371            .map(|index| (index, position(self.hint_ids[index]).unwrap_or(usize::MAX)))
372            .collect();
373        // Stable sort: unranked entries (usize::MAX) keep their relative order.
374        indexed.sort_by_key(|(_, rank)| *rank);
375        let entries = std::mem::take(&mut self.entries);
376        let hint_ids = std::mem::take(&mut self.hint_ids);
377        let mut old_entries: Vec<Option<HelpEntry>> = entries.into_iter().map(Some).collect();
378        for (index, _) in &indexed {
379            self.entries
380                .push(old_entries[*index].take().expect("entry moved once"));
381            self.hint_ids.push(hint_ids[*index]);
382        }
383        ledger
384    }
385
386    /// Record that the shortcut labelled `key` was pressed.
387    ///
388    /// Looks the entry up by its key label, records a use for its hint and
389    /// returns `true` when the key belongs to a registered entry. Call it
390    /// from `update()` when a bound key fires; the next
391    /// [`Help::apply_ranking`] moves frequently used shortcuts forward.
392    pub fn record_used(&self, ranker: &mut HintRanker, key: &str) -> bool {
393        let Some(index) = self.entries.iter().position(|entry| entry.key == key) else {
394            return false;
395        };
396        match self.hint_ids.get(index) {
397            Some(&id) => {
398                ranker.record_usage(id);
399                true
400            }
401            None => false,
402        }
403    }
404
405    /// Record that the entries were displayed without being used.
406    ///
407    /// Call once per interaction round for every registered entry except the
408    /// one that was used (`except_key`); the ranker treats it as negative
409    /// evidence, so hints nobody acts on drift to the end of the bar.
410    pub fn record_shown(&self, ranker: &mut HintRanker, except_key: Option<&str>) {
411        for (entry, &id) in self.entries.iter().zip(&self.hint_ids) {
412            if except_key.is_some_and(|key| key == entry.key) {
413                continue;
414            }
415            ranker.record_shown_not_used(id);
416        }
417    }
418
419    /// Add an entry to the help widget.
420    #[must_use]
421    pub fn entry(mut self, key: impl Into<String>, desc: impl Into<String>) -> Self {
422        self.entries.push(HelpEntry::new(key, desc));
423        self
424    }
425
426    /// Add a pre-built entry.
427    #[must_use]
428    pub fn with_entry(mut self, entry: HelpEntry) -> Self {
429        self.entries.push(entry);
430        self
431    }
432
433    /// Set all entries at once.
434    #[must_use]
435    pub fn with_entries(mut self, entries: Vec<HelpEntry>) -> Self {
436        self.entries = entries;
437        self
438    }
439
440    /// Set the display mode.
441    #[must_use]
442    pub fn with_mode(mut self, mode: HelpMode) -> Self {
443        self.mode = mode;
444        self
445    }
446
447    /// Set the separator used between entries in short mode.
448    #[must_use]
449    pub fn with_separator(mut self, sep: impl Into<String>) -> Self {
450        self.separator = sep.into();
451        self
452    }
453
454    /// Set the ellipsis string.
455    #[must_use]
456    pub fn with_ellipsis(mut self, ellipsis: impl Into<String>) -> Self {
457        self.ellipsis = ellipsis.into();
458        self
459    }
460
461    /// Set the style for key text.
462    #[must_use]
463    pub fn with_key_style(mut self, style: Style) -> Self {
464        self.key_style = style;
465        self
466    }
467
468    /// Set the style for description text.
469    #[must_use]
470    pub fn with_desc_style(mut self, style: Style) -> Self {
471        self.desc_style = style;
472        self
473    }
474
475    /// Set the style for separators and ellipsis.
476    #[must_use]
477    pub fn with_separator_style(mut self, style: Style) -> Self {
478        self.separator_style = style;
479        self
480    }
481
482    /// Get the entries.
483    #[must_use]
484    pub fn entries(&self) -> &[HelpEntry] {
485        &self.entries
486    }
487
488    /// Get the current mode.
489    #[must_use]
490    pub fn mode(&self) -> HelpMode {
491        self.mode
492    }
493
494    /// Toggle between short and full mode.
495    pub fn toggle_mode(&mut self) {
496        self.mode = match self.mode {
497            HelpMode::Short => HelpMode::Full,
498            HelpMode::Full => HelpMode::Short,
499        };
500    }
501
502    /// Add an entry mutably.
503    pub fn push_entry(&mut self, entry: HelpEntry) {
504        self.entries.push(entry);
505    }
506
507    /// Collect the enabled entries.
508    fn enabled_entries(&self) -> Vec<&HelpEntry> {
509        self.entries.iter().filter(|e| e.enabled).collect()
510    }
511
512    /// Render short mode: entries inline on one line.
513    fn render_short(&self, area: Rect, frame: &mut Frame) {
514        let entries = self.enabled_entries();
515        if entries.is_empty() || area.width == 0 || area.height == 0 {
516            return;
517        }
518
519        let deg = frame.buffer.degradation;
520        let sep_width = display_width(&self.separator);
521        let ellipsis_width = display_width(&self.ellipsis);
522        let max_x = area.right();
523        let y = area.y;
524        let mut x = area.x;
525
526        for (i, entry) in entries.iter().enumerate() {
527            if entry.key.is_empty() && entry.desc.is_empty() {
528                continue;
529            }
530
531            // Separator before non-first items
532            let sep_w = if i > 0 { sep_width } else { 0 };
533
534            // Calculate item width: key + " " + desc
535            let key_w = display_width(&entry.key);
536            let desc_w = display_width(&entry.desc);
537            let item_w = key_w + 1 + desc_w;
538            let total_item_w = sep_w + item_w;
539
540            // Check if this item fits, accounting for possible ellipsis
541            let space_left = (max_x as usize).saturating_sub(x as usize);
542            if total_item_w > space_left {
543                // Try to fit ellipsis
544                let ell_total = if i > 0 {
545                    1 + ellipsis_width
546                } else {
547                    ellipsis_width
548                };
549                if ell_total <= space_left {
550                    let ellipsis_style = if deg.apply_styling() {
551                        self.separator_style
552                    } else {
553                        Style::default()
554                    };
555                    if i > 0 {
556                        x = draw_text_span(frame, x, y, " ", ellipsis_style, max_x);
557                    }
558                    draw_text_span(frame, x, y, &self.ellipsis, ellipsis_style, max_x);
559                }
560                break;
561            }
562
563            // Draw separator
564            if i > 0 {
565                if deg.apply_styling() {
566                    x = draw_text_span(frame, x, y, &self.separator, self.separator_style, max_x);
567                } else {
568                    x = draw_text_span(frame, x, y, &self.separator, Style::default(), max_x);
569                }
570            }
571
572            // Draw key
573            if deg.apply_styling() {
574                x = draw_text_span(frame, x, y, &entry.key, self.key_style, max_x);
575                x = draw_text_span(frame, x, y, " ", self.desc_style, max_x);
576                x = draw_text_span(frame, x, y, &entry.desc, self.desc_style, max_x);
577            } else {
578                let text = format!("{} {}", entry.key, entry.desc);
579                x = draw_text_span(frame, x, y, &text, Style::default(), max_x);
580            }
581        }
582    }
583
584    /// Render full mode: entries stacked vertically with aligned columns.
585    fn render_full(&self, area: Rect, frame: &mut Frame) {
586        let entries = self.enabled_entries();
587        if entries.is_empty() || area.width == 0 || area.height == 0 {
588            return;
589        }
590
591        let deg = frame.buffer.degradation;
592
593        // Find max key width for alignment
594        let max_key_w = entries
595            .iter()
596            .filter(|e| !e.key.is_empty() || !e.desc.is_empty())
597            .map(|e| display_width(&e.key))
598            .max()
599            .unwrap_or(0);
600
601        let max_x = area.right();
602        let mut row: u16 = 0;
603        let key_style = if deg.apply_styling() {
604            self.key_style
605        } else {
606            Style::default()
607        };
608        let desc_style = if deg.apply_styling() {
609            self.desc_style
610        } else {
611            Style::default()
612        };
613
614        for entry in &entries {
615            if entry.key.is_empty() && entry.desc.is_empty() {
616                continue;
617            }
618            if row >= area.height {
619                break;
620            }
621
622            let y = area.y.saturating_add(row);
623            let mut x = area.x;
624            let key_w = display_width(&entry.key);
625            x = draw_text_span(frame, x, y, &entry.key, key_style, max_x);
626            let pad = max_key_w.saturating_sub(key_w);
627            for _ in 0..pad {
628                x = draw_text_span(frame, x, y, " ", Style::default(), max_x);
629            }
630            x = draw_text_span(frame, x, y, "  ", Style::default(), max_x);
631            draw_text_span(frame, x, y, &entry.desc, desc_style, max_x);
632
633            row += 1;
634        }
635    }
636
637    fn entry_hash(entry: &HelpEntry) -> u64 {
638        let mut hasher = std::collections::hash_map::DefaultHasher::new();
639        entry.key.hash(&mut hasher);
640        entry.desc.hash(&mut hasher);
641        entry.enabled.hash(&mut hasher);
642        entry.category.hash(&mut hasher);
643        hasher.finish()
644    }
645
646    fn hash_str(value: &str) -> u64 {
647        let mut hasher = std::collections::hash_map::DefaultHasher::new();
648        value.hash(&mut hasher);
649        hasher.finish()
650    }
651
652    fn layout_key(&self, area: Rect, degradation: DegradationLevel) -> LayoutKey {
653        LayoutKey {
654            mode: self.mode,
655            width: area.width,
656            height: area.height,
657            separator_hash: Self::hash_str(&self.separator),
658            ellipsis_hash: Self::hash_str(&self.ellipsis),
659            key_style: StyleKey::from(self.key_style),
660            desc_style: StyleKey::from(self.desc_style),
661            separator_style: StyleKey::from(self.separator_style),
662            degradation,
663        }
664    }
665
666    fn build_layout(&self, area: Rect) -> HelpLayout {
667        match self.mode {
668            HelpMode::Short => self.build_short_layout(area),
669            HelpMode::Full => self.build_full_layout(area),
670        }
671    }
672
673    fn build_short_layout(&self, area: Rect) -> HelpLayout {
674        let mut entries = Vec::new();
675        let mut ellipsis = None;
676        let sep_width = display_width(&self.separator);
677        let ellipsis_width = display_width(&self.ellipsis);
678        let max_x = area.width;
679        let mut x: u16 = 0;
680        let mut first = true;
681
682        for entry in self
683            .entries
684            .iter()
685            .filter(|e| e.enabled && (!e.key.is_empty() || !e.desc.is_empty()))
686        {
687            let key_width = display_width(&entry.key);
688            let desc_width = display_width(&entry.desc);
689            let item_width = key_width + 1 + desc_width;
690            let total_width = if first {
691                item_width
692            } else {
693                sep_width + item_width
694            };
695            let space_left = (max_x as usize).saturating_sub(x as usize);
696
697            if total_width > space_left {
698                let ell_total = if first {
699                    ellipsis_width
700                } else {
701                    1 + ellipsis_width
702                };
703                if ell_total <= space_left {
704                    ellipsis = Some(EllipsisSlot {
705                        x,
706                        width: ell_total as u16,
707                        prefix_space: !first,
708                    });
709                }
710                break;
711            }
712
713            entries.push(EntrySlot {
714                x,
715                y: 0,
716                width: total_width as u16,
717                key_width,
718            });
719            x = x.saturating_add(total_width as u16);
720            first = false;
721        }
722
723        HelpLayout {
724            mode: HelpMode::Short,
725            width: area.width,
726            entries,
727            ellipsis,
728            max_key_width: 0,
729            separator_width: sep_width,
730        }
731    }
732
733    fn build_full_layout(&self, area: Rect) -> HelpLayout {
734        let mut max_key_width = 0usize;
735        for entry in self
736            .entries
737            .iter()
738            .filter(|e| e.enabled && (!e.key.is_empty() || !e.desc.is_empty()))
739        {
740            let key_width = display_width(&entry.key);
741            max_key_width = max_key_width.max(key_width);
742        }
743
744        let mut entries = Vec::new();
745        let mut row: u16 = 0;
746        for entry in self
747            .entries
748            .iter()
749            .filter(|e| e.enabled && (!e.key.is_empty() || !e.desc.is_empty()))
750        {
751            if row >= area.height {
752                break;
753            }
754            let key_width = display_width(&entry.key);
755            let desc_width = display_width(&entry.desc);
756            let entry_width = max_key_width.saturating_add(2).saturating_add(desc_width);
757            let slot_width = entry_width.min(area.width as usize) as u16;
758            entries.push(EntrySlot {
759                x: 0,
760                y: row,
761                width: slot_width,
762                key_width,
763            });
764            row = row.saturating_add(1);
765        }
766
767        HelpLayout {
768            mode: HelpMode::Full,
769            width: area.width,
770            entries,
771            ellipsis: None,
772            max_key_width,
773            separator_width: 0,
774        }
775    }
776
777    fn render_cached(&self, area: Rect, frame: &mut Frame, layout: &HelpLayout) {
778        match layout.mode {
779            HelpMode::Short => self.render_short_cached(area, frame, layout),
780            HelpMode::Full => self.render_full_cached(area, frame, layout),
781        }
782    }
783
784    fn render_short_cached(&self, area: Rect, frame: &mut Frame, layout: &HelpLayout) {
785        if layout.entries.is_empty() || area.width == 0 || area.height == 0 {
786            return;
787        }
788
789        let deg = frame.buffer.degradation;
790        let max_x = area.right();
791        let mut enabled_iter = self
792            .entries
793            .iter()
794            .filter(|e| e.enabled && (!e.key.is_empty() || !e.desc.is_empty()));
795
796        for (idx, slot) in layout.entries.iter().enumerate() {
797            let Some(entry) = enabled_iter.next() else {
798                break;
799            };
800            let mut x = area.x.saturating_add(slot.x);
801            let y = area.y.saturating_add(slot.y);
802
803            if idx > 0 {
804                let sep_style = if deg.apply_styling() {
805                    self.separator_style
806                } else {
807                    Style::default()
808                };
809                x = draw_text_span(frame, x, y, &self.separator, sep_style, max_x);
810            }
811
812            let key_style = if deg.apply_styling() {
813                self.key_style
814            } else {
815                Style::default()
816            };
817            let desc_style = if deg.apply_styling() {
818                self.desc_style
819            } else {
820                Style::default()
821            };
822
823            x = draw_text_span(frame, x, y, &entry.key, key_style, max_x);
824            x = draw_text_span(frame, x, y, " ", desc_style, max_x);
825            draw_text_span(frame, x, y, &entry.desc, desc_style, max_x);
826        }
827
828        if let Some(ellipsis) = &layout.ellipsis {
829            let y = area.y.saturating_add(0);
830            let mut x = area.x.saturating_add(ellipsis.x);
831            let ellipsis_style = if deg.apply_styling() {
832                self.separator_style
833            } else {
834                Style::default()
835            };
836            if ellipsis.prefix_space {
837                x = draw_text_span(frame, x, y, " ", ellipsis_style, max_x);
838            }
839            draw_text_span(frame, x, y, &self.ellipsis, ellipsis_style, max_x);
840        }
841    }
842
843    fn render_full_cached(&self, area: Rect, frame: &mut Frame, layout: &HelpLayout) {
844        if layout.entries.is_empty() || area.width == 0 || area.height == 0 {
845            return;
846        }
847
848        let deg = frame.buffer.degradation;
849        let max_x = area.right();
850
851        let mut enabled_iter = self
852            .entries
853            .iter()
854            .filter(|e| e.enabled && (!e.key.is_empty() || !e.desc.is_empty()));
855
856        for slot in layout.entries.iter() {
857            let Some(entry) = enabled_iter.next() else {
858                break;
859            };
860
861            let y = area.y.saturating_add(slot.y);
862            let mut x = area.x.saturating_add(slot.x);
863
864            let key_style = if deg.apply_styling() {
865                self.key_style
866            } else {
867                Style::default()
868            };
869            let desc_style = if deg.apply_styling() {
870                self.desc_style
871            } else {
872                Style::default()
873            };
874
875            x = draw_text_span(frame, x, y, &entry.key, key_style, max_x);
876            let pad = layout.max_key_width.saturating_sub(slot.key_width);
877            for _ in 0..pad {
878                x = draw_text_span(frame, x, y, " ", Style::default(), max_x);
879            }
880            x = draw_text_span(frame, x, y, "  ", Style::default(), max_x);
881            draw_text_span(frame, x, y, &entry.desc, desc_style, max_x);
882        }
883    }
884
885    fn render_short_entry(&self, slot: &EntrySlot, entry: &HelpEntry, frame: &mut Frame) {
886        let deg = frame.buffer.degradation;
887        let max_x = slot.x.saturating_add(slot.width);
888
889        let rect = Rect::new(slot.x, slot.y, slot.width, 1);
890        frame.buffer.fill(rect, Cell::default());
891
892        let mut x = slot.x;
893        if slot.x > 0 {
894            let sep_style = if deg.apply_styling() {
895                self.separator_style
896            } else {
897                Style::default()
898            };
899            x = draw_text_span(frame, x, slot.y, &self.separator, sep_style, max_x);
900        }
901
902        let key_style = if deg.apply_styling() {
903            self.key_style
904        } else {
905            Style::default()
906        };
907        let desc_style = if deg.apply_styling() {
908            self.desc_style
909        } else {
910            Style::default()
911        };
912
913        x = draw_text_span(frame, x, slot.y, &entry.key, key_style, max_x);
914        x = draw_text_span(frame, x, slot.y, " ", desc_style, max_x);
915        draw_text_span(frame, x, slot.y, &entry.desc, desc_style, max_x);
916    }
917
918    fn render_full_entry(
919        &self,
920        slot: &EntrySlot,
921        entry: &HelpEntry,
922        layout: &HelpLayout,
923        frame: &mut Frame,
924    ) {
925        let deg = frame.buffer.degradation;
926        let max_x = slot.x.saturating_add(slot.width);
927
928        let rect = Rect::new(slot.x, slot.y, slot.width, 1);
929        frame.buffer.fill(rect, Cell::default());
930
931        let mut x = slot.x;
932        let key_style = if deg.apply_styling() {
933            self.key_style
934        } else {
935            Style::default()
936        };
937        let desc_style = if deg.apply_styling() {
938            self.desc_style
939        } else {
940            Style::default()
941        };
942
943        x = draw_text_span(frame, x, slot.y, &entry.key, key_style, max_x);
944        let pad = layout.max_key_width.saturating_sub(slot.key_width);
945        for _ in 0..pad {
946            x = draw_text_span(frame, x, slot.y, " ", Style::default(), max_x);
947        }
948        x = draw_text_span(frame, x, slot.y, "  ", Style::default(), max_x);
949        draw_text_span(frame, x, slot.y, &entry.desc, desc_style, max_x);
950    }
951}
952
953impl Widget for Help {
954    fn render(&self, area: Rect, frame: &mut Frame) {
955        if area.is_empty() || area.width == 0 || area.height == 0 {
956            return;
957        }
958
959        clear_text_area(frame, area, Style::default());
960
961        match self.mode {
962            HelpMode::Short => self.render_short(area, frame),
963            HelpMode::Full => self.render_full(area, frame),
964        }
965    }
966
967    fn is_essential(&self) -> bool {
968        false
969    }
970}
971
972impl StatefulWidget for Help {
973    type State = HelpRenderState;
974
975    fn render(&self, area: Rect, frame: &mut Frame, state: &mut HelpRenderState) {
976        if area.is_empty() || area.width == 0 || area.height == 0 {
977            state.cache = None;
978            state.dirty_rects.clear();
979            state.dirty_indices.clear();
980            state.enabled_indices.clear();
981            return;
982        }
983
984        state.dirty_rects.clear();
985        state.dirty_indices.clear();
986
987        let layout_key = self.layout_key(area, frame.buffer.degradation);
988        let enabled_count = collect_enabled_indices(&self.entries, &mut state.enabled_indices);
989
990        let cache_miss = state
991            .cache
992            .as_ref()
993            .is_none_or(|cache| cache.key != layout_key);
994
995        if cache_miss {
996            rebuild_cache(self, area, frame, state, layout_key, enabled_count);
997            blit_cache(state.cache.as_ref(), area, frame);
998            return;
999        }
1000
1001        let cache = state
1002            .cache
1003            .as_mut()
1004            .expect("cache present after miss check");
1005        if enabled_count != cache.enabled_count {
1006            rebuild_cache(self, area, frame, state, layout_key, enabled_count);
1007            blit_cache(state.cache.as_ref(), area, frame);
1008            return;
1009        }
1010
1011        let mut layout_changed = false;
1012        let visible_count = cache.layout.entries.len();
1013
1014        for (pos, entry_idx) in state.enabled_indices.iter().enumerate() {
1015            let entry = &self.entries[*entry_idx];
1016            let hash = Help::entry_hash(entry);
1017
1018            if pos >= cache.entry_hashes.len() {
1019                layout_changed = true;
1020                break;
1021            }
1022
1023            if hash != cache.entry_hashes[pos] {
1024                if pos >= visible_count || !entry_fits_slot(entry, pos, &cache.layout) {
1025                    layout_changed = true;
1026                    break;
1027                }
1028                cache.entry_hashes[pos] = hash;
1029                state.dirty_indices.push(pos);
1030            }
1031        }
1032
1033        if layout_changed {
1034            rebuild_cache(self, area, frame, state, layout_key, enabled_count);
1035            blit_cache(state.cache.as_ref(), area, frame);
1036            return;
1037        }
1038
1039        if state.dirty_indices.is_empty() {
1040            state.stats.hits += 1;
1041            blit_cache(state.cache.as_ref(), area, frame);
1042            return;
1043        }
1044
1045        // Partial update: only changed entries are redrawn into the cached buffer.
1046        state.stats.dirty_updates += 1;
1047
1048        let cache = state
1049            .cache
1050            .as_mut()
1051            .expect("cache present for dirty update");
1052        let mut cache_buffer = std::mem::take(&mut cache.buffer);
1053        cache_buffer.degradation = frame.buffer.degradation;
1054        {
1055            let mut cache_frame = Frame::from_buffer(cache_buffer, frame.pool);
1056            cache_frame.widget_budget = frame.widget_budget.clone();
1057            cache_frame.set_degradation(frame.buffer.degradation);
1058
1059            for idx in &state.dirty_indices {
1060                if let Some(entry_idx) = state.enabled_indices.get(*idx)
1061                    && let Some(slot) = cache.layout.entries.get(*idx)
1062                {
1063                    let entry = &self.entries[*entry_idx];
1064                    match cache.layout.mode {
1065                        HelpMode::Short => self.render_short_entry(slot, entry, &mut cache_frame),
1066                        HelpMode::Full => {
1067                            self.render_full_entry(slot, entry, &cache.layout, &mut cache_frame)
1068                        }
1069                    }
1070                    state
1071                        .dirty_rects
1072                        .push(Rect::new(slot.x, slot.y, slot.width, 1));
1073                }
1074            }
1075
1076            cache_buffer = cache_frame.buffer;
1077        }
1078        cache.buffer = cache_buffer;
1079
1080        blit_cache(state.cache.as_ref(), area, frame);
1081    }
1082}
1083
1084fn collect_enabled_indices(entries: &[HelpEntry], out: &mut Vec<usize>) -> usize {
1085    out.clear();
1086    for (idx, entry) in entries.iter().enumerate() {
1087        if entry.enabled && (!entry.key.is_empty() || !entry.desc.is_empty()) {
1088            out.push(idx);
1089        }
1090    }
1091    out.len()
1092}
1093
1094fn entry_fits_slot(entry: &HelpEntry, index: usize, layout: &HelpLayout) -> bool {
1095    match layout.mode {
1096        HelpMode::Short => {
1097            let entry_width = display_width(&entry.key) + 1 + display_width(&entry.desc);
1098            let slot = match layout.entries.get(index) {
1099                Some(slot) => slot,
1100                None => return false,
1101            };
1102            let sep_width = layout.separator_width;
1103            let max_width = if slot.x == 0 {
1104                slot.width as usize
1105            } else {
1106                slot.width.saturating_sub(sep_width as u16) as usize
1107            };
1108            entry_width <= max_width
1109        }
1110        HelpMode::Full => {
1111            let key_width = display_width(&entry.key);
1112            let desc_width = display_width(&entry.desc);
1113            let entry_width = layout
1114                .max_key_width
1115                .saturating_add(2)
1116                .saturating_add(desc_width);
1117            let slot = match layout.entries.get(index) {
1118                Some(slot) => slot,
1119                None => return false,
1120            };
1121            if slot.width == layout.width {
1122                key_width <= layout.max_key_width
1123            } else {
1124                key_width <= layout.max_key_width && entry_width <= slot.width as usize
1125            }
1126        }
1127    }
1128}
1129
1130fn rebuild_cache(
1131    help: &Help,
1132    area: Rect,
1133    frame: &mut Frame,
1134    state: &mut HelpRenderState,
1135    layout_key: LayoutKey,
1136    enabled_count: usize,
1137) {
1138    state.stats.misses += 1;
1139    state.stats.layout_rebuilds += 1;
1140
1141    let layout_area = Rect::new(0, 0, area.width, area.height);
1142    let layout = help.build_layout(layout_area);
1143
1144    let mut buffer = Buffer::new(area.width, area.height);
1145    buffer.degradation = frame.buffer.degradation;
1146    {
1147        let mut cache_frame = Frame::from_buffer(buffer, frame.pool);
1148        cache_frame.widget_budget = frame.widget_budget.clone();
1149        cache_frame.set_degradation(frame.buffer.degradation);
1150        help.render_cached(layout_area, &mut cache_frame, &layout);
1151        buffer = cache_frame.buffer;
1152    }
1153
1154    let mut entry_hashes = Vec::with_capacity(state.enabled_indices.len());
1155    for idx in &state.enabled_indices {
1156        entry_hashes.push(Help::entry_hash(&help.entries[*idx]));
1157    }
1158
1159    state.cache = Some(HelpCache {
1160        buffer,
1161        layout,
1162        key: layout_key,
1163        entry_hashes,
1164        enabled_count,
1165    });
1166}
1167
1168fn blit_cache(cache: Option<&HelpCache>, area: Rect, frame: &mut Frame) {
1169    let Some(cache) = cache else {
1170        return;
1171    };
1172
1173    for slot in &cache.layout.entries {
1174        let src = Rect::new(slot.x, slot.y, slot.width, 1);
1175        frame
1176            .buffer
1177            .copy_from(&cache.buffer, src, area.x + slot.x, area.y + slot.y);
1178    }
1179
1180    if let Some(ellipsis) = &cache.layout.ellipsis {
1181        let src = Rect::new(ellipsis.x, 0, ellipsis.width, 1);
1182        frame
1183            .buffer
1184            .copy_from(&cache.buffer, src, area.x + ellipsis.x, area.y);
1185    }
1186}
1187
1188/// Format for displaying key labels in hints.
1189#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1190pub enum KeyFormat {
1191    /// Plain key display: `q quit`
1192    #[default]
1193    Plain,
1194    /// Bracketed key display: `[q] quit`
1195    Bracketed,
1196}
1197
1198/// A keybinding hints widget with category grouping and context-aware filtering.
1199///
1200/// Supports two entry scopes:
1201/// - **Global**: shortcuts always visible regardless of context.
1202/// - **Contextual**: shortcuts shown only when [`show_context`](Self::with_show_context)
1203///   is enabled (typically when a particular widget has focus).
1204///
1205/// In [`HelpMode::Full`] mode with categories enabled, entries are grouped
1206/// under category headers. In [`HelpMode::Short`] mode, entries are rendered
1207/// inline.
1208///
1209/// # Example
1210///
1211/// ```
1212/// use ftui_widgets::help::{KeybindingHints, HelpCategory, KeyFormat};
1213///
1214/// let hints = KeybindingHints::new()
1215///     .with_key_format(KeyFormat::Bracketed)
1216///     .global_entry("q", "quit")
1217///     .global_entry_categorized("Tab", "next", HelpCategory::Navigation)
1218///     .contextual_entry_categorized("^s", "save", HelpCategory::File);
1219///
1220/// assert_eq!(hints.global_entries().len(), 2);
1221/// assert_eq!(hints.contextual_entries().len(), 1);
1222/// ```
1223#[derive(Debug, Clone)]
1224pub struct KeybindingHints {
1225    global_entries: Vec<HelpEntry>,
1226    contextual_entries: Vec<HelpEntry>,
1227    key_format: KeyFormat,
1228    mode: HelpMode,
1229    key_style: Style,
1230    desc_style: Style,
1231    separator_style: Style,
1232    category_style: Style,
1233    separator: String,
1234    ellipsis: String,
1235    show_categories: bool,
1236    show_context: bool,
1237}
1238
1239impl Default for KeybindingHints {
1240    fn default() -> Self {
1241        Self::new()
1242    }
1243}
1244
1245impl KeybindingHints {
1246    /// Create a new hints widget with no entries.
1247    #[must_use]
1248    pub fn new() -> Self {
1249        Self {
1250            global_entries: Vec::new(),
1251            contextual_entries: Vec::new(),
1252            key_format: KeyFormat::default(),
1253            mode: HelpMode::Short,
1254            key_style: Style::new().bold(),
1255            desc_style: Style::default(),
1256            separator_style: Style::default(),
1257            category_style: Style::new().bold().underline(),
1258            separator: " • ".to_string(),
1259            ellipsis: "…".to_string(),
1260            show_categories: true,
1261            show_context: false,
1262        }
1263    }
1264
1265    /// Add a global entry (always visible).
1266    #[must_use]
1267    pub fn global_entry(mut self, key: impl Into<String>, desc: impl Into<String>) -> Self {
1268        self.global_entries
1269            .push(HelpEntry::new(key, desc).with_category(HelpCategory::Global));
1270        self
1271    }
1272
1273    /// Add a global entry with a specific category.
1274    #[must_use]
1275    pub fn global_entry_categorized(
1276        mut self,
1277        key: impl Into<String>,
1278        desc: impl Into<String>,
1279        category: HelpCategory,
1280    ) -> Self {
1281        self.global_entries
1282            .push(HelpEntry::new(key, desc).with_category(category));
1283        self
1284    }
1285
1286    /// Add a contextual entry (shown when context is active).
1287    #[must_use]
1288    pub fn contextual_entry(mut self, key: impl Into<String>, desc: impl Into<String>) -> Self {
1289        self.contextual_entries.push(HelpEntry::new(key, desc));
1290        self
1291    }
1292
1293    /// Add a contextual entry with a specific category.
1294    #[must_use]
1295    pub fn contextual_entry_categorized(
1296        mut self,
1297        key: impl Into<String>,
1298        desc: impl Into<String>,
1299        category: HelpCategory,
1300    ) -> Self {
1301        self.contextual_entries
1302            .push(HelpEntry::new(key, desc).with_category(category));
1303        self
1304    }
1305
1306    /// Add a pre-built global entry.
1307    #[must_use]
1308    pub fn with_global_entry(mut self, entry: HelpEntry) -> Self {
1309        self.global_entries.push(entry);
1310        self
1311    }
1312
1313    /// Add a pre-built contextual entry.
1314    #[must_use]
1315    pub fn with_contextual_entry(mut self, entry: HelpEntry) -> Self {
1316        self.contextual_entries.push(entry);
1317        self
1318    }
1319
1320    /// Set the key display format.
1321    #[must_use]
1322    pub fn with_key_format(mut self, format: KeyFormat) -> Self {
1323        self.key_format = format;
1324        self
1325    }
1326
1327    /// Set the display mode.
1328    #[must_use]
1329    pub fn with_mode(mut self, mode: HelpMode) -> Self {
1330        self.mode = mode;
1331        self
1332    }
1333
1334    /// Set whether contextual entries are shown.
1335    #[must_use]
1336    pub fn with_show_context(mut self, show: bool) -> Self {
1337        self.show_context = show;
1338        self
1339    }
1340
1341    /// Set whether category headers are shown in full mode.
1342    #[must_use]
1343    pub fn with_show_categories(mut self, show: bool) -> Self {
1344        self.show_categories = show;
1345        self
1346    }
1347
1348    /// Set the style for key text.
1349    #[must_use]
1350    pub fn with_key_style(mut self, style: Style) -> Self {
1351        self.key_style = style;
1352        self
1353    }
1354
1355    /// Set the style for description text.
1356    #[must_use]
1357    pub fn with_desc_style(mut self, style: Style) -> Self {
1358        self.desc_style = style;
1359        self
1360    }
1361
1362    /// Set the style for separators.
1363    #[must_use]
1364    pub fn with_separator_style(mut self, style: Style) -> Self {
1365        self.separator_style = style;
1366        self
1367    }
1368
1369    /// Set the style for category headers.
1370    #[must_use]
1371    pub fn with_category_style(mut self, style: Style) -> Self {
1372        self.category_style = style;
1373        self
1374    }
1375
1376    /// Set the separator string for short mode.
1377    #[must_use]
1378    pub fn with_separator(mut self, sep: impl Into<String>) -> Self {
1379        self.separator = sep.into();
1380        self
1381    }
1382
1383    /// Get the global entries.
1384    #[must_use]
1385    pub fn global_entries(&self) -> &[HelpEntry] {
1386        &self.global_entries
1387    }
1388
1389    /// Get the contextual entries.
1390    #[must_use]
1391    pub fn contextual_entries(&self) -> &[HelpEntry] {
1392        &self.contextual_entries
1393    }
1394
1395    /// Get the current mode.
1396    #[must_use]
1397    pub fn mode(&self) -> HelpMode {
1398        self.mode
1399    }
1400
1401    /// Get the key format.
1402    #[must_use]
1403    pub fn key_format(&self) -> KeyFormat {
1404        self.key_format
1405    }
1406
1407    /// Toggle between short and full mode.
1408    pub fn toggle_mode(&mut self) {
1409        self.mode = match self.mode {
1410            HelpMode::Short => HelpMode::Full,
1411            HelpMode::Full => HelpMode::Short,
1412        };
1413    }
1414
1415    /// Set whether contextual entries are shown (mutable).
1416    pub fn set_show_context(&mut self, show: bool) {
1417        self.show_context = show;
1418    }
1419
1420    /// Format a key string according to the current key format.
1421    fn format_key(&self, key: &str) -> String {
1422        match self.key_format {
1423            KeyFormat::Plain => key.to_string(),
1424            KeyFormat::Bracketed => format!("[{key}]"),
1425        }
1426    }
1427
1428    /// Collect visible entries, applying scope filter and key formatting.
1429    #[must_use]
1430    pub fn visible_entries(&self) -> Vec<HelpEntry> {
1431        let mut entries = Vec::new();
1432        for e in &self.global_entries {
1433            if e.enabled {
1434                entries.push(HelpEntry {
1435                    key: self.format_key(&e.key),
1436                    desc: e.desc.clone(),
1437                    enabled: true,
1438                    category: e.category.clone(),
1439                });
1440            }
1441        }
1442        if self.show_context {
1443            for e in &self.contextual_entries {
1444                if e.enabled {
1445                    entries.push(HelpEntry {
1446                        key: self.format_key(&e.key),
1447                        desc: e.desc.clone(),
1448                        enabled: true,
1449                        category: e.category.clone(),
1450                    });
1451                }
1452            }
1453        }
1454        entries
1455    }
1456
1457    /// Group entries by category, preserving insertion order within each group.
1458    fn grouped_entries(entries: &[HelpEntry]) -> Vec<(&HelpCategory, Vec<&HelpEntry>)> {
1459        let mut groups: Vec<(&HelpCategory, Vec<&HelpEntry>)> = Vec::new();
1460        for entry in entries {
1461            if let Some(group) = groups.iter_mut().find(|(cat, _)| **cat == entry.category) {
1462                group.1.push(entry);
1463            } else {
1464                groups.push((&entry.category, vec![entry]));
1465            }
1466        }
1467        groups
1468    }
1469
1470    /// Render full mode with category headers.
1471    fn render_full_grouped(&self, entries: &[HelpEntry], area: Rect, frame: &mut Frame) {
1472        let groups = Self::grouped_entries(entries);
1473        let deg = frame.buffer.degradation;
1474        let max_x = area.right();
1475        let mut y = area.y;
1476
1477        // Find max key width across all entries for alignment.
1478        let max_key_w = entries
1479            .iter()
1480            .map(|e| display_width(&e.key))
1481            .max()
1482            .unwrap_or(0);
1483
1484        for (i, (cat, group_entries)) in groups.iter().enumerate() {
1485            if y >= area.bottom() {
1486                break;
1487            }
1488
1489            // Category header
1490            let cat_style = if deg.apply_styling() {
1491                self.category_style
1492            } else {
1493                Style::default()
1494            };
1495            draw_text_span(frame, area.x, y, cat.label(), cat_style, max_x);
1496            y += 1;
1497
1498            // Entries in this category
1499            for entry in group_entries {
1500                if y >= area.bottom() {
1501                    break;
1502                }
1503
1504                let key_style = if deg.apply_styling() {
1505                    self.key_style
1506                } else {
1507                    Style::default()
1508                };
1509                let desc_style = if deg.apply_styling() {
1510                    self.desc_style
1511                } else {
1512                    Style::default()
1513                };
1514
1515                let mut x = area.x;
1516                x = draw_text_span(frame, x, y, &entry.key, key_style, max_x);
1517                let pad = max_key_w.saturating_sub(display_width(&entry.key));
1518                for _ in 0..pad {
1519                    x = draw_text_span(frame, x, y, " ", Style::default(), max_x);
1520                }
1521                x = draw_text_span(frame, x, y, "  ", Style::default(), max_x);
1522                draw_text_span(frame, x, y, &entry.desc, desc_style, max_x);
1523                y += 1;
1524            }
1525
1526            // Blank line between groups (except after last)
1527            if i + 1 < groups.len() {
1528                y += 1;
1529            }
1530        }
1531    }
1532}
1533
1534impl Widget for KeybindingHints {
1535    fn render(&self, area: Rect, frame: &mut Frame) {
1536        if area.is_empty() || area.width == 0 || area.height == 0 {
1537            return;
1538        }
1539
1540        clear_text_area(frame, area, Style::default());
1541
1542        let entries = self.visible_entries();
1543        if entries.is_empty() {
1544            return;
1545        }
1546
1547        match self.mode {
1548            HelpMode::Short => {
1549                // In short mode, render all entries inline using Help widget.
1550                let help = Help::new()
1551                    .with_mode(HelpMode::Short)
1552                    .with_key_style(self.key_style)
1553                    .with_desc_style(self.desc_style)
1554                    .with_separator_style(self.separator_style)
1555                    .with_separator(self.separator.clone())
1556                    .with_ellipsis(self.ellipsis.clone())
1557                    .with_entries(entries);
1558                Widget::render(&help, area, frame);
1559            }
1560            HelpMode::Full => {
1561                if self.show_categories {
1562                    self.render_full_grouped(&entries, area, frame);
1563                } else {
1564                    let help = Help::new()
1565                        .with_mode(HelpMode::Full)
1566                        .with_key_style(self.key_style)
1567                        .with_desc_style(self.desc_style)
1568                        .with_entries(entries);
1569                    Widget::render(&help, area, frame);
1570                }
1571            }
1572        }
1573    }
1574
1575    fn is_essential(&self) -> bool {
1576        false
1577    }
1578}
1579
1580#[cfg(test)]
1581mod tests {
1582    use super::*;
1583    use crate::hint_ranker::RankerConfig;
1584    use ftui_render::buffer::Buffer;
1585
1586    /// A shortcut that keeps getting used rises to the front; the others keep
1587    /// their relative order. The ranker's ledger comes back for logging.
1588    #[test]
1589    fn help_reorders_entries_by_learned_usage() {
1590        let mut help = Help::new()
1591            .entry("q", "quit")
1592            .entry("s", "save")
1593            .entry("?", "help");
1594        let mut ranker = HintRanker::new(RankerConfig::default());
1595        let ids = help.register_with_ranker(&mut ranker, HintContext::Global);
1596        assert_eq!(ids.len(), 3);
1597        assert_eq!(help.hint_id(2), Some(ids[2]));
1598
1599        // "?" is used every time, "s" occasionally, "q" is shown but ignored.
1600        // (An entry with zero observations sits at its cold-start static
1601        // priority, so every entry gets evidence here.)
1602        for _ in 0..8 {
1603            ranker.record_usage(ids[2]);
1604            ranker.record_shown_not_used(ids[0]);
1605        }
1606        ranker.record_usage(ids[1]);
1607        ranker.record_shown_not_used(ids[1]);
1608        let ledger = help.apply_ranking(&mut ranker, None);
1609        assert_eq!(ledger.len(), 3, "one evidence row per hint");
1610        let keys: Vec<&str> = help.entries().iter().map(|e| e.key.as_str()).collect();
1611        assert_eq!(keys, vec!["?", "s", "q"], "ordered by learned utility");
1612        // ids follow their entries so later usage feedback still maps correctly.
1613        assert_eq!(help.hint_id(0), Some(ids[2]));
1614    }
1615
1616    /// Apps feed usage back by key label: `record_used("s")` after the key
1617    /// fires and `record_shown` for the rest, and the bar reorders itself.
1618    #[test]
1619    fn help_usage_feedback_by_key_label_reorders_the_bar() {
1620        let mut help = Help::new()
1621            .entry("q", "quit")
1622            .entry("s", "save")
1623            .entry("?", "help");
1624        let mut ranker = HintRanker::new(RankerConfig::default());
1625        assert!(
1626            !help.record_used(&mut ranker, "s"),
1627            "nothing is registered yet, so nothing can be recorded"
1628        );
1629        let ids = help.register_with_ranker(&mut ranker, HintContext::Global);
1630        for _ in 0..8 {
1631            assert!(help.record_used(&mut ranker, "s"));
1632            help.record_shown(&mut ranker, Some("s"));
1633        }
1634        assert!(
1635            !help.record_used(&mut ranker, "zzz"),
1636            "unknown labels are ignored"
1637        );
1638
1639        help.apply_ranking(&mut ranker, None);
1640        let keys: Vec<&str> = help.entries().iter().map(|e| e.key.as_str()).collect();
1641        assert_eq!(
1642            keys,
1643            vec!["s", "q", "?"],
1644            "used first; the ignored two keep their order"
1645        );
1646        assert_eq!(
1647            help.hint_id(0),
1648            Some(ids[1]),
1649            "hint ids travel with their entries"
1650        );
1651    }
1652
1653    /// The ledger `apply_ranking` returns serializes to one JSONL evidence
1654    /// row per hint with the ranker schema tag, so apps can log why the bar
1655    /// is ordered the way it is.
1656    #[test]
1657    fn help_ranking_ledger_serializes_as_hint_ranking_evidence() {
1658        let mut help = Help::new().entry("q", "quit").entry("?", "help");
1659        let mut ranker = HintRanker::new(RankerConfig::default());
1660        help.register_with_ranker(&mut ranker, HintContext::Global);
1661        help.record_used(&mut ranker, "?");
1662        let ledger = help.apply_ranking(&mut ranker, None);
1663        assert_eq!(ledger.len(), 2);
1664        for (rank, row) in ledger.iter().enumerate() {
1665            let line = row.to_jsonl();
1666            let parsed: serde_json::Value =
1667                serde_json::from_str(&line).unwrap_or_else(|e| panic!("{e}: {line}"));
1668            assert_eq!(parsed["schema"], "hint-ranking-v1");
1669            assert_eq!(parsed["rank"].as_u64(), Some(rank as u64));
1670            assert!(parsed["label"].as_str().is_some_and(|l| l.contains(' ')));
1671            assert!(parsed["net_value"].is_number() && parsed["voi"].is_number());
1672        }
1673        assert_eq!(ledger[0].label, "? help", "the used shortcut ranks first");
1674    }
1675
1676    /// A help bar generated from a KeyMap shows the winning labelled
1677    /// bindings for the active contexts, and its chord text is what
1678    /// `record_used` expects from a dispatched chord.
1679    #[test]
1680    fn help_from_keymap_lists_winning_labelled_bindings() {
1681        use ftui_core::keybinding::{Chord, Priority};
1682
1683        let chord = |s: &str| Chord::parse(s).unwrap();
1684        let mut map = KeyMap::new();
1685        let editor = map.context("editor");
1686        let quit = map.bind(chord("q"), 1);
1687        map.set_label(quit, "quit");
1688        let top = map.bind(chord("g g"), 2);
1689        map.set_label(top, "top");
1690        map.bind(chord("x"), 3); // unlabelled: skipped
1691        let save = map.bind(chord("Ctrl+s"), 4);
1692        map.set_label(save, "save");
1693        let save_buffer = map.bind_in(chord("Ctrl+s"), 5, Priority::Widget, Some(editor));
1694        map.set_label(save_buffer, "save buffer");
1695
1696        let global = Help::from_keymap(&map, &[]);
1697        let rows: Vec<(&str, &str)> = global
1698            .entries()
1699            .iter()
1700            .map(|e| (e.key.as_str(), e.desc.as_str()))
1701            .collect();
1702        assert_eq!(
1703            rows,
1704            vec![("q", "quit"), ("g g", "top"), ("Ctrl+s", "save")]
1705        );
1706
1707        let mut in_editor = Help::from_keymap(&map, &[editor]);
1708        let descs: Vec<&str> = in_editor
1709            .entries()
1710            .iter()
1711            .map(|e| e.desc.as_str())
1712            .collect();
1713        assert_eq!(
1714            descs,
1715            vec!["quit", "top", "save buffer"],
1716            "the context binding shadows the global one"
1717        );
1718
1719        let mut ranker = HintRanker::new(RankerConfig::default());
1720        in_editor.register_with_ranker(&mut ranker, HintContext::Global);
1721        assert!(in_editor.record_used(&mut ranker, &chord("g g").to_string()));
1722        assert!(
1723            !in_editor.record_used(&mut ranker, "x"),
1724            "unlabelled binding is not a hint"
1725        );
1726    }
1727
1728    /// Hysteresis: without new evidence, re-ranking must not reorder.
1729    #[test]
1730    fn help_ranking_is_stable_without_new_evidence() {
1731        let mut help = Help::new().entry("a", "alpha").entry("b", "beta");
1732        let mut ranker = HintRanker::new(RankerConfig::default());
1733        help.register_with_ranker(&mut ranker, HintContext::Global);
1734        help.apply_ranking(&mut ranker, None);
1735        let first: Vec<String> = help.entries().iter().map(|e| e.key.clone()).collect();
1736        for _ in 0..5 {
1737            help.apply_ranking(&mut ranker, None);
1738        }
1739        let after: Vec<String> = help.entries().iter().map(|e| e.key.clone()).collect();
1740        assert_eq!(first, after);
1741    }
1742
1743    /// Unregistered widgets are left alone.
1744    #[test]
1745    fn help_apply_ranking_without_registration_is_noop() {
1746        let mut help = Help::new().entry("x", "one").entry("y", "two");
1747        let mut ranker = HintRanker::new(RankerConfig::default());
1748        assert!(help.apply_ranking(&mut ranker, None).is_empty());
1749        assert_eq!(help.entries()[0].key, "x");
1750    }
1751    use ftui_render::frame::Frame;
1752    use ftui_render::grapheme_pool::GraphemePool;
1753    use proptest::prelude::*;
1754    use proptest::string::string_regex;
1755    use std::time::Instant;
1756
1757    fn row_text(buf: &Buffer, y: u16, width: u16) -> String {
1758        (0..width)
1759            .map(|x| {
1760                buf.get(x, y)
1761                    .and_then(|cell| cell.content.as_char())
1762                    .unwrap_or(' ')
1763            })
1764            .collect()
1765    }
1766
1767    fn find_char_column(buf: &Buffer, y: u16, width: u16, target: char) -> Option<usize> {
1768        row_text(buf, y, width).chars().position(|ch| ch == target)
1769    }
1770
1771    #[test]
1772    fn new_help_is_empty() {
1773        let help = Help::new();
1774        assert!(help.entries().is_empty());
1775        assert_eq!(help.mode(), HelpMode::Short);
1776    }
1777
1778    #[test]
1779    fn entry_builder() {
1780        let help = Help::new().entry("q", "quit").entry("^s", "save");
1781        assert_eq!(help.entries().len(), 2);
1782        assert_eq!(help.entries()[0].key, "q");
1783        assert_eq!(help.entries()[0].desc, "quit");
1784    }
1785
1786    #[test]
1787    fn with_entries_replaces() {
1788        let help = Help::new()
1789            .entry("old", "old")
1790            .with_entries(vec![HelpEntry::new("new", "new")]);
1791        assert_eq!(help.entries().len(), 1);
1792        assert_eq!(help.entries()[0].key, "new");
1793    }
1794
1795    #[test]
1796    fn disabled_entries_hidden() {
1797        let help = Help::new()
1798            .with_entry(HelpEntry::new("a", "shown"))
1799            .with_entry(HelpEntry::new("b", "hidden").with_enabled(false))
1800            .with_entry(HelpEntry::new("c", "also shown"));
1801        assert_eq!(help.enabled_entries().len(), 2);
1802    }
1803
1804    #[test]
1805    fn toggle_mode() {
1806        let mut help = Help::new();
1807        assert_eq!(help.mode(), HelpMode::Short);
1808        help.toggle_mode();
1809        assert_eq!(help.mode(), HelpMode::Full);
1810        help.toggle_mode();
1811        assert_eq!(help.mode(), HelpMode::Short);
1812    }
1813
1814    #[test]
1815    fn push_entry() {
1816        let mut help = Help::new();
1817        help.push_entry(HelpEntry::new("x", "action"));
1818        assert_eq!(help.entries().len(), 1);
1819    }
1820
1821    #[test]
1822    fn render_short_basic() {
1823        let help = Help::new().entry("q", "quit").entry("^s", "save");
1824
1825        let mut pool = GraphemePool::new();
1826        let mut frame = Frame::new(40, 1, &mut pool);
1827        let area = Rect::new(0, 0, 40, 1);
1828        Widget::render(&help, area, &mut frame);
1829
1830        // Check that key text appears in buffer
1831        let cell_q = frame.buffer.get(0, 0).unwrap();
1832        assert_eq!(cell_q.content.as_char(), Some('q'));
1833    }
1834
1835    #[test]
1836    fn render_short_truncation() {
1837        let help = Help::new()
1838            .entry("q", "quit")
1839            .entry("^s", "save")
1840            .entry("^x", "something very long that should not fit");
1841
1842        let mut pool = GraphemePool::new();
1843        let mut frame = Frame::new(20, 1, &mut pool);
1844        let area = Rect::new(0, 0, 20, 1);
1845        Widget::render(&help, area, &mut frame);
1846
1847        // First entry should be present
1848        let cell = frame.buffer.get(0, 0).unwrap();
1849        assert_eq!(cell.content.as_char(), Some('q'));
1850    }
1851
1852    #[test]
1853    fn render_short_truncation_keeps_ellipsis_without_styling() {
1854        let help = Help::new()
1855            .entry("q", "quit")
1856            .entry("^s", "save")
1857            .entry("^x", "something very long that should not fit");
1858
1859        let mut pool = GraphemePool::new();
1860        let mut frame = Frame::new(20, 1, &mut pool);
1861        frame.buffer.degradation = DegradationLevel::NoStyling;
1862        let area = Rect::new(0, 0, 20, 1);
1863        Widget::render(&help, area, &mut frame);
1864
1865        let saw_ellipsis = (area.x..area.right()).any(|x| {
1866            frame
1867                .buffer
1868                .get(x, area.y)
1869                .and_then(|cell| cell.content.as_char())
1870                == Some('…')
1871        });
1872        assert!(saw_ellipsis);
1873    }
1874
1875    #[test]
1876    fn render_short_empty_entries() {
1877        let help = Help::new();
1878
1879        let mut pool = GraphemePool::new();
1880        let mut frame = Frame::new(20, 1, &mut pool);
1881        let area = Rect::new(0, 0, 20, 1);
1882        Widget::render(&help, area, &mut frame);
1883
1884        // Buffer should remain default (empty cell)
1885        let cell = frame.buffer.get(0, 0).unwrap();
1886        assert!(cell.content.is_empty() || cell.content.as_char() == Some(' '));
1887    }
1888
1889    #[test]
1890    fn render_short_shrinking_clears_stale_suffix() {
1891        let long = Help::new().entry("^x", "explode").entry("^s", "save");
1892        let short = Help::new().entry("q", "quit");
1893
1894        let mut pool = GraphemePool::new();
1895        let mut frame = Frame::new(24, 1, &mut pool);
1896        let area = Rect::new(0, 0, 24, 1);
1897
1898        Widget::render(&long, area, &mut frame);
1899        Widget::render(&short, area, &mut frame);
1900
1901        assert_eq!(row_text(&frame.buffer, 0, 24), "q quit                  ");
1902    }
1903
1904    #[test]
1905    fn render_short_empty_entries_clear_stale_row() {
1906        let populated = Help::new().entry("q", "quit").entry("^s", "save");
1907        let empty = Help::new();
1908
1909        let mut pool = GraphemePool::new();
1910        let mut frame = Frame::new(20, 1, &mut pool);
1911        let area = Rect::new(0, 0, 20, 1);
1912
1913        Widget::render(&populated, area, &mut frame);
1914        Widget::render(&empty, area, &mut frame);
1915
1916        assert_eq!(row_text(&frame.buffer, 0, 20), " ".repeat(20));
1917    }
1918
1919    #[test]
1920    fn render_full_basic() {
1921        let help = Help::new()
1922            .with_mode(HelpMode::Full)
1923            .entry("q", "quit")
1924            .entry("^s", "save file");
1925
1926        let mut pool = GraphemePool::new();
1927        let mut frame = Frame::new(30, 5, &mut pool);
1928        let area = Rect::new(0, 0, 30, 5);
1929        Widget::render(&help, area, &mut frame);
1930
1931        // First row should have "q" key
1932        let cell = frame.buffer.get(0, 0).unwrap();
1933        assert!(cell.content.as_char() == Some(' ') || cell.content.as_char() == Some('q'));
1934        // Second row should have "^s" key (right-padded: " ^s")
1935        let cell_row2 = frame.buffer.get(0, 1).unwrap();
1936        assert!(
1937            cell_row2.content.as_char() == Some('^') || cell_row2.content.as_char() == Some(' ')
1938        );
1939    }
1940
1941    #[test]
1942    fn render_full_to_short_clears_stale_lower_rows() {
1943        let full = Help::new()
1944            .with_mode(HelpMode::Full)
1945            .entry("a", "alpha")
1946            .entry("b", "beta");
1947        let short = Help::new().entry("q", "quit");
1948
1949        let mut pool = GraphemePool::new();
1950        let mut frame = Frame::new(20, 2, &mut pool);
1951        let area = Rect::new(0, 0, 20, 2);
1952
1953        Widget::render(&full, area, &mut frame);
1954        Widget::render(&short, area, &mut frame);
1955
1956        assert_eq!(row_text(&frame.buffer, 0, 20), "q quit              ");
1957        assert_eq!(row_text(&frame.buffer, 1, 20), " ".repeat(20));
1958    }
1959
1960    #[test]
1961    fn render_full_respects_height() {
1962        let help = Help::new()
1963            .with_mode(HelpMode::Full)
1964            .entry("a", "first")
1965            .entry("b", "second")
1966            .entry("c", "third");
1967
1968        let mut pool = GraphemePool::new();
1969        // Only 2 rows available
1970        let mut frame = Frame::new(30, 2, &mut pool);
1971        let area = Rect::new(0, 0, 30, 2);
1972        Widget::render(&help, area, &mut frame);
1973
1974        // Only first two entries should render (height=2)
1975        // No crash, no panic
1976    }
1977
1978    #[test]
1979    fn help_entry_equality() {
1980        let a = HelpEntry::new("q", "quit");
1981        let b = HelpEntry::new("q", "quit");
1982        let c = HelpEntry::new("x", "exit");
1983        assert_eq!(a, b);
1984        assert_ne!(a, c);
1985    }
1986
1987    #[test]
1988    fn help_entry_disabled() {
1989        let entry = HelpEntry::new("q", "quit").with_enabled(false);
1990        assert!(!entry.enabled);
1991    }
1992
1993    #[test]
1994    fn with_separator() {
1995        let help = Help::new().with_separator(" | ");
1996        assert_eq!(help.separator, " | ");
1997    }
1998
1999    #[test]
2000    fn with_ellipsis() {
2001        let help = Help::new().with_ellipsis("...");
2002        assert_eq!(help.ellipsis, "...");
2003    }
2004
2005    #[test]
2006    fn render_zero_area() {
2007        let help = Help::new().entry("q", "quit");
2008
2009        let mut pool = GraphemePool::new();
2010        let mut frame = Frame::new(20, 1, &mut pool);
2011        let area = Rect::new(0, 0, 0, 0);
2012        Widget::render(&help, area, &mut frame); // Should not panic
2013    }
2014
2015    #[test]
2016    fn is_not_essential() {
2017        let help = Help::new();
2018        assert!(!help.is_essential());
2019    }
2020
2021    #[test]
2022    fn render_full_alignment() {
2023        // Verify key column alignment in full mode
2024        let help = Help::new()
2025            .with_mode(HelpMode::Full)
2026            .entry("q", "quit")
2027            .entry("ctrl+s", "save");
2028
2029        let mut pool = GraphemePool::new();
2030        let mut frame = Frame::new(30, 3, &mut pool);
2031        let area = Rect::new(0, 0, 30, 3);
2032        Widget::render(&help, area, &mut frame);
2033
2034        // "q" is 1 char, "ctrl+s" is 6 chars, max_key_w = 6
2035        // Row 0: "q      quit" (q + 5 spaces + 2 spaces + quit)
2036        // Row 1: "ctrl+s  save"
2037        // Check that descriptions start at the same column
2038        // Key col = 6, gap = 2, desc starts at col 8
2039    }
2040
2041    #[test]
2042    fn render_full_no_styling_keeps_left_aligned_key_column() {
2043        let help = Help::new()
2044            .with_mode(HelpMode::Full)
2045            .entry("q", "quit")
2046            .entry("ctrl+s", "save");
2047
2048        let mut pool = GraphemePool::new();
2049        let mut frame = Frame::new(30, 3, &mut pool);
2050        frame.buffer.degradation = DegradationLevel::NoStyling;
2051        let area = Rect::new(0, 0, 30, 3);
2052        Widget::render(&help, area, &mut frame);
2053
2054        assert_eq!(
2055            frame
2056                .buffer
2057                .get(0, 0)
2058                .and_then(|cell| cell.content.as_char()),
2059            Some('q'),
2060            "short key should stay left-aligned in degraded full mode"
2061        );
2062        assert_eq!(
2063            find_char_column(&frame.buffer, 0, area.width, 'q'),
2064            Some(0),
2065            "short key drifted right in degraded full mode"
2066        );
2067        assert_eq!(
2068            find_char_column(&frame.buffer, 0, area.width, 'q'),
2069            find_char_column(&frame.buffer, 1, area.width, 'c')
2070        );
2071    }
2072
2073    #[test]
2074    fn render_full_no_styling_uses_display_width_for_wide_keys() {
2075        let help = Help::new()
2076            .with_mode(HelpMode::Full)
2077            .entry("🦀", "crab")
2078            .entry("ctrl+s", "write");
2079
2080        let mut pool = GraphemePool::new();
2081        let mut frame = Frame::new(30, 3, &mut pool);
2082        frame.buffer.degradation = DegradationLevel::NoStyling;
2083        let area = Rect::new(0, 0, 30, 3);
2084        Widget::render(&help, area, &mut frame);
2085
2086        let crab_desc_col = find_char_column(&frame.buffer, 0, area.width, 'c');
2087        let save_desc_col = find_char_column(&frame.buffer, 1, area.width, 'w');
2088        assert_eq!(
2089            crab_desc_col, save_desc_col,
2090            "wide-key descriptions should align to the same display column in degraded full mode"
2091        );
2092    }
2093
2094    #[test]
2095    fn default_impl() {
2096        let help = Help::default();
2097        assert!(help.entries().is_empty());
2098    }
2099
2100    #[test]
2101    fn cache_hit_same_hints() {
2102        let help = Help::new().entry("q", "quit").entry("^s", "save");
2103        let mut state = HelpRenderState::default();
2104        let mut pool = GraphemePool::new();
2105        let mut frame = Frame::new(40, 1, &mut pool);
2106        let area = Rect::new(0, 0, 40, 1);
2107
2108        StatefulWidget::render(&help, area, &mut frame, &mut state);
2109        let stats_after_first = state.stats();
2110        StatefulWidget::render(&help, area, &mut frame, &mut state);
2111        let stats_after_second = state.stats();
2112
2113        assert!(
2114            stats_after_second.hits > stats_after_first.hits,
2115            "Second render should be a cache hit"
2116        );
2117        assert!(state.dirty_rects().is_empty(), "No dirty rects on hit");
2118    }
2119
2120    #[test]
2121    fn dirty_rect_only_changes() {
2122        let mut help = Help::new()
2123            .with_mode(HelpMode::Full)
2124            .entry("q", "quit")
2125            .entry("w", "write")
2126            .entry("e", "edit");
2127
2128        let mut state = HelpRenderState::default();
2129        let mut pool = GraphemePool::new();
2130        let mut frame = Frame::new(40, 3, &mut pool);
2131        let area = Rect::new(0, 0, 40, 3);
2132
2133        StatefulWidget::render(&help, area, &mut frame, &mut state);
2134
2135        help.entries[1].desc.clear();
2136        help.entries[1].desc.push_str("save");
2137
2138        StatefulWidget::render(&help, area, &mut frame, &mut state);
2139        let dirty = state.take_dirty_rects();
2140
2141        assert_eq!(dirty.len(), 1, "Only one row should be dirty");
2142        assert_eq!(dirty[0].y, 1, "Second entry row should be dirty");
2143    }
2144
2145    proptest! {
2146        #[test]
2147        fn prop_cache_hits_on_stable_entries(entries in prop::collection::vec(
2148            (string_regex("[a-z]{1,6}").unwrap(), string_regex("[a-z]{1,10}").unwrap()),
2149            1..6
2150        )) {
2151            let mut help = Help::new();
2152            for (key, desc) in entries {
2153                help = help.entry(key, desc);
2154            }
2155            let mut state = HelpRenderState::default();
2156            let mut pool = GraphemePool::new();
2157            let mut frame = Frame::new(80, 1, &mut pool);
2158            let area = Rect::new(0, 0, 80, 1);
2159
2160            StatefulWidget::render(&help, area, &mut frame, &mut state);
2161            let stats_after_first = state.stats();
2162            StatefulWidget::render(&help, area, &mut frame, &mut state);
2163            let stats_after_second = state.stats();
2164
2165            prop_assert!(stats_after_second.hits > stats_after_first.hits);
2166            prop_assert!(state.dirty_rects().is_empty());
2167        }
2168    }
2169
2170    #[test]
2171    fn perf_micro_hint_update() {
2172        let mut help = Help::new()
2173            .with_mode(HelpMode::Short)
2174            .entry("^T", "Theme")
2175            .entry("^C", "Quit")
2176            .entry("?", "Help")
2177            .entry("F12", "Debug");
2178
2179        let mut state = HelpRenderState::default();
2180        let mut pool = GraphemePool::new();
2181        let mut frame = Frame::new(120, 1, &mut pool);
2182        let area = Rect::new(0, 0, 120, 1);
2183
2184        StatefulWidget::render(&help, area, &mut frame, &mut state);
2185
2186        let iterations = 200u32;
2187        let mut times_us = Vec::with_capacity(iterations as usize);
2188        for i in 0..iterations {
2189            let label = if i % 2 == 0 { "Close" } else { "Open" };
2190            help.entries[1].desc.clear();
2191            help.entries[1].desc.push_str(label);
2192
2193            let start = Instant::now();
2194            StatefulWidget::render(&help, area, &mut frame, &mut state);
2195            let elapsed = start.elapsed();
2196            times_us.push(elapsed.as_micros() as u64);
2197        }
2198
2199        times_us.sort();
2200        let len = times_us.len();
2201        let p50 = times_us[len / 2];
2202        let p95 = times_us[((len as f64 * 0.95) as usize).min(len.saturating_sub(1))];
2203        let p99 = times_us[((len as f64 * 0.99) as usize).min(len.saturating_sub(1))];
2204        let updates_per_sec = 1_000_000u64.checked_div(p50).unwrap_or(0);
2205
2206        eprintln!(
2207            "{{\"ts\":\"2026-02-03T00:00:00Z\",\"case\":\"help_hint_update\",\"iterations\":{},\"p50_us\":{},\"p95_us\":{},\"p99_us\":{},\"updates_per_sec\":{},\"hits\":{},\"misses\":{},\"dirty_updates\":{}}}",
2208            iterations,
2209            p50,
2210            p95,
2211            p99,
2212            updates_per_sec,
2213            state.stats().hits,
2214            state.stats().misses,
2215            state.stats().dirty_updates
2216        );
2217
2218        // Budget: keep p95 under 2ms in CI (500 updates/sec).
2219        assert!(p95 <= 2000, "p95 too slow: {p95}us");
2220    }
2221
2222    // ── HelpCategory tests ─────────────────────────────────────────
2223
2224    #[test]
2225    fn help_category_default_is_general() {
2226        assert_eq!(HelpCategory::default(), HelpCategory::General);
2227    }
2228
2229    #[test]
2230    fn help_category_labels() {
2231        assert_eq!(HelpCategory::General.label(), "General");
2232        assert_eq!(HelpCategory::Navigation.label(), "Navigation");
2233        assert_eq!(HelpCategory::Editing.label(), "Editing");
2234        assert_eq!(HelpCategory::File.label(), "File");
2235        assert_eq!(HelpCategory::View.label(), "View");
2236        assert_eq!(HelpCategory::Global.label(), "Global");
2237        assert_eq!(
2238            HelpCategory::Custom("My Section".into()).label(),
2239            "My Section"
2240        );
2241    }
2242
2243    #[test]
2244    fn help_entry_with_category() {
2245        let entry = HelpEntry::new("q", "quit").with_category(HelpCategory::Navigation);
2246        assert_eq!(entry.category, HelpCategory::Navigation);
2247    }
2248
2249    #[test]
2250    fn help_entry_default_category_is_general() {
2251        let entry = HelpEntry::new("q", "quit");
2252        assert_eq!(entry.category, HelpCategory::General);
2253    }
2254
2255    #[test]
2256    fn category_changes_entry_hash() {
2257        let a = HelpEntry::new("q", "quit");
2258        let b = HelpEntry::new("q", "quit").with_category(HelpCategory::Navigation);
2259        assert_ne!(Help::entry_hash(&a), Help::entry_hash(&b));
2260    }
2261
2262    // ── KeyFormat tests ────────────────────────────────────────────
2263
2264    #[test]
2265    fn key_format_default_is_plain() {
2266        assert_eq!(KeyFormat::default(), KeyFormat::Plain);
2267    }
2268
2269    // ── KeybindingHints tests ──────────────────────────────────────
2270
2271    #[test]
2272    fn keybinding_hints_new_is_empty() {
2273        let hints = KeybindingHints::new();
2274        assert!(hints.global_entries().is_empty());
2275        assert!(hints.contextual_entries().is_empty());
2276        assert_eq!(hints.mode(), HelpMode::Short);
2277        assert_eq!(hints.key_format(), KeyFormat::Plain);
2278    }
2279
2280    #[test]
2281    fn keybinding_hints_default() {
2282        let hints = KeybindingHints::default();
2283        assert!(hints.global_entries().is_empty());
2284    }
2285
2286    #[test]
2287    fn keybinding_hints_global_entry() {
2288        let hints = KeybindingHints::new()
2289            .global_entry("q", "quit")
2290            .global_entry("^s", "save");
2291        assert_eq!(hints.global_entries().len(), 2);
2292        assert_eq!(hints.global_entries()[0].key, "q");
2293        assert_eq!(hints.global_entries()[0].category, HelpCategory::Global);
2294    }
2295
2296    #[test]
2297    fn keybinding_hints_categorized_entries() {
2298        let hints = KeybindingHints::new()
2299            .global_entry_categorized("Tab", "next", HelpCategory::Navigation)
2300            .global_entry_categorized("q", "quit", HelpCategory::Global);
2301        assert_eq!(hints.global_entries()[0].category, HelpCategory::Navigation);
2302        assert_eq!(hints.global_entries()[1].category, HelpCategory::Global);
2303    }
2304
2305    #[test]
2306    fn keybinding_hints_contextual_entry() {
2307        let hints = KeybindingHints::new()
2308            .contextual_entry("^s", "save")
2309            .contextual_entry_categorized("^f", "find", HelpCategory::Editing);
2310        assert_eq!(hints.contextual_entries().len(), 2);
2311        assert_eq!(
2312            hints.contextual_entries()[0].category,
2313            HelpCategory::General
2314        );
2315        assert_eq!(
2316            hints.contextual_entries()[1].category,
2317            HelpCategory::Editing
2318        );
2319    }
2320
2321    #[test]
2322    fn keybinding_hints_with_prebuilt_entries() {
2323        let global = HelpEntry::new("q", "quit").with_category(HelpCategory::Global);
2324        let ctx = HelpEntry::new("^s", "save").with_category(HelpCategory::File);
2325        let hints = KeybindingHints::new()
2326            .with_global_entry(global)
2327            .with_contextual_entry(ctx);
2328        assert_eq!(hints.global_entries().len(), 1);
2329        assert_eq!(hints.contextual_entries().len(), 1);
2330    }
2331
2332    #[test]
2333    fn keybinding_hints_toggle_mode() {
2334        let mut hints = KeybindingHints::new();
2335        assert_eq!(hints.mode(), HelpMode::Short);
2336        hints.toggle_mode();
2337        assert_eq!(hints.mode(), HelpMode::Full);
2338        hints.toggle_mode();
2339        assert_eq!(hints.mode(), HelpMode::Short);
2340    }
2341
2342    #[test]
2343    fn keybinding_hints_set_show_context() {
2344        let mut hints = KeybindingHints::new()
2345            .global_entry("q", "quit")
2346            .contextual_entry("^s", "save");
2347
2348        // Context off: only global visible
2349        let visible = hints.visible_entries();
2350        assert_eq!(visible.len(), 1);
2351
2352        // Context on: both visible
2353        hints.set_show_context(true);
2354        let visible = hints.visible_entries();
2355        assert_eq!(visible.len(), 2);
2356    }
2357
2358    #[test]
2359    fn keybinding_hints_bracketed_format() {
2360        let hints = KeybindingHints::new()
2361            .with_key_format(KeyFormat::Bracketed)
2362            .global_entry("q", "quit");
2363        let visible = hints.visible_entries();
2364        assert_eq!(visible[0].key, "[q]");
2365    }
2366
2367    #[test]
2368    fn keybinding_hints_plain_format() {
2369        let hints = KeybindingHints::new()
2370            .with_key_format(KeyFormat::Plain)
2371            .global_entry("q", "quit");
2372        let visible = hints.visible_entries();
2373        assert_eq!(visible[0].key, "q");
2374    }
2375
2376    #[test]
2377    fn keybinding_hints_disabled_entries_hidden() {
2378        let hints = KeybindingHints::new()
2379            .with_global_entry(HelpEntry::new("a", "shown"))
2380            .with_global_entry(HelpEntry::new("b", "hidden").with_enabled(false));
2381        let visible = hints.visible_entries();
2382        assert_eq!(visible.len(), 1);
2383        assert_eq!(visible[0].key, "a");
2384    }
2385
2386    #[test]
2387    fn keybinding_hints_grouped_entries() {
2388        let entries = vec![
2389            HelpEntry::new("Tab", "next").with_category(HelpCategory::Navigation),
2390            HelpEntry::new("q", "quit").with_category(HelpCategory::Global),
2391            HelpEntry::new("S-Tab", "prev").with_category(HelpCategory::Navigation),
2392        ];
2393        let groups = KeybindingHints::grouped_entries(&entries);
2394        assert_eq!(groups.len(), 2);
2395        assert_eq!(*groups[0].0, HelpCategory::Navigation);
2396        assert_eq!(groups[0].1.len(), 2);
2397        assert_eq!(*groups[1].0, HelpCategory::Global);
2398        assert_eq!(groups[1].1.len(), 1);
2399    }
2400
2401    #[test]
2402    fn keybinding_hints_render_short() {
2403        let hints = KeybindingHints::new()
2404            .global_entry("q", "quit")
2405            .global_entry("^s", "save");
2406
2407        let mut pool = GraphemePool::new();
2408        let mut frame = Frame::new(40, 1, &mut pool);
2409        let area = Rect::new(0, 0, 40, 1);
2410        Widget::render(&hints, area, &mut frame);
2411
2412        // First char should be 'q' (plain format)
2413        let cell = frame.buffer.get(0, 0).unwrap();
2414        assert_eq!(cell.content.as_char(), Some('q'));
2415    }
2416
2417    #[test]
2418    fn keybinding_hints_render_short_bracketed() {
2419        let hints = KeybindingHints::new()
2420            .with_key_format(KeyFormat::Bracketed)
2421            .global_entry("q", "quit");
2422
2423        let mut pool = GraphemePool::new();
2424        let mut frame = Frame::new(40, 1, &mut pool);
2425        let area = Rect::new(0, 0, 40, 1);
2426        Widget::render(&hints, area, &mut frame);
2427
2428        // First char should be '[' (bracketed format)
2429        let cell = frame.buffer.get(0, 0).unwrap();
2430        assert_eq!(cell.content.as_char(), Some('['));
2431    }
2432
2433    #[test]
2434    fn keybinding_hints_render_full_grouped() {
2435        let hints = KeybindingHints::new()
2436            .with_mode(HelpMode::Full)
2437            .with_show_categories(true)
2438            .global_entry_categorized("Tab", "next", HelpCategory::Navigation)
2439            .global_entry_categorized("q", "quit", HelpCategory::Global);
2440
2441        let mut pool = GraphemePool::new();
2442        let mut frame = Frame::new(40, 10, &mut pool);
2443        let area = Rect::new(0, 0, 40, 10);
2444        Widget::render(&hints, area, &mut frame);
2445
2446        // Row 0 should contain category header "Navigation"
2447        let mut row0 = String::new();
2448        for x in 0..40u16 {
2449            if let Some(cell) = frame.buffer.get(x, 0)
2450                && let Some(ch) = cell.content.as_char()
2451            {
2452                row0.push(ch);
2453            }
2454        }
2455        assert!(
2456            row0.contains("Navigation"),
2457            "First row should be Navigation header: {row0}"
2458        );
2459    }
2460
2461    #[test]
2462    fn keybinding_hints_render_full_no_categories() {
2463        let hints = KeybindingHints::new()
2464            .with_mode(HelpMode::Full)
2465            .with_show_categories(false)
2466            .global_entry("q", "quit")
2467            .global_entry("^s", "save");
2468
2469        let mut pool = GraphemePool::new();
2470        let mut frame = Frame::new(40, 5, &mut pool);
2471        let area = Rect::new(0, 0, 40, 5);
2472        // Should not panic
2473        Widget::render(&hints, area, &mut frame);
2474    }
2475
2476    #[test]
2477    fn keybinding_hints_render_empty() {
2478        let hints = KeybindingHints::new();
2479
2480        let mut pool = GraphemePool::new();
2481        let mut frame = Frame::new(20, 1, &mut pool);
2482        let area = Rect::new(0, 0, 20, 1);
2483        // Should not panic
2484        Widget::render(&hints, area, &mut frame);
2485        assert_eq!(row_text(&frame.buffer, 0, 20), " ".repeat(20));
2486    }
2487
2488    #[test]
2489    fn keybinding_hints_empty_clears_stale_row() {
2490        let populated = KeybindingHints::new()
2491            .global_entry("q", "quit")
2492            .global_entry("^s", "save");
2493        let empty = KeybindingHints::new();
2494
2495        let mut pool = GraphemePool::new();
2496        let mut frame = Frame::new(20, 1, &mut pool);
2497        let area = Rect::new(0, 0, 20, 1);
2498
2499        Widget::render(&populated, area, &mut frame);
2500        Widget::render(&empty, area, &mut frame);
2501
2502        assert_eq!(row_text(&frame.buffer, 0, 20), " ".repeat(20));
2503    }
2504
2505    #[test]
2506    fn keybinding_hints_full_to_short_clears_stale_lower_rows() {
2507        let full = KeybindingHints::new()
2508            .with_mode(HelpMode::Full)
2509            .with_show_categories(true)
2510            .global_entry("q", "quit")
2511            .global_entry("^s", "save");
2512        let short = KeybindingHints::new().global_entry("x", "exit");
2513
2514        let mut pool = GraphemePool::new();
2515        let mut frame = Frame::new(24, 4, &mut pool);
2516        let area = Rect::new(0, 0, 24, 4);
2517
2518        Widget::render(&full, area, &mut frame);
2519        Widget::render(&short, area, &mut frame);
2520
2521        assert_eq!(row_text(&frame.buffer, 0, 24), "x exit                  ");
2522        assert_eq!(row_text(&frame.buffer, 1, 24), " ".repeat(24));
2523        assert_eq!(row_text(&frame.buffer, 2, 24), " ".repeat(24));
2524        assert_eq!(row_text(&frame.buffer, 3, 24), " ".repeat(24));
2525    }
2526
2527    #[test]
2528    fn keybinding_hints_render_zero_area() {
2529        let hints = KeybindingHints::new().global_entry("q", "quit");
2530
2531        let mut pool = GraphemePool::new();
2532        let mut frame = Frame::new(20, 1, &mut pool);
2533        let area = Rect::new(0, 0, 0, 0);
2534        // Should not panic
2535        Widget::render(&hints, area, &mut frame);
2536    }
2537
2538    #[test]
2539    fn keybinding_hints_is_not_essential() {
2540        let hints = KeybindingHints::new();
2541        assert!(!hints.is_essential());
2542    }
2543
2544    // ── Property tests for KeybindingHints ──────────────────────────
2545
2546    proptest! {
2547        #[test]
2548        fn prop_visible_entries_count(
2549            n_global in 0..5usize,
2550            n_ctx in 0..5usize,
2551            show_ctx in proptest::bool::ANY,
2552        ) {
2553            let mut hints = KeybindingHints::new().with_show_context(show_ctx);
2554            for i in 0..n_global {
2555                hints = hints.global_entry(format!("g{i}"), format!("global {i}"));
2556            }
2557            for i in 0..n_ctx {
2558                hints = hints.contextual_entry(format!("c{i}"), format!("ctx {i}"));
2559            }
2560            let visible = hints.visible_entries();
2561            let expected = if show_ctx { n_global + n_ctx } else { n_global };
2562            prop_assert_eq!(visible.len(), expected);
2563        }
2564
2565        #[test]
2566        fn prop_bracketed_keys_wrapped(
2567            keys in prop::collection::vec(string_regex("[a-z]{1,4}").unwrap(), 1..5),
2568        ) {
2569            let mut hints = KeybindingHints::new().with_key_format(KeyFormat::Bracketed);
2570            for key in &keys {
2571                hints = hints.global_entry(key.clone(), "action");
2572            }
2573            let visible = hints.visible_entries();
2574            for entry in &visible {
2575                prop_assert!(entry.key.starts_with('['), "Key should start with [: {}", entry.key);
2576                prop_assert!(entry.key.ends_with(']'), "Key should end with ]: {}", entry.key);
2577            }
2578        }
2579
2580        #[test]
2581        fn prop_grouped_preserves_count(
2582            entries in prop::collection::vec(
2583                (string_regex("[a-z]{1,4}").unwrap(), 0..3u8),
2584                1..8
2585            ),
2586        ) {
2587            let help_entries: Vec<HelpEntry> = entries.into_iter().map(|(key, cat_idx)| {
2588                let cat = match cat_idx {
2589                    0 => HelpCategory::Navigation,
2590                    1 => HelpCategory::Editing,
2591                    _ => HelpCategory::Global,
2592                };
2593                HelpEntry::new(key, "action").with_category(cat)
2594            }).collect();
2595
2596            let total = help_entries.len();
2597            let groups = KeybindingHints::grouped_entries(&help_entries);
2598            let grouped_total: usize = groups.iter().map(|(_, v)| v.len()).sum();
2599            prop_assert_eq!(total, grouped_total, "Grouping should preserve total entry count");
2600        }
2601
2602        #[test]
2603        fn prop_render_no_panic(
2604            n_global in 0..5usize,
2605            n_ctx in 0..5usize,
2606            width in 1..80u16,
2607            height in 1..20u16,
2608            show_ctx in proptest::bool::ANY,
2609            use_full in proptest::bool::ANY,
2610            use_brackets in proptest::bool::ANY,
2611            show_cats in proptest::bool::ANY,
2612        ) {
2613            let mode = if use_full { HelpMode::Full } else { HelpMode::Short };
2614            let fmt = if use_brackets { KeyFormat::Bracketed } else { KeyFormat::Plain };
2615            let mut hints = KeybindingHints::new()
2616                .with_mode(mode)
2617                .with_key_format(fmt)
2618                .with_show_context(show_ctx)
2619                .with_show_categories(show_cats);
2620
2621            for i in 0..n_global {
2622                hints = hints.global_entry(format!("g{i}"), format!("global action {i}"));
2623            }
2624            for i in 0..n_ctx {
2625                hints = hints.contextual_entry(format!("c{i}"), format!("ctx action {i}"));
2626            }
2627
2628            let mut pool = GraphemePool::new();
2629            let mut frame = Frame::new(width, height, &mut pool);
2630            let area = Rect::new(0, 0, width, height);
2631            Widget::render(&hints, area, &mut frame);
2632            // No panic = pass
2633        }
2634    }
2635
2636    // ========================================================================
2637    // Edge-case tests (bd-1noim)
2638    // ========================================================================
2639
2640    // ── HelpCategory edge cases ─────────────────────────────────────
2641
2642    #[test]
2643    fn help_category_custom_empty_string() {
2644        let cat = HelpCategory::Custom(String::new());
2645        assert_eq!(cat.label(), "");
2646    }
2647
2648    #[test]
2649    fn help_category_custom_eq() {
2650        let a = HelpCategory::Custom("Foo".into());
2651        let b = HelpCategory::Custom("Foo".into());
2652        let c = HelpCategory::Custom("Bar".into());
2653        assert_eq!(a, b);
2654        assert_ne!(a, c);
2655    }
2656
2657    #[test]
2658    fn help_category_clone() {
2659        let cat = HelpCategory::Navigation;
2660        let cloned = cat.clone();
2661        assert_eq!(cat, cloned);
2662    }
2663
2664    #[test]
2665    fn help_category_hash_consistency() {
2666        use std::collections::hash_map::DefaultHasher;
2667        let mut h1 = DefaultHasher::new();
2668        let mut h2 = DefaultHasher::new();
2669        HelpCategory::File.hash(&mut h1);
2670        HelpCategory::File.hash(&mut h2);
2671        assert_eq!(h1.finish(), h2.finish());
2672    }
2673
2674    #[test]
2675    fn help_category_debug_format() {
2676        let dbg = format!("{:?}", HelpCategory::General);
2677        assert!(dbg.contains("General"));
2678        let dbg_custom = format!("{:?}", HelpCategory::Custom("X".into()));
2679        assert!(dbg_custom.contains("Custom"));
2680    }
2681
2682    // ── HelpEntry edge cases ────────────────────────────────────────
2683
2684    #[test]
2685    fn help_entry_empty_key_and_desc() {
2686        let entry = HelpEntry::new("", "");
2687        assert!(entry.key.is_empty());
2688        assert!(entry.desc.is_empty());
2689        assert!(entry.enabled);
2690    }
2691
2692    #[test]
2693    fn help_entry_clone() {
2694        let entry = HelpEntry::new("q", "quit").with_category(HelpCategory::File);
2695        let cloned = entry.clone();
2696        assert_eq!(entry, cloned);
2697    }
2698
2699    #[test]
2700    fn help_entry_debug_format() {
2701        let entry = HelpEntry::new("^s", "save");
2702        let dbg = format!("{:?}", entry);
2703        assert!(dbg.contains("HelpEntry"));
2704        assert!(dbg.contains("save"));
2705    }
2706
2707    // ── HelpMode edge cases ─────────────────────────────────────────
2708
2709    #[test]
2710    fn help_mode_default_is_short() {
2711        assert_eq!(HelpMode::default(), HelpMode::Short);
2712    }
2713
2714    #[test]
2715    fn help_mode_eq_and_hash() {
2716        use std::collections::hash_map::DefaultHasher;
2717        assert_eq!(HelpMode::Short, HelpMode::Short);
2718        assert_ne!(HelpMode::Short, HelpMode::Full);
2719        let mut h = DefaultHasher::new();
2720        HelpMode::Full.hash(&mut h);
2721        // Just verify it doesn't panic
2722    }
2723
2724    #[test]
2725    fn help_mode_copy() {
2726        let m = HelpMode::Full;
2727        let m2 = m; // Copy
2728        assert_eq!(m, m2);
2729    }
2730
2731    // ── Help rendering edge cases ───────────────────────────────────
2732
2733    #[test]
2734    fn render_short_all_disabled() {
2735        let help = Help::new()
2736            .with_entry(HelpEntry::new("a", "first").with_enabled(false))
2737            .with_entry(HelpEntry::new("b", "second").with_enabled(false));
2738
2739        let mut pool = GraphemePool::new();
2740        let mut frame = Frame::new(40, 1, &mut pool);
2741        let area = Rect::new(0, 0, 40, 1);
2742        Widget::render(&help, area, &mut frame);
2743        // No visible entries, buffer stays default
2744        let cell = frame.buffer.get(0, 0).unwrap();
2745        assert!(cell.content.is_empty() || cell.content.as_char() == Some(' '));
2746    }
2747
2748    #[test]
2749    fn render_short_empty_key_desc_entries_skipped() {
2750        let help = Help::new()
2751            .with_entry(HelpEntry::new("", ""))
2752            .entry("q", "quit");
2753
2754        let mut pool = GraphemePool::new();
2755        let mut frame = Frame::new(40, 1, &mut pool);
2756        let area = Rect::new(0, 0, 40, 1);
2757        Widget::render(&help, area, &mut frame);
2758        // The empty entry produces no text but separator logic still fires.
2759        // Verify 'q' appears somewhere in the rendered row.
2760        let mut found_q = false;
2761        for x in 0..40 {
2762            if let Some(cell) = frame.buffer.get(x, 0)
2763                && cell.content.as_char() == Some('q')
2764            {
2765                found_q = true;
2766                break;
2767            }
2768        }
2769        assert!(found_q, "'q' should appear in the rendered row");
2770    }
2771
2772    #[test]
2773    fn render_short_width_one() {
2774        let help = Help::new().entry("q", "quit");
2775
2776        let mut pool = GraphemePool::new();
2777        let mut frame = Frame::new(1, 1, &mut pool);
2778        let area = Rect::new(0, 0, 1, 1);
2779        Widget::render(&help, area, &mut frame);
2780        // Should not panic; may show ellipsis or partial
2781    }
2782
2783    #[test]
2784    fn render_full_width_one() {
2785        let help = Help::new().with_mode(HelpMode::Full).entry("q", "quit");
2786
2787        let mut pool = GraphemePool::new();
2788        let mut frame = Frame::new(1, 5, &mut pool);
2789        let area = Rect::new(0, 0, 1, 5);
2790        Widget::render(&help, area, &mut frame);
2791        // Should not panic
2792    }
2793
2794    #[test]
2795    fn render_full_height_one() {
2796        let help = Help::new()
2797            .with_mode(HelpMode::Full)
2798            .entry("a", "first")
2799            .entry("b", "second")
2800            .entry("c", "third");
2801
2802        let mut pool = GraphemePool::new();
2803        let mut frame = Frame::new(40, 1, &mut pool);
2804        let area = Rect::new(0, 0, 40, 1);
2805        Widget::render(&help, area, &mut frame);
2806        // Only first entry should render
2807    }
2808
2809    #[test]
2810    fn render_short_single_entry_exact_fit() {
2811        // "q quit" = 6 chars, area width = 6
2812        let help = Help::new().entry("q", "quit");
2813
2814        let mut pool = GraphemePool::new();
2815        let mut frame = Frame::new(6, 1, &mut pool);
2816        let area = Rect::new(0, 0, 6, 1);
2817        Widget::render(&help, area, &mut frame);
2818        let cell = frame.buffer.get(0, 0).unwrap();
2819        assert_eq!(cell.content.as_char(), Some('q'));
2820    }
2821
2822    #[test]
2823    fn render_short_empty_separator() {
2824        let help = Help::new()
2825            .with_separator("")
2826            .entry("a", "x")
2827            .entry("b", "y");
2828
2829        let mut pool = GraphemePool::new();
2830        let mut frame = Frame::new(40, 1, &mut pool);
2831        let area = Rect::new(0, 0, 40, 1);
2832        Widget::render(&help, area, &mut frame);
2833        // Both entries render without separator
2834        let cell = frame.buffer.get(0, 0).unwrap();
2835        assert_eq!(cell.content.as_char(), Some('a'));
2836    }
2837
2838    // ── Help builder edge cases ─────────────────────────────────────
2839
2840    #[test]
2841    fn help_with_mode_full() {
2842        let help = Help::new().with_mode(HelpMode::Full);
2843        assert_eq!(help.mode(), HelpMode::Full);
2844    }
2845
2846    #[test]
2847    fn help_clone() {
2848        let help = Help::new()
2849            .entry("q", "quit")
2850            .with_separator(" | ")
2851            .with_ellipsis("...");
2852        let cloned = help.clone();
2853        assert_eq!(cloned.entries().len(), 1);
2854        assert_eq!(cloned.separator, " | ");
2855        assert_eq!(cloned.ellipsis, "...");
2856    }
2857
2858    #[test]
2859    fn help_debug_format() {
2860        let help = Help::new().entry("q", "quit");
2861        let dbg = format!("{:?}", help);
2862        assert!(dbg.contains("Help"));
2863    }
2864
2865    // ── HelpRenderState edge cases ──────────────────────────────────
2866
2867    #[test]
2868    fn help_render_state_default() {
2869        let state = HelpRenderState::default();
2870        assert!(state.cache.is_none());
2871        assert!(state.dirty_rects().is_empty());
2872        assert_eq!(state.stats().hits, 0);
2873        assert_eq!(state.stats().misses, 0);
2874    }
2875
2876    #[test]
2877    fn help_render_state_clear_dirty_rects() {
2878        let mut state = HelpRenderState::default();
2879        state.dirty_rects.push(Rect::new(0, 0, 10, 1));
2880        assert_eq!(state.dirty_rects().len(), 1);
2881        state.clear_dirty_rects();
2882        assert!(state.dirty_rects().is_empty());
2883    }
2884
2885    #[test]
2886    fn help_render_state_take_dirty_rects() {
2887        let mut state = HelpRenderState::default();
2888        state.dirty_rects.push(Rect::new(0, 0, 5, 1));
2889        state.dirty_rects.push(Rect::new(0, 1, 5, 1));
2890        let taken = state.take_dirty_rects();
2891        assert_eq!(taken.len(), 2);
2892        assert!(state.dirty_rects().is_empty()); // cleared after take
2893    }
2894
2895    #[test]
2896    fn help_render_state_reset_stats() {
2897        let mut state = HelpRenderState::default();
2898        state.stats.hits = 42;
2899        state.stats.misses = 7;
2900        state.stats.dirty_updates = 3;
2901        state.stats.layout_rebuilds = 2;
2902        state.reset_stats();
2903        assert_eq!(state.stats(), HelpCacheStats::default());
2904    }
2905
2906    #[test]
2907    fn help_cache_stats_default() {
2908        let stats = HelpCacheStats::default();
2909        assert_eq!(stats.hits, 0);
2910        assert_eq!(stats.misses, 0);
2911        assert_eq!(stats.dirty_updates, 0);
2912        assert_eq!(stats.layout_rebuilds, 0);
2913    }
2914
2915    #[test]
2916    fn help_cache_stats_clone_eq() {
2917        let a = HelpCacheStats {
2918            hits: 5,
2919            misses: 2,
2920            dirty_updates: 1,
2921            layout_rebuilds: 3,
2922        };
2923        let b = a;
2924        assert_eq!(a, b);
2925    }
2926
2927    #[test]
2928    fn stateful_render_empty_area_clears_cache() {
2929        let help = Help::new().entry("q", "quit");
2930        let mut state = HelpRenderState::default();
2931        let mut pool = GraphemePool::new();
2932        let mut frame = Frame::new(40, 1, &mut pool);
2933        let area = Rect::new(0, 0, 40, 1);
2934
2935        // First render populates cache
2936        StatefulWidget::render(&help, area, &mut frame, &mut state);
2937        assert!(state.cache.is_some());
2938        state.dirty_rects.push(Rect::new(0, 0, 3, 1));
2939        state.dirty_indices.push(0);
2940        state.enabled_indices.push(0);
2941
2942        // Render with empty area clears cache and transient dirty state.
2943        let empty = Rect::new(0, 0, 0, 0);
2944        StatefulWidget::render(&help, empty, &mut frame, &mut state);
2945        assert!(state.cache.is_none());
2946        assert!(state.dirty_rects().is_empty());
2947        assert!(state.dirty_indices.is_empty());
2948        assert!(state.enabled_indices.is_empty());
2949    }
2950
2951    #[test]
2952    fn stateful_render_cache_miss_on_area_change() {
2953        let help = Help::new().entry("q", "quit").entry("^s", "save");
2954        let mut state = HelpRenderState::default();
2955        let mut pool = GraphemePool::new();
2956        let mut frame = Frame::new(80, 5, &mut pool);
2957
2958        StatefulWidget::render(&help, Rect::new(0, 0, 40, 1), &mut frame, &mut state);
2959        let misses1 = state.stats().misses;
2960
2961        StatefulWidget::render(&help, Rect::new(0, 0, 60, 1), &mut frame, &mut state);
2962        let misses2 = state.stats().misses;
2963
2964        assert!(misses2 > misses1, "Area change should cause cache miss");
2965    }
2966
2967    #[test]
2968    fn stateful_render_cache_miss_on_mode_change() {
2969        let mut help = Help::new().entry("q", "quit");
2970        let mut state = HelpRenderState::default();
2971        let mut pool = GraphemePool::new();
2972        let mut frame = Frame::new(40, 5, &mut pool);
2973        let area = Rect::new(0, 0, 40, 5);
2974
2975        StatefulWidget::render(&help, area, &mut frame, &mut state);
2976        let misses1 = state.stats().misses;
2977
2978        help.toggle_mode();
2979        StatefulWidget::render(&help, area, &mut frame, &mut state);
2980        let misses2 = state.stats().misses;
2981
2982        assert!(misses2 > misses1, "Mode change should cause cache miss");
2983    }
2984
2985    #[test]
2986    fn stateful_render_layout_rebuild_on_enabled_count_change() {
2987        let mut help = Help::new()
2988            .entry("q", "quit")
2989            .entry("^s", "save")
2990            .entry("^x", "exit");
2991        let mut state = HelpRenderState::default();
2992        let mut pool = GraphemePool::new();
2993        let mut frame = Frame::new(80, 1, &mut pool);
2994        let area = Rect::new(0, 0, 80, 1);
2995
2996        StatefulWidget::render(&help, area, &mut frame, &mut state);
2997        let rebuilds1 = state.stats().layout_rebuilds;
2998
2999        // Disable one entry
3000        help.entries[1].enabled = false;
3001        StatefulWidget::render(&help, area, &mut frame, &mut state);
3002        let rebuilds2 = state.stats().layout_rebuilds;
3003
3004        assert!(
3005            rebuilds2 > rebuilds1,
3006            "Enabled count change should trigger layout rebuild"
3007        );
3008    }
3009
3010    // ── KeyFormat edge cases ────────────────────────────────────────
3011
3012    #[test]
3013    fn key_format_eq_and_hash() {
3014        use std::collections::hash_map::DefaultHasher;
3015        assert_eq!(KeyFormat::Plain, KeyFormat::Plain);
3016        assert_ne!(KeyFormat::Plain, KeyFormat::Bracketed);
3017        let mut h = DefaultHasher::new();
3018        KeyFormat::Bracketed.hash(&mut h);
3019    }
3020
3021    #[test]
3022    fn key_format_copy() {
3023        let f = KeyFormat::Bracketed;
3024        let f2 = f;
3025        assert_eq!(f, f2);
3026    }
3027
3028    #[test]
3029    fn key_format_debug() {
3030        let dbg = format!("{:?}", KeyFormat::Bracketed);
3031        assert!(dbg.contains("Bracketed"));
3032    }
3033
3034    // ── KeybindingHints edge cases ──────────────────────────────────
3035
3036    #[test]
3037    fn keybinding_hints_clone() {
3038        let hints = KeybindingHints::new()
3039            .global_entry("q", "quit")
3040            .contextual_entry("^s", "save");
3041        let cloned = hints.clone();
3042        assert_eq!(cloned.global_entries().len(), 1);
3043        assert_eq!(cloned.contextual_entries().len(), 1);
3044    }
3045
3046    #[test]
3047    fn keybinding_hints_debug() {
3048        let hints = KeybindingHints::new().global_entry("q", "quit");
3049        let dbg = format!("{:?}", hints);
3050        assert!(dbg.contains("KeybindingHints"));
3051    }
3052
3053    #[test]
3054    fn keybinding_hints_with_separator() {
3055        let hints = KeybindingHints::new().with_separator(" | ");
3056        assert_eq!(hints.separator, " | ");
3057    }
3058
3059    #[test]
3060    fn keybinding_hints_with_styles() {
3061        let hints = KeybindingHints::new()
3062            .with_key_style(Style::new().bold())
3063            .with_desc_style(Style::default())
3064            .with_separator_style(Style::default())
3065            .with_category_style(Style::new().underline());
3066        // Just verify builder doesn't panic
3067        assert_eq!(hints.mode(), HelpMode::Short);
3068    }
3069
3070    #[test]
3071    fn keybinding_hints_visible_entries_disabled_contextual() {
3072        let hints = KeybindingHints::new()
3073            .with_show_context(true)
3074            .global_entry("q", "quit")
3075            .with_contextual_entry(HelpEntry::new("^s", "save").with_enabled(false));
3076        let visible = hints.visible_entries();
3077        // Only global "q" visible; disabled contextual "^s" hidden
3078        assert_eq!(visible.len(), 1);
3079        assert_eq!(visible[0].desc, "quit");
3080    }
3081
3082    #[test]
3083    fn keybinding_hints_empty_global_nonempty_ctx_hidden() {
3084        let hints = KeybindingHints::new()
3085            .contextual_entry("^s", "save")
3086            .contextual_entry("^f", "find");
3087        // Context off by default
3088        let visible = hints.visible_entries();
3089        assert!(visible.is_empty());
3090    }
3091
3092    #[test]
3093    fn keybinding_hints_render_full_grouped_height_limit() {
3094        let hints = KeybindingHints::new()
3095            .with_mode(HelpMode::Full)
3096            .with_show_categories(true)
3097            .global_entry_categorized("a", "first", HelpCategory::Navigation)
3098            .global_entry_categorized("b", "second", HelpCategory::Navigation)
3099            .global_entry_categorized("c", "third", HelpCategory::Navigation)
3100            .global_entry_categorized("d", "fourth", HelpCategory::Global)
3101            .global_entry_categorized("e", "fifth", HelpCategory::Global);
3102
3103        let mut pool = GraphemePool::new();
3104        // Only 3 rows: header + 2 entries, can't fit all
3105        let mut frame = Frame::new(40, 3, &mut pool);
3106        let area = Rect::new(0, 0, 40, 3);
3107        Widget::render(&hints, area, &mut frame);
3108        // Should not panic; clips to available height
3109    }
3110
3111    #[test]
3112    fn keybinding_hints_render_empty_area() {
3113        let hints = KeybindingHints::new().global_entry("q", "quit");
3114        let mut pool = GraphemePool::new();
3115        let mut frame = Frame::new(1, 1, &mut pool);
3116        Widget::render(&hints, Rect::new(0, 0, 0, 0), &mut frame);
3117        // Should not panic (is_empty check)
3118    }
3119
3120    // ── Help entry_hash edge cases ──────────────────────────────────
3121
3122    #[test]
3123    fn entry_hash_differs_for_different_keys() {
3124        let a = HelpEntry::new("q", "quit");
3125        let b = HelpEntry::new("x", "quit");
3126        assert_ne!(Help::entry_hash(&a), Help::entry_hash(&b));
3127    }
3128
3129    #[test]
3130    fn entry_hash_differs_for_different_descs() {
3131        let a = HelpEntry::new("q", "quit");
3132        let b = HelpEntry::new("q", "exit");
3133        assert_ne!(Help::entry_hash(&a), Help::entry_hash(&b));
3134    }
3135
3136    #[test]
3137    fn entry_hash_differs_for_enabled_flag() {
3138        let a = HelpEntry::new("q", "quit");
3139        let b = HelpEntry::new("q", "quit").with_enabled(false);
3140        assert_ne!(Help::entry_hash(&a), Help::entry_hash(&b));
3141    }
3142
3143    #[test]
3144    fn entry_hash_same_for_equal_entries() {
3145        let a = HelpEntry::new("q", "quit");
3146        let b = HelpEntry::new("q", "quit");
3147        assert_eq!(Help::entry_hash(&a), Help::entry_hash(&b));
3148    }
3149
3150    // ── Additional edge-case tests (bd-1noim, LavenderStone) ─────────
3151
3152    // ── HelpCategory: variant inequality + Custom("General") != General ──
3153
3154    #[test]
3155    fn help_category_custom_general_not_eq_general() {
3156        // Custom("General") and General are different enum variants
3157        assert_ne!(
3158            HelpCategory::Custom("General".into()),
3159            HelpCategory::General
3160        );
3161    }
3162
3163    #[test]
3164    fn help_category_all_variants_distinct() {
3165        let variants: Vec<HelpCategory> = vec![
3166            HelpCategory::General,
3167            HelpCategory::Navigation,
3168            HelpCategory::Editing,
3169            HelpCategory::File,
3170            HelpCategory::View,
3171            HelpCategory::Global,
3172            HelpCategory::Custom("X".into()),
3173        ];
3174        for (i, a) in variants.iter().enumerate() {
3175            for (j, b) in variants.iter().enumerate() {
3176                if i != j {
3177                    assert_ne!(a, b, "Variant {i} should differ from variant {j}");
3178                }
3179            }
3180        }
3181    }
3182
3183    // ── HelpEntry: field-by-field hash sensitivity ───────────────────
3184
3185    #[test]
3186    fn help_entry_hash_differs_by_category() {
3187        let a = HelpEntry::new("q", "quit");
3188        let b = HelpEntry::new("q", "quit").with_category(HelpCategory::File);
3189        assert_ne!(Help::entry_hash(&a), Help::entry_hash(&b));
3190    }
3191
3192    #[test]
3193    fn help_entry_only_key_no_desc_renders() {
3194        let help = Help::new().with_entry(HelpEntry::new("q", ""));
3195        let mut pool = GraphemePool::new();
3196        let mut frame = Frame::new(20, 1, &mut pool);
3197        let area = Rect::new(0, 0, 20, 1);
3198        Widget::render(&help, area, &mut frame);
3199        // "q " should render (key + space + empty desc)
3200        let cell = frame.buffer.get(0, 0).unwrap();
3201        assert_eq!(cell.content.as_char(), Some('q'));
3202    }
3203
3204    #[test]
3205    fn help_entry_only_desc_no_key_renders() {
3206        let help = Help::new().with_entry(HelpEntry::new("", "quit"));
3207        let mut pool = GraphemePool::new();
3208        let mut frame = Frame::new(20, 1, &mut pool);
3209        let area = Rect::new(0, 0, 20, 1);
3210        Widget::render(&help, area, &mut frame);
3211        // " quit" should render (empty key + space + desc)
3212        let cell = frame.buffer.get(1, 0).unwrap();
3213        assert_eq!(cell.content.as_char(), Some('q'));
3214    }
3215
3216    #[test]
3217    fn help_entry_unicode_key_and_desc() {
3218        let help = Help::new().with_entry(HelpEntry::new("\u{2191}", "up arrow"));
3219        let mut pool = GraphemePool::new();
3220        let mut frame = Frame::new(20, 1, &mut pool);
3221        let area = Rect::new(0, 0, 20, 1);
3222        Widget::render(&help, area, &mut frame);
3223    }
3224
3225    #[test]
3226    fn help_entry_chained_builder_overrides() {
3227        let entry = HelpEntry::new("q", "quit")
3228            .with_enabled(false)
3229            .with_category(HelpCategory::File)
3230            .with_enabled(true)
3231            .with_category(HelpCategory::View);
3232        assert!(entry.enabled);
3233        assert_eq!(entry.category, HelpCategory::View);
3234    }
3235
3236    // ── Help: rendering with area offsets ─────────────────────────────
3237
3238    #[test]
3239    fn render_short_area_offset() {
3240        let help = Help::new().entry("x", "action");
3241        let mut pool = GraphemePool::new();
3242        let mut frame = Frame::new(40, 5, &mut pool);
3243        let area = Rect::new(5, 2, 20, 1);
3244        Widget::render(&help, area, &mut frame);
3245        let cell = frame.buffer.get(5, 2).unwrap();
3246        assert_eq!(cell.content.as_char(), Some('x'));
3247        // Column 0,0 should be untouched
3248        let cell_origin = frame.buffer.get(0, 0).unwrap();
3249        assert!(cell_origin.content.is_empty() || cell_origin.content.as_char() == Some(' '));
3250    }
3251
3252    #[test]
3253    fn render_full_area_offset() {
3254        let help = Help::new().with_mode(HelpMode::Full).entry("q", "quit");
3255        let mut pool = GraphemePool::new();
3256        let mut frame = Frame::new(40, 5, &mut pool);
3257        let area = Rect::new(3, 1, 20, 3);
3258        Widget::render(&help, area, &mut frame);
3259        let cell = frame.buffer.get(3, 1).unwrap();
3260        assert_eq!(cell.content.as_char(), Some('q'));
3261    }
3262
3263    // ── Help: full mode with all entries disabled ─────────────────────
3264
3265    #[test]
3266    fn render_full_all_disabled() {
3267        let help = Help::new()
3268            .with_mode(HelpMode::Full)
3269            .with_entry(HelpEntry::new("a", "first").with_enabled(false))
3270            .with_entry(HelpEntry::new("b", "second").with_enabled(false));
3271        let mut pool = GraphemePool::new();
3272        let mut frame = Frame::new(30, 3, &mut pool);
3273        let area = Rect::new(0, 0, 30, 3);
3274        Widget::render(&help, area, &mut frame);
3275    }
3276
3277    // ── Help: ellipsis with empty ellipsis string ─────────────────────
3278
3279    #[test]
3280    fn render_short_empty_ellipsis_string() {
3281        let help = Help::new()
3282            .with_ellipsis("")
3283            .entry("q", "quit")
3284            .entry("w", "this is a very long description that overflows");
3285        let mut pool = GraphemePool::new();
3286        let mut frame = Frame::new(12, 1, &mut pool);
3287        let area = Rect::new(0, 0, 12, 1);
3288        Widget::render(&help, area, &mut frame);
3289    }
3290
3291    // ── Help: entry wider than entire area ────────────────────────────
3292
3293    #[test]
3294    fn render_short_entry_wider_than_area() {
3295        let help = Help::new().entry("verylongkey", "very long description text");
3296        let mut pool = GraphemePool::new();
3297        let mut frame = Frame::new(3, 1, &mut pool);
3298        let area = Rect::new(0, 0, 3, 1);
3299        Widget::render(&help, area, &mut frame);
3300    }
3301
3302    // ── Stateful: style change invalidates cache ──────────────────────
3303
3304    #[test]
3305    fn stateful_cache_invalidated_on_style_change() {
3306        let help1 = Help::new().entry("q", "quit");
3307        let help2 = Help::new()
3308            .entry("q", "quit")
3309            .with_key_style(Style::new().italic());
3310        let mut state = HelpRenderState::default();
3311        let mut pool = GraphemePool::new();
3312        let mut frame = Frame::new(40, 1, &mut pool);
3313        let area = Rect::new(0, 0, 40, 1);
3314
3315        StatefulWidget::render(&help1, area, &mut frame, &mut state);
3316        let misses_1 = state.stats().misses;
3317
3318        StatefulWidget::render(&help2, area, &mut frame, &mut state);
3319        assert!(
3320            state.stats().misses > misses_1,
3321            "Style change should cause cache miss"
3322        );
3323    }
3324
3325    // ── Stateful: entry addition triggers layout rebuild ──────────────
3326
3327    #[test]
3328    fn stateful_entry_addition_rebuilds_layout() {
3329        let mut help = Help::new().entry("q", "quit");
3330        let mut state = HelpRenderState::default();
3331        let mut pool = GraphemePool::new();
3332        let mut frame = Frame::new(40, 3, &mut pool);
3333        let area = Rect::new(0, 0, 40, 3);
3334
3335        StatefulWidget::render(&help, area, &mut frame, &mut state);
3336        let rebuilds_1 = state.stats().layout_rebuilds;
3337
3338        help.push_entry(HelpEntry::new("w", "write"));
3339        StatefulWidget::render(&help, area, &mut frame, &mut state);
3340        assert!(
3341            state.stats().layout_rebuilds > rebuilds_1,
3342            "Entry addition should rebuild layout"
3343        );
3344    }
3345
3346    // ── Stateful: separator change invalidates cache ──────────────────
3347
3348    #[test]
3349    fn stateful_separator_change_invalidates_cache() {
3350        let help1 = Help::new()
3351            .with_separator(" | ")
3352            .entry("q", "quit")
3353            .entry("w", "write");
3354        let help2 = Help::new()
3355            .with_separator(" - ")
3356            .entry("q", "quit")
3357            .entry("w", "write");
3358        let mut state = HelpRenderState::default();
3359        let mut pool = GraphemePool::new();
3360        let mut frame = Frame::new(40, 1, &mut pool);
3361        let area = Rect::new(0, 0, 40, 1);
3362
3363        StatefulWidget::render(&help1, area, &mut frame, &mut state);
3364        let misses_1 = state.stats().misses;
3365
3366        StatefulWidget::render(&help2, area, &mut frame, &mut state);
3367        assert!(
3368            state.stats().misses > misses_1,
3369            "Separator change should cause cache miss"
3370        );
3371    }
3372
3373    // ── Stateful: dirty update in full mode tracks correct rects ──────
3374
3375    #[test]
3376    fn stateful_full_mode_dirty_update_multiple() {
3377        let mut help = Help::new()
3378            .with_mode(HelpMode::Full)
3379            .entry("q", "quit")
3380            .entry("w", "save")
3381            .entry("e", "edit");
3382        let mut state = HelpRenderState::default();
3383        let mut pool = GraphemePool::new();
3384        let mut frame = Frame::new(40, 5, &mut pool);
3385        let area = Rect::new(0, 0, 40, 5);
3386
3387        StatefulWidget::render(&help, area, &mut frame, &mut state);
3388
3389        // Change two entries (same-length descs to stay within slot width)
3390        help.entries[0].desc = "exit".to_string();
3391        help.entries[2].desc = "view".to_string();
3392        StatefulWidget::render(&help, area, &mut frame, &mut state);
3393        let dirty = state.take_dirty_rects();
3394        assert_eq!(dirty.len(), 2, "Two changed entries produce 2 dirty rects");
3395    }
3396
3397    // ── Stateful: short mode dirty update ─────────────────────────────
3398
3399    #[test]
3400    fn stateful_short_mode_dirty_update() {
3401        let mut help = Help::new()
3402            .with_mode(HelpMode::Short)
3403            .entry("q", "quit")
3404            .entry("w", "write");
3405        let mut state = HelpRenderState::default();
3406        let mut pool = GraphemePool::new();
3407        let mut frame = Frame::new(40, 1, &mut pool);
3408        let area = Rect::new(0, 0, 40, 1);
3409
3410        StatefulWidget::render(&help, area, &mut frame, &mut state);
3411
3412        help.entries[0].desc = "exit".to_string();
3413        StatefulWidget::render(&help, area, &mut frame, &mut state);
3414        assert!(
3415            state.stats().dirty_updates > 0,
3416            "Changed desc should trigger dirty update"
3417        );
3418    }
3419
3420    // ── Layout builder edge cases ────────────────────────────────────
3421
3422    #[test]
3423    fn build_short_layout_no_enabled_entries() {
3424        let help = Help::new().with_entry(HelpEntry::new("a", "b").with_enabled(false));
3425        let layout = help.build_short_layout(Rect::new(0, 0, 40, 1));
3426        assert!(layout.entries.is_empty());
3427        assert!(layout.ellipsis.is_none());
3428    }
3429
3430    #[test]
3431    fn build_full_layout_no_enabled_entries() {
3432        let help = Help::new().with_entry(HelpEntry::new("a", "b").with_enabled(false));
3433        let layout = help.build_full_layout(Rect::new(0, 0, 40, 5));
3434        assert!(layout.entries.is_empty());
3435        assert_eq!(layout.max_key_width, 0);
3436    }
3437
3438    #[test]
3439    fn build_short_layout_triggers_ellipsis() {
3440        let help = Help::new()
3441            .entry("longkey", "long description text here")
3442            .entry("another", "even longer description text");
3443        let layout = help.build_short_layout(Rect::new(0, 0, 20, 1));
3444        // Second entry won't fit; ellipsis should appear
3445        assert!(
3446            !layout.entries.is_empty() || layout.ellipsis.is_some(),
3447            "Should have entries or ellipsis"
3448        );
3449    }
3450
3451    #[test]
3452    fn build_full_layout_respects_height() {
3453        let help = Help::new()
3454            .entry("a", "first")
3455            .entry("b", "second")
3456            .entry("c", "third")
3457            .entry("d", "fourth");
3458        let layout = help.build_full_layout(Rect::new(0, 0, 40, 2));
3459        assert_eq!(layout.entries.len(), 2, "Should respect height=2 limit");
3460    }
3461
3462    #[test]
3463    fn build_short_layout_zero_width() {
3464        let help = Help::new().entry("q", "quit");
3465        let layout = help.build_short_layout(Rect::new(0, 0, 0, 1));
3466        assert!(layout.entries.is_empty());
3467    }
3468
3469    #[test]
3470    fn build_full_layout_zero_height() {
3471        let help = Help::new().entry("q", "quit");
3472        let layout = help.build_full_layout(Rect::new(0, 0, 40, 0));
3473        assert!(layout.entries.is_empty());
3474    }
3475
3476    // ── entry_fits_slot edge cases ───────────────────────────────────
3477
3478    #[test]
3479    fn entry_fits_slot_out_of_bounds_index_short() {
3480        let help = Help::new().entry("q", "quit");
3481        let layout = help.build_short_layout(Rect::new(0, 0, 40, 1));
3482        let entry = &help.entries[0];
3483        assert!(!entry_fits_slot(entry, 999, &layout));
3484    }
3485
3486    #[test]
3487    fn entry_fits_slot_out_of_bounds_index_full() {
3488        let help = Help::new().entry("q", "quit");
3489        let layout = help.build_full_layout(Rect::new(0, 0, 40, 1));
3490        let entry = &help.entries[0];
3491        assert!(!entry_fits_slot(entry, 999, &layout));
3492    }
3493
3494    #[test]
3495    fn entry_fits_slot_full_key_too_wide() {
3496        let help = Help::new().entry("x", "d");
3497        let layout = help.build_full_layout(Rect::new(0, 0, 40, 1));
3498        if !layout.entries.is_empty() {
3499            let wide_entry = HelpEntry::new("verylongkeyname", "d");
3500            assert!(!entry_fits_slot(&wide_entry, 0, &layout));
3501        }
3502    }
3503
3504    // ── collect_enabled_indices edge cases ────────────────────────────
3505
3506    #[test]
3507    fn collect_enabled_indices_all_disabled() {
3508        let entries = vec![
3509            HelpEntry::new("a", "b").with_enabled(false),
3510            HelpEntry::new("c", "d").with_enabled(false),
3511        ];
3512        let mut out = Vec::new();
3513        let count = collect_enabled_indices(&entries, &mut out);
3514        assert_eq!(count, 0);
3515        assert!(out.is_empty());
3516    }
3517
3518    #[test]
3519    fn collect_enabled_indices_empty_entries_filtered() {
3520        let entries = vec![
3521            HelpEntry::new("", ""),
3522            HelpEntry::new("q", "quit"),
3523            HelpEntry::new("", ""),
3524        ];
3525        let mut out = Vec::new();
3526        let count = collect_enabled_indices(&entries, &mut out);
3527        assert_eq!(count, 1);
3528        assert_eq!(out, vec![1]);
3529    }
3530
3531    #[test]
3532    fn collect_enabled_indices_mixed() {
3533        let entries = vec![
3534            HelpEntry::new("a", "first"),
3535            HelpEntry::new("b", "second").with_enabled(false),
3536            HelpEntry::new("", ""),
3537            HelpEntry::new("d", "fourth"),
3538        ];
3539        let mut out = Vec::new();
3540        let count = collect_enabled_indices(&entries, &mut out);
3541        assert_eq!(count, 2);
3542        assert_eq!(out, vec![0, 3]);
3543    }
3544
3545    #[test]
3546    fn collect_enabled_indices_clears_previous_data() {
3547        let entries = vec![HelpEntry::new("a", "b")];
3548        let mut out = vec![99, 100, 101];
3549        let count = collect_enabled_indices(&entries, &mut out);
3550        assert_eq!(count, 1);
3551        assert_eq!(out, vec![0]);
3552    }
3553
3554    // ── blit_cache edge cases ────────────────────────────────────────
3555
3556    #[test]
3557    fn blit_cache_none_is_noop() {
3558        let mut pool = GraphemePool::new();
3559        let mut frame = Frame::new(10, 1, &mut pool);
3560        let area = Rect::new(0, 0, 10, 1);
3561        blit_cache(None, area, &mut frame);
3562    }
3563
3564    // ── StyleKey edge cases ──────────────────────────────────────────
3565
3566    #[test]
3567    fn style_key_from_default_style() {
3568        let sk = StyleKey::from(Style::default());
3569        assert!(sk.fg.is_none());
3570        assert!(sk.bg.is_none());
3571        assert!(sk.attrs.is_none());
3572    }
3573
3574    #[test]
3575    fn style_key_from_styled() {
3576        let style = Style::new().bold();
3577        let sk = StyleKey::from(style);
3578        assert!(sk.attrs.is_some());
3579    }
3580
3581    #[test]
3582    fn style_key_equality_and_hash() {
3583        use std::collections::hash_map::DefaultHasher;
3584        let a = StyleKey::from(Style::new().italic());
3585        let b = StyleKey::from(Style::new().italic());
3586        assert_eq!(a, b);
3587        let mut h1 = DefaultHasher::new();
3588        let mut h2 = DefaultHasher::new();
3589        a.hash(&mut h1);
3590        b.hash(&mut h2);
3591        assert_eq!(h1.finish(), h2.finish());
3592    }
3593
3594    #[test]
3595    fn style_key_different_styles_ne() {
3596        let a = StyleKey::from(Style::new().bold());
3597        let b = StyleKey::from(Style::new().italic());
3598        assert_ne!(a, b);
3599    }
3600
3601    // ── hash_str edge cases ──────────────────────────────────────────
3602
3603    #[test]
3604    fn hash_str_empty_deterministic() {
3605        assert_eq!(Help::hash_str(""), Help::hash_str(""));
3606    }
3607
3608    #[test]
3609    fn hash_str_different_strings_differ() {
3610        assert_ne!(Help::hash_str("abc"), Help::hash_str("def"));
3611    }
3612
3613    // ── KeybindingHints: custom categories in grouped view ───────────
3614
3615    #[test]
3616    fn keybinding_hints_custom_categories_grouped() {
3617        let entries = vec![
3618            HelpEntry::new("a", "one").with_category(HelpCategory::Custom("Alpha".into())),
3619            HelpEntry::new("b", "two").with_category(HelpCategory::Custom("Beta".into())),
3620            HelpEntry::new("c", "three").with_category(HelpCategory::Custom("Alpha".into())),
3621        ];
3622        let groups = KeybindingHints::grouped_entries(&entries);
3623        assert_eq!(groups.len(), 2);
3624        assert_eq!(groups[0].1.len(), 2); // Alpha has 2 entries
3625        assert_eq!(groups[1].1.len(), 1); // Beta has 1 entry
3626    }
3627
3628    #[test]
3629    fn keybinding_hints_all_contextual_context_on() {
3630        let hints = KeybindingHints::new()
3631            .with_show_context(true)
3632            .contextual_entry("^s", "save")
3633            .contextual_entry("^f", "find");
3634        let visible = hints.visible_entries();
3635        assert_eq!(visible.len(), 2);
3636    }
3637
3638    #[test]
3639    fn keybinding_hints_format_key_plain_empty() {
3640        let hints = KeybindingHints::new().with_key_format(KeyFormat::Plain);
3641        assert_eq!(hints.format_key(""), "");
3642    }
3643
3644    #[test]
3645    fn keybinding_hints_format_key_bracketed_empty() {
3646        let hints = KeybindingHints::new().with_key_format(KeyFormat::Bracketed);
3647        assert_eq!(hints.format_key(""), "[]");
3648    }
3649
3650    #[test]
3651    fn keybinding_hints_format_key_bracketed_unicode() {
3652        let hints = KeybindingHints::new().with_key_format(KeyFormat::Bracketed);
3653        assert_eq!(hints.format_key("\u{2191}"), "[\u{2191}]");
3654    }
3655
3656    // ── KeybindingHints: render full grouped with single category ─────
3657
3658    #[test]
3659    fn keybinding_hints_render_full_grouped_single_category() {
3660        let hints = KeybindingHints::new()
3661            .with_mode(HelpMode::Full)
3662            .with_show_categories(true)
3663            .global_entry_categorized("a", "first", HelpCategory::Navigation)
3664            .global_entry_categorized("b", "second", HelpCategory::Navigation);
3665        let mut pool = GraphemePool::new();
3666        let mut frame = Frame::new(40, 10, &mut pool);
3667        let area = Rect::new(0, 0, 40, 10);
3668        Widget::render(&hints, area, &mut frame);
3669        // Single category: header "Navigation" + 2 entries, no trailing blank
3670    }
3671
3672    // ── HelpCacheStats trait coverage ─────────────────────────────────
3673
3674    #[test]
3675    fn help_cache_stats_ne() {
3676        let a = HelpCacheStats::default();
3677        let b = HelpCacheStats {
3678            hits: 1,
3679            ..Default::default()
3680        };
3681        assert_ne!(a, b);
3682    }
3683
3684    #[test]
3685    fn help_cache_stats_debug() {
3686        let stats = HelpCacheStats {
3687            hits: 5,
3688            misses: 2,
3689            dirty_updates: 1,
3690            layout_rebuilds: 3,
3691        };
3692        let dbg = format!("{stats:?}");
3693        assert!(dbg.contains("hits"));
3694        assert!(dbg.contains("misses"));
3695        assert!(dbg.contains("dirty_updates"));
3696        assert!(dbg.contains("layout_rebuilds"));
3697    }
3698
3699    // ── LayoutKey copy + hash coverage ────────────────────────────────
3700
3701    #[test]
3702    fn layout_key_copy_and_eq() {
3703        let help = Help::new().entry("q", "quit");
3704        let area = Rect::new(0, 0, 40, 1);
3705        let key1 = help.layout_key(area, DegradationLevel::Full);
3706        let key2 = key1; // Copy
3707        assert_eq!(key1, key2);
3708    }
3709
3710    #[test]
3711    fn layout_key_differs_by_mode() {
3712        let help_s = Help::new().entry("q", "quit");
3713        let help_f = Help::new().with_mode(HelpMode::Full).entry("q", "quit");
3714        let area = Rect::new(0, 0, 40, 1);
3715        let deg = DegradationLevel::Full;
3716        assert_ne!(help_s.layout_key(area, deg), help_f.layout_key(area, deg));
3717    }
3718
3719    #[test]
3720    fn layout_key_differs_by_dimensions() {
3721        let help = Help::new().entry("q", "quit");
3722        let deg = DegradationLevel::Full;
3723        let k1 = help.layout_key(Rect::new(0, 0, 40, 1), deg);
3724        let k2 = help.layout_key(Rect::new(0, 0, 80, 1), deg);
3725        assert_ne!(k1, k2);
3726    }
3727
3728    #[test]
3729    fn layout_key_hash_consistent() {
3730        use std::collections::hash_map::DefaultHasher;
3731        let help = Help::new().entry("q", "quit");
3732        let key = help.layout_key(Rect::new(0, 0, 40, 1), DegradationLevel::Full);
3733        let mut h1 = DefaultHasher::new();
3734        let mut h2 = DefaultHasher::new();
3735        key.hash(&mut h1);
3736        key.hash(&mut h2);
3737        assert_eq!(h1.finish(), h2.finish());
3738    }
3739}