Skip to main content

pacsea/events/
utils.rs

1use crossterm::event::KeyEvent;
2use tokio::sync::mpsc;
3
4use crate::state::{AppState, PackageItem};
5use std::time::Instant;
6
7/// What: Check if a key event matches any chord in a list, handling Shift+char edge cases.
8///
9/// Inputs:
10/// - `ke`: Key event from terminal
11/// - `list`: List of configured key chords to match against
12///
13/// Output:
14/// - `true` if the key event matches any chord in the list, `false` otherwise
15///
16/// Details:
17/// - Treats Shift+<char> from config as equivalent to uppercase char without Shift from terminal.
18/// - Handles cases where terminals report Shift inconsistently.
19#[must_use]
20pub fn matches_any(ke: &KeyEvent, list: &[crate::theme::KeyChord]) -> bool {
21    list.iter().any(|c| {
22        if (c.code, c.mods) == (ke.code, ke.modifiers) {
23            return true;
24        }
25        match (c.code, ke.code) {
26            (crossterm::event::KeyCode::Char(cfg_ch), crossterm::event::KeyCode::Char(ev_ch)) => {
27                let cfg_has_shift = c.mods.contains(crossterm::event::KeyModifiers::SHIFT);
28                if !cfg_has_shift {
29                    return false;
30                }
31                // Accept uppercase event regardless of SHIFT flag
32                if ev_ch == cfg_ch.to_ascii_uppercase() {
33                    return true;
34                }
35                // Accept lowercase char if terminal reports SHIFT in modifiers
36                if ke.modifiers.contains(crossterm::event::KeyModifiers::SHIFT)
37                    && ev_ch.to_ascii_lowercase() == cfg_ch
38                {
39                    return true;
40                }
41                false
42            }
43            _ => false,
44        }
45    })
46}
47
48/// What: Return the number of Unicode scalar values (characters) in the input.
49///
50/// Input: `s` string to measure
51/// Output: Character count as `usize`
52///
53/// Details: Counts Unicode scalar values using `s.chars().count()`.
54#[must_use]
55pub fn char_count(s: &str) -> usize {
56    s.chars().count()
57}
58
59/// What: Convert a character index to a byte index for slicing.
60///
61/// Input: `s` source string; `ci` character index
62/// Output: Byte index into `s` corresponding to `ci`
63///
64/// Details: Returns 0 for `ci==0`; returns `s.len()` when `ci>=char_count(s)`; otherwise maps
65/// the character index to a byte offset via `char_indices()`.
66#[must_use]
67pub fn byte_index_for_char(s: &str, ci: usize) -> usize {
68    let cc = char_count(s);
69    if ci == 0 {
70        return 0;
71    }
72    if ci >= cc {
73        return s.len();
74    }
75    s.char_indices().map(|(i, _)| i).nth(ci).unwrap_or(s.len())
76}
77
78/// What: Advance selection in the Recent pane to the next/previous match of the pane-find pattern.
79///
80/// Input: `app` mutable application state; `forward` when true searches downward, else upward
81/// Output: No return value; updates `history_state` selection when a match is found
82///
83/// Details: Searches within the filtered Recent indices and wraps around the list; matching is
84/// case-insensitive against the current pane-find pattern.
85pub fn find_in_recent(app: &mut AppState, forward: bool) {
86    let Some(pattern) = app.pane_find.clone() else {
87        return;
88    };
89    let inds = crate::ui::helpers::filtered_recent_indices(app);
90    if inds.is_empty() {
91        return;
92    }
93    let start = app.history_state.selected().unwrap_or(0);
94    let mut vi = start;
95    let n = inds.len();
96    for _ in 0..n {
97        vi = if forward {
98            (vi + 1) % n
99        } else if vi == 0 {
100            n - 1
101        } else {
102            vi - 1
103        };
104        let i = inds[vi];
105        if let Some(s) = app.recent_value_at(i)
106            && s.to_lowercase().contains(&pattern.to_lowercase())
107        {
108            app.history_state.select(Some(vi));
109            break;
110        }
111    }
112}
113
114/// What: Advance selection in the Install pane to the next/previous item matching the pane-find pattern.
115///
116/// Input: `app` mutable application state; `forward` when true searches downward, else upward
117/// Output: No return value; updates `install_state` selection when a match is found
118///
119/// Details: Operates on visible indices and tests case-insensitive matches against package name
120/// or description; wraps around the list.
121pub fn find_in_install(app: &mut AppState, forward: bool) {
122    let Some(pattern) = app.pane_find.clone() else {
123        return;
124    };
125    let inds = crate::ui::helpers::filtered_install_indices(app);
126    if inds.is_empty() {
127        return;
128    }
129    let start = app.install_state.selected().unwrap_or(0);
130    let mut vi = start;
131    let n = inds.len();
132    for _ in 0..n {
133        vi = if forward {
134            (vi + 1) % n
135        } else if vi == 0 {
136            n - 1
137        } else {
138            vi - 1
139        };
140        let i = inds[vi];
141        if let Some(p) = app.install_list.get(i)
142            && (p.name.to_lowercase().contains(&pattern.to_lowercase())
143                || p.description
144                    .to_lowercase()
145                    .contains(&pattern.to_lowercase()))
146        {
147            app.install_state.select(Some(vi));
148            break;
149        }
150    }
151}
152
153/// What: Ensure details reflect the currently selected result.
154///
155/// Input: `app` mutable application state; `details_tx` channel for details requests
156/// Output: No return value; uses cache or sends a details request
157///
158/// Details: If details for the selected item exist in the cache, they are applied immediately;
159/// otherwise, the item is sent over `details_tx` to be fetched asynchronously.
160pub fn refresh_selected_details(
161    app: &mut AppState,
162    details_tx: &mpsc::UnboundedSender<PackageItem>,
163) {
164    if let Some(item) = app.results.get(app.selected).cloned() {
165        // Reset scroll when package changes
166        app.details_scroll = 0;
167        if let Some(cached) = app.details_cache.get(&item.name).cloned() {
168            app.details = cached;
169        } else {
170            let _ = details_tx.send(item);
171        }
172        queue_selected_aur_vote_state_check(app);
173    }
174}
175
176/// What: Queue a live AUR vote-state check for the currently selected result.
177///
178/// Inputs:
179/// - `app`: Mutable application state with current results selection.
180///
181/// Output:
182/// - None (updates vote-state cache and pending request fields).
183///
184/// Details:
185/// - Only queues checks for selected AUR packages when AUR voting is enabled.
186/// - Marks selected package as `Loading` and stores a single pending request.
187/// - Replaces an older pending request when selection changes rapidly.
188pub fn queue_selected_aur_vote_state_check(app: &mut AppState) {
189    let settings = crate::theme::settings();
190    if !settings.aur_vote_enabled {
191        return;
192    }
193    if !app.aur_vote_state_lookup_supported {
194        return;
195    }
196    let Some(item) = app.results.get(app.selected) else {
197        return;
198    };
199    if !matches!(item.source, crate::state::Source::Aur) {
200        return;
201    }
202
203    let pkgbase = item.name.clone();
204    if let Some(previous) = app.pending_aur_vote_state_request.replace(pkgbase.clone())
205        && previous != pkgbase
206        && matches!(
207            app.aur_vote_state_by_pkgbase.get(&previous),
208            Some(crate::state::app_state::AurVoteStateUi::Loading)
209        )
210    {
211        app.aur_vote_state_by_pkgbase
212            .insert(previous, crate::state::app_state::AurVoteStateUi::Unknown);
213    }
214    let should_mark_loading = !matches!(
215        app.aur_vote_state_by_pkgbase.get(&pkgbase),
216        Some(
217            crate::state::app_state::AurVoteStateUi::Voted
218                | crate::state::app_state::AurVoteStateUi::NotVoted
219        )
220    );
221    if should_mark_loading {
222        app.aur_vote_state_by_pkgbase
223            .insert(pkgbase, crate::state::app_state::AurVoteStateUi::Loading);
224    }
225}
226
227/// What: Move selection and queue live AUR vote-state check for selected package.
228///
229/// Inputs:
230/// - `app`: Mutable application state.
231/// - `delta`: Signed selection movement.
232/// - `details_tx`: Channel for async details requests.
233/// - `comments_tx`: Channel for async AUR comments requests.
234///
235/// Output:
236/// - None (mutates selection/details state and queues optional vote-state check).
237///
238/// Details:
239/// - Uses existing `logic::move_sel_cached` for selection/details coordination.
240/// - Then schedules live vote-state check for selected AUR package.
241pub fn move_sel_cached_with_vote_state(
242    app: &mut AppState,
243    delta: isize,
244    details_tx: &mpsc::UnboundedSender<PackageItem>,
245    comments_tx: &mpsc::UnboundedSender<String>,
246) {
247    crate::logic::move_sel_cached(app, delta, details_tx, comments_tx);
248    queue_selected_aur_vote_state_check(app);
249}
250
251/// Move news selection by delta, keeping it in view.
252pub fn move_news_selection(app: &mut AppState, delta: isize) {
253    if app.news_results.is_empty() {
254        app.news_selected = 0;
255        app.news_list_state.select(None);
256        app.details.url.clear();
257        return;
258    }
259    let len = app.news_results.len();
260    if app.news_selected >= len {
261        app.news_selected = len.saturating_sub(1);
262    }
263    app.news_list_state.select(Some(app.news_selected));
264    let steps = delta.unsigned_abs();
265    for _ in 0..steps {
266        if delta.is_negative() {
267            app.news_list_state.select_previous();
268        } else {
269            app.news_list_state.select_next();
270        }
271    }
272    let sel = app.news_list_state.selected().unwrap_or(0);
273    app.news_selected = std::cmp::min(sel, len.saturating_sub(1));
274    app.news_list_state.select(Some(app.news_selected));
275    update_news_url(app);
276}
277
278/// What: Compute updates-modal scroll offset that vertically centers the selected entry.
279///
280/// Inputs:
281/// - `entry_line_starts`: Mapping from entry index to first rendered line in wrapped output.
282/// - `total_lines`: Total rendered line count across wrapped updates rows.
283/// - `content_rect`: Optional updates content rectangle tuple `(x, y, width, height)`.
284/// - `selected`: Selected entry index.
285/// - `total_items`: Number of entries in the updates list.
286/// - `_current_scroll`: Reserved for callers; scroll is derived from selection and geometry only.
287///
288/// Output:
289/// - Returns the clamped scroll offset as `u16`.
290///
291/// Details:
292/// - Derives `visible_lines` from `content_rect` height and falls back to `1` when absent.
293/// - Uses rendered-line mapping to support wrapped rows consistently.
294/// - Centers the first rendered line of the selected entry (`⌊visible_lines / 2⌋` rows above it)
295///   when possible; clamps to `[0, max_scroll]` near list ends so the list never overscrolls.
296#[must_use]
297pub fn compute_updates_modal_scroll_for_selection(
298    entry_line_starts: &[u16],
299    total_lines: u16,
300    content_rect: Option<(u16, u16, u16, u16)>,
301    selected: usize,
302    total_items: usize,
303    _current_scroll: u16,
304) -> u16 {
305    let selected_line = entry_line_starts
306        .get(selected)
307        .copied()
308        .unwrap_or_else(|| u16::try_from(selected).unwrap_or(u16::MAX));
309    let visible_lines = content_rect.map_or(1, |(_, _, _, h)| h.max(1));
310    let half = visible_lines / 2;
311    let ideal = selected_line.saturating_sub(half);
312
313    let fallback_total = u16::try_from(total_items).unwrap_or(u16::MAX);
314    let max_scroll = total_lines
315        .max(fallback_total)
316        .saturating_sub(visible_lines);
317    ideal.min(max_scroll)
318}
319
320/// What: Compute visible updates indices for a slash-filter query.
321///
322/// Inputs:
323/// - `entries`: Full updates entries (`name`, `old_version`, `new_version`).
324/// - `query`: Filter query string entered in Updates modal.
325///
326/// Output:
327/// - Stable vector of original-entry indices that match query order.
328///
329/// Details:
330/// - Empty/whitespace query returns all entries.
331/// - Matching is fuzzy + case-insensitive against package name and source label.
332/// - Source labels are lowercase: `pacman` for official packages and `aur` for AUR packages.
333#[must_use]
334pub fn compute_updates_filtered_indices(
335    entries: &[(String, String, String)],
336    query: &str,
337) -> Vec<usize> {
338    let normalized = query.trim();
339    if normalized.is_empty() {
340        return (0..entries.len()).collect();
341    }
342
343    let query_lower = normalized.to_lowercase();
344
345    entries
346        .iter()
347        .enumerate()
348        .filter_map(|(idx, (name, _, _))| {
349            let source_label = if crate::index::find_package_by_name(name).is_some() {
350                "pacman"
351            } else {
352                "aur"
353            };
354            let name_lower = name.to_lowercase();
355            let matches_name = crate::util::fuzzy_match_rank(&name_lower, &query_lower).is_some();
356            let matches_source =
357                crate::util::fuzzy_match_rank(source_label, &query_lower).is_some();
358            if matches_name || matches_source {
359                Some(idx)
360            } else {
361                None
362            }
363        })
364        .collect()
365}
366
367/// Synchronize details URL and content with currently selected news item.
368/// Also triggers content fetching if channel is provided and content is not cached.
369pub fn update_news_url(app: &mut AppState) {
370    if let Some(item) = app.news_results.get(app.news_selected)
371        && let Some(url) = &item.url
372    {
373        app.details.url.clone_from(url);
374        // Check if content is cached
375        let mut cached = app.news_content_cache.get(url).cloned();
376        if let Some(ref c) = cached
377            && url.contains("://archlinux.org/packages/")
378            && !c.starts_with("Package Info:")
379        {
380            // Cached pre-metadata version: force refresh
381            cached = None;
382            tracing::debug!(
383                url,
384                "news content cache missing package metadata; will refetch"
385            );
386        }
387        app.news_content = cached;
388        if app.news_content.is_some() {
389            tracing::debug!(url, "news content served from cache");
390        } else {
391            // Content not cached - set debounce timer to wait 0.5 seconds before fetching
392            app.news_content_debounce_timer = Some(std::time::Instant::now());
393            tracing::debug!(url, "news content not cached, setting debounce timer");
394        }
395        app.news_content_scroll = 0;
396    } else {
397        app.details.url.clear();
398        app.news_content = None;
399        app.news_content_debounce_timer = None;
400    }
401    app.news_content_loading = false;
402}
403
404/// Request news content fetch if not cached or loading.
405/// Implements 0.5 second debounce - only requests after user stays on item for 0.5 seconds.
406pub fn maybe_request_news_content(
407    app: &mut AppState,
408    news_content_req_tx: &mpsc::UnboundedSender<String>,
409) {
410    // Only request if in news mode with a selected item that has a URL
411    if !matches!(app.app_mode, crate::state::types::AppMode::News) {
412        tracing::trace!("news_content: skip request, not in news mode");
413        return;
414    }
415    if app.news_content_loading {
416        tracing::debug!(
417            selected = app.news_selected,
418            "news_content: skip request, already loading"
419        );
420        return;
421    }
422    if let Some(item) = app.news_results.get(app.news_selected)
423        && let Some(url) = &item.url
424        && app.news_content.is_none()
425        && !app.news_content_cache.contains_key(url)
426    {
427        // Check debounce timer - only request after 0.5 seconds of staying on the item
428        // 500ms balances user experience with server load: long enough to avoid excessive
429        // fetches during rapid navigation, short enough to feel responsive.
430        const DEBOUNCE_DELAY_MS: u64 = 500;
431        if let Some(timer) = app.news_content_debounce_timer {
432            // Safe to unwrap: elapsed will be small (well within u64)
433            #[allow(clippy::cast_possible_truncation)]
434            let elapsed = timer.elapsed().as_millis() as u64;
435            if elapsed < DEBOUNCE_DELAY_MS {
436                // Debounce not expired yet - wait longer
437                tracing::trace!(
438                    selected = app.news_selected,
439                    url,
440                    elapsed_ms = elapsed,
441                    remaining_ms = DEBOUNCE_DELAY_MS - elapsed,
442                    "news_content: debounce timer not expired, waiting"
443                );
444                return;
445            }
446            // Debounce expired - clear timer and proceed with request
447            app.news_content_debounce_timer = None;
448        } else {
449            // No debounce timer set - this shouldn't happen, but set it now
450            app.news_content_debounce_timer = Some(std::time::Instant::now());
451            tracing::debug!(
452                selected = app.news_selected,
453                url,
454                "news_content: no debounce timer, setting one now"
455            );
456            return;
457        }
458
459        app.news_content_loading = true;
460        app.news_content_loading_since = Some(Instant::now());
461        tracing::debug!(
462            selected = app.news_selected,
463            title = item.title,
464            url,
465            "news_content: requesting article content (debounce expired)"
466        );
467        if let Err(e) = news_content_req_tx.send(url.clone()) {
468            tracing::warn!(
469                error = %e,
470                selected = app.news_selected,
471                title = item.title,
472                url,
473                "news_content: failed to enqueue content request"
474            );
475            app.news_content_loading = false;
476            app.news_content_loading_since = None;
477            app.news_content = Some(format!("Failed to load content: {e}"));
478            app.toast_message = Some("News content request failed".to_string());
479            app.toast_expires_at = Some(Instant::now() + std::time::Duration::from_secs(3));
480        }
481    } else {
482        tracing::trace!(
483            selected = app.news_selected,
484            has_item = app.news_results.get(app.news_selected).is_some(),
485            has_url = app
486                .news_results
487                .get(app.news_selected)
488                .and_then(|it| it.url.as_ref())
489                .is_some(),
490            content_cached = app
491                .news_results
492                .get(app.news_selected)
493                .and_then(|it| it.url.as_ref())
494                .is_some_and(|u| app.news_content_cache.contains_key(u)),
495            has_content = app.news_content.is_some(),
496            "news_content: skip request (cached/absent URL/already loaded)"
497        );
498    }
499}
500
501/// What: Ensure details reflect the selected item in the Install pane.
502///
503/// Input: `app` mutable application state; `details_tx` channel for details requests
504/// Output: No return value; focuses details on the selected Install item and uses cache or requests fetch
505///
506/// Details: Sets `details_focus`, populates a placeholder from the selected item, then uses the
507/// cache when present; otherwise sends a request over `details_tx`.
508pub fn refresh_install_details(
509    app: &mut AppState,
510    details_tx: &mpsc::UnboundedSender<PackageItem>,
511) {
512    let Some(vsel) = app.install_state.selected() else {
513        return;
514    };
515    let inds = crate::ui::helpers::filtered_install_indices(app);
516    if inds.is_empty() || vsel >= inds.len() {
517        return;
518    }
519    let i = inds[vsel];
520    if let Some(item) = app.install_list.get(i).cloned() {
521        // Reset scroll when package changes
522        app.details_scroll = 0;
523        // Focus details on the install selection
524        app.details_focus = Some(item.name.clone());
525
526        // Provide an immediate placeholder reflecting the selection
527        app.details.name.clone_from(&item.name);
528        app.details.version.clone_from(&item.version);
529        app.details.description.clear();
530        match &item.source {
531            crate::state::Source::Official { repo, arch } => {
532                app.details.repository.clone_from(repo);
533                app.details.architecture.clone_from(arch);
534            }
535            crate::state::Source::Aur => {
536                app.details.repository = "AUR".to_string();
537                app.details.architecture = "any".to_string();
538            }
539        }
540
541        if let Some(cached) = app.details_cache.get(&item.name).cloned() {
542            app.details = cached;
543        } else {
544            let _ = details_tx.send(item);
545        }
546    }
547}
548
549/// What: Ensure details reflect the selected item in the Remove pane.
550///
551/// Input: `app` mutable application state; `details_tx` channel for details requests
552/// Output: No return value; focuses details on the selected Remove item and uses cache or requests fetch
553///
554/// Details: Sets `details_focus`, populates a placeholder from the selected item, then uses the
555/// cache when present; otherwise sends a request over `details_tx`.
556pub fn refresh_remove_details(app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>) {
557    let Some(vsel) = app.remove_state.selected() else {
558        return;
559    };
560    if app.remove_list.is_empty() || vsel >= app.remove_list.len() {
561        return;
562    }
563    if let Some(item) = app.remove_list.get(vsel).cloned() {
564        // Reset scroll when package changes
565        app.details_scroll = 0;
566        app.details_focus = Some(item.name.clone());
567        app.details.name.clone_from(&item.name);
568        app.details.version.clone_from(&item.version);
569        app.details.description.clear();
570        match &item.source {
571            crate::state::Source::Official { repo, arch } => {
572                app.details.repository.clone_from(repo);
573                app.details.architecture.clone_from(arch);
574            }
575            crate::state::Source::Aur => {
576                app.details.repository = "AUR".to_string();
577                app.details.architecture = "any".to_string();
578            }
579        }
580        if let Some(cached) = app.details_cache.get(&item.name).cloned() {
581            app.details = cached;
582        } else {
583            let _ = details_tx.send(item);
584        }
585    }
586}
587
588/// What: Ensure details reflect the selected item in the Downgrade pane.
589///
590/// Input: `app` mutable application state; `details_tx` channel for details requests
591/// Output: No return value; focuses details on the selected Downgrade item and uses cache or requests fetch
592///
593/// Details: Sets `details_focus`, populates a placeholder from the selected item, then uses the
594/// cache when present; otherwise sends a request over `details_tx`.
595pub fn refresh_downgrade_details(
596    app: &mut AppState,
597    details_tx: &mpsc::UnboundedSender<PackageItem>,
598) {
599    let Some(vsel) = app.downgrade_state.selected() else {
600        return;
601    };
602    if app.downgrade_list.is_empty() || vsel >= app.downgrade_list.len() {
603        return;
604    }
605    if let Some(item) = app.downgrade_list.get(vsel).cloned() {
606        // Reset scroll when package changes
607        app.details_scroll = 0;
608        app.details_focus = Some(item.name.clone());
609        app.details.name.clone_from(&item.name);
610        app.details.version.clone_from(&item.version);
611        app.details.description.clear();
612        match &item.source {
613            crate::state::Source::Official { repo, arch } => {
614                app.details.repository.clone_from(repo);
615                app.details.architecture.clone_from(arch);
616            }
617            crate::state::Source::Aur => {
618                app.details.repository = "AUR".to_string();
619                app.details.architecture = "any".to_string();
620            }
621        }
622        if let Some(cached) = app.details_cache.get(&item.name).cloned() {
623            app.details = cached;
624        } else {
625            let _ = details_tx.send(item);
626        }
627    }
628}
629
630#[cfg(test)]
631mod tests {
632    use super::*;
633
634    /// What: Produce a baseline `AppState` tailored for utils tests.
635    ///
636    /// Inputs:
637    /// - None; relies on `Default::default()` for deterministic state.
638    ///
639    /// Output:
640    /// - Fresh `AppState` instance for individual unit tests.
641    ///
642    /// Details:
643    /// - Centralizes setup so each test starts from a clean copy without repeated boilerplate.
644    fn new_app() -> AppState {
645        AppState::default()
646    }
647
648    #[test]
649    /// What: Ensure `char_count` returns the number of Unicode scalar values.
650    ///
651    /// Inputs:
652    /// - Strings `"abc"`, `"π"`, and `"aπb"`.
653    ///
654    /// Output:
655    /// - Counts `3`, `1`, and `3` respectively.
656    ///
657    /// Details:
658    /// - Demonstrates correct handling of multi-byte characters.
659    fn char_count_basic() {
660        assert_eq!(char_count("abc"), 3);
661        assert_eq!(char_count("π"), 1);
662        assert_eq!(char_count("aπb"), 3);
663    }
664
665    #[test]
666    /// What: Verify `byte_index_for_char` translates character indices to UTF-8 byte offsets.
667    ///
668    /// Inputs:
669    /// - String `"aπb"` with char indices 0 through 3.
670    ///
671    /// Output:
672    /// - Returns byte offsets `0`, `1`, `3`, and `len`.
673    ///
674    /// Details:
675    /// - Confirms the function respects variable-width encoding.
676    fn byte_index_for_char_basic() {
677        let s = "aπb";
678        assert_eq!(byte_index_for_char(s, 0), 0);
679        assert_eq!(byte_index_for_char(s, 1), 1);
680        assert_eq!(byte_index_for_char(s, 2), 1 + "π".len());
681        assert_eq!(byte_index_for_char(s, 3), s.len());
682    }
683
684    #[test]
685    /// What: Ensure `find_in_recent` cycles through entries matching the pane filter.
686    ///
687    /// Inputs:
688    /// - Recent list `alpha`, `beta`, `gamma` with filter `"a"`.
689    ///
690    /// Output:
691    /// - Selection rotates among matching entries without panicking.
692    ///
693    /// Details:
694    /// - Provides smoke coverage for the wrap-around logic inside the helper.
695    fn find_in_recent_basic() {
696        let mut app = new_app();
697        app.load_recent_items(&["alpha".to_string(), "beta".to_string(), "gamma".to_string()]);
698        app.pane_find = Some("a".into());
699        app.history_state.select(Some(0));
700        find_in_recent(&mut app, true);
701        assert!(app.history_state.selected().is_some());
702    }
703
704    #[test]
705    /// What: Check `find_in_install` advances selection to the next matching entry by name or description.
706    ///
707    /// Inputs:
708    /// - Install list with `ripgrep` and `fd`, filter term `"rip"` while selection starts on the second item.
709    ///
710    /// Output:
711    /// - Selection wraps to the first item containing the filter term.
712    ///
713    /// Details:
714    /// - Protects against regressions in forward search and wrap-around behaviour.
715    fn find_in_install_basic() {
716        let mut app = new_app();
717        app.install_list = vec![
718            crate::state::PackageItem {
719                name: "ripgrep".into(),
720                version: "1".into(),
721                description: "fast search".into(),
722                source: crate::state::Source::Aur,
723                popularity: None,
724                out_of_date: None,
725                orphaned: false,
726            },
727            crate::state::PackageItem {
728                name: "fd".into(),
729                version: "1".into(),
730                description: "find".into(),
731                source: crate::state::Source::Aur,
732                popularity: None,
733                out_of_date: None,
734                orphaned: false,
735            },
736        ];
737        app.pane_find = Some("rip".into());
738        // Start from visible selection 1 so advancing wraps to 0 matching "ripgrep"
739        app.install_state.select(Some(1));
740        find_in_install(&mut app, true);
741        assert_eq!(app.install_state.selected(), Some(0));
742    }
743
744    #[test]
745    /// What: Ensure `refresh_selected_details` dispatches a fetch when cache misses occur.
746    ///
747    /// Inputs:
748    /// - Results list with a single entry and an empty details cache.
749    ///
750    /// Output:
751    /// - Sends the selected item through `details_tx`, confirming a fetch request.
752    ///
753    /// Details:
754    /// - Uses an unbounded channel to observe the request without performing actual I/O.
755    fn refresh_selected_details_requests_when_missing() {
756        let mut app = new_app();
757        app.results = vec![crate::state::PackageItem {
758            name: "rg".into(),
759            version: "1".into(),
760            description: String::new(),
761            source: crate::state::Source::Aur,
762            popularity: None,
763            out_of_date: None,
764            orphaned: false,
765        }];
766        app.selected = 0;
767        let (tx, mut rx) = mpsc::unbounded_channel();
768        refresh_selected_details(&mut app, &tx);
769        let got = rx.try_recv().ok();
770        assert!(got.is_some());
771    }
772
773    #[test]
774    /// What: Ensure vote-state checks are skipped when live lookup is unsupported.
775    ///
776    /// Inputs:
777    /// - A selected AUR package with cached `Voted` state and lookup support disabled.
778    ///
779    /// Output:
780    /// - No pending request is queued and cached state remains unchanged.
781    ///
782    /// Details:
783    /// - Prevents replacing persisted stable vote-state with transient loading state
784    ///   after the runtime detects unsupported `list-votes`.
785    fn queue_vote_state_check_skips_when_lookup_unsupported() {
786        let mut app = new_app();
787        app.results = vec![crate::state::PackageItem {
788            name: "pacsea-bin".into(),
789            version: "1".into(),
790            description: String::new(),
791            source: crate::state::Source::Aur,
792            popularity: None,
793            out_of_date: None,
794            orphaned: false,
795        }];
796        app.selected = 0;
797        app.aur_vote_state_lookup_supported = false;
798        app.aur_vote_state_by_pkgbase.insert(
799            "pacsea-bin".into(),
800            crate::state::app_state::AurVoteStateUi::Voted,
801        );
802
803        queue_selected_aur_vote_state_check(&mut app);
804
805        assert!(app.pending_aur_vote_state_request.is_none());
806        assert!(matches!(
807            app.aur_vote_state_by_pkgbase.get("pacsea-bin"),
808            Some(crate::state::app_state::AurVoteStateUi::Voted)
809        ));
810    }
811
812    #[test]
813    /// What: Ensure queuing live vote-state checks does not overwrite stable cached state.
814    ///
815    /// Inputs:
816    /// - Selected AUR package with existing `Voted` cache.
817    ///
818    /// Output:
819    /// - Request is queued, but cached state stays `Voted` instead of switching to `Loading`.
820    ///
821    /// Details:
822    /// - Prevents stable persisted state from disappearing during transient live checks.
823    fn queue_vote_state_check_preserves_stable_cached_state() {
824        let mut app = new_app();
825        app.results = vec![crate::state::PackageItem {
826            name: "pacsea-bin".into(),
827            version: "1".into(),
828            description: String::new(),
829            source: crate::state::Source::Aur,
830            popularity: None,
831            out_of_date: None,
832            orphaned: false,
833        }];
834        app.selected = 0;
835        app.aur_vote_state_by_pkgbase.insert(
836            "pacsea-bin".into(),
837            crate::state::app_state::AurVoteStateUi::Voted,
838        );
839
840        queue_selected_aur_vote_state_check(&mut app);
841
842        assert_eq!(
843            app.pending_aur_vote_state_request,
844            Some("pacsea-bin".to_string())
845        );
846        assert!(matches!(
847            app.aur_vote_state_by_pkgbase.get("pacsea-bin"),
848            Some(crate::state::app_state::AurVoteStateUi::Voted)
849        ));
850    }
851
852    #[test]
853    /// What: Ensure missing updates content rect falls back to one visible line.
854    ///
855    /// Inputs:
856    /// - Wrapped line starts with no viewport rect and selection on later entry.
857    ///
858    /// Output:
859    /// - Scroll moves to selected line and remains clamped.
860    ///
861    /// Details:
862    /// - Guards deterministic behavior when geometry is unavailable.
863    fn updates_scroll_fallback_visible_lines_when_rect_missing() {
864        let scroll = compute_updates_modal_scroll_for_selection(&[0, 3, 5], 7, None, 1, 3, 0);
865        assert_eq!(scroll, 3);
866    }
867
868    #[test]
869    /// What: Ensure tiny viewport heights still keep selected wrapped line visible.
870    ///
871    /// Inputs:
872    /// - Height-1 and height-2 content rects with later selected entries.
873    ///
874    /// Output:
875    /// - Scroll adjusts forward without overshooting bounds.
876    ///
877    /// Details:
878    /// - Prevents regressions in very small terminal layouts.
879    fn updates_scroll_handles_tiny_viewport_heights() {
880        let height_one = Some((0, 0, 40, 1));
881        let scroll_one =
882            compute_updates_modal_scroll_for_selection(&[0, 3, 5], 7, height_one, 1, 3, 0);
883        assert_eq!(scroll_one, 3);
884
885        let height_two = Some((0, 0, 40, 2));
886        let scroll_two =
887            compute_updates_modal_scroll_for_selection(&[0, 3, 5], 7, height_two, 2, 3, 0);
888        assert_eq!(scroll_two, 4);
889    }
890
891    #[test]
892    /// What: Ensure updates modal scroll centers the selected rendered line when space allows.
893    ///
894    /// Inputs:
895    /// - Ten logical lines, viewport height five, selection on line four (entry index 2).
896    ///
897    /// Output:
898    /// - Scroll offset two so line four sits in the middle row of the viewport.
899    ///
900    /// Details:
901    /// - Complements edge-clamp tests by checking the common middle-of-list case.
902    fn updates_scroll_centers_selection_in_viewport() {
903        let starts: Vec<u16> = (0..10).collect();
904        let rect = Some((0, 0, 40, 5));
905        let scroll = compute_updates_modal_scroll_for_selection(&starts, 10, rect, 4, 10, 0);
906        assert_eq!(scroll, 2);
907    }
908
909    #[test]
910    /// What: Ensure large viewport clamps updates modal scroll to top.
911    ///
912    /// Inputs:
913    /// - Viewport height greater than total rendered lines.
914    ///
915    /// Output:
916    /// - Scroll returns to zero.
917    ///
918    /// Details:
919    /// - Confirms no overscroll when all rows fit on screen.
920    fn updates_scroll_clamps_to_zero_when_viewport_exceeds_total() {
921        let large_rect = Some((0, 0, 40, 20));
922        let scroll =
923            compute_updates_modal_scroll_for_selection(&[0, 3, 5], 7, large_rect, 2, 3, 10);
924        assert_eq!(scroll, 0);
925    }
926
927    #[test]
928    /// What: Ensure updates filter returns all indices for empty query.
929    ///
930    /// Inputs:
931    /// - Three updates entries and an empty query.
932    ///
933    /// Output:
934    /// - Returns all original entry indices in stable order.
935    ///
936    /// Details:
937    /// - Guards no-op filter behavior when slash mode is entered/cleared.
938    fn updates_filter_returns_all_indices_for_empty_query() {
939        let entries = vec![
940            ("ripgrep".to_string(), "13".to_string(), "14".to_string()),
941            ("fd".to_string(), "8".to_string(), "9".to_string()),
942            ("bat".to_string(), "1".to_string(), "2".to_string()),
943        ];
944        let indices = compute_updates_filtered_indices(&entries, "");
945        assert_eq!(indices, vec![0, 1, 2]);
946    }
947
948    #[test]
949    /// What: Ensure updates filter performs fuzzy case-insensitive package matching.
950    ///
951    /// Inputs:
952    /// - Entries containing "ripgrep" and query "RG".
953    ///
954    /// Output:
955    /// - Includes the "ripgrep" entry index.
956    ///
957    /// Details:
958    /// - Validates phase-4 matcher behavior for shorthand package queries.
959    fn updates_filter_matches_package_name_fuzzy_case_insensitive() {
960        let entries = vec![
961            ("ripgrep".to_string(), "13".to_string(), "14".to_string()),
962            ("fd".to_string(), "8".to_string(), "9".to_string()),
963        ];
964        let indices = compute_updates_filtered_indices(&entries, "RG");
965        assert_eq!(indices, vec![0]);
966    }
967
968    #[test]
969    /// What: Ensure updates filter can match source labels.
970    ///
971    /// Inputs:
972    /// - Entries expected to include AUR rows and query "aur".
973    ///
974    /// Output:
975    /// - Every returned index maps to an AUR package.
976    ///
977    /// Details:
978    /// - Verifies source-label matching path used by slash filter.
979    fn updates_filter_matches_source_label() {
980        let entries = vec![
981            (
982                "pacsea-bin".to_string(),
983                "0.9".to_string(),
984                "1.0".to_string(),
985            ),
986            (
987                "pacsea-git".to_string(),
988                "0.9".to_string(),
989                "1.0".to_string(),
990            ),
991        ];
992        let indices = compute_updates_filtered_indices(&entries, "aur");
993        assert!(
994            !indices.is_empty(),
995            "expected at least one AUR package available in fixture"
996        );
997        for idx in indices {
998            let (name, _, _) = &entries[idx];
999            assert!(crate::index::find_package_by_name(name).is_none());
1000        }
1001    }
1002}