返回 CodeWhale
picker.rs
1 //! Picker: the list behind the mode picker, the status-line picker, and
2 //! every other "choose one" or "choose some" list.
3 //!
4 //! A selected row carries three cues, because a fill alone measures only
5 //! about 1.3:1 against its neighbours: the `▸` marker lit in `Primary`, the
6 //! label in bold, and the `Selected` ground where grounds paint. Checked rows
7 //! show `●` and unchecked `○` (`[x]` and `[ ]` in ASCII), so on/off is a
8 //! shape, not a color. Disabled rows say why.
9 //!
10 //! With a query line the picker is a fuzzy finder. The caller owns the text
11 //! and its editing; the picker paints the query it is given
12 //! ([`Picker::query`]), ranks with [`PickerMatches::rank`] (the matcher in
13 //! [`crate::fuzzy_score`]), underlines the matched characters as well as
14 //! coloring them, and says "No matches" with an [`crate::EmptyState`] rather
15 //! than a count of zero. Tabs ([`PickerTabs`]) filter by category, and a
16 //! preview pane ([`PickerPreview`]) sits beside the list at
17 //! [`PICKER_PREVIEW_MIN_WIDTH`] columns and up and is left out below it.
18 //! [`PickerState::handle_picker_key`] separates the keys that move from the
19 //! keys that belong to the query. Without any of these, a picker is the plain
20 //! list it always was.
21 //!
22 //! Replaces the row rendering in the engine's `views/mode_picker.rs` and
23 //! `views/status_picker.rs`, and `menu_style::selected_row_style`
24 //! (`Hmbown/CodeWhale` `58b1dd3dd`).
25
26 use std::borrow::Cow;
27
28 use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
29 use ratatui::{
30 buffer::Buffer,
31 layout::Rect,
32 style::{Modifier, Style},
33 text::{Line, Span},
34 widgets::Widget,
35 };
36 use unicode_segmentation::UnicodeSegmentation;
37
38 use super::list::{paint_scrollbar, settle_at, step_to};
39 use crate::{EmptyState, Paint, Role, Theme, fuzzy_score, glyphs, text};
40
41 /// One row.
42 #[derive(Clone, Debug, Default, PartialEq, Eq)]
43 pub struct PickerItem {
44 pub label: Cow<'static, str>,
45 /// Muted words after the label: what choosing this does.
46 pub detail: Option<Cow<'static, str>>,
47 /// A shortcut shown before the label (`1`, `2`, `3`).
48 pub key: Option<char>,
49 /// `Some` makes this a checklist row.
50 pub checked: Option<bool>,
51 /// `Some(reason)` greys the row and shows the reason as its detail.
52 pub disabled: Option<Cow<'static, str>>,
53 }
54
55 impl PickerItem {
56 #[must_use]
57 pub fn new(label: impl Into<Cow<'static, str>>) -> Self {
58 Self {
59 label: label.into(),
60 ..Self::default()
61 }
62 }
63
64 #[must_use]
65 pub fn detail(mut self, detail: impl Into<Cow<'static, str>>) -> Self {
66 self.detail = Some(detail.into());
67 self
68 }
69
70 #[must_use]
71 pub fn key(mut self, key: char) -> Self {
72 self.key = Some(key);
73 self
74 }
75
76 #[must_use]
77 pub fn checked(mut self, checked: bool) -> Self {
78 self.checked = Some(checked);
79 self
80 }
81
82 #[must_use]
83 pub fn disabled(mut self, reason: impl Into<Cow<'static, str>>) -> Self {
84 self.disabled = Some(reason.into());
85 self
86 }
87 }
88
89 /// Which row is selected and how far the list has scrolled.
90 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
91 pub struct PickerState {
92 pub selected: usize,
93 pub offset: usize,
94 }
95
96 impl PickerState {
97 #[must_use]
98 pub const fn new(selected: usize) -> Self {
99 Self {
100 selected,
101 offset: 0,
102 }
103 }
104
105 pub fn next(&mut self, len: usize) {
106 if len > 0 {
107 self.selected = self.selected.min(len - 1).saturating_add(1) % len;
108 }
109 }
110
111 pub fn prev(&mut self, len: usize) {
112 if len > 0 {
113 self.selected = if self.selected.min(len - 1) == 0 {
114 len - 1
115 } else {
116 self.selected.min(len - 1) - 1
117 };
118 }
119 }
120
121 pub fn home(&mut self) {
122 self.selected = 0;
123 }
124
125 pub fn end(&mut self, len: usize) {
126 self.selected = len.saturating_sub(1);
127 }
128
129 /// Move a page, clamped at the ends.
130 pub fn page(&mut self, len: usize, rows: u16, down: bool) {
131 let step = usize::from(rows.max(1));
132 self.selected = if down {
133 self.selected
134 .saturating_add(step)
135 .min(len.saturating_sub(1))
136 } else {
137 self.selected
138 .min(len.saturating_sub(1))
139 .saturating_sub(step)
140 };
141 }
142
143 /// The offset that keeps the selection on screen in `rows` rows.
144 #[must_use]
145 pub fn visible_offset(&self, len: usize, rows: usize) -> usize {
146 let rows = rows.max(1);
147 let selected = self.selected.min(len.saturating_sub(1));
148 let mut offset = self.offset.min(len.saturating_sub(rows));
149 if selected < offset {
150 offset = selected;
151 } else if selected >= offset.saturating_add(rows) {
152 offset = selected + 1 - rows;
153 }
154 offset
155 }
156
157 /// Store the offset [`Picker`] painted with, so scrolling is stable.
158 pub fn scroll_into_view(&mut self, len: usize, rows: u16) {
159 self.selected = self.selected.min(len.saturating_sub(1));
160 self.offset = self.visible_offset(len, usize::from(rows));
161 }
162 }
163
164 /// What a key did to a [`PickerState`]: the message a host reacts to.
165 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
166 pub enum PickerOutcome {
167 /// The key means nothing to a picker; the host may use it.
168 Ignored,
169 /// The selection moved (or tried to); repaint.
170 Moved,
171 /// Enter: row `n` was chosen.
172 Chose(usize),
173 /// Space: row `n` was toggled (a checklist row).
174 Toggled(usize),
175 /// Esc: the picker was dismissed.
176 Cancelled,
177 /// A picker with a query line: the key belongs to the query. Feed it to
178 /// the text editor, then rebuild the [`PickerMatches`] and
179 /// [`PickerState::reset`]. Only [`PickerState::handle_picker_key`]
180 /// returns it.
181 Query,
182 /// Tabs: the active tab is now `n`. Store it, rebuild the matches and
183 /// repaint; the state has already been reset.
184 Tab(usize),
185 }
186
187 impl PickerState {
188 /// Apply a key press to the state for a list of `len` rows shown in
189 /// `rows` rows, and say what happened. Keys: `↑`/`↓` (wrapping), `Home`,
190 /// `End`, `PgUp`, `PgDn`, `Enter`, `Space`, `Esc`. Releases and other
191 /// keys are [`PickerOutcome::Ignored`]; so is every key on an empty list.
192 /// Modified keys belong to the host. Held keys repeat navigation only.
193 pub fn handle_key(&mut self, key: KeyEvent, len: usize, rows: u16) -> PickerOutcome {
194 if key.kind == KeyEventKind::Release
195 || len == 0
196 || !key.modifiers.is_empty()
197 || (key.kind == KeyEventKind::Repeat
198 && matches!(key.code, KeyCode::Enter | KeyCode::Esc | KeyCode::Char(' ')))
199 {
200 return PickerOutcome::Ignored;
201 }
202 self.scroll_into_view(len, rows);
203 match key.code {
204 KeyCode::Up => self.prev(len),
205 KeyCode::Down => self.next(len),
206 KeyCode::Home => self.home(),
207 KeyCode::End => self.end(len),
208 KeyCode::PageUp => self.page(len, rows, false),
209 KeyCode::PageDown => self.page(len, rows, true),
210 KeyCode::Enter => return PickerOutcome::Chose(self.selected),
211 KeyCode::Char(' ') => return PickerOutcome::Toggled(self.selected),
212 KeyCode::Esc => return PickerOutcome::Cancelled,
213 _ => return PickerOutcome::Ignored,
214 }
215 self.scroll_into_view(len, rows);
216 PickerOutcome::Moved
217 }
218 }
219
220 impl PickerState {
221 /// Back to the first row, as after the query or the tab changed.
222 pub fn reset(&mut self) {
223 *self = Self::default();
224 }
225
226 /// [`PickerState::handle_key`] for a picker with a query line, tabs,
227 /// filtered rows or disabled rows: it asks `picker` how many rows are
228 /// shown, which are disabled, and whether a query is being typed.
229 ///
230 /// Rows are the *shown* rows: with a filter, `Chose(n)` is the `n`th
231 /// match, and [`Picker::item_index`] gives the item it stands for.
232 ///
233 /// Keys, with a query line (typing): `↑`/`↓`, `PgUp`/`PgDn`, `Enter`,
234 /// `Esc`, `Tab`/`Shift+Tab` (tabs) and `Ctrl+Space` (toggle) are the
235 /// picker's; every other key press is [`PickerOutcome::Query`], for the
236 /// host's text editor, so letters, `Space`, `Backspace`, `←`/`→`,
237 /// `Home` and `End` are never eaten. Without a query line, `Home`/`End`
238 /// and `←`/`→` (tabs) also move, and `Space` toggles. Navigation skips
239 /// disabled rows, and `Enter`/`Space` on one are ignored. `Esc` cancels
240 /// even with nothing shown. Held keys repeat editing/navigation only;
241 /// modified activation/navigation and releases are ignored.
242 ///
243 /// When the query or the tab changes, rebuild the [`PickerMatches`] and
244 /// [`PickerState::reset`] (a tab change resets for you).
245 pub fn handle_picker_key(
246 &mut self,
247 key: KeyEvent,
248 picker: &Picker<'_>,
249 rows: u16,
250 ) -> PickerOutcome {
251 if key.kind == KeyEventKind::Release {
252 return PickerOutcome::Ignored;
253 }
254 let allowed_modifiers = match key.code {
255 KeyCode::Tab | KeyCode::BackTab => {
256 key.modifiers.is_empty() || key.modifiers == KeyModifiers::SHIFT
257 }
258 KeyCode::Char(' ') => {
259 key.modifiers.is_empty() || key.modifiers == KeyModifiers::CONTROL
260 }
261 KeyCode::Enter
262 | KeyCode::Esc
263 | KeyCode::Up
264 | KeyCode::Down
265 | KeyCode::PageUp
266 | KeyCode::PageDown => key.modifiers.is_empty(),
267 _ => true,
268 };
269 if !allowed_modifiers {
270 return PickerOutcome::Ignored;
271 }
272 let len = picker.shown_len();
273 let typing = picker.query.is_some();
274 if key.kind == KeyEventKind::Repeat
275 && (matches!(key.code, KeyCode::Enter | KeyCode::Esc)
276 || (key.code == KeyCode::Char(' ')
277 && (!typing || key.modifiers == KeyModifiers::CONTROL)))
278 {
279 return PickerOutcome::Ignored;
280 }
281 let enabled = |i: usize| {
282 picker
283 .shown_item(i)
284 .is_none_or(|(item, _)| item.disabled.is_none())
285 };
286 let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
287 let tabs = picker.tabs.map_or(0, |t| t.labels.len());
288 let tab = |forward: bool, state: &mut Self| {
289 let active = picker
290 .tabs
291 .map_or(0, |t| t.active.min(tabs.saturating_sub(1)));
292 let next = if forward {
293 (active + 1) % tabs
294 } else {
295 (active + tabs - 1) % tabs
296 };
297 state.reset();
298 PickerOutcome::Tab(next)
299 };
300 if len > 0 {
301 self.selected = self.selected.min(len - 1);
302 }
303 let page = usize::from(rows.max(1));
304 match key.code {
305 KeyCode::Esc => return PickerOutcome::Cancelled,
306 KeyCode::Tab | KeyCode::BackTab if tabs > 1 => {
307 let back =
308 key.code == KeyCode::BackTab || key.modifiers.contains(KeyModifiers::SHIFT);
309 return tab(!back, self);
310 }
311 // No tabs to change: Tab is the host's (focus), never the query's.
312 KeyCode::Tab | KeyCode::BackTab => return PickerOutcome::Ignored,
313 KeyCode::Left | KeyCode::Right if !typing && tabs > 1 => {
314 if !key.modifiers.is_empty() {
315 return PickerOutcome::Ignored;
316 }
317 return tab(key.code == KeyCode::Right, self);
318 }
319 KeyCode::Enter => {
320 return if len > 0 && enabled(self.selected) {
321 PickerOutcome::Chose(self.selected)
322 } else {
323 PickerOutcome::Ignored
324 };
325 }
326 KeyCode::Char(' ') if ctrl || !typing => {
327 return if len > 0 && enabled(self.selected) {
328 PickerOutcome::Toggled(self.selected)
329 } else {
330 PickerOutcome::Ignored
331 };
332 }
333 KeyCode::Up | KeyCode::Down | KeyCode::PageUp | KeyCode::PageDown if len > 0 => {
334 self.selected = match key.code {
335 KeyCode::Up => step_to(self.selected, len, false, enabled),
336 KeyCode::Down => step_to(self.selected, len, true, enabled),
337 KeyCode::PageUp => {
338 settle_at(self.selected.saturating_sub(page), len, false, enabled)
339 }
340 _ => settle_at((self.selected + page).min(len - 1), len, true, enabled),
341 };
342 }
343 KeyCode::Home if !typing && len > 0 && key.modifiers.is_empty() => {
344 self.selected = settle_at(0, len, true, enabled)
345 }
346 KeyCode::End if !typing && len > 0 && key.modifiers.is_empty() => {
347 self.selected = settle_at(len - 1, len, false, enabled);
348 }
349 _ => {
350 return if typing && !matches!(key.code, KeyCode::Up | KeyCode::Down) {
351 PickerOutcome::Query
352 } else {
353 PickerOutcome::Ignored
354 };
355 }
356 }
357 self.scroll_into_view(len, rows);
358 PickerOutcome::Moved
359 }
360 }
361
362 /// The words a [`Picker`] shows itself. The kit owns no copy beyond this
363 /// English default: a host fills one per locale and passes it with
364 /// [`Picker::words`].
365 #[derive(Clone, Debug, PartialEq, Eq)]
366 pub struct PickerWords {
367 /// The query line while it is empty.
368 pub placeholder: Cow<'static, str>,
369 /// Before the quoted query when nothing matches: `No matches for "x"`.
370 pub no_matches: Cow<'static, str>,
371 /// The one next step when nothing matches.
372 pub no_matches_action: Cow<'static, str>,
373 /// When there is nothing to choose from at all.
374 pub empty: Cow<'static, str>,
375 }
376
377 static ENGLISH: PickerWords = PickerWords {
378 placeholder: Cow::Borrowed("Type to filter"),
379 no_matches: Cow::Borrowed("No matches for"),
380 no_matches_action: Cow::Borrowed("Edit the search to see more"),
381 empty: Cow::Borrowed("Nothing to choose from"),
382 };
383
384 impl Default for PickerWords {
385 fn default() -> Self {
386 ENGLISH.clone()
387 }
388 }
389
390 /// The query line's text and where the cursor is. The caller owns editing:
391 /// it passes what the line holds, the picker paints it and filters nothing
392 /// by itself (see [`PickerMatches::rank`]).
393 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
394 pub struct PickerQuery<'a> {
395 pub text: &'a str,
396 /// The cursor's column in display cells from the start of `text`.
397 pub cursor: usize,
398 }
399
400 impl<'a> PickerQuery<'a> {
401 #[must_use]
402 pub const fn new(text: &'a str, cursor: usize) -> Self {
403 Self { text, cursor }
404 }
405 }
406
407 /// Categories across the top. Each item belongs to one tab (or to every
408 /// tab); `Tab` and `Shift+Tab` (`←`/`→` without a query line) move between
409 /// them through [`PickerOutcome::Tab`].
410 #[derive(Clone, Copy, Debug)]
411 pub struct PickerTabs<'a> {
412 pub labels: &'a [Cow<'static, str>],
413 pub active: usize,
414 /// The tab each item belongs to, by item index; `None`, or an index past
415 /// the end, puts the item in every tab.
416 pub of: &'a [Option<usize>],
417 /// A tab that shows every item (an "All" tab), if there is one.
418 pub all: Option<usize>,
419 /// Optional per-tab match counts, shown beside each tab label.
420 pub counts: Option<&'a [usize]>,
421 }
422
423 impl<'a> PickerTabs<'a> {
424 #[must_use]
425 pub const fn new(labels: &'a [Cow<'static, str>], active: usize) -> Self {
426 Self {
427 labels,
428 active,
429 of: &[],
430 all: None,
431 counts: None,
432 }
433 }
434
435 /// Which tab each item belongs to.
436 #[must_use]
437 pub const fn assign(mut self, of: &'a [Option<usize>]) -> Self {
438 self.of = of;
439 self
440 }
441
442 /// The tab that shows every item.
443 #[must_use]
444 pub const fn all(mut self, index: usize) -> Self {
445 self.all = Some(index);
446 self
447 }
448
449 /// Per-tab match counts shown beside each tab label. Tabs with a count of
450 /// zero recede while a search query is active.
451 #[must_use]
452 pub const fn counts(mut self, counts: &'a [usize]) -> Self {
453 self.counts = Some(counts);
454 self
455 }
456
457 fn shows(&self, item: usize) -> bool {
458 self.all == Some(self.active)
459 || self
460 .of
461 .get(item)
462 .copied()
463 .flatten()
464 .is_none_or(|tab| tab == self.active)
465 }
466 }
467
468 /// A caller-painted pane beside the list: what the highlighted item is.
469 /// Paint into `area` through `theme`; `item` is the highlighted item and
470 /// `index` its place in the picker's `items`. Any
471 /// `Fn(Rect, &mut Buffer, &Theme, &PickerItem, usize)` is one.
472 pub trait PickerPreview {
473 fn paint_preview(
474 &self,
475 area: Rect,
476 buf: &mut Buffer,
477 theme: &Theme,
478 item: &PickerItem,
479 index: usize,
480 );
481 }
482
483 impl<F> PickerPreview for F
484 where
485 F: Fn(Rect, &mut Buffer, &Theme, &PickerItem, usize),
486 {
487 fn paint_preview(
488 &self,
489 area: Rect,
490 buf: &mut Buffer,
491 theme: &Theme,
492 item: &PickerItem,
493 index: usize,
494 ) {
495 self(area, buf, theme, item, index);
496 }
497 }
498
499 /// One item that passed the filter.
500 #[derive(Clone, Debug, PartialEq, Eq)]
501 pub struct PickerMatch {
502 /// The item's index in the picker's `items`.
503 pub index: usize,
504 pub score: i32,
505 /// `char` indices of the query in the item's display-safe label, to
506 /// highlight; empty when the query matched the detail instead, or there
507 /// is no query.
508 pub positions: Vec<usize>,
509 }
510
511 /// A detail match ranks below every label match.
512 const DETAIL_PENALTY: i32 = 10_000;
513
514 /// The items a picker shows: the ones in the active tab that match the
515 /// query, best first. Build it when the query or the tab changes, keep it
516 /// across frames, and hand it to [`Picker::matches`] and to
517 /// [`PickerState::handle_picker_key`] (through the picker).
518 #[derive(Clone, Debug, Default, PartialEq, Eq)]
519 pub struct PickerMatches {
520 rows: Vec<PickerMatch>,
521 }
522
523 impl PickerMatches {
524 /// Filter and rank `items` by `query` (a fuzzy subsequence match on the
525 /// label, then on the detail), keeping the active tab's items. An empty
526 /// query keeps every item of the tab in its original order.
527 #[must_use]
528 pub fn rank(items: &[PickerItem], query: &str, tabs: Option<&PickerTabs<'_>>) -> Self {
529 let mut rows: Vec<PickerMatch> = items
530 .iter()
531 .enumerate()
532 .filter(|(index, _)| tabs.is_none_or(|t| t.shows(*index)))
533 .filter_map(|(index, item)| {
534 let label = text::display_safe(&item.label);
535 if let Some(m) = fuzzy_score(query, &label) {
536 return Some(PickerMatch {
537 index,
538 score: m.score,
539 positions: m.positions,
540 });
541 }
542 let detail = text::display_safe(item.detail.as_deref()?);
543 fuzzy_score(query, &detail).map(|m| PickerMatch {
544 index,
545 score: m.score - DETAIL_PENALTY,
546 positions: Vec::new(),
547 })
548 })
549 .collect();
550 rows.sort_by_key(|m| (std::cmp::Reverse(m.score), m.index));
551 Self { rows }
552 }
553
554 #[must_use]
555 pub fn len(&self) -> usize {
556 self.rows.len()
557 }
558
559 #[must_use]
560 pub fn is_empty(&self) -> bool {
561 self.rows.is_empty()
562 }
563
564 /// The `shown`th match.
565 #[must_use]
566 pub fn get(&self, shown: usize) -> Option<&PickerMatch> {
567 self.rows.get(shown)
568 }
569
570 pub fn iter(&self) -> impl Iterator<Item = &PickerMatch> {
571 self.rows.iter()
572 }
573 }
574
575 /// The narrowest picker that shows its preview pane; below this the pane is
576 /// left out and the list takes the width.
577 pub const PICKER_PREVIEW_MIN_WIDTH: u16 = 56;
578 /// The narrowest the preview pane is drawn, and the narrowest list beside it.
579 const PREVIEW_MIN: u16 = 20;
580
581 /// Where a [`Picker`] puts its parts in an area.
582 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
583 pub struct PickerLayout {
584 pub tabs: Option<Rect>,
585 pub query: Option<Rect>,
586 pub list: Rect,
587 /// The rule between the list and the preview, one column wide.
588 pub separator: Option<Rect>,
589 pub preview: Option<Rect>,
590 }
591
592 /// Spans plus the cells they cover.
593 #[derive(Default)]
594 struct Row {
595 spans: Vec<Span<'static>>,
596 used: usize,
597 }
598
599 impl Row {
600 fn push(&mut self, s: String, style: Style) {
601 self.used += text::width(&s);
602 self.spans.push(Span::styled(s, style));
603 }
604 }
605
606 /// `label` cut to `width` cells and padded, as runs that are or are not on a
607 /// matched position. Cuts and pads exactly as [`text::pad`] does.
608 fn label_runs(
609 label: &str,
610 positions: &[usize],
611 width: usize,
612 ascii: bool,
613 base: Style,
614 hit: Style,
615 ) -> Vec<(String, Style)> {
616 let fitted = text::truncate(label, width, ascii);
617 // The ellipsis a cut adds is not part of the label.
618 let common = fitted
619 .chars()
620 .zip(label.chars())
621 .take_while(|(a, b)| a == b)
622 .count();
623 let mut runs: Vec<(String, Style)> = Vec::new();
624 let mut at = 0;
625 for g in fitted.graphemes(true) {
626 let n = g.chars().count();
627 let hot = at < common && (at..at + n).any(|c| positions.binary_search(&c).is_ok());
628 at += n;
629 let style = if hot { hit } else { base };
630 match runs.last_mut() {
631 Some((s, st)) if *st == style => s.push_str(g),
632 _ => runs.push((g.to_owned(), style)),
633 }
634 }
635 let gap = width.saturating_sub(text::width(&fitted));
636 if gap > 0 {
637 match runs.last_mut() {
638 Some((s, st)) if *st == base => s.push_str(&" ".repeat(gap)),
639 _ => runs.push((" ".repeat(gap), base)),
640 }
641 }
642 runs
643 }
644
645 /// A list of [`PickerItem`]s, optionally with a query line, tabs, a filter
646 /// and a preview pane.
647 ///
648 /// ```text
649 /// ● All Models Themes
650 /// › shore▏ 2/17
651 /// ▸ Shoreline Graphite ground │ Shoreline
652 /// Shoreline light Paper ground │ ● Working
653 /// ```
654 ///
655 /// Alone it is the plain list it always was. Add pieces as the picker needs
656 /// them: [`Picker::query`] (the caller edits the text, the picker paints it
657 /// and highlights the match), [`Picker::matches`] (what [`PickerMatches`]
658 /// kept), [`Picker::tabs`], [`Picker::preview`] (beside the list at
659 /// [`PICKER_PREVIEW_MIN_WIDTH`] columns and up, dropped below) and
660 /// [`Picker::words`].
661 ///
662 /// Ratatui's stateful adapter persists selection and the viewport offset in
663 /// your own [`PickerState`], overriding the constructor's state snapshot:
664 ///
665 /// ```no_run
666 /// use codewhale_ratatui::{Paint, Picker, PickerItem, PickerState, Theme};
667 /// # fn draw(frame: &mut ratatui::Frame<'_>, state: &mut PickerState) {
668 /// let theme = Theme::detect().tui();
669 /// let items = [PickerItem::new("Underwater"), PickerItem::new("Dracula")];
670 /// let picker = Picker::new(&items, PickerState::default()).query("", 0);
671 /// frame.render_stateful_widget(picker.themed(&theme), frame.area(), state);
672 /// # }
673 /// ```
674 #[derive(Clone, Copy)]
675 pub struct Picker<'a> {
676 pub items: &'a [PickerItem],
677 pub state: PickerState,
678 query: Option<PickerQuery<'a>>,
679 tabs: Option<PickerTabs<'a>>,
680 matches: Option<&'a PickerMatches>,
681 preview: Option<&'a dyn PickerPreview>,
682 preview_min: u16,
683 words: Option<&'a PickerWords>,
684 clear_hint: Option<&'a str>,
685 }
686
687 impl std::fmt::Debug for Picker<'_> {
688 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
689 f.debug_struct("Picker")
690 .field("items", &self.items)
691 .field("state", &self.state)
692 .field("query", &self.query)
693 .field("tabs", &self.tabs)
694 .field("matches", &self.matches)
695 .field("preview", &self.preview.is_some())
696 .finish_non_exhaustive()
697 }
698 }
699
700 impl<'a> Picker<'a> {
701 #[must_use]
702 pub const fn new(items: &'a [PickerItem], state: PickerState) -> Self {
703 Self {
704 items,
705 state,
706 query: None,
707 tabs: None,
708 matches: None,
709 preview: None,
710 preview_min: PICKER_PREVIEW_MIN_WIDTH,
711 words: None,
712 clear_hint: None,
713 }
714 }
715
716 /// Show a query line holding `text` with the cursor at `cursor` (display
717 /// cells from the start). The caller edits; filtering is
718 /// [`PickerMatches::rank`].
719 #[must_use]
720 pub const fn query(mut self, text: &'a str, cursor: usize) -> Self {
721 self.query = Some(PickerQuery::new(text, cursor));
722 self
723 }
724
725 /// Show a right-aligned `Esc clear` hint on the query line when `query` is
726 /// non-empty and width permits.
727 #[must_use]
728 pub const fn show_clear_hint(mut self, show: bool) -> Self {
729 self.clear_hint = if show { Some("Esc clear") } else { None };
730 self
731 }
732
733 /// Show a custom right-aligned clear hint on the query line when `query`
734 /// is non-empty and width permits.
735 #[must_use]
736 pub const fn clear_hint(mut self, hint: &'a str) -> Self {
737 self.clear_hint = if hint.is_empty() { None } else { Some(hint) };
738 self
739 }
740
741 /// Show tabs across the top.
742 #[must_use]
743 pub const fn tabs(mut self, tabs: PickerTabs<'a>) -> Self {
744 self.tabs = Some(tabs);
745 self
746 }
747
748 /// Show only these items, in this order, with their matches highlighted.
749 /// Selection and scrolling then index the matches.
750 #[must_use]
751 pub const fn matches(mut self, matches: &'a PickerMatches) -> Self {
752 self.matches = Some(matches);
753 self
754 }
755
756 /// Show a pane beside the list for the highlighted item.
757 #[must_use]
758 pub const fn preview(mut self, preview: &'a dyn PickerPreview) -> Self {
759 self.preview = Some(preview);
760 self
761 }
762
763 /// The width from which the preview pane shows (default
764 /// [`PICKER_PREVIEW_MIN_WIDTH`]).
765 #[must_use]
766 pub const fn preview_min_width(mut self, width: u16) -> Self {
767 self.preview_min = width;
768 self
769 }
770
771 /// Words for the placeholder and the empty states (default English).
772 #[must_use]
773 pub const fn words(mut self, words: &'a PickerWords) -> Self {
774 self.words = Some(words);
775 self
776 }
777
778 fn words_or_default(&self) -> &PickerWords {
779 self.words.unwrap_or(&ENGLISH)
780 }
781
782 /// How many rows are shown: the matches, or every item.
783 #[must_use]
784 pub fn shown_len(&self) -> usize {
785 self.matches.map_or(self.items.len(), PickerMatches::len)
786 }
787
788 /// The index in `items` of the `shown`th row.
789 #[must_use]
790 pub fn item_index(&self, shown: usize) -> Option<usize> {
791 match self.matches {
792 Some(m) => m.get(shown).map(|m| m.index),
793 None => (shown < self.items.len()).then_some(shown),
794 }
795 }
796
797 /// The `shown`th row's item and the label positions to highlight.
798 fn shown_item(&self, shown: usize) -> Option<(&'a PickerItem, &'a [usize])> {
799 match self.matches {
800 Some(m) => {
801 let m = m.get(shown)?;
802 Some((self.items.get(m.index)?, m.positions.as_slice()))
803 }
804 None => Some((self.items.get(shown)?, &[])),
805 }
806 }
807
808 /// Where the parts go in `area`.
809 #[must_use]
810 pub fn layout(&self, area: Rect) -> PickerLayout {
811 let tabs = self.tabs.is_some_and(|t| !t.labels.is_empty());
812 let query = self.query.is_some();
813 // A row for the list outranks the tabs, and the tabs the query.
814 let (tabs, query) = if area.height > u16::from(tabs) + u16::from(query) {
815 (tabs, query)
816 } else if area.height > u16::from(query) {
817 (false, query)
818 } else {
819 (false, false)
820 };
821 let mut y = area.y;
822 let mut row = |wanted: bool| {
823 wanted.then(|| {
824 let r = Rect {
825 y,
826 height: 1,
827 ..area
828 };
829 y += 1;
830 r
831 })
832 };
833 let tabs = row(tabs);
834 let query = row(query);
835 let body = Rect {
836 y,
837 height: area.bottom().saturating_sub(y),
838 ..area
839 };
840 let pane =
841 (self.preview.is_some() && self.shown_len() > 0 && body.width >= self.preview_min)
842 .then(|| {
843 let pane = (body.width * 2 / 5).max(PREVIEW_MIN);
844 (body.width.saturating_sub(pane + 3), pane)
845 })
846 .filter(|&(list, _)| list >= PREVIEW_MIN);
847 match pane {
848 Some((list_w, pane_w)) => PickerLayout {
849 tabs,
850 query,
851 list: Rect {
852 width: list_w,
853 ..body
854 },
855 separator: Some(Rect {
856 x: body.x + list_w + 1,
857 width: 1,
858 ..body
859 }),
860 preview: Some(Rect {
861 x: body.x + list_w + 3,
862 width: pane_w,
863 ..body
864 }),
865 },
866 None => PickerLayout {
867 tabs,
868 query,
869 list: body,
870 separator: None,
871 preview: None,
872 },
873 }
874 }
875
876 /// How many rows the list shows in `area`: what to pass
877 /// [`PickerState::handle_picker_key`].
878 #[must_use]
879 pub fn list_rows(&self, area: Rect) -> u16 {
880 self.layout(area).list.height
881 }
882
883 /// Where the terminal cursor belongs when the query line has focus, for
884 /// `Frame::set_cursor_position`. It follows the text when a long query
885 /// is cut to its end.
886 #[must_use]
887 pub fn cursor(&self, area: Rect) -> Option<ratatui::layout::Position> {
888 let rect = self.layout(area).query?;
889 let view = self.query_view(self.query?, rect.width, false)?;
890 let col = u16::try_from(view.cursor).unwrap_or(u16::MAX);
891 Some(ratatui::layout::Position::new(
892 (rect.x + QUERY_INDENT)
893 .saturating_add(col)
894 .min(rect.right().saturating_sub(1)),
895 rect.y,
896 ))
897 }
898
899 /// The shown row under a click at `(column, row)` when the picker was
900 /// painted in `area`, for hosts that take mouse input. Without a filter
901 /// that is the item's index; otherwise pass it to
902 /// [`Picker::item_index`].
903 #[must_use]
904 pub fn row_at(&self, area: Rect, column: u16, row: u16) -> Option<usize> {
905 let list = self.layout(area).list;
906 let shown = self.shown_len();
907 let inside =
908 column >= list.x && column < list.right() && row >= list.y && row < list.bottom();
909 let reserved = if shown > usize::from(list.height) && list.width > 2 {
910 2
911 } else {
912 0
913 };
914 if !inside || column >= list.right().saturating_sub(reserved) {
915 return None;
916 }
917 let offset = self.state.visible_offset(shown, usize::from(list.height));
918 let index = offset + usize::from(row - list.y);
919 (index < shown).then_some(index)
920 }
921
922 fn label_column(&self) -> usize {
923 (0..self.shown_len())
924 .filter_map(|at| self.shown_item(at))
925 .map(|(item, _)| text::width(&text::display_safe(&item.label)))
926 .max()
927 .unwrap_or(0)
928 }
929
930 fn row(
931 &self,
932 selected: bool,
933 item: &PickerItem,
934 positions: &[usize],
935 width: usize,
936 label_col: usize,
937 theme: &Theme,
938 ) -> Line<'static> {
939 let ascii = theme.ascii();
940 let disabled = item.disabled.is_some();
941
942 let mut row = Row::default();
943
944 let marker = glyphs::pick(glyphs::selection_marker(selected), ascii);
945 row.push(format!("{marker} "), theme.fg(Role::Accent));
946 if let Some(key) = item.key {
947 row.push(format!("{key} "), theme.fg(Role::Muted));
948 }
949 if let Some(checked) = item.checked {
950 let (mark, role) = match (checked, ascii) {
951 (true, false) => (glyphs::CURRENT, Role::Foreground),
952 (false, false) => (glyphs::AVAILABLE, Role::Muted),
953 (true, true) => ("[x]", Role::Foreground),
954 (false, true) => ("[ ]", Role::Muted),
955 };
956 row.push(format!("{mark} "), theme.fg(role));
957 }
958
959 let label_style = if disabled {
960 theme.fg(Role::Muted).add_modifier(Modifier::DIM)
961 } else if selected {
962 theme.fg(Role::Foreground).add_modifier(Modifier::BOLD)
963 } else {
964 theme.fg(Role::Foreground)
965 };
966 let label = text::display_safe(&item.label);
967 let label_w = label_col.min(width.saturating_sub(row.used));
968 if positions.is_empty() {
969 row.push(text::pad(&label, label_w, ascii), label_style);
970 } else {
971 // Matched characters are underlined as well as colored, so the
972 // match shows without color.
973 let hit = if disabled {
974 label_style.add_modifier(Modifier::UNDERLINED)
975 } else {
976 label_style
977 .patch(theme.fg(Role::Accent))
978 .add_modifier(Modifier::UNDERLINED)
979 };
980 for (run, style) in label_runs(&label, positions, label_w, ascii, label_style, hit) {
981 row.push(run, style);
982 }
983 }
984
985 let detail = item.disabled.as_ref().or(item.detail.as_ref());
986 if let Some(detail) = detail {
987 let room = width.saturating_sub(row.used + 2);
988 if room >= 4 {
989 let detail = text::display_safe(detail);
990 row.push(" ".into(), theme.fg(Role::Muted));
991 row.push(
992 text::truncate_words(&detail, room, ascii).into_owned(),
993 theme.fg(Role::Muted),
994 );
995 }
996 }
997
998 let spans = row.spans;
999 let mut line = Line::from(spans);
1000 if selected {
1001 line = line.style(theme.bg(Role::Selected));
1002 }
1003 line
1004 }
1005
1006 fn paint_rows(&self, list: Rect, buf: &mut Buffer, theme: &Theme) {
1007 let shown = self.shown_len();
1008 let rows = usize::from(list.height);
1009 let overflow = shown > rows;
1010 // The scrollbar takes the last column and keeps one cell of air.
1011 let body = Rect {
1012 width: list
1013 .width
1014 .saturating_sub(2 * u16::from(overflow && list.width > 2)),
1015 ..list
1016 };
1017 let offset = self.state.visible_offset(shown, rows);
1018 let selected = self.state.selected.min(shown.saturating_sub(1));
1019 let label_col = self.label_column();
1020 for (row, at) in (offset..shown).take(rows).enumerate() {
1021 let Some((item, positions)) = self.shown_item(at) else {
1022 continue;
1023 };
1024 let rect = Rect {
1025 y: body.y + row as u16,
1026 height: 1,
1027 ..body
1028 };
1029 if at == selected {
1030 buf.set_style(rect, theme.bg(Role::Selected));
1031 }
1032 self.row(
1033 at == selected,
1034 item,
1035 positions,
1036 usize::from(body.width),
1037 label_col,
1038 theme,
1039 )
1040 .render(rect, buf);
1041 }
1042 if overflow && list.width > 2 {
1043 paint_scrollbar(list, buf, theme, shown, offset, rows);
1044 }
1045 }
1046
1047 fn paint_empty(&self, list: Rect, buf: &mut Buffer, theme: &Theme) {
1048 let words = self.words_or_default();
1049 let query = self
1050 .query
1051 .map(|q| text::display_safe(q.text).trim().to_owned())
1052 .unwrap_or_default();
1053 let empty = if query.is_empty() {
1054 EmptyState::new(words.empty.as_ref())
1055 } else {
1056 let (open, close) = if theme.ascii() {
1057 ("\"", "\"")
1058 } else {
1059 ("\u{201c}", "\u{201d}")
1060 };
1061 let query = text::truncate(&query, 24, theme.ascii());
1062 EmptyState::new(format!("{} {open}{query}{close}", words.no_matches))
1063 .action(words.no_matches_action.as_ref())
1064 };
1065 empty.paint(list, buf, theme);
1066 }
1067
1068 fn paint_tabs(&self, tabs: PickerTabs<'_>, rect: Rect, buf: &mut Buffer, theme: &Theme) {
1069 const GAP: usize = 2;
1070 let ascii = theme.ascii();
1071 let n = tabs.labels.len();
1072 if n == 0 {
1073 return;
1074 }
1075 let active = tabs.active.min(n - 1);
1076 let mark = glyphs::pick(glyphs::CURRENT, ascii);
1077 let searching = self
1078 .query
1079 .is_some_and(|q| !text::display_safe(q.text).trim().is_empty());
1080 let labels: Vec<(String, Option<usize>)> = tabs
1081 .labels
1082 .iter()
1083 .enumerate()
1084 .map(|(i, l)| {
1085 let safe = text::display_safe(l);
1086 let count = tabs.counts.and_then(|c| c.get(i).copied());
1087 let text = match count {
1088 Some(n) => format!("{safe} ({n})"),
1089 None => safe.into_owned(),
1090 };
1091 (text, count)
1092 })
1093 .collect();
1094 let cost = |i: usize| {
1095 text::width(&labels[i].0)
1096 + if i == active {
1097 text::width(mark) + 1
1098 } else {
1099 0
1100 }
1101 };
1102 let room = usize::from(rect.width);
1103 // Cells the `…` on a hidden side takes, with its space.
1104 let more = |lo: usize, hi: usize| 2 * usize::from(lo > 0) + 2 * usize::from(hi + 1 < n);
1105 let (mut lo, mut hi) = (active, active);
1106 let mut used = cost(active);
1107 loop {
1108 if hi + 1 < n && used + GAP + cost(hi + 1) + more(lo, hi + 1) <= room {
1109 used += GAP + cost(hi + 1);
1110 hi += 1;
1111 } else if lo > 0 && used + GAP + cost(lo - 1) + more(lo - 1, hi) <= room {
1112 used += GAP + cost(lo - 1);
1113 lo -= 1;
1114 } else {
1115 break;
1116 }
1117 }
1118 let mut spans: Vec<Span<'static>> = Vec::new();
1119 let ellipsis = glyphs::pick(glyphs::ELLIPSIS, ascii);
1120 if lo > 0 {
1121 spans.push(Span::styled(format!("{ellipsis} "), theme.fg(Role::Hint)));
1122 }
1123 for (i, (label, count)) in labels.iter().enumerate().take(hi + 1).skip(lo) {
1124 if i > lo {
1125 spans.push(Span::raw(" ".repeat(GAP)));
1126 }
1127 if i == active {
1128 spans.push(Span::styled(format!("{mark} "), theme.fg(Role::Accent)));
1129 let room = room.saturating_sub(text::width(mark) + 1);
1130 spans.push(Span::styled(
1131 text::truncate(label, room, ascii).into_owned(),
1132 theme.fg(Role::Foreground).add_modifier(Modifier::BOLD),
1133 ));
1134 } else {
1135 let mut style = theme.fg(Role::Muted);
1136 if searching && *count == Some(0) {
1137 style = style.add_modifier(Modifier::DIM);
1138 }
1139 spans.push(Span::styled(label.clone(), style));
1140 }
1141 }
1142 if hi + 1 < n {
1143 spans.push(Span::styled(format!(" {ellipsis}"), theme.fg(Role::Hint)));
1144 }
1145 Line::from(spans).render(rect, buf);
1146 }
1147
1148 /// What the query line shows in `width` cells: the text (or the
1149 /// placeholder), the cursor's column in it, and the count at the right.
1150 fn query_view(&self, query: PickerQuery<'_>, width: u16, ascii: bool) -> Option<QueryView> {
1151 let room = usize::from(width.checked_sub(QUERY_INDENT)?);
1152 let typed = text::display_safe(query.text);
1153
1154 let count_only = (!typed.is_empty() && self.shown_len() > 0)
1155 .then(|| format!("{}/{}", self.shown_len(), self.items.len()));
1156 let clear = (!typed.is_empty())
1157 .then_some(self.clear_hint)
1158 .flatten()
1159 .map(|h| text::display_safe(h).into_owned())
1160 .filter(|h| !h.is_empty());
1161 let sep = if ascii { " " } else { " · " };
1162 let count = match (count_only, clear) {
1163 (Some(c), Some(h)) => {
1164 let combined = format!("{c}{sep}{h}");
1165 if text::width(&combined) + 2 < room {
1166 Some(combined)
1167 } else if text::width(&c) + 2 < room {
1168 Some(c)
1169 } else {
1170 None
1171 }
1172 }
1173 (Some(c), None) => (text::width(&c) + 2 < room).then_some(c),
1174 (None, Some(h)) => (text::width(&h) + 2 < room).then_some(h),
1175 (None, None) => None,
1176 };
1177 let room = room.saturating_sub(count.as_ref().map_or(0, |c| text::width(c) + 2));
1178
1179 let mut cursor = query.cursor.min(text::width(&typed));
1180 let (shown, hint) = if typed.is_empty() {
1181 let words = self.words_or_default();
1182 (
1183 text::truncate(&words.placeholder, room, ascii).into_owned(),
1184 true,
1185 )
1186 } else if text::width(&typed) <= room {
1187 (typed.into_owned(), false)
1188 } else {
1189 // Keep the end, where the cursor usually is.
1190 let ellipsis = glyphs::pick(glyphs::ELLIPSIS, ascii);
1191 let budget = room.saturating_sub(text::width(ellipsis));
1192 let mut tail: Vec<&str> = Vec::new();
1193 let mut used = 0;
1194 for g in typed.graphemes(true).rev() {
1195 let w = text::width(g);
1196 if used + w > budget {
1197 break;
1198 }
1199 used += w;
1200 tail.push(g);
1201 }
1202 tail.reverse();
1203 let skipped = text::width(&typed) - used;
1204 cursor = cursor.saturating_sub(skipped) + text::width(ellipsis);
1205 (format!("{ellipsis}{}", tail.concat()), false)
1206 };
1207 Some(QueryView {
1208 shown,
1209 hint,
1210 cursor,
1211 room,
1212 count,
1213 })
1214 }
1215
1216 fn paint_query(&self, query: PickerQuery<'_>, rect: Rect, buf: &mut Buffer, theme: &Theme) {
1217 let ascii = theme.ascii();
1218 // `/` where ASCII-safe: `>` would read as the selection marker below.
1219 let prompt = if ascii { "/" } else { "\u{203a}" };
1220 buf.set_string(rect.x, rect.y, prompt, theme.fg(Role::Accent));
1221 let Some(view) = self.query_view(query, rect.width, ascii) else {
1222 return;
1223 };
1224 let x0 = rect.x + QUERY_INDENT;
1225 let style = if view.hint {
1226 theme.fg(Role::Hint)
1227 } else {
1228 theme.fg(Role::Foreground)
1229 };
1230 buf.set_stringn(x0, rect.y, &view.shown, view.room, style);
1231 if let Some(count) = &view.count {
1232 let x = rect
1233 .right()
1234 .saturating_sub(u16::try_from(text::width(count)).unwrap_or(0));
1235 buf.set_string(x, rect.y, count, theme.fg(Role::Hint));
1236 }
1237 // A reversed cell at the cursor shows it in every profile.
1238 if let Ok(col) = u16::try_from(view.cursor)
1239 && view.cursor <= view.room
1240 {
1241 let at = x0 + col;
1242 if at < rect.right() {
1243 buf[(at, rect.y)].modifier.insert(Modifier::REVERSED);
1244 }
1245 }
1246 }
1247 }
1248
1249 /// The query line as it is painted.
1250 struct QueryView {
1251 shown: String,
1252 /// `shown` is the placeholder.
1253 hint: bool,
1254 /// The cursor's column in `shown`.
1255 cursor: usize,
1256 /// Cells left for `shown`, before the count.
1257 room: usize,
1258 count: Option<String>,
1259 }
1260
1261 /// The query line's text starts after `› `.
1262 const QUERY_INDENT: u16 = 2;
1263
1264 impl Paint for Picker<'_> {
1265 fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
1266 let area = area.intersection(buf.area);
1267 if area.is_empty() {
1268 return;
1269 }
1270 let layout = self.layout(area);
1271 if let (Some(rect), Some(tabs)) = (layout.tabs, self.tabs) {
1272 self.paint_tabs(tabs, rect, buf, theme);
1273 }
1274 if let (Some(rect), Some(query)) = (layout.query, self.query) {
1275 self.paint_query(query, rect, buf, theme);
1276 }
1277 if layout.list.is_empty() {
1278 return;
1279 }
1280 let shown = self.shown_len();
1281 if shown == 0 {
1282 self.paint_empty(layout.list, buf, theme);
1283 return;
1284 }
1285 self.paint_rows(layout.list, buf, theme);
1286 if let (Some(rule), Some(pane), Some(preview)) =
1287 (layout.separator, layout.preview, self.preview)
1288 {
1289 let bar = glyphs::pick("\u{2502}", theme.ascii());
1290 for y in rule.y..rule.bottom() {
1291 buf.set_string(rule.x, y, bar, theme.fg(Role::Border));
1292 }
1293 let at = self.state.selected.min(shown - 1);
1294 if let (Some((item, _)), Some(index)) = (self.shown_item(at), self.item_index(at)) {
1295 preview.paint_preview(pane, buf, theme, item, index);
1296 }
1297 }
1298 }
1299
1300 fn height(&self, _width: u16, _theme: &Theme) -> u16 {
1301 let head = u16::from(self.tabs.is_some_and(|t| !t.labels.is_empty()))
1302 + u16::from(self.query.is_some());
1303 let body = match self.shown_len() {
1304 0 => 3,
1305 n => u16::try_from(n).unwrap_or(u16::MAX),
1306 };
1307 head.saturating_add(body)
1308 }
1309 }
1310
1311 /// Render with persistent host state instead of the constructor's snapshot.
1312 /// Query rows, tabs and clipping are included in the stored scroll offset.
1313 impl ratatui::widgets::StatefulWidget for crate::Themed<'_, Picker<'_>> {
1314 type State = PickerState;
1315 fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
1316 ratatui::widgets::StatefulWidget::render(&self, area, buf, state);
1317 }
1318 }
1319
1320 impl ratatui::widgets::StatefulWidget for &crate::Themed<'_, Picker<'_>> {
1321 type State = PickerState;
1322 fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
1323 let area = area.intersection(buf.area);
1324 if area.is_empty() {
1325 return;
1326 }
1327 let mut view = Picker {
1328 items: self.component.items,
1329 state: *state,
1330 query: self.component.query,
1331 tabs: self.component.tabs,
1332 matches: self.component.matches,
1333 preview: self.component.preview,
1334 preview_min: self.component.preview_min,
1335 words: self.component.words,
1336 clear_hint: self.component.clear_hint,
1337 };
1338 let viewport = view.layout(area).list;
1339 if !viewport.is_empty() {
1340 state.scroll_into_view(view.shown_len(), viewport.height);
1341 view.state = *state;
1342 }
1343 view.paint(area, buf, self.theme);
1344 }
1345 }
1346
1347 #[cfg(test)]
1348 mod tests {
1349 use super::*;
1350
1351 #[test]
1352 fn clicks_map_to_the_scrolled_row() {
1353 let items: Vec<PickerItem> = (0..10)
1354 .map(|i| PickerItem::new(format!("Item {i}")))
1355 .collect();
1356 let picker = Picker::new(&items, PickerState::new(9));
1357 let area = Rect::new(2, 3, 20, 4);
1358 assert_eq!(picker.row_at(area, 5, 3), Some(6));
1359 assert_eq!(picker.row_at(area, 5, 6), Some(9));
1360 assert_eq!(picker.row_at(area, 1, 3), None);
1361 assert_eq!(picker.row_at(area, 5, 7), None);
1362 }
1363
1364 /// A disabled row says why, in place of its detail, and recedes.
1365 #[test]
1366 fn disabled_rows_say_why() {
1367 use crate::testing::{Profile, render, text};
1368 let items = [
1369 PickerItem::new("Workspace").detail("This folder"),
1370 PickerItem::new("Git branch")
1371 .detail("Current branch")
1372 .disabled("Not a git repository"),
1373 ];
1374 let picker = Picker::new(&items, PickerState::new(0));
1375 for profile in Profile::ALL {
1376 let theme = profile.theme();
1377 let buf = render(48, 2, |area, buf| picker.paint(area, buf, &theme));
1378 let shown = text(&buf);
1379 let row = shown.lines().nth(1).unwrap_or_default();
1380 assert!(
1381 row.contains("Not a git repository"),
1382 "{}: {row}",
1383 profile.name()
1384 );
1385 assert!(!row.contains("Current branch"), "{}: {row}", profile.name());
1386 let label = row.find("Git").expect("label drawn");
1387 let cell = &buf[(u16::try_from(label).unwrap_or(0), 1)];
1388 assert!(
1389 cell.modifier.contains(Modifier::DIM),
1390 "{}: disabled label recedes",
1391 profile.name()
1392 );
1393 }
1394 }
1395
1396 #[test]
1397 fn keys_move_choose_toggle_and_cancel() {
1398 let key = |code| KeyEvent::new(code, crossterm::event::KeyModifiers::NONE);
1399 let mut s = PickerState::new(0);
1400 assert_eq!(s.handle_key(key(KeyCode::Up), 3, 2), PickerOutcome::Moved);
1401 assert_eq!(s.selected, 2, "wraps");
1402 assert_eq!(s.offset, 1, "keeps the selection in view");
1403 assert_eq!(s.handle_key(key(KeyCode::Home), 3, 2), PickerOutcome::Moved);
1404 assert_eq!(s.handle_key(key(KeyCode::Down), 3, 2), PickerOutcome::Moved);
1405 assert_eq!(
1406 s.handle_key(key(KeyCode::Enter), 3, 2),
1407 PickerOutcome::Chose(1)
1408 );
1409 assert_eq!(
1410 s.handle_key(key(KeyCode::Char(' ')), 3, 2),
1411 PickerOutcome::Toggled(1)
1412 );
1413 assert_eq!(
1414 s.handle_key(key(KeyCode::Esc), 3, 2),
1415 PickerOutcome::Cancelled
1416 );
1417 assert_eq!(
1418 s.handle_key(key(KeyCode::Char('x')), 3, 2),
1419 PickerOutcome::Ignored
1420 );
1421 let mut release = key(KeyCode::Down);
1422 release.kind = KeyEventKind::Release;
1423 assert_eq!(s.handle_key(release, 3, 2), PickerOutcome::Ignored);
1424 assert_eq!(s.selected, 1, "a release moves nothing");
1425 assert_eq!(
1426 PickerState::default().handle_key(key(KeyCode::Enter), 0, 2),
1427 PickerOutcome::Ignored,
1428 "an empty list chooses nothing"
1429 );
1430 }
1431
1432 #[test]
1433 fn state_wraps_pages_and_keeps_selection_visible() {
1434 let mut s = PickerState::new(0);
1435 s.prev(3);
1436 assert_eq!(s.selected, 2);
1437 s.next(3);
1438 assert_eq!(s.selected, 0);
1439 s.page(20, 5, true);
1440 assert_eq!(s.selected, 5);
1441 assert_eq!(s.visible_offset(20, 4), 2);
1442 s.end(20);
1443 s.scroll_into_view(20, 4);
1444 assert_eq!(s.offset, 16);
1445 s.home();
1446 assert_eq!(s.visible_offset(20, 4), 0);
1447 }
1448
1449 #[test]
1450 fn picker_tabs_counts_and_zero_match_dimming() {
1451 use crate::testing::{Profile, render, text};
1452 let labels = [
1453 Cow::Borrowed("All"),
1454 Cow::Borrowed("Dark"),
1455 Cow::Borrowed("Light"),
1456 ];
1457 let counts = [2, 0, 2];
1458 let items = [PickerItem::new("Shoreline"), PickerItem::new("Sandbar")];
1459 let tabs = PickerTabs::new(&labels, 0).counts(&counts);
1460 let picker = Picker::new(&items, PickerState::new(0))
1461 .tabs(tabs)
1462 .query("sh", 2);
1463 for profile in Profile::ALL {
1464 let theme = profile.theme();
1465 let buf = render(48, 4, |area, buf| picker.paint(area, buf, &theme));
1466 let shown = text(&buf);
1467 let row0 = shown.lines().next().unwrap_or_default();
1468 assert!(row0.contains("All (2)"), "{}: {row0}", profile.name());
1469 assert!(row0.contains("Dark (0)"), "{}: {row0}", profile.name());
1470 assert!(row0.contains("Light (2)"), "{}: {row0}", profile.name());
1471 let dark_col = row0.find("Dark").expect("Dark tab painted");
1472 assert!(
1473 buf[(u16::try_from(dark_col).unwrap_or(0), 0)]
1474 .modifier
1475 .contains(Modifier::DIM),
1476 "{}: 0-match tab dims while searching",
1477 profile.name()
1478 );
1479 }
1480 }
1481
1482 #[test]
1483 fn picker_query_shows_clear_hint_when_enabled_and_non_empty() {
1484 use crate::testing::{Profile, render, text};
1485 let items = [PickerItem::new("Shoreline"), PickerItem::new("Sandbar")];
1486 let matches = PickerMatches::rank(&items, "shore", None);
1487 for profile in Profile::ALL {
1488 let theme = profile.theme();
1489 let active = Picker::new(&items, PickerState::new(0))
1490 .query("shore", 5)
1491 .matches(&matches)
1492 .show_clear_hint(true);
1493 let buf = render(48, 3, |area, buf| active.paint(area, buf, &theme));
1494 let row0 = text(&buf).lines().next().unwrap_or_default().to_owned();
1495 assert!(row0.contains("1/2"), "{}: {row0}", profile.name());
1496 assert!(row0.contains("Esc clear"), "{}: {row0}", profile.name());
1497
1498 let empty = Picker::new(&items, PickerState::new(0))
1499 .query("", 0)
1500 .show_clear_hint(true);
1501 let empty_buf = render(48, 3, |area, buf| empty.paint(area, buf, &theme));
1502 let empty_row0 = text(&empty_buf)
1503 .lines()
1504 .next()
1505 .unwrap_or_default()
1506 .to_owned();
1507 assert!(!empty_row0.contains("Esc clear"), "{empty_row0}");
1508
1509 let narrow = render(14, 3, |area, buf| active.paint(area, buf, &theme));
1510 let narrow_row0 = text(&narrow).lines().next().unwrap_or_default().to_owned();
1511 assert!(!narrow_row0.contains("Esc clear"), "{narrow_row0}");
1512 assert!(narrow_row0.contains("1/2"), "{narrow_row0}");
1513 }
1514 }
1515 }
1516
1516 lines RUST