Skip to main content

ftui_widgets/
virtualized.rs

1#![forbid(unsafe_code)]
2
3//! Virtualization primitives for efficient rendering of large content.
4//!
5//! This module provides the foundational types for rendering only visible
6//! portions of large datasets, enabling smooth performance with 100K+ items.
7//!
8//! # Core Types
9//!
10//! - [`Virtualized<T>`] - Generic container with visible range calculation
11//! - [`VirtualizedStorage`] - Owned vs external storage abstraction
12//! - [`ItemHeight`] - Fixed vs variable height support
13//! - [`HeightCache`] - LRU cache for measured item heights
14//!
15//! # Example
16//!
17//! ```ignore
18//! use ftui_widgets::virtualized::{Virtualized, ItemHeight};
19//!
20//! // Create with owned storage
21//! let mut virt: Virtualized<String> = Virtualized::new(10_000);
22//!
23//! // Add items
24//! for i in 0..1000 {
25//!     virt.push(format!("Line {}", i));
26//! }
27//!
28//! // Get visible range for viewport height
29//! let range = virt.visible_range(24);
30//! println!("Visible: {}..{}", range.start, range.end);
31//! ```
32
33use std::cell::Cell as StdCell;
34use std::collections::VecDeque;
35use std::ops::Range;
36use std::time::Duration;
37
38use crate::scrollbar::{Scrollbar, ScrollbarOrientation, ScrollbarState};
39use crate::{StatefulWidget, clear_text_area};
40use ftui_core::geometry::Rect;
41use ftui_render::cell::Cell;
42use ftui_render::frame::Frame;
43use ftui_style::Style;
44
45/// A virtualized content container that tracks scroll state and computes visible ranges.
46///
47/// # Design Rationale
48/// - Generic over item type for flexibility
49/// - Supports both owned storage and external data sources
50/// - Computes visible ranges for O(visible) rendering
51/// - Optional overscan for smooth scrolling
52/// - Momentum scrolling support
53#[derive(Debug, Clone)]
54pub struct Virtualized<T> {
55    /// The stored items (or external storage reference).
56    storage: VirtualizedStorage<T>,
57    /// Current scroll offset (in items).
58    scroll_offset: usize,
59    /// Number of visible items (cached from last render).
60    visible_count: StdCell<usize>,
61    /// Overscan: extra items rendered above/below visible.
62    overscan: usize,
63    /// Height calculation strategy.
64    item_height: ItemHeight,
65    /// Whether to auto-scroll on new items.
66    follow_mode: bool,
67    /// Scroll velocity for momentum scrolling.
68    scroll_velocity: f32,
69}
70
71/// Storage strategy for virtualized items.
72#[derive(Debug, Clone)]
73pub enum VirtualizedStorage<T> {
74    /// Owned vector of items.
75    Owned(VecDeque<T>),
76    /// External storage with known length.
77    /// Note: External fetch is handled at the widget level.
78    External {
79        /// Total number of items available.
80        len: usize,
81        /// Maximum items to keep in local cache.
82        cache_capacity: usize,
83    },
84}
85
86/// Height calculation strategy for items.
87#[derive(Debug, Clone)]
88pub enum ItemHeight {
89    /// All items have fixed height.
90    Fixed(u16),
91    /// Items have variable height, cached lazily (linear scan).
92    Variable(HeightCache),
93    /// Items have variable height with O(log n) scroll-to-index via Fenwick tree.
94    VariableFenwick(VariableHeightsFenwick),
95}
96
97/// LRU cache for measured item heights.
98#[derive(Debug, Clone)]
99pub struct HeightCache {
100    /// Height measurements indexed by (item index - base_offset).
101    cache: Vec<Option<u16>>,
102    /// Offset of the first entry in the cache (cache[0] corresponds to this item index).
103    base_offset: usize,
104    /// Default height for unmeasured items.
105    default_height: u16,
106    /// Maximum entries to cache (for memory bounds).
107    capacity: usize,
108}
109
110impl<T> Virtualized<T> {
111    /// Create a new virtualized container with owned storage.
112    ///
113    /// # Arguments
114    /// * `capacity` - Maximum items to retain in memory.
115    #[must_use]
116    pub fn new(capacity: usize) -> Self {
117        Self {
118            storage: VirtualizedStorage::Owned(VecDeque::with_capacity(capacity.min(1024))),
119            scroll_offset: 0,
120            visible_count: StdCell::new(0),
121            overscan: 2,
122            item_height: ItemHeight::Fixed(1),
123            follow_mode: false,
124            scroll_velocity: 0.0,
125        }
126    }
127
128    /// Create with external storage reference.
129    #[must_use]
130    pub fn external(len: usize, cache_capacity: usize) -> Self {
131        Self {
132            storage: VirtualizedStorage::External {
133                len,
134                cache_capacity,
135            },
136            scroll_offset: 0,
137            visible_count: StdCell::new(0),
138            overscan: 2,
139            item_height: ItemHeight::Fixed(1),
140            follow_mode: false,
141            scroll_velocity: 0.0,
142        }
143    }
144
145    /// Set item height strategy.
146    #[must_use]
147    pub fn with_item_height(mut self, height: ItemHeight) -> Self {
148        self.item_height = height;
149        self
150    }
151
152    /// Set fixed item height.
153    #[must_use]
154    pub fn with_fixed_height(mut self, height: u16) -> Self {
155        self.item_height = ItemHeight::Fixed(height);
156        self
157    }
158
159    /// Set variable heights with O(log n) Fenwick tree tracking.
160    ///
161    /// This is more efficient than `Variable(HeightCache)` for large lists
162    /// as scroll-to-index mapping is O(log n) instead of O(visible).
163    #[must_use]
164    pub fn with_variable_heights_fenwick(mut self, default_height: u16, capacity: usize) -> Self {
165        self.item_height =
166            ItemHeight::VariableFenwick(VariableHeightsFenwick::new(default_height, capacity));
167        self
168    }
169
170    /// Set overscan amount.
171    #[must_use]
172    pub fn with_overscan(mut self, overscan: usize) -> Self {
173        self.overscan = overscan;
174        self
175    }
176
177    /// Enable follow mode.
178    #[must_use]
179    pub fn with_follow(mut self, follow: bool) -> Self {
180        self.follow_mode = follow;
181        self
182    }
183
184    /// Get total number of items.
185    #[must_use]
186    pub fn len(&self) -> usize {
187        match &self.storage {
188            VirtualizedStorage::Owned(items) => items.len(),
189            VirtualizedStorage::External { len, .. } => *len,
190        }
191    }
192
193    /// Check if empty.
194    #[must_use]
195    pub fn is_empty(&self) -> bool {
196        self.len() == 0
197    }
198
199    /// Get current scroll offset.
200    ///
201    /// The internal sentinel value (`usize::MAX`, used for lazy scroll-to-bottom)
202    /// is clamped to the actual item count so callers never see it.
203    #[must_use]
204    pub fn scroll_offset(&self) -> usize {
205        self.scroll_offset.min(self.len().saturating_sub(1))
206    }
207
208    /// Get current visible count (from last render).
209    #[must_use]
210    pub fn visible_count(&self) -> usize {
211        self.visible_count.get()
212    }
213
214    /// Check if follow mode is enabled.
215    #[must_use]
216    pub fn follow_mode(&self) -> bool {
217        self.follow_mode
218    }
219
220    /// Calculate visible range for given viewport height.
221    #[must_use]
222    pub fn visible_range(&self, viewport_height: u16) -> Range<usize> {
223        if self.is_empty() || viewport_height == 0 {
224            self.visible_count.set(0);
225            return 0..0;
226        }
227
228        let items_visible = match &self.item_height {
229            // Use div_ceil to include partially visible items
230            ItemHeight::Fixed(h) if *h > 0 => viewport_height.div_ceil(*h) as usize,
231            ItemHeight::Fixed(_) => viewport_height as usize,
232            ItemHeight::Variable(cache) => {
233                // Sum heights until we fill or exceed viewport
234                let len = self.len();
235                let start = self.scroll_offset.min(len.saturating_sub(1));
236                let mut count = 0;
237                let mut total_height = 0u16;
238                while start + count < len {
239                    let next = cache.get(start + count);
240
241                    // Always include the item
242                    total_height = total_height.saturating_add(next);
243                    count += 1;
244
245                    // Stop if we've filled the viewport
246                    if total_height >= viewport_height {
247                        break;
248                    }
249                }
250                if total_height < viewport_height && start > 0 {
251                    // The tail from `start` cannot fill the viewport (e.g.
252                    // after scroll_to_bottom's lazy sentinel, or an offset
253                    // near the end). Anchor to the bottom like the Fixed arm:
254                    // count the trailing items that fit, so the clamped start
255                    // below shows a full last screenful instead of blank rows.
256                    count = 0;
257                    total_height = 0;
258                    while count < len {
259                        let next = cache.get(len - 1 - count);
260                        total_height = total_height.saturating_add(next);
261                        count += 1;
262                        if total_height >= viewport_height {
263                            break;
264                        }
265                    }
266                }
267                count
268            }
269            ItemHeight::VariableFenwick(tracker) => {
270                // O(log n) using Fenwick tree
271                let len = self.len();
272                let start = self.scroll_offset.min(len.saturating_sub(1));
273                let total = tracker.total_height();
274                let suffix = total.saturating_sub(tracker.offset_of_item(start));
275                if suffix < u32::from(viewport_height) {
276                    // Same bottom anchoring as the Variable arm, in O(log n):
277                    // when the last screenful is shown, its first (possibly
278                    // partially visible) item contains offset total-viewport.
279                    let anchor = total.saturating_sub(u32::from(viewport_height));
280                    len.saturating_sub(tracker.find_item_at_offset(anchor))
281                        .max(1)
282                } else {
283                    tracker.visible_count(start, viewport_height).max(1)
284                }
285            }
286        };
287
288        let max_offset = self.len().saturating_sub(items_visible);
289        let start = self.scroll_offset.min(max_offset);
290        let end = start.saturating_add(items_visible).min(self.len());
291        self.visible_count.set(items_visible);
292        start..end
293    }
294
295    /// Get render range with overscan for smooth scrolling.
296    #[must_use]
297    pub fn render_range(&self, viewport_height: u16) -> Range<usize> {
298        let visible = self.visible_range(viewport_height);
299        let start = visible.start.saturating_sub(self.overscan);
300        let end = visible.end.saturating_add(self.overscan).min(self.len());
301        start..end
302    }
303
304    /// Scroll by delta (positive = down/forward).
305    pub fn scroll(&mut self, delta: i32) {
306        if self.is_empty() {
307            return;
308        }
309        let visible_count = self.visible_count.get();
310        let max_offset = if visible_count > 0 {
311            self.len().saturating_sub(visible_count)
312        } else {
313            self.len().saturating_sub(1)
314        };
315        // Clamp current offset BEFORE adding delta, so lazy MAX doesn't swallow negative deltas
316        let clamped_current = self.scroll_offset.min(max_offset);
317        let new_offset = clamped_current
318            .saturating_add_signed(delta as isize)
319            .min(max_offset);
320        self.scroll_offset = new_offset;
321
322        // Disable follow mode on manual scroll
323        if delta != 0 {
324            self.follow_mode = false;
325        }
326    }
327
328    /// Scroll to specific item index.
329    pub fn scroll_to(&mut self, idx: usize) {
330        self.scroll_offset = idx.min(self.len().saturating_sub(1));
331        self.follow_mode = false;
332    }
333
334    /// Scroll to bottom.
335    pub fn scroll_to_bottom(&mut self) {
336        if self.is_empty() {
337            self.scroll_offset = 0;
338            return;
339        }
340
341        let visible_count = self.visible_count.get();
342        if visible_count == 0 {
343            // Viewport unknown; keep a sentinel and let `visible_range` clamp lazily.
344            self.scroll_offset = usize::MAX;
345        } else if self.len() > visible_count {
346            self.scroll_offset = self.len().saturating_sub(visible_count);
347        } else {
348            self.scroll_offset = 0;
349        }
350    }
351
352    /// Scroll to top.
353    pub fn scroll_to_top(&mut self) {
354        self.scroll_offset = 0;
355        self.follow_mode = false;
356    }
357
358    /// Alias for scroll_to_top (Home key).
359    pub fn scroll_to_start(&mut self) {
360        self.scroll_to_top();
361    }
362
363    /// Scroll to bottom and enable follow mode (End key).
364    pub fn scroll_to_end(&mut self) {
365        self.scroll_to_bottom();
366        self.follow_mode = true;
367    }
368
369    /// Page up (scroll by visible count - 1).
370    pub fn page_up(&mut self) {
371        let visible_count = self.visible_count.get();
372        if visible_count > 0 {
373            let step = if visible_count > 1 {
374                visible_count - 1
375            } else {
376                1
377            };
378            let delta = i32::try_from(step).unwrap_or(i32::MAX);
379            self.scroll(-delta);
380        }
381    }
382
383    /// Page down (scroll by visible count - 1).
384    pub fn page_down(&mut self) {
385        let visible_count = self.visible_count.get();
386        if visible_count > 0 {
387            let step = if visible_count > 1 {
388                visible_count - 1
389            } else {
390                1
391            };
392            let delta = i32::try_from(step).unwrap_or(i32::MAX);
393            self.scroll(delta);
394        }
395    }
396
397    /// Set follow mode.
398    pub fn set_follow(&mut self, follow: bool) {
399        self.follow_mode = follow;
400        if follow {
401            self.scroll_to_bottom();
402        }
403    }
404
405    /// Check if scrolled to bottom.
406    #[must_use]
407    pub fn is_at_bottom(&self) -> bool {
408        let visible_count = self.visible_count.get();
409        if self.len() <= visible_count {
410            true
411        } else {
412            self.scroll_offset >= self.len().saturating_sub(visible_count)
413        }
414    }
415
416    /// Start momentum scroll.
417    pub fn fling(&mut self, velocity: f32) {
418        self.scroll_velocity = velocity;
419    }
420
421    /// Apply momentum scroll tick.
422    pub fn tick(&mut self, dt: Duration) {
423        if self.scroll_velocity.abs() > 0.1 {
424            let delta = (self.scroll_velocity * dt.as_secs_f32()) as i32;
425            if delta != 0 {
426                self.scroll(delta);
427            }
428            // Apply friction
429            self.scroll_velocity *= 0.95;
430        } else {
431            self.scroll_velocity = 0.0;
432        }
433    }
434
435    /// Update visible count (called during render).
436    pub fn set_visible_count(&self, count: usize) {
437        self.visible_count.set(count);
438    }
439
440    /// Get reference to the item height strategy.
441    #[must_use]
442    pub fn item_height(&self) -> &ItemHeight {
443        &self.item_height
444    }
445
446    /// Get mutable reference to the item height strategy.
447    ///
448    /// Useful for updating variable height trackers (e.g. resizing Fenwick tree)
449    /// when items are added.
450    pub fn item_height_mut(&mut self) -> &mut ItemHeight {
451        &mut self.item_height
452    }
453}
454
455impl<T> Virtualized<T> {
456    /// Push an item (owned storage only).
457    pub fn push(&mut self, item: T) {
458        if let VirtualizedStorage::Owned(items) = &mut self.storage {
459            items.push_back(item);
460            if self.follow_mode {
461                self.scroll_to_bottom();
462            }
463        }
464    }
465
466    /// Get item by index (owned storage only).
467    #[must_use = "use the returned item (if any)"]
468    pub fn get(&self, idx: usize) -> Option<&T> {
469        if let VirtualizedStorage::Owned(items) = &self.storage {
470            items.get(idx)
471        } else {
472            None
473        }
474    }
475
476    /// Get mutable item by index (owned storage only).
477    #[must_use = "use the returned item (if any)"]
478    pub fn get_mut(&mut self, idx: usize) -> Option<&mut T> {
479        if let VirtualizedStorage::Owned(items) = &mut self.storage {
480            items.get_mut(idx)
481        } else {
482            None
483        }
484    }
485
486    /// Clear all items (owned storage only).
487    pub fn clear(&mut self) {
488        if let VirtualizedStorage::Owned(items) = &mut self.storage {
489            items.clear();
490        }
491        self.scroll_offset = 0;
492    }
493
494    /// Trim items from the front to keep at most `max` items (owned storage only).
495    ///
496    /// Returns the number of items removed.
497    pub fn trim_front(&mut self, max: usize) -> usize {
498        if let VirtualizedStorage::Owned(items) = &mut self.storage
499            && items.len() > max
500        {
501            let to_remove = items.len() - max;
502            items.drain(..to_remove);
503            // Adjust scroll_offset if it was pointing beyond the new start
504            self.scroll_offset = self.scroll_offset.saturating_sub(to_remove);
505            return to_remove;
506        }
507        0
508    }
509
510    /// Iterate over items (owned storage only).
511    /// Returns empty iterator for external storage.
512    pub fn iter(&self) -> Box<dyn Iterator<Item = &T> + '_> {
513        match &self.storage {
514            VirtualizedStorage::Owned(items) => Box::new(items.iter()),
515            VirtualizedStorage::External { .. } => Box::new(std::iter::empty()),
516        }
517    }
518
519    /// Update external storage length.
520    pub fn set_external_len(&mut self, len: usize) {
521        if let VirtualizedStorage::External { len: l, .. } = &mut self.storage {
522            *l = len;
523            if self.follow_mode {
524                self.scroll_to_bottom();
525            }
526        }
527    }
528}
529
530impl Default for HeightCache {
531    fn default() -> Self {
532        Self::new(1, 1000)
533    }
534}
535
536impl HeightCache {
537    /// Create a new height cache.
538    #[must_use]
539    pub fn new(default_height: u16, capacity: usize) -> Self {
540        Self {
541            cache: Vec::new(),
542            base_offset: 0,
543            default_height,
544            capacity,
545        }
546    }
547
548    /// Get height for item, returning default if not cached.
549    #[must_use]
550    pub fn get(&self, idx: usize) -> u16 {
551        if idx < self.base_offset {
552            return self.default_height;
553        }
554        let local = idx - self.base_offset;
555        self.cache
556            .get(local)
557            .and_then(|h| *h)
558            .unwrap_or(self.default_height)
559    }
560
561    /// Set height for item.
562    pub fn set(&mut self, idx: usize, height: u16) {
563        if self.capacity == 0 {
564            return;
565        }
566        if idx < self.base_offset {
567            // Index has been trimmed away; ignore
568            return;
569        }
570        let mut local = idx - self.base_offset;
571
572        // If the jump is so large that we'd drain the entire current cache anyway,
573        // reset the window to avoid a huge allocation of Nones.
574        if local + 1 >= self.cache.len() + self.capacity {
575            self.base_offset = idx.saturating_add(1).saturating_sub(self.capacity);
576            self.cache.clear();
577            local = idx - self.base_offset;
578        }
579
580        if local >= self.cache.len() {
581            self.cache.resize(local + 1, None);
582        }
583        self.cache[local] = Some(height);
584
585        // Trim if over capacity: remove oldest entries and adjust base_offset
586        if self.cache.len() > self.capacity {
587            let to_remove = self.cache.len() - self.capacity;
588            self.cache.drain(0..to_remove);
589            self.base_offset += to_remove;
590        }
591    }
592
593    /// Clear cached heights.
594    pub fn clear(&mut self) {
595        self.cache.clear();
596        self.base_offset = 0;
597    }
598}
599
600// ============================================================================
601// VariableHeightsFenwick - O(log n) scroll-to-index mapping
602// ============================================================================
603
604use crate::fenwick::FenwickTree;
605
606/// Variable height tracker using Fenwick tree for O(log n) prefix sum queries.
607///
608/// This enables efficient scroll offset to item index mapping for virtualized
609/// lists with variable height items.
610///
611/// # Operations
612///
613/// | Operation | Time |
614/// |-----------|------|
615/// | `find_item_at_offset` | O(log n) |
616/// | `offset_of_item` | O(log n) |
617/// | `set_height` | O(log n) |
618/// | `total_height` | O(log n) |
619///
620/// # Invariants
621///
622/// 1. `tree.prefix(i)` == sum of heights [0..=i]
623/// 2. `find_item_at_offset(offset)` returns largest i where prefix(i-1) < offset
624/// 3. Heights are u32 internally (u16 input widened for large lists)
625#[derive(Debug, Clone)]
626pub struct VariableHeightsFenwick {
627    /// Fenwick tree storing item heights.
628    tree: FenwickTree,
629    /// Default height for items not yet measured.
630    default_height: u16,
631    /// Number of items tracked.
632    len: usize,
633}
634
635impl Default for VariableHeightsFenwick {
636    fn default() -> Self {
637        Self::new(1, 0)
638    }
639}
640
641impl VariableHeightsFenwick {
642    /// Create a new height tracker with given default height and initial capacity.
643    #[must_use]
644    pub fn new(default_height: u16, capacity: usize) -> Self {
645        let tree = if capacity > 0 {
646            // Initialize with default heights
647            let heights: Vec<u32> = vec![u32::from(default_height); capacity];
648            FenwickTree::from_values(&heights)
649        } else {
650            FenwickTree::new(0)
651        };
652        Self {
653            tree,
654            default_height,
655            len: capacity,
656        }
657    }
658
659    /// Create from a slice of heights.
660    #[must_use]
661    pub fn from_heights(heights: &[u16], default_height: u16) -> Self {
662        let heights_u32: Vec<u32> = heights.iter().map(|&h| u32::from(h)).collect();
663        Self {
664            tree: FenwickTree::from_values(&heights_u32),
665            default_height,
666            len: heights.len(),
667        }
668    }
669
670    /// Number of items tracked.
671    #[must_use]
672    pub fn len(&self) -> usize {
673        self.len
674    }
675
676    /// Whether tracking is empty.
677    #[must_use]
678    pub fn is_empty(&self) -> bool {
679        self.len == 0
680    }
681
682    /// Get the default height for unmeasured items.
683    #[must_use]
684    pub fn default_height(&self) -> u16 {
685        self.default_height
686    }
687
688    /// Get height of a specific item. O(log n).
689    #[must_use]
690    pub fn get(&self, idx: usize) -> u16 {
691        if idx >= self.len {
692            return self.default_height;
693        }
694        // Fenwick get returns the individual value at idx
695        self.tree.get(idx).min(u32::from(u16::MAX)) as u16
696    }
697
698    /// Set height of a specific item. O(log n).
699    pub fn set(&mut self, idx: usize, height: u16) {
700        if idx >= self.len {
701            // Need to resize
702            self.resize(idx + 1);
703        }
704        self.tree.set(idx, u32::from(height));
705    }
706
707    /// Get the y-offset (in pixels/rows) of an item. O(log n).
708    ///
709    /// Returns the sum of heights of all items before `idx`.
710    #[must_use]
711    pub fn offset_of_item(&self, idx: usize) -> u32 {
712        if idx == 0 || self.len == 0 {
713            return 0;
714        }
715        let clamped = idx.min(self.len);
716        if clamped > 0 {
717            self.tree.prefix(clamped - 1)
718        } else {
719            0
720        }
721    }
722
723    /// Find the item index at a given scroll offset. O(log n).
724    ///
725    /// Returns the index of the item that occupies the given offset.
726    /// If offset is beyond all items, returns `self.len`.
727    ///
728    /// Item i occupies offsets [offset_of_item(i), offset_of_item(i+1)).
729    #[must_use]
730    pub fn find_item_at_offset(&self, offset: u32) -> usize {
731        if self.len == 0 {
732            return 0;
733        }
734        if offset == 0 {
735            return 0;
736        }
737        // find_prefix returns largest i where prefix(i) <= offset
738        // prefix(i) = sum of heights [0..=i] = y-coordinate just past item i
739        // If prefix(i) <= offset, then offset is at or past the end of item i,
740        // so offset is in item i+1.
741        //
742        // We use `offset` directly (not `offset - 1`). When `offset == prefix(i)` exactly,
743        // `find_prefix` returns `i`, and we correctly map that to item `i+1` below.
744        match self.tree.find_prefix(offset) {
745            Some(i) => {
746                // prefix(i) <= offset
747                // Item i spans [prefix(i-1), prefix(i)), so offset >= prefix(i)
748                // means offset is in item i+1 or beyond
749                (i + 1).min(self.len)
750            }
751            None => {
752                // offset < prefix(0), so offset is within item 0
753                0
754            }
755        }
756    }
757
758    /// Count how many items are visible within a viewport starting at `start_idx`. O(log n).
759    ///
760    /// Visibility here means partially or fully visible. The first partially
761    /// visible trailing item is counted.
762    ///
763    /// Returns **at least 1** when `start_idx < len` and `viewport_height > 0`,
764    /// even if the first item is taller than the viewport.
765    #[must_use]
766    pub fn visible_count(&self, start_idx: usize, viewport_height: u16) -> usize {
767        if self.len == 0 || viewport_height == 0 {
768            return 0;
769        }
770        let start = start_idx.min(self.len);
771        let start_offset = self.offset_of_item(start);
772        let end_offset = start_offset.saturating_add(u32::from(viewport_height));
773
774        // Find last item that fits
775        let end_idx = self.find_item_at_offset(end_offset);
776
777        // Count items from start to end (including partially visible trailing item)
778        if end_idx > start {
779            // `find_item_at_offset` returns `len` when `end_offset` is at/after the end
780            // of the list. In that case, everything from `start` to the end fits.
781            if end_idx >= self.len {
782                return self.len.saturating_sub(start);
783            }
784            // Check if end_idx item is visible (partially or fully)
785            let end_item_start = self.offset_of_item(end_idx);
786            if end_offset > end_item_start {
787                end_idx - start + 1
788            } else {
789                end_idx - start
790            }
791        } else {
792            // At least show one item if viewport has space
793            if viewport_height > 0 && start < self.len {
794                1
795            } else {
796                0
797            }
798        }
799    }
800
801    /// Get total height of all items. O(log n).
802    #[must_use]
803    pub fn total_height(&self) -> u32 {
804        self.tree.total()
805    }
806
807    /// Resize the tracker to accommodate `new_len` items.
808    ///
809    /// New items are initialized with default height.
810    pub fn resize(&mut self, new_len: usize) {
811        if new_len == self.len {
812            return;
813        }
814        self.tree.resize(new_len);
815        // Set default heights for new items
816        if new_len > self.len {
817            for i in self.len..new_len {
818                self.tree.set(i, u32::from(self.default_height));
819            }
820        }
821        self.len = new_len;
822    }
823
824    /// Clear all height data.
825    pub fn clear(&mut self) {
826        self.tree = FenwickTree::new(0);
827        self.len = 0;
828    }
829
830    /// Rebuild from a fresh set of heights.
831    pub fn rebuild(&mut self, heights: &[u16]) {
832        let heights_u32: Vec<u32> = heights.iter().map(|&h| u32::from(h)).collect();
833        self.tree = FenwickTree::from_values(&heights_u32);
834        self.len = heights.len();
835    }
836}
837
838// ============================================================================
839// VirtualizedList Widget
840// ============================================================================
841
842/// Trait for items that can render themselves.
843///
844/// Implement this trait for item types that should render in a `VirtualizedList`.
845pub trait RenderItem {
846    /// Render the item into the frame at the given area.
847    ///
848    /// # Arguments
849    ///
850    /// * `area` - The area to render into.
851    /// * `frame` - The frame to render into.
852    /// * `selected` - Whether the item is selected.
853    /// * `skip_rows` - Number of rows to skip from the top of the item content.
854    ///   This is non-zero when the item partially overlaps the top of the viewport.
855    fn render(&self, area: Rect, frame: &mut Frame, selected: bool, skip_rows: u16);
856
857    /// Height of this item in terminal rows.
858    fn height(&self) -> u16 {
859        1
860    }
861}
862
863/// State for the VirtualizedList widget.
864#[derive(Debug, Clone)]
865pub struct VirtualizedListState {
866    /// Currently selected index.
867    pub selected: Option<usize>,
868    /// Scroll offset.
869    scroll_offset: usize,
870    /// Visible count (from last render).
871    visible_count: usize,
872    /// Overscan amount.
873    overscan: usize,
874    /// Whether follow mode is enabled.
875    follow_mode: bool,
876    /// Scroll velocity for momentum.
877    scroll_velocity: f32,
878    /// Drag anchor for scrollbar thumb (offset from thumb top).
879    scrollbar_drag_anchor: Option<usize>,
880    /// Optional persistence ID for state saving/restoration.
881    persistence_id: Option<String>,
882}
883
884impl Default for VirtualizedListState {
885    fn default() -> Self {
886        Self::new()
887    }
888}
889
890impl VirtualizedListState {
891    /// Create a new state.
892    #[must_use]
893    pub fn new() -> Self {
894        Self {
895            selected: None,
896            scroll_offset: 0,
897            visible_count: 0,
898            overscan: 2,
899            follow_mode: false,
900            scroll_velocity: 0.0,
901            scrollbar_drag_anchor: None,
902            persistence_id: None,
903        }
904    }
905
906    /// Create with overscan.
907    #[must_use]
908    pub fn with_overscan(mut self, overscan: usize) -> Self {
909        self.overscan = overscan;
910        self
911    }
912
913    /// Create with follow mode enabled.
914    #[must_use]
915    pub fn with_follow(mut self, follow: bool) -> Self {
916        self.follow_mode = follow;
917        self
918    }
919
920    /// Create with a persistence ID for state saving.
921    #[must_use]
922    pub fn with_persistence_id(mut self, id: impl Into<String>) -> Self {
923        self.persistence_id = Some(id.into());
924        self
925    }
926
927    /// Get the persistence ID, if set.
928    #[must_use = "use the persistence id (if any)"]
929    pub fn persistence_id(&self) -> Option<&str> {
930        self.persistence_id.as_deref()
931    }
932
933    /// Get raw scroll offset.
934    ///
935    /// **Warning:** After `scroll_to_bottom`, this may return `usize::MAX`
936    /// (a lazy sentinel that gets clamped during rendering). Use
937    /// [`scroll_offset_clamped`](Self::scroll_offset_clamped) with a known
938    /// `total_items` to get a safe value for display or indexing.
939    #[must_use]
940    pub fn scroll_offset(&self) -> usize {
941        self.scroll_offset
942    }
943
944    /// Get scroll offset clamped against a known total item count.
945    ///
946    /// Prefer this over [`scroll_offset()`](Self::scroll_offset) when the total is available,
947    /// because `scroll_to_bottom` may store `usize::MAX` internally.
948    #[must_use]
949    pub fn scroll_offset_clamped(&self, total_items: usize) -> usize {
950        if total_items == 0 {
951            return 0;
952        }
953        self.scroll_offset.min(total_items.saturating_sub(1))
954    }
955
956    /// Get visible item count (from last render).
957    #[must_use]
958    pub fn visible_count(&self) -> usize {
959        self.visible_count
960    }
961
962    /// Scroll by delta (positive = down).
963    pub fn scroll(&mut self, delta: i32, total_items: usize) {
964        if total_items == 0 {
965            return;
966        }
967        let max_offset = if self.visible_count > 0 {
968            total_items.saturating_sub(self.visible_count)
969        } else {
970            total_items.saturating_sub(1)
971        };
972        // Clamp current offset BEFORE adding delta, so lazy MAX doesn't swallow negative deltas
973        let clamped_current = self.scroll_offset.min(max_offset);
974        let new_offset = clamped_current
975            .saturating_add_signed(delta as isize)
976            .min(max_offset);
977        self.scroll_offset = new_offset;
978
979        if delta != 0 {
980            self.follow_mode = false;
981        }
982    }
983
984    /// Scroll to specific index.
985    pub fn scroll_to(&mut self, idx: usize, total_items: usize) {
986        self.scroll_offset = idx.min(total_items.saturating_sub(1));
987        self.follow_mode = false;
988    }
989
990    /// Scroll to top.
991    pub fn scroll_to_top(&mut self) {
992        self.scroll_offset = 0;
993        self.follow_mode = false;
994    }
995
996    /// Scroll to bottom.
997    pub fn scroll_to_bottom(&mut self, total_items: usize) {
998        if total_items == 0 {
999            self.scroll_offset = 0;
1000        } else {
1001            // Set to MAX; render() will clamp to (total - viewport)
1002            // once viewport height is known.
1003            self.scroll_offset = usize::MAX;
1004        }
1005    }
1006
1007    /// Page up (scroll by visible count - 1).
1008    pub fn page_up(&mut self, total_items: usize) {
1009        if self.visible_count > 0 {
1010            let step = if self.visible_count > 1 {
1011                self.visible_count - 1
1012            } else {
1013                1
1014            };
1015            let delta = i32::try_from(step).unwrap_or(i32::MAX);
1016            self.scroll(-delta, total_items);
1017        }
1018    }
1019
1020    /// Page down (scroll by visible count - 1).
1021    pub fn page_down(&mut self, total_items: usize) {
1022        if self.visible_count > 0 {
1023            let step = if self.visible_count > 1 {
1024                self.visible_count - 1
1025            } else {
1026                1
1027            };
1028            let delta = i32::try_from(step).unwrap_or(i32::MAX);
1029            self.scroll(delta, total_items);
1030        }
1031    }
1032
1033    /// Select an item.
1034    pub fn select(&mut self, index: Option<usize>) {
1035        self.selected = index;
1036    }
1037
1038    /// Select previous item.
1039    pub fn select_previous(&mut self, total_items: usize) {
1040        if total_items == 0 {
1041            self.selected = None;
1042            return;
1043        }
1044        self.selected = Some(match self.selected {
1045            Some(i) if i > 0 => i - 1,
1046            Some(_) => 0,
1047            None => 0,
1048        });
1049    }
1050
1051    /// Select next item.
1052    pub fn select_next(&mut self, total_items: usize) {
1053        if total_items == 0 {
1054            self.selected = None;
1055            return;
1056        }
1057        self.selected = Some(match self.selected {
1058            Some(i) if i < total_items - 1 => i + 1,
1059            Some(i) => i,
1060            None => 0,
1061        });
1062    }
1063
1064    /// Check if at bottom.
1065    #[must_use]
1066    pub fn is_at_bottom(&self, total_items: usize) -> bool {
1067        if total_items <= self.visible_count {
1068            true
1069        } else {
1070            self.scroll_offset >= total_items - self.visible_count
1071        }
1072    }
1073
1074    /// Enable/disable follow mode.
1075    pub fn set_follow(&mut self, follow: bool, total_items: usize) {
1076        self.follow_mode = follow;
1077        if follow {
1078            self.scroll_to_bottom(total_items);
1079        }
1080    }
1081
1082    /// Check if follow mode is enabled.
1083    #[must_use]
1084    pub fn follow_mode(&self) -> bool {
1085        self.follow_mode
1086    }
1087
1088    /// Start momentum scroll.
1089    pub fn fling(&mut self, velocity: f32) {
1090        self.scroll_velocity = velocity;
1091    }
1092
1093    /// Apply momentum scrolling tick.
1094    pub fn tick(&mut self, dt: Duration, total_items: usize) {
1095        if self.scroll_velocity.abs() > 0.1 {
1096            let delta = (self.scroll_velocity * dt.as_secs_f32()) as i32;
1097            if delta != 0 {
1098                self.scroll(delta, total_items);
1099            }
1100            self.scroll_velocity *= 0.95;
1101        } else {
1102            self.scroll_velocity = 0.0;
1103        }
1104    }
1105
1106    /// Handle mouse events, including scrollbar interaction.
1107    ///
1108    /// The caller must provide the hit test result and the expected hit ID for
1109    /// the scrollbar.
1110    pub fn handle_mouse(
1111        &mut self,
1112        event: &ftui_core::event::MouseEvent,
1113        hit: Option<(
1114            ftui_render::frame::HitId,
1115            ftui_render::frame::HitRegion,
1116            u64,
1117        )>,
1118        scrollbar_hit_id: ftui_render::frame::HitId,
1119        total_items: usize,
1120        viewport_height: u16,
1121        fixed_item_height: u16,
1122    ) -> crate::mouse::MouseResult {
1123        // Construct temporary scrollbar state
1124        let items_per_viewport = viewport_height.div_ceil(fixed_item_height.max(1)) as usize;
1125        let mut scrollbar_state =
1126            ScrollbarState::new(total_items, self.scroll_offset, items_per_viewport);
1127
1128        // Restore drag anchor
1129        scrollbar_state.drag_anchor = self.scrollbar_drag_anchor;
1130
1131        let result = scrollbar_state.handle_mouse(event, hit, scrollbar_hit_id);
1132
1133        // Sync back
1134        self.scroll_offset = scrollbar_state.position;
1135        self.scrollbar_drag_anchor = scrollbar_state.drag_anchor;
1136
1137        if result == crate::mouse::MouseResult::Scrolled {
1138            self.follow_mode = false;
1139        }
1140
1141        result
1142    }
1143}
1144
1145// ============================================================================
1146// Stateful Persistence Implementation for VirtualizedListState
1147// ============================================================================
1148
1149/// Persistable state for a [`VirtualizedListState`].
1150///
1151/// Contains the user-facing scroll state that should survive sessions.
1152/// Transient values like scroll_velocity and visible_count are not persisted.
1153#[derive(Clone, Debug, Default, PartialEq)]
1154#[cfg_attr(
1155    feature = "state-persistence",
1156    derive(serde::Serialize, serde::Deserialize)
1157)]
1158pub struct VirtualizedListPersistState {
1159    /// Selected item index.
1160    pub selected: Option<usize>,
1161    /// Scroll offset (first visible item).
1162    pub scroll_offset: usize,
1163    /// Whether follow mode is enabled.
1164    pub follow_mode: bool,
1165}
1166
1167impl crate::stateful::Stateful for VirtualizedListState {
1168    type State = VirtualizedListPersistState;
1169
1170    fn state_key(&self) -> crate::stateful::StateKey {
1171        crate::stateful::StateKey::new(
1172            "VirtualizedList",
1173            self.persistence_id.as_deref().unwrap_or("default"),
1174        )
1175    }
1176
1177    fn save_state(&self) -> VirtualizedListPersistState {
1178        VirtualizedListPersistState {
1179            selected: self.selected,
1180            scroll_offset: self.scroll_offset,
1181            follow_mode: self.follow_mode,
1182        }
1183    }
1184
1185    fn restore_state(&mut self, state: VirtualizedListPersistState) {
1186        self.selected = state.selected;
1187        self.scroll_offset = state.scroll_offset;
1188        self.follow_mode = state.follow_mode;
1189        // Reset transient values
1190        self.scroll_velocity = 0.0;
1191        self.scrollbar_drag_anchor = None;
1192    }
1193}
1194
1195/// A virtualized list widget that renders only visible items.
1196///
1197/// This widget efficiently renders large lists by only drawing items
1198/// that are currently visible in the viewport, with optional overscan
1199/// for smooth scrolling.
1200///
1201/// # Limitations
1202///
1203/// Currently, `VirtualizedList` only supports **fixed height** items.
1204/// For variable height virtualization, use the [`Virtualized`] primitive directly.
1205#[derive(Debug)]
1206pub struct VirtualizedList<'a, T> {
1207    /// Items to render.
1208    items: &'a [T],
1209    /// Base style.
1210    style: Style,
1211    /// Style for selected item.
1212    highlight_style: Style,
1213    /// Whether to show scrollbar.
1214    show_scrollbar: bool,
1215    /// Fixed item height.
1216    fixed_height: u16,
1217    /// Optional hit ID for scrollbar interaction.
1218    hit_id: Option<ftui_render::frame::HitId>,
1219}
1220
1221impl<'a, T> VirtualizedList<'a, T> {
1222    /// Create a new virtualized list.
1223    #[must_use]
1224    pub fn new(items: &'a [T]) -> Self {
1225        Self {
1226            items,
1227            style: Style::default(),
1228            highlight_style: Style::default(),
1229            show_scrollbar: true,
1230            fixed_height: 1,
1231            hit_id: None,
1232        }
1233    }
1234
1235    /// Set base style.
1236    #[must_use]
1237    pub fn style(mut self, style: Style) -> Self {
1238        self.style = style;
1239        self
1240    }
1241
1242    /// Set highlight style for selected item.
1243    #[must_use]
1244    pub fn highlight_style(mut self, style: Style) -> Self {
1245        self.highlight_style = style;
1246        self
1247    }
1248
1249    /// Enable/disable scrollbar.
1250    #[must_use]
1251    pub fn show_scrollbar(mut self, show: bool) -> Self {
1252        self.show_scrollbar = show;
1253        self
1254    }
1255
1256    /// Set fixed item height.
1257    #[must_use]
1258    pub fn fixed_height(mut self, height: u16) -> Self {
1259        self.fixed_height = height;
1260        self
1261    }
1262
1263    /// Set hit ID for scrollbar interaction.
1264    #[must_use]
1265    pub fn hit_id(mut self, id: ftui_render::frame::HitId) -> Self {
1266        self.hit_id = Some(id);
1267        self
1268    }
1269}
1270
1271impl<T: RenderItem> StatefulWidget for VirtualizedList<'_, T> {
1272    type State = VirtualizedListState;
1273
1274    fn render(&self, area: Rect, frame: &mut Frame, state: &mut Self::State) {
1275        #[cfg(feature = "tracing")]
1276        let _span = tracing::debug_span!(
1277            "widget_render",
1278            widget = "VirtualizedList",
1279            x = area.x,
1280            y = area.y,
1281            w = area.width,
1282            h = area.height,
1283            items = self.items.len()
1284        )
1285        .entered();
1286
1287        if area.is_empty() {
1288            return;
1289        }
1290
1291        // Clear the full owned viewport so empty renders and shorter rows do
1292        // not leak prior buffer content.
1293        clear_text_area(frame, area, self.style);
1294
1295        let total_items = self.items.len();
1296        if total_items == 0 {
1297            return;
1298        }
1299
1300        // Reserve space for scrollbar if needed
1301        let fixed_h = self.fixed_height.max(1);
1302        // Use div_ceil to include partially visible items and avoid 0 count for large items
1303        let items_per_viewport = area.height.div_ceil(fixed_h) as usize;
1304        let fully_visible_items = (area.height / fixed_h) as usize;
1305        let needs_scrollbar = self.show_scrollbar && total_items > fully_visible_items;
1306        let content_width = if needs_scrollbar {
1307            area.width.saturating_sub(1)
1308        } else {
1309            area.width
1310        };
1311
1312        // Ensure selection is within bounds
1313        if let Some(selected) = state.selected
1314            && selected >= total_items
1315        {
1316            // Use saturating_sub to handle empty list case (total_items = 0)
1317            state.selected = if total_items > 0 {
1318                Some(total_items - 1)
1319            } else {
1320                None
1321            };
1322        }
1323
1324        // Ensure visible range includes selected item (it must be fully visible if possible)
1325        if let Some(selected) = state.selected {
1326            let vis_count = fully_visible_items.max(1);
1327            if selected >= state.scroll_offset.saturating_add(vis_count) {
1328                state.scroll_offset = selected.saturating_sub(vis_count.saturating_sub(1));
1329            } else if selected < state.scroll_offset {
1330                state.scroll_offset = selected;
1331            }
1332        }
1333
1334        // Clamp scroll offset
1335        let max_offset = if fully_visible_items > 0 {
1336            total_items.saturating_sub(fully_visible_items)
1337        } else {
1338            total_items.saturating_sub(1)
1339        };
1340        state.scroll_offset = state.scroll_offset.min(max_offset);
1341
1342        // Update visible count — use fully_visible_items (not items_per_viewport
1343        // which includes partial items via div_ceil) so scroll calculations
1344        // (page size, max_offset) use a consistent metric.
1345        state.visible_count = fully_visible_items.max(1).min(total_items);
1346
1347        // Calculate render range with overscan
1348        let render_start = state.scroll_offset.saturating_sub(state.overscan);
1349        let render_end = state
1350            .scroll_offset
1351            .saturating_add(items_per_viewport)
1352            .saturating_add(state.overscan)
1353            .min(total_items);
1354
1355        // Render visible items
1356        for idx in render_start..render_end {
1357            // Calculate Y position relative to viewport
1358            // Use relative arithmetic to prevent overflow when indices exceed i32::MAX.
1359            let relative_idx = if idx >= state.scroll_offset {
1360                i32::try_from(idx - state.scroll_offset).unwrap_or(i32::MAX)
1361            } else {
1362                // Handle overscan items before the scroll offset
1363                -(i32::try_from(state.scroll_offset - idx).unwrap_or(i32::MAX))
1364            };
1365
1366            let height_i32 = i32::from(self.fixed_height);
1367            let y_offset = relative_idx.saturating_mul(height_i32);
1368
1369            // Skip items above viewport
1370            // We use area.y as the viewport top.
1371            // Absolute top of item = area.y + y_offset.
1372            // Absolute bottom of item = area.y + y_offset + height.
1373            // If absolute_bottom <= area.y, it is fully above.
1374            // i.e. y_offset + height <= 0
1375            if y_offset.saturating_add(height_i32) <= 0 {
1376                continue;
1377            }
1378
1379            // Stop if below viewport
1380            if y_offset >= i32::from(area.height) {
1381                break;
1382            }
1383
1384            // Check if item starts off-screen top.
1385            // If so, we must render partially by skipping the top rows.
1386            let skip_rows = if y_offset < 0 {
1387                y_offset.unsigned_abs() as u16
1388            } else {
1389                0
1390            };
1391
1392            // Calculate actual render area
1393            // Use i32 arithmetic to avoid overflow when casting y_offset to i16
1394            let y = i32::from(area.y)
1395                .saturating_add(y_offset)
1396                .clamp(i32::from(area.y), i32::from(u16::MAX)) as u16;
1397
1398            if y >= area.bottom() {
1399                break;
1400            }
1401
1402            let visible_height = self
1403                .fixed_height
1404                .saturating_sub(skip_rows)
1405                .min(area.bottom().saturating_sub(y));
1406
1407            if visible_height == 0 {
1408                continue;
1409            }
1410
1411            let row_area = Rect::new(area.x, y, content_width, visible_height);
1412
1413            let is_selected = state.selected == Some(idx);
1414
1415            let row_style = if is_selected {
1416                self.highlight_style.merge(&self.style)
1417            } else {
1418                self.style
1419            };
1420            clear_text_area(frame, row_area, row_style);
1421
1422            // Render the item
1423            self.items[idx].render(row_area, frame, is_selected, skip_rows);
1424        }
1425
1426        // Render scrollbar
1427        if needs_scrollbar {
1428            let scrollbar_area = Rect::new(area.right().saturating_sub(1), area.y, 1, area.height);
1429
1430            let mut scrollbar_state =
1431                ScrollbarState::new(total_items, state.scroll_offset, items_per_viewport);
1432
1433            // Sync drag anchor from persistent state to transient scrollbar state
1434            scrollbar_state.drag_anchor = state.scrollbar_drag_anchor;
1435
1436            let mut scrollbar = Scrollbar::new(ScrollbarOrientation::VerticalRight);
1437            if let Some(id) = self.hit_id {
1438                scrollbar = scrollbar.hit_id(id);
1439            }
1440            scrollbar.render(scrollbar_area, frame, &mut scrollbar_state);
1441        }
1442    }
1443}
1444
1445// ============================================================================
1446// Simple RenderItem implementations for common types
1447// ============================================================================
1448
1449impl RenderItem for String {
1450    fn render(&self, area: Rect, frame: &mut Frame, _selected: bool, skip_rows: u16) {
1451        if area.is_empty() {
1452            return;
1453        }
1454        let max_chars = area.width as usize;
1455        // String is assumed to be single-line in this implementation, so skip_rows > 0
1456        // implies the whole item is skipped. However, for robustness we check bounds.
1457        // If a String *did* contain newlines and we rendered it multiline, skip_rows would apply.
1458        // Here we just render the first line.
1459        if skip_rows > 0 {
1460            return;
1461        }
1462        for (i, ch) in self.chars().take(max_chars).enumerate() {
1463            frame
1464                .buffer
1465                .set(area.x.saturating_add(i as u16), area.y, Cell::from_char(ch));
1466        }
1467    }
1468}
1469
1470impl RenderItem for &str {
1471    fn render(&self, area: Rect, frame: &mut Frame, _selected: bool, skip_rows: u16) {
1472        if area.is_empty() {
1473            return;
1474        }
1475        if skip_rows > 0 {
1476            return;
1477        }
1478        let max_chars = area.width as usize;
1479        for (i, ch) in self.chars().take(max_chars).enumerate() {
1480            frame
1481                .buffer
1482                .set(area.x.saturating_add(i as u16), area.y, Cell::from_char(ch));
1483        }
1484    }
1485}
1486
1487#[cfg(test)]
1488mod tests {
1489    use super::*;
1490    use proptest::prelude::*;
1491
1492    fn raw_row_text(frame: &Frame, y: u16) -> String {
1493        let width = frame.buffer.width();
1494        let mut actual = String::new();
1495        for x in 0..width {
1496            let ch = frame
1497                .buffer
1498                .get(x, y)
1499                .and_then(|cell| cell.content.as_char())
1500                .unwrap_or(' ');
1501            actual.push(ch);
1502        }
1503        actual
1504    }
1505
1506    #[test]
1507    fn test_new_virtualized() {
1508        let virt: Virtualized<String> = Virtualized::new(100);
1509        assert_eq!(virt.len(), 0);
1510        assert!(virt.is_empty());
1511    }
1512
1513    #[test]
1514    fn test_push_and_len() {
1515        let mut virt: Virtualized<i32> = Virtualized::new(100);
1516        virt.push(1);
1517        virt.push(2);
1518        virt.push(3);
1519        assert_eq!(virt.len(), 3);
1520        assert!(!virt.is_empty());
1521    }
1522
1523    #[test]
1524    fn test_visible_range_fixed_height() {
1525        let mut virt: Virtualized<i32> = Virtualized::new(100).with_fixed_height(2);
1526        for i in 0..20 {
1527            virt.push(i);
1528        }
1529        // 10 items visible with height 2 in viewport 20
1530        let range = virt.visible_range(20);
1531        assert_eq!(range, 0..10);
1532    }
1533
1534    #[test]
1535    fn test_visible_range_variable_height_clamps() {
1536        let mut cache = HeightCache::new(1, 16);
1537        cache.set(0, 3);
1538        cache.set(1, 3);
1539        cache.set(2, 3);
1540        let mut virt: Virtualized<i32> =
1541            Virtualized::new(10).with_item_height(ItemHeight::Variable(cache));
1542        for i in 0..3 {
1543            virt.push(i);
1544        }
1545        let range = virt.visible_range(5);
1546        // Includes the partially visible second item.
1547        assert_eq!(range, 0..2);
1548    }
1549
1550    #[test]
1551    fn test_visible_range_variable_height_exact_fit() {
1552        let mut cache = HeightCache::new(1, 16);
1553        cache.set(0, 2);
1554        cache.set(1, 3);
1555        let mut virt: Virtualized<i32> =
1556            Virtualized::new(10).with_item_height(ItemHeight::Variable(cache));
1557        for i in 0..2 {
1558            virt.push(i);
1559        }
1560        let range = virt.visible_range(5);
1561        assert_eq!(range, 0..2);
1562    }
1563
1564    #[test]
1565    fn test_visible_range_with_scroll() {
1566        let mut virt: Virtualized<i32> = Virtualized::new(100).with_fixed_height(1);
1567        for i in 0..50 {
1568            virt.push(i);
1569        }
1570        virt.scroll(10);
1571        let range = virt.visible_range(10);
1572        assert_eq!(range, 10..20);
1573    }
1574
1575    #[test]
1576    fn test_visible_range_variable_height_excludes_partial() {
1577        let mut cache = HeightCache::new(1, 16);
1578        cache.set(0, 6);
1579        cache.set(1, 6);
1580        let mut virt: Virtualized<i32> =
1581            Virtualized::new(100).with_item_height(ItemHeight::Variable(cache));
1582        virt.push(1);
1583        virt.push(2);
1584        virt.push(3);
1585
1586        let range = virt.visible_range(10);
1587        // Includes the partially visible second item.
1588        assert_eq!(range, 0..2);
1589    }
1590
1591    #[test]
1592    fn test_visible_range_variable_height_exact_fit_larger() {
1593        let mut cache = HeightCache::new(1, 16);
1594        cache.set(0, 4);
1595        cache.set(1, 6);
1596        let mut virt: Virtualized<i32> =
1597            Virtualized::new(100).with_item_height(ItemHeight::Variable(cache));
1598        virt.push(1);
1599        virt.push(2);
1600        virt.push(3);
1601
1602        let range = virt.visible_range(10);
1603        assert_eq!(range, 0..2);
1604    }
1605
1606    #[test]
1607    fn test_visible_range_variable_height_default_for_unmeasured() {
1608        let cache = HeightCache::new(2, 16);
1609        let mut virt: Virtualized<i32> =
1610            Virtualized::new(10).with_item_height(ItemHeight::Variable(cache));
1611        for i in 0..3 {
1612            virt.push(i);
1613        }
1614
1615        // Default height = 2, viewport 5 fits 2 items (2 + 2) but not the third.
1616        let range = virt.visible_range(5);
1617        // Includes the partially visible third item.
1618        assert_eq!(range, 0..3);
1619    }
1620
1621    #[test]
1622    fn test_visible_range_variable_bottom_anchor_after_lazy_scroll_to_bottom() {
1623        let mut virt: Virtualized<i32> =
1624            Virtualized::new(100).with_item_height(ItemHeight::Variable(HeightCache::new(2, 64)));
1625        for i in 0..20 {
1626            virt.push(i);
1627        }
1628        // Viewport unknown (visible_count = 0): scroll_to_bottom stores the
1629        // lazy sentinel. The last screenful is 5 items of height 2.
1630        virt.scroll_to_bottom();
1631        assert_eq!(virt.visible_range(10), 15..20);
1632    }
1633
1634    #[test]
1635    fn test_visible_range_fenwick_bottom_anchor_after_lazy_scroll_to_bottom() {
1636        let mut virt: Virtualized<i32> = Virtualized::new(100).with_variable_heights_fenwick(2, 20);
1637        for i in 0..20 {
1638            virt.push(i);
1639        }
1640        // Regression: this used to return the empty range 20..20 because the
1641        // unclamped sentinel offset reached the tracker as start_idx == len.
1642        virt.scroll_to_bottom();
1643        assert_eq!(virt.visible_range(10), 15..20);
1644    }
1645
1646    #[test]
1647    fn test_visible_range_fenwick_bottom_anchor_counts_partial_top_item() {
1648        // Heights [3,2,5,1,4]: the last 5 rows are exactly items 3 (h=1) and
1649        // 4 (h=4); a 6-row viewport additionally clips into item 2.
1650        let tracker = VariableHeightsFenwick::from_heights(&[3, 2, 5, 1, 4], 1);
1651        let mut virt: Virtualized<i32> =
1652            Virtualized::new(10).with_item_height(ItemHeight::VariableFenwick(tracker));
1653        for i in 0..5 {
1654            virt.push(i);
1655        }
1656        virt.scroll_to_bottom();
1657        assert_eq!(virt.visible_range(5), 3..5);
1658        virt.scroll_to_bottom();
1659        assert_eq!(virt.visible_range(6), 2..5);
1660    }
1661
1662    #[test]
1663    fn test_visible_range_variable_near_end_clamps_like_fixed() {
1664        // Scrolling to the last item must not leave blank rows below it,
1665        // matching the Fixed arm's max_offset clamping.
1666        let mut virt: Virtualized<i32> =
1667            Virtualized::new(100).with_item_height(ItemHeight::Variable(HeightCache::new(2, 64)));
1668        for i in 0..20 {
1669            virt.push(i);
1670        }
1671        virt.scroll_to(18);
1672        assert_eq!(virt.visible_range(10), 15..20);
1673    }
1674
1675    #[test]
1676    fn test_render_range_with_overscan() {
1677        let mut virt: Virtualized<i32> =
1678            Virtualized::new(100).with_fixed_height(1).with_overscan(2);
1679        for i in 0..50 {
1680            virt.push(i);
1681        }
1682        virt.scroll(10);
1683        let range = virt.render_range(10);
1684        // Visible: 10..20, Overscan: 2
1685        // Render: 8..22
1686        assert_eq!(range, 8..22);
1687    }
1688
1689    #[test]
1690    fn test_scroll_bounds() {
1691        let mut virt: Virtualized<i32> = Virtualized::new(100);
1692        for i in 0..10 {
1693            virt.push(i);
1694        }
1695
1696        // Can't scroll negative
1697        virt.scroll(-100);
1698        assert_eq!(virt.scroll_offset(), 0);
1699
1700        // Can't scroll past end
1701        virt.scroll(100);
1702        assert_eq!(virt.scroll_offset(), 9);
1703    }
1704
1705    #[test]
1706    fn test_scroll_to() {
1707        let mut virt: Virtualized<i32> = Virtualized::new(100);
1708        for i in 0..20 {
1709            virt.push(i);
1710        }
1711
1712        virt.scroll_to(15);
1713        assert_eq!(virt.scroll_offset(), 15);
1714
1715        // Clamps to max
1716        virt.scroll_to(100);
1717        assert_eq!(virt.scroll_offset(), 19);
1718    }
1719
1720    #[test]
1721    fn test_follow_mode() {
1722        let mut virt: Virtualized<i32> = Virtualized::new(100).with_follow(true);
1723        virt.set_visible_count(5);
1724
1725        for i in 0..10 {
1726            virt.push(i);
1727        }
1728
1729        // Should be at bottom
1730        assert!(virt.is_at_bottom());
1731
1732        // Manual scroll disables follow
1733        virt.scroll(-5);
1734        assert!(!virt.follow_mode());
1735    }
1736
1737    #[test]
1738    fn test_scroll_to_start_and_end() {
1739        let mut virt: Virtualized<i32> = Virtualized::new(100);
1740        virt.set_visible_count(5);
1741        for i in 0..20 {
1742            virt.push(i);
1743        }
1744
1745        // scroll_to_start goes to top and disables follow
1746        virt.scroll_to(10);
1747        virt.set_follow(true);
1748        virt.scroll_to_start();
1749        assert_eq!(virt.scroll_offset(), 0);
1750        assert!(!virt.follow_mode());
1751
1752        // scroll_to_end goes to bottom and enables follow
1753        virt.scroll_to_end();
1754        assert!(virt.is_at_bottom());
1755        assert!(virt.follow_mode());
1756    }
1757
1758    #[test]
1759    fn test_virtualized_page_navigation() {
1760        let mut virt: Virtualized<i32> = Virtualized::new(100);
1761        virt.set_visible_count(5);
1762        for i in 0..30 {
1763            virt.push(i);
1764        }
1765
1766        virt.scroll_to(15);
1767        virt.page_up();
1768        // Page navigation keeps 1 row of context (visible_count - 1).
1769        assert_eq!(virt.scroll_offset(), 11);
1770
1771        virt.page_down();
1772        assert_eq!(virt.scroll_offset(), 15);
1773
1774        // Page up at start clamps to 0
1775        virt.scroll_to(2);
1776        virt.page_up();
1777        assert_eq!(virt.scroll_offset(), 0);
1778    }
1779
1780    #[test]
1781    fn test_height_cache() {
1782        let mut cache = HeightCache::new(1, 100);
1783
1784        // Default value
1785        assert_eq!(cache.get(0), 1);
1786        assert_eq!(cache.get(50), 1);
1787
1788        // Set value
1789        cache.set(5, 3);
1790        assert_eq!(cache.get(5), 3);
1791
1792        // Other indices still default
1793        assert_eq!(cache.get(4), 1);
1794        assert_eq!(cache.get(6), 1);
1795    }
1796
1797    #[test]
1798    fn test_height_cache_large_index_window() {
1799        let mut cache = HeightCache::new(1, 8);
1800        cache.set(10_000, 4);
1801        assert_eq!(cache.get(10_000), 4);
1802        assert_eq!(cache.get(0), 1);
1803        assert!(cache.cache.len() <= cache.capacity);
1804    }
1805
1806    #[test]
1807    fn test_clear() {
1808        let mut virt: Virtualized<i32> = Virtualized::new(100);
1809        for i in 0..10 {
1810            virt.push(i);
1811        }
1812        virt.scroll(5);
1813
1814        virt.clear();
1815        assert_eq!(virt.len(), 0);
1816        assert_eq!(virt.scroll_offset(), 0);
1817    }
1818
1819    #[test]
1820    fn test_get_item() {
1821        let mut virt: Virtualized<String> = Virtualized::new(100);
1822        virt.push("hello".to_string());
1823        virt.push("world".to_string());
1824
1825        assert_eq!(virt.get(0), Some(&"hello".to_string()));
1826        assert_eq!(virt.get(1), Some(&"world".to_string()));
1827        assert_eq!(virt.get(2), None);
1828    }
1829
1830    #[test]
1831    fn test_external_storage_len() {
1832        let mut virt: Virtualized<i32> = Virtualized::external(1000, 100);
1833        assert_eq!(virt.len(), 1000);
1834
1835        virt.set_external_len(2000);
1836        assert_eq!(virt.len(), 2000);
1837    }
1838
1839    #[test]
1840    fn test_momentum_scrolling() {
1841        let mut virt: Virtualized<i32> = Virtualized::new(100);
1842        for i in 0..50 {
1843            virt.push(i);
1844        }
1845
1846        virt.fling(10.0);
1847
1848        // Simulate tick
1849        virt.tick(Duration::from_millis(100));
1850
1851        // Should have scrolled
1852        assert!(virt.scroll_offset() > 0);
1853    }
1854
1855    // ========================================================================
1856    // VirtualizedListState tests
1857    // ========================================================================
1858
1859    #[test]
1860    fn test_virtualized_list_state_new() {
1861        let state = VirtualizedListState::new();
1862        assert_eq!(state.selected, None);
1863        assert_eq!(state.scroll_offset(), 0);
1864        assert_eq!(state.visible_count(), 0);
1865    }
1866
1867    #[test]
1868    fn test_virtualized_list_state_select_next() {
1869        let mut state = VirtualizedListState::new();
1870
1871        state.select_next(10);
1872        assert_eq!(state.selected, Some(0));
1873
1874        state.select_next(10);
1875        assert_eq!(state.selected, Some(1));
1876
1877        // At last item, stays there
1878        state.selected = Some(9);
1879        state.select_next(10);
1880        assert_eq!(state.selected, Some(9));
1881    }
1882
1883    #[test]
1884    fn test_virtualized_list_state_select_previous() {
1885        let mut state = VirtualizedListState::new();
1886        state.selected = Some(5);
1887
1888        state.select_previous(10);
1889        assert_eq!(state.selected, Some(4));
1890
1891        state.selected = Some(0);
1892        state.select_previous(10);
1893        assert_eq!(state.selected, Some(0));
1894    }
1895
1896    #[test]
1897    fn test_virtualized_list_state_scroll() {
1898        let mut state = VirtualizedListState::new();
1899
1900        state.scroll(5, 20);
1901        assert_eq!(state.scroll_offset(), 5);
1902
1903        state.scroll(-3, 20);
1904        assert_eq!(state.scroll_offset(), 2);
1905
1906        // Can't scroll negative
1907        state.scroll(-100, 20);
1908        assert_eq!(state.scroll_offset(), 0);
1909
1910        // Can't scroll past end
1911        state.scroll(100, 20);
1912        assert_eq!(state.scroll_offset(), 19);
1913    }
1914
1915    #[test]
1916    fn test_virtualized_list_state_follow_mode() {
1917        let mut state = VirtualizedListState::new().with_follow(true);
1918        assert!(state.follow_mode());
1919
1920        // Manual scroll disables follow
1921        state.scroll(5, 20);
1922        assert!(!state.follow_mode());
1923    }
1924
1925    #[test]
1926    fn test_render_item_string() {
1927        // Verify String implements RenderItem
1928        let s = String::from("hello");
1929        assert_eq!(s.height(), 1);
1930    }
1931
1932    #[test]
1933    fn test_page_up_down() {
1934        let mut virt: Virtualized<i32> = Virtualized::new(100);
1935        for i in 0..50 {
1936            virt.push(i);
1937        }
1938        virt.set_visible_count(10);
1939
1940        // Start at top
1941        assert_eq!(virt.scroll_offset(), 0);
1942
1943        // Page down
1944        virt.page_down();
1945        assert_eq!(virt.scroll_offset(), 9);
1946
1947        // Page down again
1948        virt.page_down();
1949        assert_eq!(virt.scroll_offset(), 18);
1950
1951        // Page up
1952        virt.page_up();
1953        assert_eq!(virt.scroll_offset(), 9);
1954
1955        // Page up again
1956        virt.page_up();
1957        assert_eq!(virt.scroll_offset(), 0);
1958
1959        // Page up at top stays at 0
1960        virt.page_up();
1961        assert_eq!(virt.scroll_offset(), 0);
1962    }
1963
1964    // ========================================================================
1965    // Performance invariant tests (bd-uo6v)
1966    // ========================================================================
1967
1968    #[test]
1969    fn test_render_scales_with_visible_not_total() {
1970        use ftui_render::grapheme_pool::GraphemePool;
1971        use std::time::Instant;
1972
1973        // Setup: VirtualizedList with 1K items
1974        let small_items: Vec<String> = (0..1_000).map(|i| format!("Line {}", i)).collect();
1975        let small_list = VirtualizedList::new(&small_items);
1976        let mut small_state = VirtualizedListState::new();
1977
1978        let area = Rect::new(0, 0, 80, 24);
1979        let mut pool = GraphemePool::new();
1980        let mut frame = Frame::new(80, 24, &mut pool);
1981
1982        // Warm up
1983        small_list.render(area, &mut frame, &mut small_state);
1984
1985        let start = Instant::now();
1986        for _ in 0..100 {
1987            frame.buffer.clear();
1988            small_list.render(area, &mut frame, &mut small_state);
1989        }
1990        let small_time = start.elapsed();
1991
1992        // Setup: VirtualizedList with 100K items
1993        let large_items: Vec<String> = (0..100_000).map(|i| format!("Line {}", i)).collect();
1994        let large_list = VirtualizedList::new(&large_items);
1995        let mut large_state = VirtualizedListState::new();
1996
1997        // Warm up
1998        large_list.render(area, &mut frame, &mut large_state);
1999
2000        let start = Instant::now();
2001        for _ in 0..100 {
2002            frame.buffer.clear();
2003            large_list.render(area, &mut frame, &mut large_state);
2004        }
2005        let large_time = start.elapsed();
2006
2007        // 100K should be within 3x of 1K (both render ~24 items)
2008        assert!(
2009            large_time < small_time * 3,
2010            "Render does not scale O(visible): 1K={:?}, 100K={:?}",
2011            small_time,
2012            large_time
2013        );
2014    }
2015
2016    #[test]
2017    fn test_scroll_is_constant_time() {
2018        use std::time::Instant;
2019
2020        let mut small: Virtualized<i32> = Virtualized::new(1_000);
2021        for i in 0..1_000 {
2022            small.push(i);
2023        }
2024        small.set_visible_count(24);
2025
2026        let mut large: Virtualized<i32> = Virtualized::new(100_000);
2027        for i in 0..100_000 {
2028            large.push(i);
2029        }
2030        large.set_visible_count(24);
2031
2032        let iterations = 10_000;
2033
2034        // Warm up both paths so the timed runs are not skewed by first-touch
2035        // page faults / branch predictor / cache warming.
2036        for _ in 0..iterations {
2037            small.scroll(1);
2038            small.scroll(-1);
2039            large.scroll(1);
2040            large.scroll(-1);
2041        }
2042
2043        // Take the best (minimum) of several timed runs for each list. The
2044        // minimum is the measurement least contaminated by scheduling jitter,
2045        // GC of other processes, and CI load — exactly the noise that made the
2046        // old single-shot comparison flaky.
2047        let measure = |v: &mut Virtualized<i32>| -> std::time::Duration {
2048            let runs = 5;
2049            let mut best = std::time::Duration::MAX;
2050            for _ in 0..runs {
2051                let start = Instant::now();
2052                for _ in 0..iterations {
2053                    v.scroll(1);
2054                    v.scroll(-1);
2055                }
2056                best = best.min(start.elapsed());
2057            }
2058            best
2059        };
2060
2061        let small_time = measure(&mut small);
2062        let large_time = measure(&mut large);
2063
2064        // The real signal we care about is "scroll cost does NOT grow with list
2065        // size" (i.e. it is O(1), not O(n)). With n differing by 100x, a truly
2066        // O(n) scroll would make `large_time` ~100x `small_time`. A generous
2067        // constant-factor ceiling distinguishes O(1) from O(n) without flaking
2068        // on scheduling jitter, so we allow a wide multiplier here.
2069        let ceiling = small_time
2070            .checked_mul(10)
2071            .unwrap_or(std::time::Duration::MAX);
2072        assert!(
2073            large_time < ceiling,
2074            "Scroll is not O(1) (grows with list size): 1K={:?}, 100K={:?}",
2075            small_time,
2076            large_time
2077        );
2078    }
2079
2080    #[test]
2081    fn render_partially_offscreen_top_skips_item() {
2082        use ftui_render::grapheme_pool::GraphemePool;
2083
2084        // Items with height 2, each rendering its index as a character
2085        struct IndexedItem(usize);
2086        impl RenderItem for IndexedItem {
2087            fn render(&self, area: Rect, frame: &mut Frame, _selected: bool, _skip_rows: u16) {
2088                let ch = char::from_digit(self.0 as u32, 10).unwrap();
2089                for y in area.y..area.bottom() {
2090                    frame.buffer.set(area.x, y, Cell::from_char(ch));
2091                }
2092            }
2093            fn height(&self) -> u16 {
2094                2
2095            }
2096        }
2097
2098        // Need 4+ items so scroll_offset=1 is valid:
2099        // items_per_viewport = 5/2 = 2, max_offset = 4-2 = 2
2100        let items = vec![
2101            IndexedItem(0),
2102            IndexedItem(1),
2103            IndexedItem(2),
2104            IndexedItem(3),
2105        ];
2106        let list = VirtualizedList::new(&items).fixed_height(2);
2107
2108        // Scroll so item 1 is at top, item 0 is in overscan (above viewport)
2109        let mut state = VirtualizedListState::new().with_overscan(1);
2110        state.scroll_offset = 1; // Item 1 is top visible. Item 0 is in overscan.
2111
2112        let mut pool = GraphemePool::new();
2113        let mut frame = Frame::new(10, 5, &mut pool);
2114
2115        // Render at y=0 (terminal top edge)
2116        list.render(Rect::new(0, 0, 10, 5), &mut frame, &mut state);
2117
2118        // With scroll_offset=1 and overscan=1:
2119        // - render_start = 1 - 1 = 0 (include item 0 in overscan)
2120        // - Item 0 would render at y_offset = (0-1)*2 = -2
2121        // - area.y + y_offset = 0 + (-2) = -2 < 0, so item 0 must be SKIPPED
2122        // - Item 1 renders at y_offset = (1-1)*2 = 0
2123        //
2124        // Row 0 should be '1' (from Item 1), NOT '0' (from Item 0 ghosting)
2125        let cell = frame.buffer.get(0, 0).unwrap();
2126        assert_eq!(cell.content.as_char(), Some('1'));
2127    }
2128
2129    #[test]
2130    fn render_bottom_boundary_clips_partial_item() {
2131        use ftui_render::grapheme_pool::GraphemePool;
2132
2133        struct IndexedItem(u16);
2134        impl RenderItem for IndexedItem {
2135            fn render(&self, area: Rect, frame: &mut Frame, _selected: bool, _skip_rows: u16) {
2136                let ch = char::from_digit(self.0 as u32, 10).unwrap();
2137                for y in area.y..area.bottom() {
2138                    frame.buffer.set(area.x, y, Cell::from_char(ch));
2139                }
2140            }
2141            fn height(&self) -> u16 {
2142                2
2143            }
2144        }
2145
2146        let items = vec![IndexedItem(0), IndexedItem(1), IndexedItem(2)];
2147        let list = VirtualizedList::new(&items)
2148            .fixed_height(2)
2149            .show_scrollbar(false);
2150        let mut state = VirtualizedListState::new();
2151
2152        let mut pool = GraphemePool::new();
2153        let mut frame = Frame::new(4, 4, &mut pool);
2154
2155        // Viewport height 3 means the second item is only partially visible.
2156        list.render(Rect::new(0, 0, 4, 3), &mut frame, &mut state);
2157
2158        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('0'));
2159        assert_eq!(frame.buffer.get(0, 1).unwrap().content.as_char(), Some('0'));
2160        assert_eq!(frame.buffer.get(0, 2).unwrap().content.as_char(), Some('1'));
2161        // Row outside the viewport should remain empty.
2162        assert_eq!(frame.buffer.get(0, 3).unwrap().content.as_char(), None);
2163    }
2164
2165    #[test]
2166    fn render_after_fling_advances_visible_rows() {
2167        use ftui_render::grapheme_pool::GraphemePool;
2168
2169        struct IndexedItem(u16);
2170        impl RenderItem for IndexedItem {
2171            fn render(&self, area: Rect, frame: &mut Frame, _selected: bool, _skip_rows: u16) {
2172                let ch = char::from_digit(self.0 as u32, 10).unwrap();
2173                for y in area.y..area.bottom() {
2174                    frame.buffer.set(area.x, y, Cell::from_char(ch));
2175                }
2176            }
2177        }
2178
2179        let items: Vec<IndexedItem> = (0..10).map(IndexedItem).collect();
2180        let list = VirtualizedList::new(&items)
2181            .fixed_height(1)
2182            .show_scrollbar(false);
2183        let mut state = VirtualizedListState::new();
2184
2185        let mut pool = GraphemePool::new();
2186        let mut frame = Frame::new(4, 3, &mut pool);
2187        let area = Rect::new(0, 0, 4, 3);
2188
2189        // Initial render establishes visible_count and baseline top row.
2190        list.render(area, &mut frame, &mut state);
2191        assert_eq!(state.scroll_offset(), 0);
2192        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('0'));
2193
2194        // Momentum scroll: 40.0 * 0.1s = 4 rows.
2195        state.fling(40.0);
2196        state.tick(Duration::from_millis(100), items.len());
2197        assert_eq!(state.scroll_offset(), 4);
2198
2199        frame.buffer.clear();
2200        list.render(area, &mut frame, &mut state);
2201        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('4'));
2202    }
2203
2204    #[test]
2205    fn render_empty_virtualized_list_clears_stale_viewport() {
2206        use ftui_render::grapheme_pool::GraphemePool;
2207
2208        let items: Vec<String> = Vec::new();
2209        let list = VirtualizedList::new(&items).show_scrollbar(false);
2210        let mut state = VirtualizedListState::new();
2211        let mut pool = GraphemePool::new();
2212        let mut frame = Frame::new(6, 3, &mut pool);
2213        let area = Rect::new(0, 0, 6, 3);
2214        frame.buffer.fill(area, Cell::from_char('X'));
2215
2216        list.render(area, &mut frame, &mut state);
2217
2218        assert_eq!(raw_row_text(&frame, 0), "      ");
2219        assert_eq!(raw_row_text(&frame, 1), "      ");
2220        assert_eq!(raw_row_text(&frame, 2), "      ");
2221    }
2222
2223    #[test]
2224    fn render_shorter_virtualized_row_clears_stale_suffix() {
2225        use ftui_render::grapheme_pool::GraphemePool;
2226
2227        let long_items = vec!["Hello".to_string()];
2228        let short_items = vec!["Hi".to_string()];
2229        let area = Rect::new(0, 0, 6, 1);
2230        let mut state = VirtualizedListState::new();
2231        let mut pool = GraphemePool::new();
2232        let mut frame = Frame::new(6, 1, &mut pool);
2233
2234        VirtualizedList::new(&long_items)
2235            .show_scrollbar(false)
2236            .render(area, &mut frame, &mut state);
2237        VirtualizedList::new(&short_items)
2238            .show_scrollbar(false)
2239            .render(area, &mut frame, &mut state);
2240
2241        assert_eq!(raw_row_text(&frame, 0), "Hi    ");
2242    }
2243
2244    #[test]
2245    fn test_memory_bounded_by_ring_capacity() {
2246        use crate::log_ring::LogRing;
2247
2248        let mut ring: LogRing<String> = LogRing::new(1_000);
2249
2250        // Add 100K items
2251        for i in 0..100_000 {
2252            ring.push(format!("Line {}", i));
2253        }
2254
2255        // Only 1K in memory
2256        assert_eq!(ring.len(), 1_000);
2257        assert_eq!(ring.total_count(), 100_000);
2258        assert_eq!(ring.first_index(), 99_000);
2259
2260        // Can still access recent items
2261        assert!(ring.get(99_999).is_some());
2262        assert!(ring.get(99_000).is_some());
2263        // Old items evicted
2264        assert!(ring.get(0).is_none());
2265        assert!(ring.get(98_999).is_none());
2266    }
2267
2268    #[test]
2269    fn test_visible_range_constant_regardless_of_total() {
2270        let mut small: Virtualized<i32> = Virtualized::new(100);
2271        for i in 0..100 {
2272            small.push(i);
2273        }
2274        let small_range = small.visible_range(24);
2275
2276        let mut large: Virtualized<i32> = Virtualized::new(100_000);
2277        for i in 0..100_000 {
2278            large.push(i);
2279        }
2280        let large_range = large.visible_range(24);
2281
2282        // Both should return exactly 24 visible items
2283        assert_eq!(small_range.end - small_range.start, 24);
2284        assert_eq!(large_range.end - large_range.start, 24);
2285    }
2286
2287    #[test]
2288    fn test_virtualized_list_state_page_up_down() {
2289        let mut state = VirtualizedListState::new();
2290        state.visible_count = 10;
2291
2292        // Page down
2293        state.page_down(50);
2294        assert_eq!(state.scroll_offset(), 9);
2295
2296        // Page down again
2297        state.page_down(50);
2298        assert_eq!(state.scroll_offset(), 18);
2299
2300        // Page up
2301        state.page_up(50);
2302        assert_eq!(state.scroll_offset(), 9);
2303
2304        // Page up again
2305        state.page_up(50);
2306        assert_eq!(state.scroll_offset(), 0);
2307    }
2308
2309    // ========================================================================
2310    // VariableHeightsFenwick tests (bd-2zbk.7)
2311    // ========================================================================
2312
2313    #[test]
2314    fn test_variable_heights_fenwick_new() {
2315        let tracker = VariableHeightsFenwick::new(2, 10);
2316        assert_eq!(tracker.len(), 10);
2317        assert!(!tracker.is_empty());
2318        assert_eq!(tracker.default_height(), 2);
2319    }
2320
2321    #[test]
2322    fn test_variable_heights_fenwick_empty() {
2323        let tracker = VariableHeightsFenwick::new(1, 0);
2324        assert!(tracker.is_empty());
2325        assert_eq!(tracker.total_height(), 0);
2326    }
2327
2328    #[test]
2329    fn test_variable_heights_fenwick_from_heights() {
2330        let heights = vec![3, 2, 5, 1, 4];
2331        let tracker = VariableHeightsFenwick::from_heights(&heights, 1);
2332
2333        assert_eq!(tracker.len(), 5);
2334        assert_eq!(tracker.get(0), 3);
2335        assert_eq!(tracker.get(1), 2);
2336        assert_eq!(tracker.get(2), 5);
2337        assert_eq!(tracker.get(3), 1);
2338        assert_eq!(tracker.get(4), 4);
2339        assert_eq!(tracker.total_height(), 15);
2340    }
2341
2342    #[test]
2343    fn test_variable_heights_fenwick_offset_of_item() {
2344        // Heights: [3, 2, 5, 1, 4] -> offsets: [0, 3, 5, 10, 11]
2345        let heights = vec![3, 2, 5, 1, 4];
2346        let tracker = VariableHeightsFenwick::from_heights(&heights, 1);
2347
2348        assert_eq!(tracker.offset_of_item(0), 0);
2349        assert_eq!(tracker.offset_of_item(1), 3);
2350        assert_eq!(tracker.offset_of_item(2), 5);
2351        assert_eq!(tracker.offset_of_item(3), 10);
2352        assert_eq!(tracker.offset_of_item(4), 11);
2353        assert_eq!(tracker.offset_of_item(5), 15); // beyond end
2354    }
2355
2356    #[test]
2357    fn test_variable_heights_fenwick_find_item_at_offset() {
2358        // Heights: [3, 2, 5, 1, 4] -> cumulative: [3, 5, 10, 11, 15]
2359        let heights = vec![3, 2, 5, 1, 4];
2360        let tracker = VariableHeightsFenwick::from_heights(&heights, 1);
2361
2362        // Offset 0 should be item 0
2363        assert_eq!(tracker.find_item_at_offset(0), 0);
2364        // Offset 1 should be item 0 (within first item)
2365        assert_eq!(tracker.find_item_at_offset(1), 0);
2366        // Offset 3 should be item 1 (starts at offset 3)
2367        assert_eq!(tracker.find_item_at_offset(3), 1);
2368        // Offset 5 should be item 2
2369        assert_eq!(tracker.find_item_at_offset(5), 2);
2370        // Offset 10 should be item 3
2371        assert_eq!(tracker.find_item_at_offset(10), 3);
2372        // Offset 11 should be item 4
2373        assert_eq!(tracker.find_item_at_offset(11), 4);
2374        // Offset 15 should be end (beyond all items)
2375        assert_eq!(tracker.find_item_at_offset(15), 5);
2376    }
2377
2378    #[test]
2379    fn test_variable_heights_fenwick_visible_count() {
2380        // Heights: [3, 2, 5, 1, 4]
2381        let heights = vec![3, 2, 5, 1, 4];
2382        let tracker = VariableHeightsFenwick::from_heights(&heights, 1);
2383
2384        // Viewport 5: items 0 (h=3) + 1 (h=2) = 5 exactly
2385        assert_eq!(tracker.visible_count(0, 5), 2);
2386
2387        // Viewport 4: item 0 fits and item 1 is partially visible.
2388        assert_eq!(tracker.visible_count(0, 4), 2);
2389
2390        // Viewport 10: items 0+1+2 = 10 exactly
2391        assert_eq!(tracker.visible_count(0, 10), 3);
2392
2393        // From item 2, viewport 6: item 2 (h=5) + item 3 (h=1) = 6
2394        assert_eq!(tracker.visible_count(2, 6), 2);
2395    }
2396
2397    #[test]
2398    fn test_variable_heights_fenwick_visible_count_viewport_beyond_total_height() {
2399        let heights = vec![1, 1, 1];
2400        let tracker = VariableHeightsFenwick::from_heights(&heights, 1);
2401
2402        // Viewport extends past the end: must never overcount.
2403        assert_eq!(tracker.visible_count(0, 10), 3);
2404        assert_eq!(tracker.visible_count(1, 10), 2);
2405        assert_eq!(tracker.visible_count(2, 10), 1);
2406    }
2407
2408    #[test]
2409    fn test_variable_heights_fenwick_set() {
2410        let mut tracker = VariableHeightsFenwick::new(1, 5);
2411
2412        // All items should start with default height
2413        assert_eq!(tracker.get(0), 1);
2414        assert_eq!(tracker.total_height(), 5);
2415
2416        // Set item 2 to height 10
2417        tracker.set(2, 10);
2418        assert_eq!(tracker.get(2), 10);
2419        assert_eq!(tracker.total_height(), 14); // 1+1+10+1+1
2420    }
2421
2422    #[test]
2423    fn test_variable_heights_fenwick_resize() {
2424        let mut tracker = VariableHeightsFenwick::new(2, 3);
2425        assert_eq!(tracker.len(), 3);
2426        assert_eq!(tracker.total_height(), 6);
2427
2428        // Grow
2429        tracker.resize(5);
2430        assert_eq!(tracker.len(), 5);
2431        assert_eq!(tracker.total_height(), 10);
2432        assert_eq!(tracker.get(4), 2);
2433
2434        // Shrink
2435        tracker.resize(2);
2436        assert_eq!(tracker.len(), 2);
2437        assert_eq!(tracker.total_height(), 4);
2438    }
2439
2440    #[test]
2441    fn test_variable_heights_fenwick_point_update_and_range_query() {
2442        fn range_sum(tracker: &VariableHeightsFenwick, left: usize, right: usize) -> u32 {
2443            tracker
2444                .offset_of_item(right.saturating_add(1))
2445                .saturating_sub(tracker.offset_of_item(left))
2446        }
2447
2448        let mut tracker = VariableHeightsFenwick::from_heights(&[2, 4, 1, 3, 5, 2], 1);
2449        let mut naive = [2_u32, 4, 1, 3, 5, 2];
2450
2451        tracker.set(2, 7);
2452        naive[2] = 7;
2453        tracker.set(5, 1);
2454        naive[5] = 1;
2455        tracker.set(0, 6);
2456        naive[0] = 6;
2457
2458        let mut running = 0u32;
2459        for (i, value) in naive.iter().enumerate() {
2460            running = running.saturating_add(*value);
2461            assert_eq!(tracker.offset_of_item(i + 1), running);
2462        }
2463
2464        let naive_sum = |left: usize, right: usize| -> u32 { naive[left..=right].iter().sum() };
2465        assert_eq!(range_sum(&tracker, 0, 0), naive_sum(0, 0));
2466        assert_eq!(range_sum(&tracker, 1, 3), naive_sum(1, 3));
2467        assert_eq!(range_sum(&tracker, 2, 5), naive_sum(2, 5));
2468    }
2469
2470    proptest! {
2471        #![proptest_config(ProptestConfig::with_cases(96))]
2472
2473        #[test]
2474        fn property_variable_heights_fenwick_prefix_sums_match_naive(
2475            heights in proptest::collection::vec(1u16..=32u16, 1..160)
2476        ) {
2477            let tracker = VariableHeightsFenwick::from_heights(&heights, 1);
2478
2479            let mut naive_prefix = 0u32;
2480            prop_assert_eq!(tracker.offset_of_item(0), 0);
2481            for (i, height) in heights.iter().enumerate() {
2482                naive_prefix = naive_prefix.saturating_add(u32::from(*height));
2483                prop_assert_eq!(
2484                    tracker.offset_of_item(i + 1),
2485                    naive_prefix,
2486                    "prefix mismatch at index {} for heights {:?}",
2487                    i,
2488                    heights
2489                );
2490            }
2491        }
2492
2493        #[test]
2494        fn property_variable_heights_fenwick_visible_count_matches_naive(
2495            heights in proptest::collection::vec(1u16..=24u16, 1..128),
2496            start_idx in 0usize..192usize,
2497            viewport_height in 1u16..=120u16
2498        ) {
2499            fn naive_visible_count(heights: &[u16], start_idx: usize, viewport_height: u16) -> usize {
2500                if heights.is_empty() || viewport_height == 0 {
2501                    return 0;
2502                }
2503                let start = start_idx.min(heights.len());
2504                if start >= heights.len() {
2505                    return 0;
2506                }
2507
2508                let start_offset: u32 = heights[..start].iter().map(|&h| u32::from(h)).sum();
2509                let end_offset = start_offset.saturating_add(u32::from(viewport_height));
2510                let mut count = 0usize;
2511                let mut cursor = start_offset;
2512                for &height in &heights[start..] {
2513                    if cursor >= end_offset {
2514                        break;
2515                    }
2516                    count = count.saturating_add(1);
2517                    cursor = cursor.saturating_add(u32::from(height));
2518                }
2519
2520                if count == 0 { 1 } else { count }
2521            }
2522
2523            let tracker = VariableHeightsFenwick::from_heights(&heights, 1);
2524            let expected = naive_visible_count(&heights, start_idx, viewport_height);
2525            let actual = tracker.visible_count(start_idx, viewport_height);
2526            prop_assert_eq!(
2527                actual,
2528                expected,
2529                "visible_count mismatch for start={} viewport={} heights={:?}",
2530                start_idx,
2531                viewport_height,
2532                heights
2533            );
2534        }
2535    }
2536
2537    #[test]
2538    fn test_virtualized_with_variable_heights_fenwick() {
2539        let mut virt: Virtualized<i32> = Virtualized::new(100).with_variable_heights_fenwick(2, 10);
2540
2541        for i in 0..10 {
2542            virt.push(i);
2543        }
2544
2545        // All items height 2, viewport 6 -> 3 items visible
2546        let range = virt.visible_range(6);
2547        assert_eq!(range.end - range.start, 3);
2548    }
2549
2550    #[test]
2551    fn test_variable_heights_fenwick_performance() {
2552        use std::time::Instant;
2553
2554        // Create large tracker
2555        let n = 100_000;
2556        let heights: Vec<u16> = (0..n).map(|i| (i % 10 + 1) as u16).collect();
2557        let tracker = VariableHeightsFenwick::from_heights(&heights, 1);
2558
2559        // Warm up
2560        let _ = tracker.find_item_at_offset(500_000);
2561        let _ = tracker.offset_of_item(50_000);
2562
2563        // Benchmark find_item_at_offset (O(log n))
2564        let start = Instant::now();
2565        let mut _sink = 0usize;
2566        for i in 0..10_000 {
2567            _sink = _sink.wrapping_add(tracker.find_item_at_offset((i * 50) as u32));
2568        }
2569        let find_time = start.elapsed();
2570
2571        // Benchmark offset_of_item (O(log n))
2572        let start = Instant::now();
2573        let mut _sink2 = 0u32;
2574        for i in 0..10_000 {
2575            _sink2 = _sink2.wrapping_add(tracker.offset_of_item((i * 10) % n));
2576        }
2577        let offset_time = start.elapsed();
2578
2579        eprintln!("=== VariableHeightsFenwick Performance (n={n}) ===");
2580        eprintln!("10k find_item_at_offset: {:?}", find_time);
2581        eprintln!("10k offset_of_item:      {:?}", offset_time);
2582
2583        // Both should be under 50ms for 10k operations
2584        assert!(
2585            find_time < std::time::Duration::from_millis(50),
2586            "find_item_at_offset too slow: {:?}",
2587            find_time
2588        );
2589        assert!(
2590            offset_time < std::time::Duration::from_millis(50),
2591            "offset_of_item too slow: {:?}",
2592            offset_time
2593        );
2594    }
2595
2596    #[test]
2597    fn test_variable_heights_fenwick_scales_logarithmically() {
2598        use std::time::Instant;
2599
2600        // Small dataset
2601        let small_n = 1_000;
2602        let small_heights: Vec<u16> = (0..small_n).map(|i| (i % 5 + 1) as u16).collect();
2603        let small_tracker = VariableHeightsFenwick::from_heights(&small_heights, 1);
2604
2605        // Large dataset
2606        let large_n = 100_000;
2607        let large_heights: Vec<u16> = (0..large_n).map(|i| (i % 5 + 1) as u16).collect();
2608        let large_tracker = VariableHeightsFenwick::from_heights(&large_heights, 1);
2609
2610        let iterations = 5_000;
2611
2612        // Time small
2613        let start = Instant::now();
2614        for i in 0..iterations {
2615            let _ = small_tracker.find_item_at_offset((i * 2) as u32);
2616        }
2617        let small_time = start.elapsed();
2618
2619        // Time large
2620        let start = Instant::now();
2621        for i in 0..iterations {
2622            let _ = large_tracker.find_item_at_offset((i * 200) as u32);
2623        }
2624        let large_time = start.elapsed();
2625
2626        // Large should be within 10x of small (O(log n) vs O(n) would be 100x).
2627        // Use a generous bound to avoid flakiness on loaded CI workers.
2628        assert!(
2629            large_time < small_time * 10,
2630            "Not O(log n): small={:?}, large={:?}",
2631            small_time,
2632            large_time
2633        );
2634    }
2635
2636    // ========================================================================
2637    // Edge-case tests (bd-2f15w)
2638    // ========================================================================
2639
2640    // ── Virtualized: construction & empty state ─────────────────────────
2641
2642    #[test]
2643    fn new_zero_capacity() {
2644        let virt: Virtualized<i32> = Virtualized::new(0);
2645        assert_eq!(virt.len(), 0);
2646        assert!(virt.is_empty());
2647        assert_eq!(virt.scroll_offset(), 0);
2648        assert_eq!(virt.visible_count(), 0);
2649        assert!(!virt.follow_mode());
2650    }
2651
2652    #[test]
2653    fn external_zero_len_zero_cache() {
2654        let virt: Virtualized<i32> = Virtualized::external(0, 0);
2655        assert_eq!(virt.len(), 0);
2656        assert!(virt.is_empty());
2657    }
2658
2659    #[test]
2660    fn external_storage_returns_none_for_get() {
2661        let virt: Virtualized<i32> = Virtualized::external(100, 10);
2662        assert_eq!(virt.get(0), None);
2663        assert_eq!(virt.get(50), None);
2664    }
2665
2666    #[test]
2667    fn external_storage_returns_none_for_get_mut() {
2668        let mut virt: Virtualized<i32> = Virtualized::external(100, 10);
2669        assert!(virt.get_mut(0).is_none());
2670    }
2671
2672    #[test]
2673    fn push_on_external_is_noop() {
2674        let mut virt: Virtualized<i32> = Virtualized::external(5, 10);
2675        virt.push(42);
2676        // Length unchanged because push only works on Owned
2677        assert_eq!(virt.len(), 5);
2678    }
2679
2680    #[test]
2681    fn iter_on_external_is_empty() {
2682        let virt: Virtualized<i32> = Virtualized::external(100, 10);
2683        assert_eq!(virt.iter().count(), 0);
2684    }
2685
2686    #[test]
2687    fn set_external_len_on_owned_is_noop() {
2688        let mut virt: Virtualized<i32> = Virtualized::new(100);
2689        virt.push(1);
2690        virt.set_external_len(999);
2691        assert_eq!(virt.len(), 1); // unchanged
2692    }
2693
2694    // ── Virtualized: visible_range edge cases ───────────────────────────
2695
2696    #[test]
2697    fn visible_range_zero_viewport() {
2698        let mut virt: Virtualized<i32> = Virtualized::new(100);
2699        virt.push(1);
2700        let range = virt.visible_range(0);
2701        assert_eq!(range, 0..0);
2702        assert_eq!(virt.visible_count(), 0);
2703    }
2704
2705    #[test]
2706    fn visible_range_empty_container() {
2707        let virt: Virtualized<i32> = Virtualized::new(100);
2708        let range = virt.visible_range(24);
2709        assert_eq!(range, 0..0);
2710    }
2711
2712    #[test]
2713    fn visible_range_fixed_height_zero() {
2714        // Fixed(0) should not divide by zero; falls through to viewport_height items
2715        let mut virt: Virtualized<i32> = Virtualized::new(100).with_fixed_height(0);
2716        for i in 0..10 {
2717            virt.push(i);
2718        }
2719        let range = virt.visible_range(5);
2720        // ItemHeight::Fixed(0) → viewport_height as usize = 5
2721        assert_eq!(range, 0..5);
2722    }
2723
2724    #[test]
2725    fn visible_range_fewer_items_than_viewport() {
2726        let mut virt: Virtualized<i32> = Virtualized::new(100);
2727        for i in 0..3 {
2728            virt.push(i);
2729        }
2730        let range = virt.visible_range(24);
2731        // Only 3 items, viewport fits 24
2732        assert_eq!(range, 0..3);
2733    }
2734
2735    #[test]
2736    fn visible_range_single_item() {
2737        let mut virt: Virtualized<i32> = Virtualized::new(100);
2738        virt.push(42);
2739        let range = virt.visible_range(1);
2740        assert_eq!(range, 0..1);
2741    }
2742
2743    // ── Virtualized: render_range edge cases ────────────────────────────
2744
2745    #[test]
2746    fn render_range_at_start_clamps_overscan() {
2747        let mut virt: Virtualized<i32> =
2748            Virtualized::new(100).with_fixed_height(1).with_overscan(5);
2749        for i in 0..20 {
2750            virt.push(i);
2751        }
2752        // At scroll_offset=0, start.saturating_sub(5) = 0
2753        let range = virt.render_range(10);
2754        assert_eq!(range.start, 0);
2755    }
2756
2757    #[test]
2758    fn render_range_at_end_clamps_overscan() {
2759        let mut virt: Virtualized<i32> =
2760            Virtualized::new(100).with_fixed_height(1).with_overscan(5);
2761        for i in 0..20 {
2762            virt.push(i);
2763        }
2764        virt.set_visible_count(10);
2765        virt.scroll_to(10); // offset=10, visible 10..20
2766        let range = virt.render_range(10);
2767        // end = min(20 + 5, 20) = 20
2768        assert_eq!(range.end, 20);
2769    }
2770
2771    #[test]
2772    fn render_range_zero_overscan() {
2773        let mut virt: Virtualized<i32> =
2774            Virtualized::new(100).with_fixed_height(1).with_overscan(0);
2775        for i in 0..20 {
2776            virt.push(i);
2777        }
2778        virt.set_visible_count(10);
2779        virt.scroll_to(5);
2780        let range = virt.render_range(10);
2781        // No overscan: render_range == visible_range
2782        let visible = virt.visible_range(10);
2783        assert_eq!(range, visible);
2784    }
2785
2786    // ── Virtualized: scroll edge cases ──────────────────────────────────
2787
2788    #[test]
2789    fn scroll_on_empty_is_noop() {
2790        let mut virt: Virtualized<i32> = Virtualized::new(100);
2791        virt.scroll(10);
2792        assert_eq!(virt.scroll_offset(), 0);
2793    }
2794
2795    #[test]
2796    fn scroll_delta_zero_does_not_disable_follow() {
2797        let mut virt: Virtualized<i32> = Virtualized::new(100).with_follow(true);
2798        virt.push(1);
2799        virt.scroll(0);
2800        // delta=0 doesn't disable follow_mode
2801        assert!(virt.follow_mode());
2802    }
2803
2804    #[test]
2805    fn scroll_negative_beyond_start() {
2806        let mut virt: Virtualized<i32> = Virtualized::new(100);
2807        for i in 0..10 {
2808            virt.push(i);
2809        }
2810        virt.scroll(-1);
2811        assert_eq!(virt.scroll_offset(), 0);
2812    }
2813
2814    #[test]
2815    fn scroll_to_on_empty() {
2816        let mut virt: Virtualized<i32> = Virtualized::new(100);
2817        // scroll_to on empty: idx.min(0.saturating_sub(1)) = idx.min(0) = 0
2818        virt.scroll_to(100);
2819        assert_eq!(virt.scroll_offset(), 0);
2820    }
2821
2822    #[test]
2823    fn scroll_to_top_already_at_top() {
2824        let mut virt: Virtualized<i32> = Virtualized::new(100);
2825        virt.push(1);
2826        virt.scroll_to_top();
2827        assert_eq!(virt.scroll_offset(), 0);
2828    }
2829
2830    #[test]
2831    fn scroll_to_bottom_fewer_items_than_visible() {
2832        let mut virt: Virtualized<i32> = Virtualized::new(100);
2833        virt.set_visible_count(10);
2834        for i in 0..3 {
2835            virt.push(i);
2836        }
2837        virt.scroll_to_bottom();
2838        // len (3) <= visible_count (10), so offset = 0
2839        assert_eq!(virt.scroll_offset(), 0);
2840    }
2841
2842    #[test]
2843    fn scroll_to_bottom_visible_count_zero() {
2844        let mut virt: Virtualized<i32> = Virtualized::new(100);
2845        for i in 0..20 {
2846            virt.push(i);
2847        }
2848        // visible_count=0 (default), scroll_to_bottom stores a sentinel internally.
2849        virt.scroll_to_bottom();
2850        // Internal field stores MAX sentinel…
2851        assert_eq!(virt.scroll_offset, usize::MAX);
2852        // …but public API clamps to last valid index.
2853        assert_eq!(virt.scroll_offset(), 19);
2854    }
2855
2856    // ── Virtualized: page navigation edge cases ─────────────────────────
2857
2858    #[test]
2859    fn page_up_visible_count_zero_is_noop() {
2860        let mut virt: Virtualized<i32> = Virtualized::new(100);
2861        for i in 0..20 {
2862            virt.push(i);
2863        }
2864        virt.scroll_to(10);
2865        // visible_count=0, page_up is no-op
2866        virt.page_up();
2867        assert_eq!(virt.scroll_offset(), 10);
2868    }
2869
2870    #[test]
2871    fn page_down_visible_count_zero_is_noop() {
2872        let mut virt: Virtualized<i32> = Virtualized::new(100);
2873        for i in 0..20 {
2874            virt.push(i);
2875        }
2876        // visible_count=0, page_down is no-op
2877        virt.page_down();
2878        assert_eq!(virt.scroll_offset(), 0);
2879    }
2880
2881    // ── Virtualized: is_at_bottom edge cases ────────────────────────────
2882
2883    #[test]
2884    fn is_at_bottom_fewer_items_than_visible() {
2885        let mut virt: Virtualized<i32> = Virtualized::new(100);
2886        virt.set_visible_count(10);
2887        for i in 0..3 {
2888            virt.push(i);
2889        }
2890        assert!(virt.is_at_bottom());
2891    }
2892
2893    #[test]
2894    fn is_at_bottom_empty() {
2895        let virt: Virtualized<i32> = Virtualized::new(100);
2896        // len=0 <= visible_count=0, so true
2897        assert!(virt.is_at_bottom());
2898    }
2899
2900    // ── Virtualized: trim_front edge cases ──────────────────────────────
2901
2902    #[test]
2903    fn trim_front_under_max_returns_zero() {
2904        let mut virt: Virtualized<i32> = Virtualized::new(100);
2905        for i in 0..5 {
2906            virt.push(i);
2907        }
2908        let removed = virt.trim_front(10);
2909        assert_eq!(removed, 0);
2910        assert_eq!(virt.len(), 5);
2911    }
2912
2913    #[test]
2914    fn trim_front_adjusts_scroll_offset() {
2915        let mut virt: Virtualized<i32> = Virtualized::new(100);
2916        for i in 0..20 {
2917            virt.push(i);
2918        }
2919        virt.scroll_to(10);
2920        let removed = virt.trim_front(15);
2921        assert_eq!(removed, 5);
2922        assert_eq!(virt.len(), 15);
2923        // scroll_offset adjusted: 10 - 5 = 5
2924        assert_eq!(virt.scroll_offset(), 5);
2925    }
2926
2927    #[test]
2928    fn trim_front_scroll_offset_saturates_to_zero() {
2929        let mut virt: Virtualized<i32> = Virtualized::new(100);
2930        for i in 0..20 {
2931            virt.push(i);
2932        }
2933        virt.scroll_to(2);
2934        let removed = virt.trim_front(10);
2935        assert_eq!(removed, 10);
2936        // scroll_offset 2 - 10 saturates to 0
2937        assert_eq!(virt.scroll_offset(), 0);
2938    }
2939
2940    #[test]
2941    fn trim_front_on_external_returns_zero() {
2942        let mut virt: Virtualized<i32> = Virtualized::external(100, 10);
2943        let removed = virt.trim_front(5);
2944        assert_eq!(removed, 0);
2945    }
2946
2947    #[test]
2948    fn scroll_to_bottom_sets_sentinel_for_lazy_clamping() {
2949        let mut virt: Virtualized<i32> = Virtualized::new(100);
2950        for i in 0..20 {
2951            virt.push(i);
2952        }
2953
2954        // Before rendering, visible_count is 0.
2955        // scroll_to_bottom should set MAX instead of 0.
2956        virt.scroll_to_bottom();
2957        assert_eq!(virt.scroll_offset, usize::MAX);
2958
2959        // Render (simulate by calling visible_range with height 10)
2960        // Should clamp start to 20 - 10 = 10.
2961        let range = virt.visible_range(10);
2962        assert_eq!(range, 10..20);
2963        assert_eq!(virt.visible_count(), 10);
2964    }
2965
2966    // ── Virtualized: clear edge cases ───────────────────────────────────
2967
2968    #[test]
2969    fn clear_on_external_resets_scroll() {
2970        let mut virt: Virtualized<i32> = Virtualized::external(100, 10);
2971        virt.scroll_to(50);
2972        virt.clear();
2973        assert_eq!(virt.scroll_offset(), 0);
2974        // External len unchanged since clear only clears Owned
2975        assert_eq!(virt.len(), 100);
2976    }
2977
2978    // ── Virtualized: momentum scrolling edge cases ──────────────────────
2979
2980    #[test]
2981    fn tick_zero_velocity_is_noop() {
2982        let mut virt: Virtualized<i32> = Virtualized::new(100);
2983        for i in 0..20 {
2984            virt.push(i);
2985        }
2986        virt.tick(Duration::from_millis(100));
2987        assert_eq!(virt.scroll_offset(), 0);
2988    }
2989
2990    #[test]
2991    fn tick_below_threshold_stops_momentum() {
2992        let mut virt: Virtualized<i32> = Virtualized::new(100);
2993        for i in 0..20 {
2994            virt.push(i);
2995        }
2996        virt.fling(0.05); // below 0.1 threshold
2997        virt.tick(Duration::from_millis(100));
2998        // velocity <= 0.1, so it's zeroed out
2999        assert_eq!(virt.scroll_offset(), 0);
3000    }
3001
3002    #[test]
3003    fn tick_zero_duration_no_scroll() {
3004        let mut virt: Virtualized<i32> = Virtualized::new(100);
3005        for i in 0..50 {
3006            virt.push(i);
3007        }
3008        virt.fling(100.0);
3009        virt.tick(Duration::ZERO);
3010        // delta = (100.0 * 0.0) as i32 = 0, no scroll
3011        assert_eq!(virt.scroll_offset(), 0);
3012    }
3013
3014    #[test]
3015    fn fling_negative_scrolls_up() {
3016        let mut virt: Virtualized<i32> = Virtualized::new(100);
3017        for i in 0..50 {
3018            virt.push(i);
3019        }
3020        virt.scroll(20);
3021        let before = virt.scroll_offset();
3022        virt.fling(-50.0);
3023        virt.tick(Duration::from_millis(100));
3024        assert!(virt.scroll_offset() < before);
3025    }
3026
3027    // ── Virtualized: follow mode edge cases ─────────────────────────────
3028
3029    #[test]
3030    fn follow_mode_auto_scrolls_on_push() {
3031        let mut virt: Virtualized<i32> = Virtualized::new(100).with_follow(true);
3032        virt.set_visible_count(5);
3033        for i in 0..20 {
3034            virt.push(i);
3035        }
3036        // With follow mode, should be at bottom
3037        assert!(virt.is_at_bottom());
3038        assert_eq!(virt.scroll_offset(), 15); // 20 - 5
3039    }
3040
3041    #[test]
3042    fn set_follow_false_does_not_scroll() {
3043        let mut virt: Virtualized<i32> = Virtualized::new(100);
3044        virt.set_visible_count(5);
3045        for i in 0..20 {
3046            virt.push(i);
3047        }
3048        virt.scroll_to(5);
3049        virt.set_follow(false);
3050        assert_eq!(virt.scroll_offset(), 5); // unchanged
3051    }
3052
3053    #[test]
3054    fn scroll_to_start_disables_follow() {
3055        let mut virt: Virtualized<i32> = Virtualized::new(100).with_follow(true);
3056        virt.set_visible_count(5);
3057        for i in 0..20 {
3058            virt.push(i);
3059        }
3060        virt.scroll_to_start();
3061        assert!(!virt.follow_mode());
3062        assert_eq!(virt.scroll_offset(), 0);
3063    }
3064
3065    #[test]
3066    fn scroll_to_end_enables_follow() {
3067        let mut virt: Virtualized<i32> = Virtualized::new(100);
3068        virt.set_visible_count(5);
3069        for i in 0..20 {
3070            virt.push(i);
3071        }
3072        assert!(!virt.follow_mode());
3073        virt.scroll_to_end();
3074        assert!(virt.follow_mode());
3075        assert!(virt.is_at_bottom());
3076    }
3077
3078    #[test]
3079    fn external_follow_mode_scrolls_on_set_external_len() {
3080        let mut virt: Virtualized<i32> = Virtualized::external(10, 100).with_follow(true);
3081        virt.set_visible_count(5);
3082        virt.set_external_len(20);
3083        assert_eq!(virt.len(), 20);
3084        assert!(virt.is_at_bottom());
3085    }
3086
3087    // ── Virtualized: builder chain ──────────────────────────────────────
3088
3089    #[test]
3090    fn builder_chain_all_options() {
3091        let virt: Virtualized<i32> = Virtualized::new(100)
3092            .with_fixed_height(3)
3093            .with_overscan(5)
3094            .with_follow(true);
3095        assert!(virt.follow_mode());
3096        // Verify visible_range uses height=3
3097        // (no items, so empty range regardless)
3098        let range = virt.visible_range(9);
3099        assert_eq!(range, 0..0);
3100    }
3101
3102    // ── HeightCache edge cases ──────────────────────────────────────────
3103
3104    #[test]
3105    fn height_cache_default() {
3106        let cache = HeightCache::default();
3107        assert_eq!(cache.get(0), 1); // default_height=1
3108        assert_eq!(cache.capacity, 1000);
3109    }
3110
3111    #[test]
3112    fn height_cache_get_before_base_offset() {
3113        let mut cache = HeightCache::new(5, 100);
3114        // Set something to push base_offset forward
3115        cache.set(200, 10); // This resets window since 200 > capacity
3116        // Index 0 < base_offset, returns default
3117        assert_eq!(cache.get(0), 5);
3118    }
3119
3120    #[test]
3121    fn height_cache_set_before_base_offset_ignored() {
3122        let mut cache = HeightCache::new(5, 100);
3123        cache.set(200, 10);
3124        let base = cache.base_offset;
3125        cache.set(0, 99); // before base_offset, should be ignored
3126        assert_eq!(cache.get(0), 5); // still default
3127        assert_eq!(cache.base_offset, base); // unchanged
3128    }
3129
3130    #[test]
3131    fn height_cache_capacity_zero_ignores_all_sets() {
3132        let mut cache = HeightCache::new(3, 0);
3133        cache.set(0, 10);
3134        cache.set(5, 20);
3135        // Everything returns default since capacity=0
3136        assert_eq!(cache.get(0), 3);
3137        assert_eq!(cache.get(5), 3);
3138    }
3139
3140    #[test]
3141    fn height_cache_clear_resets_base() {
3142        let mut cache = HeightCache::new(1, 100);
3143        cache.set(50, 10);
3144        cache.clear();
3145        assert_eq!(cache.base_offset, 0);
3146        assert_eq!(cache.get(50), 1); // back to default
3147    }
3148
3149    #[test]
3150    fn height_cache_eviction_trims_oldest() {
3151        let mut cache = HeightCache::new(1, 4);
3152        // Set indices 0..6 to fill and trigger eviction
3153        for i in 0..6 {
3154            cache.set(i, (i + 10) as u16);
3155        }
3156        // Cache capacity=4, so indices 0-1 should be evicted
3157        assert!(cache.cache.len() <= cache.capacity);
3158        // Recent indices should be accessible
3159        assert_eq!(cache.get(5), 15);
3160        assert_eq!(cache.get(4), 14);
3161        assert_eq!(cache.get(3), 13);
3162        assert_eq!(cache.get(2), 12);
3163        // Old indices return default
3164        assert_eq!(cache.get(1), 1);
3165        assert_eq!(cache.get(0), 1);
3166    }
3167
3168    // ── VariableHeightsFenwick edge cases ───────────────────────────────
3169
3170    #[test]
3171    fn fenwick_default_is_empty() {
3172        let tracker = VariableHeightsFenwick::default();
3173        assert!(tracker.is_empty());
3174        assert_eq!(tracker.len(), 0);
3175        assert_eq!(tracker.total_height(), 0);
3176        assert_eq!(tracker.default_height(), 1);
3177    }
3178
3179    #[test]
3180    fn fenwick_get_beyond_len_returns_default() {
3181        let tracker = VariableHeightsFenwick::new(3, 5);
3182        assert_eq!(tracker.get(5), 3); // beyond len
3183        assert_eq!(tracker.get(100), 3);
3184    }
3185
3186    #[test]
3187    fn fenwick_set_beyond_len_resizes() {
3188        let mut tracker = VariableHeightsFenwick::new(2, 3);
3189        assert_eq!(tracker.len(), 3);
3190        tracker.set(10, 7);
3191        assert!(tracker.len() > 10);
3192        assert_eq!(tracker.get(10), 7);
3193    }
3194
3195    #[test]
3196    fn fenwick_offset_of_item_zero_always_zero() {
3197        let tracker = VariableHeightsFenwick::new(5, 10);
3198        assert_eq!(tracker.offset_of_item(0), 0);
3199
3200        let empty = VariableHeightsFenwick::new(5, 0);
3201        assert_eq!(empty.offset_of_item(0), 0);
3202    }
3203
3204    #[test]
3205    fn fenwick_find_item_at_offset_empty() {
3206        let tracker = VariableHeightsFenwick::new(1, 0);
3207        assert_eq!(tracker.find_item_at_offset(0), 0);
3208        assert_eq!(tracker.find_item_at_offset(100), 0);
3209    }
3210
3211    #[test]
3212    fn fenwick_visible_count_zero_viewport() {
3213        let tracker = VariableHeightsFenwick::new(2, 10);
3214        assert_eq!(tracker.visible_count(0, 0), 0);
3215    }
3216
3217    #[test]
3218    fn fenwick_visible_count_start_beyond_len() {
3219        let tracker = VariableHeightsFenwick::new(2, 5);
3220        // start_idx clamped to len
3221        let count = tracker.visible_count(100, 10);
3222        // start=5 (clamped), offset=total, no items visible
3223        assert_eq!(count, 0);
3224    }
3225
3226    #[test]
3227    fn fenwick_clear_then_operations() {
3228        let mut tracker = VariableHeightsFenwick::new(3, 5);
3229        assert_eq!(tracker.total_height(), 15);
3230        tracker.clear();
3231        assert_eq!(tracker.len(), 0);
3232        assert_eq!(tracker.total_height(), 0);
3233        assert_eq!(tracker.find_item_at_offset(0), 0);
3234    }
3235
3236    #[test]
3237    fn fenwick_rebuild_replaces_data() {
3238        let mut tracker = VariableHeightsFenwick::new(1, 10);
3239        assert_eq!(tracker.total_height(), 10);
3240        tracker.rebuild(&[5, 3, 2]);
3241        assert_eq!(tracker.len(), 3);
3242        assert_eq!(tracker.total_height(), 10);
3243        assert_eq!(tracker.get(0), 5);
3244        assert_eq!(tracker.get(1), 3);
3245        assert_eq!(tracker.get(2), 2);
3246    }
3247
3248    #[test]
3249    fn fenwick_resize_same_size_is_noop() {
3250        let mut tracker = VariableHeightsFenwick::new(2, 5);
3251        tracker.set(2, 10);
3252        tracker.resize(5);
3253        // Item 2 still has custom height
3254        assert_eq!(tracker.get(2), 10);
3255        assert_eq!(tracker.len(), 5);
3256    }
3257
3258    // ── VirtualizedListState edge cases ─────────────────────────────────
3259
3260    #[test]
3261    fn list_state_default_matches_new() {
3262        let d = VirtualizedListState::default();
3263        let n = VirtualizedListState::new();
3264        assert_eq!(d.selected, n.selected);
3265        assert_eq!(d.scroll_offset(), n.scroll_offset());
3266        assert_eq!(d.visible_count(), n.visible_count());
3267        assert_eq!(d.follow_mode(), n.follow_mode());
3268    }
3269
3270    #[test]
3271    fn list_state_select_next_on_empty() {
3272        let mut state = VirtualizedListState::new();
3273        state.select_next(0);
3274        assert_eq!(state.selected, None);
3275    }
3276
3277    #[test]
3278    fn list_state_select_previous_on_empty() {
3279        let mut state = VirtualizedListState::new();
3280        state.select_previous(0);
3281        assert_eq!(state.selected, None);
3282    }
3283
3284    #[test]
3285    fn list_state_select_previous_from_none() {
3286        let mut state = VirtualizedListState::new();
3287        state.select_previous(10);
3288        assert_eq!(state.selected, Some(0));
3289    }
3290
3291    #[test]
3292    fn list_state_select_next_from_none() {
3293        let mut state = VirtualizedListState::new();
3294        state.select_next(10);
3295        assert_eq!(state.selected, Some(0));
3296    }
3297
3298    #[test]
3299    fn list_state_scroll_zero_items() {
3300        let mut state = VirtualizedListState::new();
3301        state.scroll(10, 0);
3302        assert_eq!(state.scroll_offset(), 0);
3303    }
3304
3305    #[test]
3306    fn list_state_scroll_to_clamps() {
3307        let mut state = VirtualizedListState::new();
3308        state.scroll_to(100, 10);
3309        assert_eq!(state.scroll_offset(), 9);
3310    }
3311
3312    #[test]
3313    fn list_state_scroll_to_bottom_zero_items() {
3314        let mut state = VirtualizedListState::new();
3315        state.scroll_to_bottom(0);
3316        assert_eq!(state.scroll_offset(), 0);
3317    }
3318
3319    #[test]
3320    fn list_state_is_at_bottom_zero_items() {
3321        let state = VirtualizedListState::new();
3322        assert!(state.is_at_bottom(0));
3323    }
3324
3325    #[test]
3326    fn list_state_page_up_visible_count_zero() {
3327        let mut state = VirtualizedListState::new();
3328        state.scroll_offset = 5;
3329        state.page_up(20);
3330        // visible_count=0, no-op
3331        assert_eq!(state.scroll_offset(), 5);
3332    }
3333
3334    #[test]
3335    fn list_state_page_down_visible_count_zero() {
3336        let mut state = VirtualizedListState::new();
3337        state.page_down(20);
3338        // visible_count=0, no-op
3339        assert_eq!(state.scroll_offset(), 0);
3340    }
3341
3342    #[test]
3343    fn list_state_set_follow_false_no_scroll() {
3344        let mut state = VirtualizedListState::new();
3345        state.scroll_offset = 5;
3346        state.set_follow(false, 20);
3347        assert_eq!(state.scroll_offset(), 5); // unchanged
3348        assert!(!state.follow_mode());
3349    }
3350
3351    #[test]
3352    fn list_state_persistence_id() {
3353        let state = VirtualizedListState::new().with_persistence_id("my-list");
3354        assert_eq!(state.persistence_id(), Some("my-list"));
3355    }
3356
3357    #[test]
3358    fn list_state_persistence_id_none() {
3359        let state = VirtualizedListState::new();
3360        assert_eq!(state.persistence_id(), None);
3361    }
3362
3363    #[test]
3364    fn list_state_momentum_tick_zero_items() {
3365        let mut state = VirtualizedListState::new();
3366        state.fling(50.0);
3367        state.tick(Duration::from_millis(100), 0);
3368        // total_items=0, scroll is no-op
3369        assert_eq!(state.scroll_offset(), 0);
3370    }
3371
3372    // ── VirtualizedListPersistState edge cases ──────────────────────────
3373
3374    #[test]
3375    fn persist_state_default() {
3376        let ps = VirtualizedListPersistState::default();
3377        assert_eq!(ps.selected, None);
3378        assert_eq!(ps.scroll_offset, 0);
3379        assert!(!ps.follow_mode);
3380    }
3381
3382    #[test]
3383    fn persist_state_eq() {
3384        let a = VirtualizedListPersistState {
3385            selected: Some(5),
3386            scroll_offset: 10,
3387            follow_mode: true,
3388        };
3389        let b = a.clone();
3390        assert_eq!(a, b);
3391    }
3392
3393    // ── Stateful trait impl edge cases ──────────────────────────────────
3394
3395    #[test]
3396    fn stateful_state_key_with_persistence_id() {
3397        use crate::stateful::Stateful;
3398        let state = VirtualizedListState::new().with_persistence_id("logs");
3399        let key = state.state_key();
3400        assert_eq!(key.widget_type, "VirtualizedList");
3401        assert_eq!(key.instance_id, "logs");
3402    }
3403
3404    #[test]
3405    fn stateful_state_key_default_instance() {
3406        use crate::stateful::Stateful;
3407        let state = VirtualizedListState::new();
3408        let key = state.state_key();
3409        assert_eq!(key.instance_id, "default");
3410    }
3411
3412    #[test]
3413    fn stateful_save_restore_roundtrip() {
3414        use crate::stateful::Stateful;
3415        let mut state = VirtualizedListState::new();
3416        state.selected = Some(7);
3417        state.scroll_offset = 15;
3418        state.follow_mode = true;
3419        state.scroll_velocity = 42.0; // transient — not persisted
3420
3421        let saved = state.save_state();
3422        assert_eq!(saved.selected, Some(7));
3423        assert_eq!(saved.scroll_offset, 15);
3424        assert!(saved.follow_mode);
3425
3426        let mut restored = VirtualizedListState::new();
3427        restored.scroll_velocity = 99.0;
3428        restored.restore_state(saved);
3429        assert_eq!(restored.selected, Some(7));
3430        assert_eq!(restored.scroll_offset, 15);
3431        assert!(restored.follow_mode);
3432        // velocity reset to 0 on restore
3433        assert_eq!(restored.scroll_velocity, 0.0);
3434    }
3435
3436    // ── VirtualizedList widget edge cases ───────────────────────────────
3437
3438    #[test]
3439    fn virtualized_list_builder() {
3440        let items: Vec<String> = vec!["a".into()];
3441        let list = VirtualizedList::new(&items)
3442            .style(Style::default())
3443            .highlight_style(Style::default())
3444            .show_scrollbar(false)
3445            .fixed_height(3);
3446        assert_eq!(list.fixed_height, 3);
3447        assert!(!list.show_scrollbar);
3448    }
3449
3450    // ── VirtualizedStorage Debug/Clone ───────────────────────────────────
3451
3452    #[test]
3453    fn virtualized_storage_debug() {
3454        let storage: VirtualizedStorage<i32> = VirtualizedStorage::Owned(VecDeque::new());
3455        let dbg = format!("{:?}", storage);
3456        assert!(dbg.contains("Owned"));
3457
3458        let ext: VirtualizedStorage<i32> = VirtualizedStorage::External {
3459            len: 100,
3460            cache_capacity: 10,
3461        };
3462        let dbg = format!("{:?}", ext);
3463        assert!(dbg.contains("External"));
3464    }
3465
3466    #[test]
3467    fn test_virtualized_list_handle_mouse_drag_smooth() {
3468        use crate::scrollbar::SCROLLBAR_PART_THUMB;
3469        use ftui_core::event::{MouseButton, MouseEvent, MouseEventKind};
3470        use ftui_render::frame::{HitId, HitRegion};
3471
3472        let mut state = VirtualizedListState::new();
3473        let scrollbar_hit_id = HitId::new(1);
3474        let total_items = 100;
3475        let viewport_height = 10;
3476        let fixed_height = 1;
3477
3478        // Simulate click on thumb.
3479        // Track length 10. Thumb size 1. Content 100.
3480        // Thumb at top (pos 0).
3481        // Click at track_pos 0 (top of thumb).
3482        // Hit data: [8: part] [28: len] [28: pos]
3483        let track_len = 10u64;
3484        let track_pos = 0u64;
3485        let hit_data = (SCROLLBAR_PART_THUMB << 56)
3486            | ((track_len & 0x0FFF_FFFF) << 28)
3487            | (track_pos & 0x0FFF_FFFF);
3488
3489        let down_event = MouseEvent::new(MouseEventKind::Down(MouseButton::Left), 0, 0);
3490        let hit = Some((scrollbar_hit_id, HitRegion::Scrollbar, hit_data));
3491
3492        state.handle_mouse(
3493            &down_event,
3494            hit,
3495            scrollbar_hit_id,
3496            total_items,
3497            viewport_height,
3498            fixed_height,
3499        );
3500
3501        assert!(
3502            state.scrollbar_drag_anchor.is_some(),
3503            "Drag anchor should be set on down"
3504        );
3505        assert_eq!(
3506            state.scrollbar_drag_anchor.unwrap(),
3507            0,
3508            "Anchor should be 0 (clicked top of thumb)"
3509        );
3510
3511        // Drag down by 1 cell.
3512        // track_pos = 1. anchor = 0. target thumb top = 1.
3513        // available = 9. max_pos = 90.
3514        // pos = (1 * 90) / 9 = 10.
3515        let drag_pos = 1u64;
3516        let drag_data = (SCROLLBAR_PART_THUMB << 56)
3517            | ((track_len & 0x0FFF_FFFF) << 28)
3518            | (drag_pos & 0x0FFF_FFFF);
3519        let drag_event = MouseEvent::new(MouseEventKind::Drag(MouseButton::Left), 0, 1);
3520        let drag_hit = Some((scrollbar_hit_id, HitRegion::Scrollbar, drag_data));
3521
3522        state.handle_mouse(
3523            &drag_event,
3524            drag_hit,
3525            scrollbar_hit_id,
3526            total_items,
3527            viewport_height,
3528            fixed_height,
3529        );
3530
3531        assert_eq!(
3532            state.scroll_offset, 10,
3533            "Scroll offset should update smoothly"
3534        );
3535    }
3536}