docs(comments): rewrite comments across all crates to the guidelines

Sweep every first-party crate source (1956 .rs files) to the project comment
guidelines: delete redundant restatements, decorative banners, change
narration, and end-of-line comments; keep and tighten the crucial ones
(invariants, bug rationale, SAFETY blocks, ported-source attribution).

No functional code changed. Every edit is proven comment-only against the
prior tree by a comment-stripping lexer (string/char/raw-string aware) plus a
separate doctest-fence check. Where removing a comment made rustfmt or clippy
want to re-lay-out adjacent code, the minimal triggering comment is restored so
code tokens stay byte-identical.

Gates green: cargo fmt --all --check (0 diffs), cargo check and cargo clippy
--workspace --all-targets (0 warnings).

Adds scripts/check_codegen_comment_guidelines.py — the enforcement gate for
these guidelines (flags banners, end-of-line comments, change narration, and
commented-out code).
This commit is contained in:
ZacharyZhang-NY committed 2026-07-23 16:55:39 -04:00
1 parent ff0fb56c67
commit a02b555e66
1458 files changed
+10729 -21750

No files matched your search

@@ -41,10 +41,6 @@ pub enum ListLayoutCache {
}
impl ListLayoutCache {
// -----------------------------------------------------------------------
// Constructors
// -----------------------------------------------------------------------
/// Create a fixed-height cache for `count` items (all height 1).
pub fn fixed(count: usize) -> Self {
Self::FixedHeight { count }
@@ -91,10 +87,6 @@ impl ListLayoutCache {
}
}
// -----------------------------------------------------------------------
// Queries
// -----------------------------------------------------------------------
/// Total height in visual lines.
pub fn total_height(&self) -> usize {
match self {
@@ -146,15 +138,15 @@ impl ListLayoutCache {
}
Self::Variable { prefix_sums, .. } => {
if prefix_sums.len() <= 1 {
return None; // empty
return None;
}
// Binary search: find the largest i such that prefix_sums[i] <= y.
// partition_point returns the first index where prefix_sums[i] > y,
// so we subtract 1.
let pos = prefix_sums.partition_point(|&s| s <= y);
let idx = pos.saturating_sub(1);
// Clamp to valid item range
let max_idx = prefix_sums.len() - 2; // last valid item index
// Clamp to valid item range: last valid item index.
let max_idx = prefix_sums.len() - 2;
Some(idx.min(max_idx))
}
}
@@ -169,10 +161,6 @@ impl ListLayoutCache {
}
}
// ===========================================================================
// Tests
// ===========================================================================
#[cfg(test)]
mod tests {
use super::*;
@@ -257,7 +245,8 @@ mod tests {
assert_eq!(cache.virtual_y(0), 0);
assert_eq!(cache.item_at_y(0), Some(0));
assert_eq!(cache.item_at_y(4), Some(0));
assert_eq!(cache.item_at_y(5), Some(0)); // clamped
// Clamped.
assert_eq!(cache.item_at_y(5), Some(0));
}
#[test]
@@ -26,10 +26,6 @@ use ratatui::layout::Rect;
use ratatui::style::Color;
use ratatui::text::Line;
// ---------------------------------------------------------------------------
// ListPaneStyle — configurable colors for the framework's post-pass overlays
// ---------------------------------------------------------------------------
/// Visual style configuration for a `ListPane`.
///
/// Controls colors for selection highlighting, input bar, and other
@@ -107,10 +103,6 @@ impl Default for ListPaneStyle {
}
}
// ---------------------------------------------------------------------------
// ListItem trait
// ---------------------------------------------------------------------------
/// Trait that items in a `ListPane` must implement.
///
/// Items are owned by the **model** (not the view). The view borrows them
@@ -133,10 +125,6 @@ impl Default for ListPaneStyle {
/// rendering; the default [`render()`] and [`desired_height()`] are derived
/// automatically. Items that override [`render()`] bypass the framework.
pub trait ListItem {
// =======================================================================
// Content-based API (preferred)
// =======================================================================
/// The styled content to display — one logical line of text.
///
/// The framework handles wrapping (Wrap mode) and truncation (NoWrap mode)
@@ -184,10 +172,6 @@ pub trait ListItem {
None
}
// =======================================================================
// Custom rendering API (escape hatch)
// =======================================================================
/// Render this item into the given area.
///
/// Override this **only** when the content/prefix model doesn't fit.
@@ -236,10 +220,6 @@ pub trait ListItem {
(textwrap::wrap(&flat, opts).len() as u16).max(1)
}
// =======================================================================
// Identity & behavior
// =======================================================================
/// Stable identity that survives insertions, removals, and reordering.
///
/// Must be unique within the list. Used so that selection state persists
@@ -266,10 +246,6 @@ pub trait ListItem {
false
}
// =======================================================================
// Search / filter
// =======================================================================
/// Plain text for search/filter matching.
///
/// The framework calls `regex.is_match(item.search_text())` during
@@ -61,7 +61,6 @@ pub struct ListPane<'a, T: ListItem> {
}
impl<'a, T: ListItem> ListPane<'a, T> {
/// Create a new `ListPane` widget borrowing the given items.
pub fn new(items: &'a [T]) -> Self {
Self {
items,
@@ -70,13 +69,11 @@ impl<'a, T: ListItem> ListPane<'a, T> {
}
}
/// Set whether this pane has keyboard focus.
pub fn focused(mut self, focused: bool) -> Self {
self.focused = focused;
self
}
/// Set the visual style for selection/highlight overlays.
pub fn style(mut self, style: ListPaneStyle) -> Self {
self.style = style;
self
@@ -124,16 +121,13 @@ impl<T: ListItem> StatefulWidget for ListPane<'_, T> {
let scaled_total = (total_height / scale) as u16;
let scaled_offset = (state.scroll_offset() / scale) as u16;
// Split area for scrollbar if content overflows.
let (content_area, scrollbar_area) = maybe_split_for_scrollbar(list_area, scaled_total);
// Store scrollbar area for click/scroll hit-testing.
state.set_scrollbar_area(scrollbar_area);
// Render items into the content area.
self.render_items(content_area, buf, state);
// Render corner overlay indicators.
render_corner_indicators(content_area, buf, state, &self.style);
// Render "Copied!" toast (bottom-right corner, briefly after y-copy).
@@ -153,7 +147,6 @@ impl<T: ListItem> StatefulWidget for ListPane<'_, T> {
}
}
// Render scrollbar with style colors.
let track_style = Style::default().bg(self.style.scrollbar_bg);
let thumb_style = Style::default()
.fg(self.style.scrollbar_fg)
@@ -239,7 +232,6 @@ impl<T: ListItem> ListPane<'_, T> {
}
}
/// Render the visible items into the content area.
fn render_items(&self, area: Rect, buf: &mut Buffer, state: &ListPaneState) {
let visible = state.visible_range();
if visible.is_empty() {
@@ -271,7 +263,6 @@ impl<T: ListItem> ListPane<'_, T> {
// How many rows to skip at the top of this item (only for the first item).
let skip = if vi == first_vi { skip_rows } else { 0 };
// How many rows of this item are actually visible.
let visible_h = item_h.saturating_sub(skip);
let rows_available = viewport_bottom.saturating_sub(cursor_y);
let rows_to_render = visible_h.min(rows_available);
@@ -295,7 +286,6 @@ impl<T: ListItem> ListPane<'_, T> {
// If partially visible (skip > 0 or truncated at bottom), render
// into a scratch area and blit the visible portion.
if skip == 0 && rows_to_render == item_h {
// Fast path: render directly into buf.
let item_area = Rect {
x: area.x,
y: cursor_y,
@@ -315,7 +305,6 @@ impl<T: ListItem> ListPane<'_, T> {
item.render(item_area, buf, is_selected, self.focused);
}
} else {
// Slow path: render into a temp buffer, then blit the visible rows.
let full_area = Rect {
x: 0,
y: 0,
@@ -356,11 +345,10 @@ impl<T: ListItem> ListPane<'_, T> {
}
}
// --- Post-pass 1: Selection background overlay ---
// Patches only the bg of each cell, preserving fg, content, and
// modifiers. Applied after item render so items don't need to
// know about selection colors.
// Shown when focused, or when `show_selection_when_unfocused` is set.
// Selection background overlay: patches only the bg of each cell,
// preserving fg, content, and modifiers. Applied after item render
// so items don't need to know about selection colors. Shown when
// focused, or when `show_selection_when_unfocused` is set.
let show_sel = self.focused || state.show_selection_when_unfocused();
if is_selected && show_sel {
// Use different bg for visual range vs cursor line.
@@ -381,10 +369,10 @@ impl<T: ListItem> ListPane<'_, T> {
buf.set_style(sel_area, Style::default().bg(bg));
}
// --- Post-pass 2: Match highlight overlay ---
// Invert (REVERSED) the cells covering each match of the active
// query. Gated on `show_highlights` so callers can suppress the
// overlay (e.g. after accepting a filter, where every line matches).
// Match highlight overlay: inverts (REVERSED) the cells covering
// each match of the active query. Gated on `show_highlights` so
// callers can suppress the overlay (e.g. after accepting a
// filter, where every line matches).
if state.show_highlights
&& let Some(matcher) = state.matcher()
{
@@ -402,11 +390,11 @@ impl<T: ListItem> ListPane<'_, T> {
);
}
// --- Post-pass 3: Truncation ellipsis ---
// If the item's full wrapped height exceeds its allocated layout
// height, place "…" on the last rendered row. This only triggers
// in NoWrap mode (where item_h == 1 regardless of content length).
// Viewport clipping does NOT trigger this — only true text truncation.
// Truncation ellipsis: if the item's full wrapped height exceeds
// its allocated layout height, place "…" on the last rendered
// row. This only triggers in NoWrap mode (where item_h == 1
// regardless of content length). Viewport clipping does NOT
// trigger this — only true text truncation.
if item.desired_height(area.width) > item_h && rows_to_render > 0 {
let last_y = cursor_y + rows_to_render - 1;
render_truncation_ellipsis(buf, last_y, area.x, area.width);
@@ -417,10 +405,6 @@ impl<T: ListItem> ListPane<'_, T> {
}
}
// ---------------------------------------------------------------------------
// Truncation ellipsis
// ---------------------------------------------------------------------------
/// Place a `…` at the end of text on row `y` to indicate truncation.
///
/// Scans from right to left for the rightmost non-space cell. If there is
@@ -435,7 +419,8 @@ fn render_truncation_ellipsis(buf: &mut Buffer, y: u16, x_start: u16, width: u16
return;
}
let x_end = x_start + width; // exclusive
// exclusive
let x_end = x_start + width;
// Find rightmost non-space cell.
let mut last_text_x: Option<u16> = None;
@@ -447,9 +432,12 @@ fn render_truncation_ellipsis(buf: &mut Buffer, y: u16, x_start: u16, width: u16
}
let (ellipsis_x, donor_x) = match last_text_x {
Some(x) if x + 1 < x_end => (x + 1, x), // append after text, inherit from text
Some(x) => (x, x), // replace last char, keep its style
None => return, // entire row is blank
// append after text, inherit from text
Some(x) if x + 1 < x_end => (x + 1, x),
// replace last char, keep its style
Some(x) => (x, x),
// entire row is blank
None => return,
};
// Inherit fg from the donor cell, preserve bg of the target cell.
@@ -459,10 +447,6 @@ fn render_truncation_ellipsis(buf: &mut Buffer, y: u16, x_start: u16, width: u16
cell.fg = fg;
}
// ---------------------------------------------------------------------------
// Corner overlay indicators
// ---------------------------------------------------------------------------
/// Render single-character corner indicators for scroll position / follow mode.
///
/// - Top-right: `▲` (dim) when content is scrolled down (more above).
@@ -505,7 +489,6 @@ fn render_corner_indicators(
buf[(pos.0 - 1, pos.1)].set_symbol(" ");
}
}
// Indicator: set symbol + fg, preserve bg
buf[pos].set_symbol(symbol);
buf[pos].fg = fg;
buf[pos].modifier = ratatui::style::Modifier::empty();
@@ -528,10 +511,6 @@ fn render_corner_indicators(
}
}
// ---------------------------------------------------------------------------
// Input bar rendering
// ---------------------------------------------------------------------------
/// Render the bottom bar: active input bar or accepted matcher status.
///
/// When the input bar is open: left-aligned editable `search: ` or `filter: ` + textarea.
@@ -549,7 +528,6 @@ fn render_bottom_bar(
return;
}
// Background for the entire bar row.
buf.set_style(area, Style::default().bg(style.input_bar_bg));
if let Some(mode) = state.input_mode() {
@@ -590,17 +568,12 @@ fn render_bottom_bar(
.bg(style.input_bar_bg)
.add_modifier(Modifier::DIM);
// Right-align.
let x = area.x.saturating_add(area.width.saturating_sub(status_w));
let status_line = Line::from(Span::styled(status, dim_style));
buf.set_line_safe(x, area.y, &status_line, area.width);
}
}
// ===========================================================================
// Tests
// ===========================================================================
#[cfg(test)]
mod tests {
use super::*;
@@ -663,7 +636,8 @@ mod tests {
}
fn search_text_col_offset(&self) -> u16 {
1 // prefix ">" or " "
// prefix ">" or " "
1
}
}
@@ -732,7 +706,6 @@ mod tests {
let area = Rect::new(0, 0, 20, 3);
state.prepare_layout(&items, area.width, area.height);
// Scroll down by 5.
state.scroll_down(5);
let mut buf = Buffer::empty(area);
@@ -783,7 +756,6 @@ mod tests {
let mut state = ListPaneState::new(WrapMode::NoWrap, false);
let area = Rect::new(0, 0, 20, 5);
// Filter to items containing "alph".
state.set_filter(Some(FilterMatcher::substring("alph")));
state.prepare_layout(&items, area.width, area.height);
@@ -803,7 +775,8 @@ mod tests {
// Text "hello" (6 chars with prefix " ") in a 20-char-wide area,
// so the "…" should be appended at position 6.
let items = vec![
RenderTestItem::new(0, "hello").with_height(3), // would be 3 lines tall
// would be 3 lines tall
RenderTestItem::new(0, "hello").with_height(3),
];
let mut state = ListPaneState::new(WrapMode::NoWrap, false);
let area = Rect::new(0, 0, 20, 5);
@@ -862,8 +835,6 @@ mod tests {
assert_eq!(row, ">short");
}
// -- Match highlight tests ------------------------------------------------
#[test]
fn highlight_match_inverts_correct_cells() {
// Items: "alpha", "beta", "alphabet"
@@ -1000,7 +971,7 @@ mod tests {
StatefulWidget::render(pane, area, &mut buf, &mut state);
// Find where "tool" appears visually in the buffer.
// The match is at byte offset 32 in the plain text.
// The match is at byte offset 33 in the plain text.
let byte_pos = text.find("tool").unwrap();
assert_eq!(byte_pos, 33);
@@ -1248,10 +1219,6 @@ mod tests {
);
}
// =========================================================================
// Long line wrapping bug regression tests
// =========================================================================
/// A content-based test item (uses the framework's wrapping).
#[derive(Debug)]
struct ContentTestItem {
@@ -1304,10 +1271,6 @@ mod tests {
s
}
// =========================================================================
// Long line wrapping regression tests
// =========================================================================
#[test]
fn long_line_desired_height_is_accurate() {
let width: u16 = 112;
@@ -1585,10 +1548,6 @@ mod tests {
);
}
// =========================================================================
// Scrollbar width mismatch bug (regression tests for the fix)
// =========================================================================
#[test]
fn scrollbar_width_mismatch_bug_repro() {
// BUG REPRODUCTION: Documents the scrollbar width mismatch issue.
@@ -1728,7 +1687,8 @@ mod tests {
let mut items = vec![
RenderTestItem::new(0, "row-0"),
RenderTestItem::new(1, "row-1"),
RenderTestItem::new(2, "zzz"), // filtered out
// filtered out
RenderTestItem::new(2, "zzz"),
RenderTestItem::new(3, "row-3"),
RenderTestItem::new(4, "row-4"),
];
@@ -23,7 +23,8 @@ impl ListPaneState {
layout: ListLayoutCache::fixed(0),
wrap_mode,
last_stamp: None,
filter_dirty: true, // force first build
// Force the first build.
filter_dirty: true,
last_item_count: 0,
scroll_anchor: None,
scroll_screen_y: None,
@@ -54,10 +55,6 @@ impl ListPaneState {
}
}
// =======================================================================
// Public accessors
// =======================================================================
pub fn scroll_offset(&self) -> usize {
self.scroll_offset
}
@@ -84,7 +81,8 @@ impl ListPaneState {
/// The index will be resolved on the next `prepare_layout` call.
pub fn select_by_id(&mut self, id: u64) {
self.selected_id = Some(id);
self.selected_index = None; // will be resolved in prepare_layout
// Will be resolved in prepare_layout.
self.selected_index = None;
}
pub fn multi_range(&self) -> Option<Range<usize>> {
@@ -230,7 +228,7 @@ impl ListPaneState {
&& std::time::Instant::now() >= t
{
self.copy_toast_until = None;
return true; // toast just expired, need redraw
return true;
}
false
}
@@ -282,10 +280,6 @@ impl ListPaneState {
}
}
// =======================================================================
// Visual select mode
// =======================================================================
/// Enter visual selection mode, anchored at the current selection.
///
/// If in follow mode, exits follow first (materializes cursor),
@@ -321,10 +315,6 @@ impl ListPaneState {
}
}
// =======================================================================
// Clipboard (copy)
// =======================================================================
/// Replace the clipboard provider (e.g. with a system clipboard).
pub fn set_clipboard_provider(&mut self, provider: Box<dyn ClipboardProvider>) {
self.clipboard = provider;
@@ -405,10 +395,6 @@ impl ListPaneState {
true
}
// =======================================================================
// Scrollbar interaction
// =======================================================================
/// Set scroll offset to a specific value and select the nearest item
/// at viewport center.
///
@@ -472,10 +458,6 @@ impl ListPaneState {
}
}
// =======================================================================
// Wrap mode
// =======================================================================
/// Toggle wrap mode: NoWrap ↔ Wrap.
///
/// Records a scroll anchor so that `prepare_layout` will keep the
@@ -500,10 +482,6 @@ impl ListPaneState {
// Wrap mode change forces full rebuild on next prepare_layout.
}
// =======================================================================
// Filter
// =======================================================================
/// Set or clear the matcher (filter or search).
///
/// Caller should call `prepare_layout` afterward to recompute
@@ -518,10 +496,6 @@ impl ListPaneState {
self.set_matcher(matcher);
}
// =======================================================================
// Match navigation (n / N)
// =======================================================================
/// Jump to the next match after the current selection.
///
/// In Filter mode, moves to the next filtered item.
@@ -585,10 +559,6 @@ impl ListPaneState {
}
}
// =======================================================================
// prepare_layout — the ONE generic entry point
// =======================================================================
/// Recompute layout, resolve stable-ID selection → indices, clamp scroll.
///
/// Call this once per frame before rendering. `items` is the full
@@ -617,7 +587,7 @@ impl ListPaneState {
viewport_height
};
// -- Build visible-item index map (filter) ----------------------------
// Build visible-item index map (filter).
let filter_changed = self.filter_dirty;
if filter_changed {
self.filter_dirty = false;
@@ -661,7 +631,7 @@ impl ListPaneState {
}
};
// -- SCROLLBAR WIDTH FIX: Determine effective width for layout ---------
// SCROLLBAR WIDTH FIX: determine effective width for layout.
//
// In Wrap mode, the scrollbar takes SCROLLBAR_TOTAL_COLS (2) columns.
// If we compute heights at full width but render at narrow width (due to
@@ -682,7 +652,7 @@ impl ListPaneState {
width
};
// -- Maintain per-physical-item height cache (ALL modes) ----------------
// Maintain per-physical-item height cache (all modes).
//
// The height cache stores `desired_height(effective_width)` for every
// physical item, regardless of the current wrap mode. It is:
@@ -715,7 +685,7 @@ impl ListPaneState {
}
}
// -- Decide whether we can skip / incrementally update the layout -----
// Decide whether we can skip / incrementally update the layout.
let (width_same, mode_same, count_grew, old_count) = match self.last_stamp {
Some(s) => (
s.width == effective_width,
@@ -757,7 +727,7 @@ impl ListPaneState {
}
// else: count_same + same width/mode/filter → cache is still valid.
// -- SCROLLBAR WIDTH FIX Phase 2: Check if we guessed wrong ------------
// SCROLLBAR WIDTH FIX Phase 2: check if we guessed wrong.
//
// If we computed at full width but total_height > viewport (scrollbar
// will actually be shown), recompute at narrower width.
@@ -784,14 +754,13 @@ impl ListPaneState {
}
}
// Update dirty-tracking stamp with effective_width.
self.last_stamp = Some(LayoutStamp {
width: effective_width,
count: vis_count,
wrap: self.wrap_mode,
});
// -- Resolve selected_id → selected_index -----------------------------
// Resolve selected_id → selected_index.
self.selected_index = self
.selected_id
.and_then(|sid| (0..vis_count).find(|&vi| items[to_physical(vi)].stable_id() == sid));
@@ -801,14 +770,14 @@ impl ListPaneState {
self.selected_id = None;
}
// -- Visual mode: sync multi_selected_ids from anchor + cursor --------
// Visual mode: sync multi_selected_ids from anchor + cursor.
if self.visual_mode
&& let (Some(anchor), Some(cursor)) = (self.visual_anchor_id, self.selected_id)
{
self.multi_selected_ids = Some((anchor, cursor));
}
// -- Resolve multi_selected_ids → multi_range -------------------------
// Resolve multi_selected_ids → multi_range.
self.multi_range = self.multi_selected_ids.and_then(|(a, b)| {
let a_idx = (0..vis_count).find(|&vi| items[to_physical(vi)].stable_id() == a);
let b_idx = (0..vis_count).find(|&vi| items[to_physical(vi)].stable_id() == b);
@@ -822,7 +791,7 @@ impl ListPaneState {
}
});
// -- Apply scroll anchor (wrap toggle y-stability) --------------------
// Apply scroll anchor (wrap toggle y-stability).
// If a scroll anchor was set (e.g. by cycle_wrap_mode), adjust
// scroll_offset so the selected item appears at the recorded screen-y.
if let Some(desired_screen_y) = self.scroll_anchor.take()
@@ -832,7 +801,7 @@ impl ListPaneState {
self.scroll_offset = new_item_y.saturating_sub(desired_screen_y);
}
// -- Follow mode: auto-scroll to bottom, no cursor ----------------------
// Follow mode: auto-scroll to bottom, no cursor.
if self.follow_mode {
let total = self.layout.total_height();
let vp = self.viewport_height as usize;
@@ -842,7 +811,7 @@ impl ListPaneState {
self.selected_index = None;
}
// -- Auto-select if nothing selected (NAV mode only) --------------------
// Auto-select if nothing selected (NAV mode only).
// A list with items but no selection feels broken (no highlight, j/k do
// nothing visible). Auto-select the first selectable item.
// In follow mode, selection is always None — skip this block.
@@ -860,10 +829,9 @@ impl ListPaneState {
// (which uses `to_physical` closure that borrows `vis`).
self.vis_map = vis;
// -- Clamp scroll -------------------------------------------------------
self.clamp_scroll();
// -- Keep selection visible after eviction --------------------------------
// Keep selection visible after eviction.
// Only when items SHRINK (eviction from front), which shifts indices and
// can push the selection off-screen. NOT on append (which just extends
// below) — that would fight with user's click/scroll position via margin.
@@ -873,10 +841,6 @@ impl ListPaneState {
}
}
// =======================================================================
// Scroll
// =======================================================================
/// Scroll down by `n` visual lines (viewport only, no follow logic).
///
/// This is a low-level primitive. Higher-level methods
@@ -931,16 +895,17 @@ impl ListPaneState {
fn scroll_keeping_screen_y<T: ListItem>(&mut self, delta: isize, items: &[T]) {
let is_down = delta > 0;
// -- Handle FOLLOW mode -----------------------------------------------
// Handle FOLLOW mode.
if self.follow_mode {
if is_down {
return; // no-op: already at the bottom
// No-op: already at the bottom.
return;
}
// Upward: exit follow, materialize cursor, then scroll.
self.exit_follow(items);
}
// -- NAV mode scroll --------------------------------------------------
// NAV mode scroll.
if !is_down {
self.reset_edge_state();
}
@@ -966,17 +931,19 @@ impl ListPaneState {
}
let actual_scroll = self.scroll_offset as isize - offset_before as isize;
let leftover = delta - actual_scroll; // lines the viewport couldn't consume
// Lines the viewport couldn't consume.
let leftover = delta - actual_scroll;
// Restore selection at the pinned screen-y, then apply leftover.
if let Some(sy) = screen_y {
self.scroll_screen_y = Some(sy); // persist for next scroll
// Persist for next scroll.
self.scroll_screen_y = Some(sy);
// Target virtual-y: pinned screen-y + leftover movement.
let target_y = (self.scroll_offset + sy).saturating_add_signed(leftover);
self.select_nearest_at_y(target_y, items);
}
// -- One-past logic for downward scrolls ------------------------------
// One-past logic for downward scrolls.
// Suppressed in visual mode (don't snap to follow mid-selection).
if self.config.follow_enabled && !self.visual_mode && is_down && self.is_at_bottom() {
if self.at_content_edge {
@@ -1083,10 +1050,11 @@ impl ListPaneState {
// Mouse wheel exits visual mode (mouse = single-select interaction).
self.clear_visual_if_active();
// -- Handle FOLLOW mode -----------------------------------------------
// Handle FOLLOW mode.
if self.follow_mode {
if is_down {
return; // no-op: already at the bottom
// No-op: already at the bottom.
return;
}
// Upward: exit follow, materialize cursor, then scroll.
self.exit_follow(items);
@@ -1128,7 +1096,7 @@ impl ListPaneState {
self.select_nearest_at_y(target_y, items);
}
// -- Overscroll counter for mouse wheel -------------------------------
// Overscroll counter for mouse wheel.
// Suppressed in visual mode.
if self.config.follow_enabled && !self.visual_mode && is_down && self.is_at_bottom() {
let scroll_amount = lines.unsigned_abs().min(u8::MAX as u32) as u8;
@@ -1200,10 +1168,6 @@ impl ListPaneState {
total <= vp || self.scroll_offset >= total.saturating_sub(vp)
}
// =======================================================================
// Follow ↔ NAV transitions
// =======================================================================
/// Engage follow mode: jump viewport to bottom, hide cursor.
///
/// No-op when `follow_enabled` is false in config.
@@ -1254,10 +1218,6 @@ impl ListPaneState {
self.overscroll_ticks = 0;
}
// =======================================================================
// Selection
// =======================================================================
/// Select the next selectable item (downward) — `j` / `↓`.
///
/// Behavior:
@@ -1266,7 +1226,8 @@ impl ListPaneState {
/// one-past logic applies (second j at end → engage follow).
pub fn select_next<T: ListItem>(&mut self, items: &[T]) {
if self.follow_mode {
return; // no-op: already at the bottom
// No-op: already at the bottom.
return;
}
self.scroll_screen_y = None;
@@ -1371,7 +1332,8 @@ impl ListPaneState {
pub fn select_last<T: ListItem>(&mut self, items: &[T]) {
if self.config.follow_enabled && !self.visual_mode {
if self.follow_mode {
return; // already following — no-op
// Already following — no-op.
return;
}
self.engage_follow();
return;
@@ -1452,10 +1414,6 @@ impl ListPaneState {
self.clamp_scroll();
}
// =======================================================================
// Visible range (for rendering)
// =======================================================================
/// Return the range of visible-item indices that overlap the viewport.
///
/// For `FixedHeight`, this is `scroll_offset .. scroll_offset + viewport_height`
@@ -1496,10 +1454,6 @@ impl ListPaneState {
(self.scroll_offset - first_y) as u16
}
// =======================================================================
// Keyboard input
// =======================================================================
/// Handle a key event for navigation, search, and filter.
///
/// Returns `true` if the key was consumed (state changed), `false` if
@@ -1516,7 +1470,7 @@ impl ListPaneState {
event: &crossterm::event::KeyEvent,
items: &[T],
) -> bool {
// -- Input bar active: intercept Enter/Esc, route typing to textarea --
// Input bar active: intercept Enter/Esc, route typing to textarea.
if let Some(mode) = self.input_mode {
// GotoLine mode has its own Enter/Esc/text handling.
if mode == InputBarMode::GotoLine {
@@ -1568,7 +1522,8 @@ impl ListPaneState {
return true;
}
if key!(Enter).matches(event) || key!(Esc).matches(event) {
return false; // let the caller handle
// Let the caller handle Enter/Esc.
return false;
}
// Shift+Enter / Alt+Enter: insert a literal newline.
if key!(Enter, SHIFT).matches(event) || key!(Enter, ALT).matches(event) {
@@ -1628,10 +1583,11 @@ impl ListPaneState {
if self.input_textarea.text() != old_text {
self.apply_input_buffer(items);
}
return true; // always consume when input bar is open
// Always consume when input bar is open.
return true;
}
// -- Normal mode: check for search/filter/follow keys first -----------
// Normal mode: check for search/filter/follow keys first.
// '/' → open search bar (clears visual mode)
if self.config.search_enabled && key!('/').matches(event) {
@@ -1834,10 +1790,6 @@ impl ListPaneState {
false
}
// =======================================================================
// Input bar lifecycle
// =======================================================================
/// Open the input bar in the given mode.
fn open_input<T: ListItem>(&mut self, mode: InputBarMode, items: &[T]) {
self.input_mode = Some(mode);
@@ -1891,11 +1843,8 @@ impl ListPaneState {
self.cancel_input();
}
// ── Goto-line mode ────────────────────────────────────────────────
/// Open the goto-line input bar. Saves a snapshot for cancel/restore.
fn open_goto_line<T: ListItem>(&mut self, items: &[T]) {
// Save snapshot.
self.goto_line_snapshot = Some(GotoLineSnapshot {
scroll_offset: self.scroll_offset,
selected_id: self.selected_id,
@@ -1926,7 +1875,8 @@ impl ListPaneState {
self.selected_id = snap.selected_id;
self.visual_mode = snap.visual_mode;
self.visual_anchor_id = snap.visual_anchor_id;
self.selected_index = None; // will be resolved in prepare_layout
// Will be resolved in prepare_layout.
self.selected_index = None;
}
return;
}
@@ -2163,10 +2113,6 @@ impl ListPaneState {
}
}
// =======================================================================
// Mouse event handling
// =======================================================================
/// Handle a mouse event within this pane's area.
///
/// `pane_area` is the screen `Rect` where the pane was rendered (used
@@ -17,10 +17,6 @@ use crate::key;
use crate::render::scrollbar::SCROLLBAR_TOTAL_COLS;
use crate::search::{QueryKind, TextMatcher};
// ---------------------------------------------------------------------------
// ListMatcher — unified filter / search
// ---------------------------------------------------------------------------
/// Whether the matcher hides non-matching items or just highlights them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MatchMode {
@@ -40,7 +36,6 @@ pub enum MatchMode {
#[derive(Debug, Clone)]
pub struct ListMatcher {
text: TextMatcher,
/// Whether this matcher hides or highlights.
pub mode: MatchMode,
/// Physical indices of items whose `search_text()` matches, sorted ascending.
pub match_indices: Vec<usize>,
@@ -122,10 +117,6 @@ impl ListMatcher {
}
}
// ---------------------------------------------------------------------------
// Backward-compatible aliases
// ---------------------------------------------------------------------------
/// Backward-compatible alias for [`ListMatcher`].
///
/// Existing code that constructs `FilterMatcher::substring(...)` or
@@ -167,10 +158,6 @@ impl ListFilter {
}
}
// ---------------------------------------------------------------------------
// InputBarMode — search vs filter
// ---------------------------------------------------------------------------
/// Which mode the input bar is in.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputBarMode {
@@ -199,7 +186,8 @@ impl InputBarMode {
match self {
InputBarMode::Search => MatchMode::Search,
InputBarMode::Filter => MatchMode::Filter,
InputBarMode::GotoLine => MatchMode::Search, // unused, but needed for exhaustive match
// Unused, but needed for exhaustive match.
InputBarMode::GotoLine => MatchMode::Search,
InputBarMode::Comment => MatchMode::Search,
}
}
@@ -215,10 +203,6 @@ struct GotoLineSnapshot {
visual_anchor_id: Option<u64>,
}
// ---------------------------------------------------------------------------
// LayoutStamp — dirty-tracking for prepare_layout
// ---------------------------------------------------------------------------
/// Snapshot of parameters used to build the current layout cache.
///
/// Stored in [`ListPaneState`] and compared each frame to decide whether
@@ -234,24 +218,18 @@ struct LayoutStamp {
wrap: WrapMode,
}
// ---------------------------------------------------------------------------
// ListPaneState
// ---------------------------------------------------------------------------
/// View state for a scrollable list pane.
///
/// **Non-generic** — the item type `T: ListItem` only appears at the
/// boundaries: [`prepare_layout`] and `ListPane<'a, T>` (the widget).
#[derive(Debug)]
pub struct ListPaneState {
// -- Scroll ---------------------------------------------------------------
/// Scroll offset in visual lines from the top of the content.
scroll_offset: usize,
/// Viewport height in terminal rows (set by [`prepare_layout`]).
viewport_height: u16,
// -- Selection (stable IDs) -----------------------------------------------
/// Currently selected item, stored as a stable ID.
/// Resolved to `selected_index` in [`prepare_layout`].
selected_id: Option<u64>,
@@ -274,14 +252,12 @@ pub struct ListPaneState {
/// The range is [anchor, cursor] (cursor = `selected_id`).
visual_anchor_id: Option<u64>,
// -- Layout ---------------------------------------------------------------
/// Layout cache (heights + prefix sums, or fixed-height).
layout: ListLayoutCache,
/// Current wrap mode.
wrap_mode: WrapMode,
// -- Layout dirty tracking ------------------------------------------------
/// Parameters of the last layout build (for incremental / skip logic).
/// `None` if no layout has been computed yet.
last_stamp: Option<LayoutStamp>,
@@ -310,12 +286,10 @@ pub struct ListPaneState {
/// by any intentional selection movement (j/k, click, g/G, etc.).
scroll_screen_y: Option<usize>,
// -- Modes ----------------------------------------------------------------
/// Follow mode: auto-scroll to bottom when new items appear.
/// In follow mode the cursor is hidden (no selection highlight).
pub follow_mode: bool,
// -- Follow / NAV edge tracking -------------------------------------------
/// NAV only: true when the last downward action was clamped at the
/// content bottom (viewport or selection at the end). The next
/// downward action with this flag set engages follow ("one-past").
@@ -343,7 +317,6 @@ pub struct ListPaneState {
/// `None` when scrollbar is not shown (content fits viewport).
last_scrollbar_area: Option<Rect>,
// -- Highlight visibility -------------------------------------------------
/// Whether the highlight post-pass should render match inversions.
///
/// Callers set this to `false` after accepting a filter (Enter) to avoid
@@ -353,7 +326,6 @@ pub struct ListPaneState {
/// Defaults to `true` (highlights always shown).
pub show_highlights: bool,
// -- Height cache (Wrap mode) ---------------------------------------------
/// Per-physical-item height cache for Wrap mode.
///
/// Indexed by physical item index. Computed once when the width changes
@@ -367,11 +339,9 @@ pub struct ListPaneState {
/// Width at which `height_cache` was computed.
height_cache_width: u16,
// -- Config ---------------------------------------------------------------
/// Feature flags controlling which behaviors are active.
config: ListPaneConfig,
// -- Input bar (search / filter) ------------------------------------------
/// Active input bar mode, or `None` if the bar is closed.
input_mode: Option<InputBarMode>,
@@ -384,11 +354,9 @@ pub struct ListPaneState {
/// Cached screen position of the input bar cursor (set during render).
input_cursor_screen_pos: Option<(u16, u16)>,
// -- Mouse / scrollbar ----------------------------------------------------
/// Whether a scrollbar drag is in progress.
scrollbar_dragging: bool,
// -- Clipboard ------------------------------------------------------------
/// Clipboard provider for `y` (copy). Default is `InternalClipboard`
/// (in-memory). Host app can inject system clipboard via
/// [`set_clipboard_provider`].
@@ -410,10 +378,6 @@ pub struct ListPaneState {
/// Tunable — start with 1 (easy to trigger), increase if too twitchy.
const MOUSE_OVERSCROLL_THRESHOLD: u8 = 1;
// ---------------------------------------------------------------------------
// ListPaneConfig — feature flags
// ---------------------------------------------------------------------------
/// Configuration flags for a `ListPaneState`.
///
/// Controls which features are available. Use-case examples:
@@ -515,10 +479,6 @@ impl ListPaneConfig {
mod methods;
// ===========================================================================
// Goto-line input parsing
// ===========================================================================
/// Parsed result of goto-line input.
enum GotoTarget {
/// Single line number (1-based, clamped to item count).
@@ -571,10 +531,6 @@ fn parse_goto_input(text: &str, max_lines: usize) -> GotoTarget {
}
}
// ===========================================================================
// Tests
// ===========================================================================
#[cfg(test)]
mod tests {
use super::*;
@@ -651,8 +607,6 @@ mod tests {
}
}
// -- Scroll tests ---------------------------------------------------------
#[test]
fn scroll_basics() {
let items: Vec<TestItem> = (0..20).map(TestItem::new).collect();
@@ -670,7 +624,7 @@ mod tests {
// Can't scroll past content
state.scroll_down(100);
assert_eq!(state.scroll_offset(), 10); // 20 - 10
assert_eq!(state.scroll_offset(), 10);
state.scroll_up(100);
assert_eq!(state.scroll_offset(), 0);
@@ -710,12 +664,12 @@ mod tests {
let mut state = new_streaming(WrapMode::NoWrap, true);
state.prepare_layout(&items, 80, 5);
// follow mode → scroll to bottom
assert_eq!(state.scroll_offset(), 5); // 10 - 5
assert_eq!(state.scroll_offset(), 5);
// Add more items
items.extend((10..15).map(TestItem::new));
state.prepare_layout(&items, 80, 5);
assert_eq!(state.scroll_offset(), 10); // 15 - 5
assert_eq!(state.scroll_offset(), 10);
// Manual scroll breaks follow mode
state.scroll_up(3);
@@ -746,8 +700,6 @@ mod tests {
assert_eq!(state.scroll_offset(), 0);
}
// -- Selection tests ------------------------------------------------------
#[test]
fn select_next_prev() {
let items: Vec<TestItem> = (0..5).map(TestItem::new).collect();
@@ -805,7 +757,7 @@ mod tests {
// G / select_last now engages follow (no cursor).
state.select_last(&items);
assert!(state.follow_mode);
assert_eq!(state.selected_index(), None); // no cursor in follow
assert_eq!(state.selected_index(), None);
// g / select_first exits follow, selects first.
state.select_first(&items);
@@ -867,8 +819,6 @@ mod tests {
assert!(state.selected_index().is_some());
}
// -- Filter + selection tests ---------------------------------------------
#[test]
fn select_with_filter() {
let items = vec![
@@ -916,8 +866,6 @@ mod tests {
assert_eq!(state.selected_id(), Some(2));
}
// -- Visible range tests --------------------------------------------------
#[test]
fn visible_range_fixed_height() {
let items: Vec<TestItem> = (0..20).map(TestItem::new).collect();
@@ -955,8 +903,6 @@ mod tests {
assert_eq!(state.first_item_skip_rows(), 1);
}
// -- Filter tests ---------------------------------------------------------
#[test]
fn filter_reduces_visible_items() {
let items = vec![
@@ -985,8 +931,6 @@ mod tests {
assert_eq!(state.visible_count(), 4);
}
// -- Wrap mode tests ------------------------------------------------------
#[test]
fn wrap_mode_variable_heights() {
let items = vec![
@@ -997,7 +941,7 @@ mod tests {
let mut state = ListPaneState::new(WrapMode::Wrap, false);
state.prepare_layout(&items, 80, 10);
assert_eq!(state.total_height(), 6); // 3 + 2 + 1
assert_eq!(state.total_height(), 6);
}
#[test]
@@ -1014,8 +958,6 @@ mod tests {
assert_eq!(state.total_height(), 3);
}
// -- Keyboard input tests -------------------------------------------------
#[test]
fn key_j_k_selects() {
let items: Vec<TestItem> = (0..10).map(TestItem::new).collect();
@@ -1072,7 +1014,7 @@ mod tests {
state.prepare_layout(&items, 80, 10);
assert!(state.handle_key_event(&key!('d', CONTROL).to_key_event(), &items));
assert_eq!(state.scroll_offset(), 5); // half of 10
assert_eq!(state.scroll_offset(), 5);
assert!(state.handle_key_event(&key!('u', CONTROL).to_key_event(), &items));
assert_eq!(state.scroll_offset(), 0);
@@ -1150,8 +1092,6 @@ mod tests {
assert!(!state.handle_key_event(&key!('x').to_key_event(), &items));
}
// -- Selection follows scroll (vim/lnav screen-y preservation) ----------
#[test]
fn ctrl_d_selection_stays_at_same_screen_y() {
let items: Vec<TestItem> = (0..30).map(TestItem::new).collect();
@@ -1166,7 +1106,7 @@ mod tests {
// Selection should move from 3 to 8 (same screen-y = 3).
assert!(state.handle_key_event(&key!('d', CONTROL).to_key_event(), &items));
assert_eq!(state.scroll_offset(), 5);
assert_eq!(state.selected_index(), Some(8)); // 3 + 5
assert_eq!(state.selected_index(), Some(8));
}
#[test]
@@ -1184,7 +1124,7 @@ mod tests {
// Selection should move from 13 to 8 (same screen-y = 3).
assert!(state.handle_key_event(&key!('u', CONTROL).to_key_event(), &items));
assert_eq!(state.scroll_offset(), 5);
assert_eq!(state.selected_index(), Some(8)); // 13 - 5
assert_eq!(state.selected_index(), Some(8));
}
#[test]
@@ -1213,12 +1153,12 @@ mod tests {
// Mouse wheel down 3 — selection follows at same screen-y.
state.scroll_lines(3, &items);
assert_eq!(state.scroll_offset(), 3);
assert_eq!(state.selected_index(), Some(8)); // 5 + 3
assert_eq!(state.selected_index(), Some(8));
// Mouse wheel up 2
state.scroll_lines(-2, &items);
assert_eq!(state.scroll_offset(), 1);
assert_eq!(state.selected_index(), Some(6)); // 8 - 2
assert_eq!(state.selected_index(), Some(6));
}
#[test]
@@ -1313,16 +1253,15 @@ mod tests {
// Ctrl-j scrolls down 1 line
assert!(state.handle_key_event(&key!('j', CONTROL).to_key_event(), &items));
assert_eq!(state.scroll_offset(), 1);
assert_eq!(state.selected_index(), Some(5)); // 4 + 1, screen-y still 4
// Screen-y stays 4.
assert_eq!(state.selected_index(), Some(5));
// Ctrl-k scrolls up 1 line
assert!(state.handle_key_event(&key!('k', CONTROL).to_key_event(), &items));
assert_eq!(state.scroll_offset(), 0);
assert_eq!(state.selected_index(), Some(4)); // back to 4
assert_eq!(state.selected_index(), Some(4));
}
// -- Dirty flag / incremental append tests --------------------------------
#[test]
fn prepare_layout_skips_rebuild_when_clean() {
// With Wrap mode + variable heights, calling prepare_layout with
@@ -1354,7 +1293,7 @@ mod tests {
// Append an item → incremental path
items.push(TestItem::new(2).with_height(4));
state.prepare_layout(&items, 80, 10);
assert_eq!(state.total_height(), 9); // 3 + 2 + 4
assert_eq!(state.total_height(), 9);
assert_eq!(state.visible_count(), 3);
}
@@ -1408,7 +1347,8 @@ mod tests {
// Selection should survive (stable id).
assert_eq!(state.selected_id(), Some(10));
assert_eq!(state.selected_index(), Some(5)); // shifted
// Selection shifts because item id=2 moved to a new index.
assert_eq!(state.selected_index(), Some(5));
assert_eq!(state.visible_count(), 15);
assert_eq!(state.total_height(), 15);
}
@@ -1454,8 +1394,6 @@ mod tests {
assert_eq!(state.visible_count(), 7);
}
// -- Center selected tests ------------------------------------------------
#[test]
fn center_selected_places_item_mid_viewport() {
let items: Vec<TestItem> = (0..30).map(TestItem::new).collect();
@@ -1491,8 +1429,6 @@ mod tests {
assert_eq!(state.scroll_offset(), 10);
}
// -- Click-to-select tests ------------------------------------------------
#[test]
fn select_at_y_selectable() {
let items: Vec<TestItem> = (0..10).map(TestItem::new).collect();
@@ -1522,8 +1458,6 @@ mod tests {
assert_eq!(state.selected_index(), Some(0));
}
// -- Scroll past non-selectable (viewport-constrained) --------------------
#[test]
fn scroll_past_non_selectable_stays_in_viewport() {
// Items: 0, 1, 2(non-sel), 3, 4, 5, 6, 7, 8, 9
@@ -1549,8 +1483,6 @@ mod tests {
assert_eq!(sel, 3);
}
// -- Ctrl-d/u edge cases: cursor continues when viewport is clamped -----
#[test]
fn ctrl_d_at_bottom_moves_cursor_past_viewport_clamp() {
// 20 items, viewport 10. Max scroll = 10.
@@ -1567,8 +1499,10 @@ mod tests {
// Actual scroll = 2. Leftover = 3.
// Target virtual-y = (10 + 3) + 3 = 16 → item 16.
state.half_page_down(&items);
assert_eq!(state.scroll_offset(), 10); // clamped at max
assert_eq!(state.selected_index(), Some(16)); // cursor kept going
// Clamped at max.
assert_eq!(state.scroll_offset(), 10);
// Cursor kept going.
assert_eq!(state.selected_index(), Some(16));
}
#[test]
@@ -1587,8 +1521,10 @@ mod tests {
// Actual scroll = -3. Leftover = -2.
// Target virtual-y = (0 + 3) - 2 = 1 → item 1.
state.half_page_up(&items);
assert_eq!(state.scroll_offset(), 0); // clamped at min
assert_eq!(state.selected_index(), Some(1)); // cursor kept going
// Clamped at min.
assert_eq!(state.scroll_offset(), 0);
// Cursor kept going.
assert_eq!(state.selected_index(), Some(1));
}
#[test]
@@ -1672,8 +1608,6 @@ mod tests {
assert_eq!(state.selected_index(), Some(3));
}
// -- ListMatcher tests ----------------------------------------------------
#[test]
fn matcher_substring_builds_match_indices() {
let items = vec![
@@ -1706,7 +1640,8 @@ mod tests {
let mut m = ListMatcher::new("[invalid", QueryKind::Regex, MatchMode::Filter);
assert!(m.is_error());
m.rebuild_matches(&items);
assert!(m.match_indices.is_empty()); // bad regex matches nothing
// Bad regex matches nothing.
assert!(m.match_indices.is_empty());
}
#[test]
@@ -1823,8 +1758,6 @@ mod tests {
assert_eq!(state.selected_index(), Some(3));
}
// -- Follow mode: one-past and overscroll tests --------------------------
#[test]
fn j_one_past_engages_follow() {
// j on last item twice → follow.
@@ -1837,17 +1770,20 @@ mod tests {
state.select_next(&items);
}
assert_eq!(state.selected_index(), Some(9));
assert!(!state.follow_mode); // at last item, but NOT follow yet
// At last item, but NOT follow yet.
assert!(!state.follow_mode);
// First j at end → at_content_edge = true, no mode change.
state.select_next(&items);
assert!(!state.follow_mode);
assert_eq!(state.selected_index(), Some(9)); // still there
// Still there.
assert_eq!(state.selected_index(), Some(9));
// Second j at end → engage follow.
state.select_next(&items);
assert!(state.follow_mode);
assert_eq!(state.selected_index(), None); // no cursor in follow
// No cursor in follow.
assert_eq!(state.selected_index(), None);
}
#[test]
@@ -1892,7 +1828,8 @@ mod tests {
// Second ctrl-d → scroll to offset 10 (max). at_content_edge = true.
state.half_page_down(&items);
assert_eq!(state.scroll_offset(), 10);
assert!(!state.follow_mode); // one-past: not yet
// One-past: not yet.
assert!(!state.follow_mode);
// Third ctrl-d → at bottom + at_content_edge → follow.
state.half_page_down(&items);
@@ -1925,7 +1862,8 @@ mod tests {
// Scroll to bottom.
state.scroll_lines(10, &items);
assert_eq!(state.scroll_offset(), 10);
assert!(!state.follow_mode); // first hit: at_content_edge = true
// First hit: at_content_edge = true.
assert!(!state.follow_mode);
// Another scroll at bottom → overscroll counter fires.
state.scroll_lines(3, &items);
@@ -2010,12 +1948,10 @@ mod tests {
items.extend((20..25).map(TestItem::new));
state.prepare_layout(&items, 80, 10);
assert_eq!(state.scroll_offset(), 15); // 25 - 10
assert_eq!(state.scroll_offset(), 15);
assert!(state.follow_mode);
}
// -- Follow mode: no cursor -----------------------------------------------
#[test]
fn follow_mode_has_no_selection() {
let items: Vec<TestItem> = (0..10).map(TestItem::new).collect();
@@ -2032,7 +1968,8 @@ mod tests {
let items: Vec<TestItem> = (0..10).map(TestItem::new).collect();
let mut state = new_streaming(WrapMode::NoWrap, false);
state.prepare_layout(&items, 80, 5);
assert_eq!(state.selected_index(), Some(0)); // auto-select in NAV
// Auto-select in NAV.
assert_eq!(state.selected_index(), Some(0));
// Engage follow.
state.select_last(&items);
@@ -2044,8 +1981,6 @@ mod tests {
assert_eq!(state.selected_index(), None);
}
// -- Follow → NAV transitions ---------------------------------------------
#[test]
fn j_in_follow_is_noop() {
let items: Vec<TestItem> = (0..10).map(TestItem::new).collect();
@@ -2071,7 +2006,8 @@ mod tests {
assert!(!state.follow_mode);
// Should be one item above the last visible.
let sel = state.selected_index().unwrap();
assert!(sel < 9); // moved up from the last visible
// Moved up from the last visible.
assert!(sel < 9);
}
#[test]
@@ -2089,8 +2025,6 @@ mod tests {
assert!(state.selected_index().is_some());
}
// -- NAV mode: new items don't reset edge state ---------------------------
#[test]
fn new_items_dont_reset_edge_state() {
let mut items: Vec<TestItem> = (0..10).map(TestItem::new).collect();
@@ -2161,16 +2095,16 @@ mod tests {
// n → next match = physical 2 (vis 1).
state.next_match(&items);
assert_eq!(state.selected_index(), Some(1)); // vis index 1
assert_eq!(state.selected_id(), Some(2)); // physical id 2
// Vis index 1.
assert_eq!(state.selected_index(), Some(1));
// Physical id 2.
assert_eq!(state.selected_id(), Some(2));
// n → wraps to physical 0 (vis 0).
state.next_match(&items);
assert_eq!(state.selected_index(), Some(0));
}
// -- Config gating tests --------------------------------------------------
#[test]
fn follow_disabled_g_selects_last_item() {
let config = ListPaneConfig {
@@ -2194,7 +2128,8 @@ mod tests {
..ListPaneConfig::default()
};
let state = ListPaneState::new_with_config(WrapMode::NoWrap, true, config);
assert!(!state.follow_mode); // forced off by config
// Forced off by config.
assert!(!state.follow_mode);
}
#[test]
@@ -2238,7 +2173,8 @@ mod tests {
state.half_page_down(&items);
}
assert!(!state.follow_mode);
assert_eq!(state.scroll_offset(), 10); // at bottom
// At bottom.
assert_eq!(state.scroll_offset(), 10);
}
#[test]
@@ -2288,8 +2224,6 @@ mod tests {
assert_eq!(state.wrap_mode(), WrapMode::NoWrap);
}
// -- Toggle follow tests --------------------------------------------------
#[test]
fn toggle_follow_from_nav_engages() {
let items: Vec<TestItem> = (0..20).map(TestItem::new).collect();
@@ -2315,8 +2249,6 @@ mod tests {
assert!(state.selected_index().is_some());
}
// -- Copy tests -----------------------------------------------------------
/// Helper: create a state with copy enabled.
fn new_with_copy() -> ListPaneState {
ListPaneState::new_with_config(
@@ -2485,8 +2417,6 @@ mod tests {
assert!(!state.copy_selected(&items));
}
// -- Visual select tests --------------------------------------------------
/// Helper: create a state with visual select + copy enabled.
fn new_with_visual() -> ListPaneState {
ListPaneState::new_with_config(
@@ -2536,11 +2466,12 @@ mod tests {
// Select item 3, enter visual, move down to 5.
state.select_at(3, &items);
state.enter_visual_mode(&items);
state.select_next(&items); // → 4
state.select_next(&items); // → 5
state.prepare_layout(&items, 80, 10); // resolve range
state.select_next(&items);
state.select_next(&items);
// Resolve range.
state.prepare_layout(&items, 80, 10);
assert_eq!(state.multi_range(), Some(3..6)); // [3, 4, 5]
assert_eq!(state.multi_range(), Some(3..6));
assert_eq!(state.selected_index(), Some(5));
}
@@ -2553,11 +2484,11 @@ mod tests {
// Select item 5, enter visual, move up to 3.
state.select_at(5, &items);
state.enter_visual_mode(&items);
state.select_prev(&items); // → 4
state.select_prev(&items); // → 3
state.select_prev(&items);
state.select_prev(&items);
state.prepare_layout(&items, 80, 10);
assert_eq!(state.multi_range(), Some(3..6)); // [3, 4, 5]
assert_eq!(state.multi_range(), Some(3..6));
assert_eq!(state.selected_index(), Some(3));
}
@@ -2577,7 +2508,7 @@ mod tests {
assert_eq!(state.selected_index(), Some(2));
state.prepare_layout(&items, 80, 10);
assert_eq!(state.multi_range(), Some(0..3)); // [0, 1, 2]
assert_eq!(state.multi_range(), Some(0..3));
}
#[test]
@@ -2603,9 +2534,10 @@ mod tests {
// Select items 1..=3 visually.
state.select_at(1, &items);
state.enter_visual_mode(&items);
state.select_next(&items); // → 2
state.select_next(&items); // → 3
state.prepare_layout(&items, 80, 10); // resolve range
state.select_next(&items);
state.select_next(&items);
// Resolve range.
state.prepare_layout(&items, 80, 10);
// y copies and clears visual mode.
state.handle_key_event(&key!('y').to_key_event(), &items);
@@ -2673,7 +2605,8 @@ mod tests {
fn select_next_scrolls_in_small_viewport() {
let items: Vec<TestItem> = (0..12).map(TestItem::new).collect();
let mut state = ListPaneState::new(WrapMode::NoWrap, false);
state.prepare_layout(&items, 80, 4); // width=80, viewport_height=4
// width=80, viewport_height=4.
state.prepare_layout(&items, 80, 4);
for step in 0..12 {
state.select_next(&items);
@@ -2700,7 +2633,8 @@ mod tests {
for step in 0..12 {
// simulate render: prepare_layout first
state.prepare_layout(&items, 80, 4); // width=80, viewport_height=4
// width=80, viewport_height=4.
state.prepare_layout(&items, 80, 4);
// simulate key: select_next
state.select_next(&items);
let idx = state.selected_index.unwrap();
@@ -2721,8 +2655,10 @@ mod tests {
fn scroll_lines_works_in_small_viewport() {
let items: Vec<TestItem> = (0..12).map(TestItem::new).collect();
let mut state = ListPaneState::new(WrapMode::NoWrap, false);
state.prepare_layout(&items, 80, 4); // width=80, viewport_height=4
state.select_next(&items); // select first
// width=80, viewport_height=4.
state.prepare_layout(&items, 80, 4);
// Select first.
state.select_next(&items);
let total = state.layout.total_height();
let vp = state.viewport_height;