1use iced::advanced::layout::{self, Layout};
12use iced::advanced::text as core_text;
13use iced::advanced::widget::operation::Focusable;
14use iced::advanced::widget::operation::scrollable::{AbsoluteOffset, RelativeOffset, Scrollable};
15use iced::advanced::widget::{Id, Operation, Tree, Widget, tree};
16use iced::advanced::{Clipboard, Shell, renderer};
17use iced::alignment::Vertical;
18use iced::keyboard::{self, Key, Modifiers, key::Named};
19use iced::time::{Duration, Instant};
20use iced::widget::text::{LineHeight, Shaping, Wrapping};
21use iced::widget::text_input;
22use iced::widget::{container, stack};
23use iced::{
24 Alignment, Background, Border, Color, Element, Event, Length, Padding, Pixels, Point,
25 Rectangle, Renderer, Size, Theme, Vector, mouse, touch, window,
26};
27
28use super::navigate::{
29 TypeAhead, centred_offset, clamp_offset, moves, offset_for_thumb, step, thumb,
30};
31use crate::forms::matching;
32use crate::icon::{opacity, themed};
33use crate::overlay::menu::{self, RowStatus, reveal_offset};
34use crate::primitives::input::{self, Shortcut, Shortcuts};
35use crate::primitives::scroll_area::{self, Interaction, THICKNESS};
36use crate::theme::{self, Tokens, fade, radius, space, text_size};
37
38pub(super) const SEARCH_HEIGHT: f32 = ROW_HEIGHT + 1.0 + space::XS;
40const ROW_HEIGHT: f32 = 32.0;
42const MESSAGE_HEIGHT: f32 = 40.0;
44const NOTICE_HEIGHT: f32 = 28.0;
46const BAR_MARGIN: f32 = 2.0;
48const GUTTER: f32 = THICKNESS + 2.0 * BAR_MARGIN;
50const WHEEL_LINE: f32 = 60.0;
52const TOUCH_SLOP: f32 = 8.0;
54const TEXT_X: f32 = space::XS + space::SM;
56
57pub(super) struct Search<'a, Message> {
60 pub(super) filters: bool,
61 pub(super) on_custom: Option<Box<dyn Fn(String) -> Option<Message> + 'a>>,
62 pub(super) placeholder: String,
63 pub(super) shortcuts: Shortcuts,
64 pub(super) on_anchor: bool,
67 pub(super) prefer_custom: bool,
69 pub(super) commit_on_leave: bool,
71}
72
73pub fn list_id() -> Id {
76 Id::new("iced-cube-select-list")
77}
78
79pub fn search_id() -> Id {
81 Id::new("iced-cube-select-search")
82}
83
84pub(super) fn state_mut(tree: &mut Tree) -> Option<&mut ListState> {
86 if tree.tag == tree::Tag::of::<ListState>() {
87 return Some(tree.state.downcast_mut::<ListState>());
88 }
89 tree.children.iter_mut().find_map(state_mut)
90}
91
92pub(super) fn state_ref(tree: &Tree) -> Option<&ListState> {
94 if tree.tag == tree::Tag::of::<ListState>() {
95 return Some(tree.state.downcast_ref::<ListState>());
96 }
97 tree.children.iter().find_map(state_ref)
98}
99
100pub(super) struct List<'a, Message> {
102 pub(super) rows: Vec<Element<'a, Message>>,
103 pub(super) labels: Vec<String>,
105 pub(super) choices: Vec<Option<Message>>,
106 pub(super) selected: Option<usize>,
107 pub(super) max_rows: Option<usize>,
109 pub(super) search: Option<Search<'a, Message>>,
110 pub(super) pause: Duration,
111 pub(super) empty: String,
112 pub(super) no_results: String,
113 pub(super) not_valid: String,
115}
116
117#[derive(Debug, Default)]
119pub(super) struct ListState {
120 query: String,
121 edited: bool,
123 refilter: bool,
126 steered: bool,
128 anchor: Option<Rectangle>,
130 rejected: bool,
132 shown: Vec<usize>,
134 highlight: Option<usize>,
136 offset: f32,
137 reveal: Option<Reveal>,
138 typed: TypeAhead,
139 frame: Option<Instant>,
141 press: Option<Target>,
142 grab: Option<f32>,
144 finger: Option<Finger>,
145 over_bar: bool,
146 viewport: f32,
147 content: f32,
148}
149
150#[derive(Debug, Clone, Copy, PartialEq, Eq)]
152enum Reveal {
153 Centre,
154 Nearest,
155}
156
157#[derive(Debug, Clone, Copy, PartialEq, Eq)]
159enum Target {
160 Row(usize),
161 Custom,
162}
163
164#[derive(Debug, Clone, Copy)]
165struct Finger {
166 id: touch::Finger,
167 y: f32,
168 offset: f32,
169 target: Option<Target>,
170 moved: bool,
171}
172
173impl ListState {
174 pub(super) fn edit(&mut self, query: String) {
177 self.query = query;
178 self.edited = true;
179 self.rejected = false;
180 self.steered = false;
181 self.refilter = true;
182 }
183
184 pub(super) fn edited_query(&self) -> Option<&str> {
186 self.edited.then_some(self.query.as_str())
187 }
188
189 pub(super) fn is_rejected(&self) -> bool {
190 self.rejected
191 }
192
193 pub(super) fn set_anchor(&mut self, anchor: Rectangle) {
194 self.anchor = Some(anchor);
195 }
196
197 fn page_rows(&self) -> usize {
198 (self.viewport / ROW_HEIGHT).floor().max(1.0) as usize
199 }
200
201 fn position(&self, option: Option<usize>) -> Option<usize> {
202 option.and_then(|option| self.shown.iter().position(|&shown| shown == option))
203 }
204}
205
206impl Scrollable for ListState {
207 fn snap_to(&mut self, offset: RelativeOffset<Option<f32>>) {
208 if let Some(y) = offset.y {
209 self.offset = clamp_offset(
210 y * (self.content - self.viewport),
211 self.content,
212 self.viewport,
213 );
214 }
215 }
216
217 fn scroll_to(&mut self, offset: AbsoluteOffset<Option<f32>>) {
218 if let Some(y) = offset.y {
219 self.offset = clamp_offset(y, self.content, self.viewport);
220 }
221 }
222
223 fn scroll_by(&mut self, offset: AbsoluteOffset, _bounds: Rectangle, _content: Rectangle) {
224 self.offset = clamp_offset(self.offset + offset.y, self.content, self.viewport);
225 }
226}
227
228#[derive(Debug, Clone, PartialEq)]
230enum Outcome<Message> {
231 Used,
233 Chosen(Message),
236 Field,
238 Ignored,
240}
241
242fn field(
245 search_placeholder: &str,
246 query: &str,
247 rejected: bool,
248 shortcuts: Shortcuts,
249) -> Element<'static, String> {
250 let vertical = (ROW_HEIGHT - menu::LINE_HEIGHT) / 2.0;
251 let text = iced::widget::text_input(search_placeholder, query)
252 .id(search_id())
253 .size(text_size::SM)
254 .line_height(LineHeight::Absolute(Pixels(menu::LINE_HEIGHT)))
255 .padding(Padding {
256 top: vertical,
257 bottom: vertical,
258 left: TEXT_X + menu::ICON_SIZE + space::SM,
259 right: TEXT_X,
260 })
261 .width(Length::Fill)
262 .style(move |theme, _status| field_style(&Tokens::of(theme), rejected, true));
263 let shortcuts = shortcuts.without(Shortcut::EscapeUnfocus);
265 let input = input::with_shortcuts(
266 text,
267 query,
268 false,
269 Some(Box::new(|value| value)),
270 input::default_keymap(),
271 shortcuts,
272 );
273 let icon = themed(
274 crate::lucide!(Search),
275 menu::ICON_SIZE,
276 opacity(true),
277 |theme| Tokens::of(theme).muted_foreground,
278 );
279 stack![
280 input,
281 container(icon)
282 .height(Length::Fill)
283 .align_y(Alignment::Center)
284 .padding(Padding::ZERO.left(TEXT_X)),
285 ]
286 .into()
287}
288
289pub(super) fn field_style(tokens: &Tokens, rejected: bool, enabled: bool) -> text_input::Style {
294 let value = match (rejected, enabled) {
295 (true, _) => tokens.destructive_text,
296 (false, false) => fade(tokens.foreground, 0.5),
297 (false, true) => tokens.foreground,
298 };
299 let placeholder = if enabled {
300 tokens.muted_foreground
301 } else {
302 fade(tokens.muted_foreground, 0.5)
303 };
304 text_input::Style {
305 background: Background::Color(Color::TRANSPARENT),
306 border: Border::default(),
307 icon: tokens.muted_foreground,
308 placeholder,
309 value,
310 selection: fade(tokens.primary, 0.25),
311 }
312}
313
314struct FocusField;
317
318impl Operation for FocusField {
319 fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
320 operate(self);
321 }
322
323 fn focusable(&mut self, _id: Option<&Id>, _bounds: Rectangle, state: &mut dyn Focusable) {
324 if !state.is_focused() {
325 state.focus();
326 }
327 }
328}
329
330pub(super) fn relay<Message, Inner>(shell: &mut Shell<'_, Message>, inner: &Shell<'_, Inner>) {
332 if inner.is_event_captured() {
333 shell.capture_event();
334 }
335 shell.request_redraw_at(inner.redraw_request());
336 if inner.is_layout_invalid() {
337 shell.invalidate_layout();
338 }
339 if inner.are_widgets_invalid() {
340 shell.invalidate_widgets();
341 }
342 shell.input_method_mut().merge(inner.input_method());
343}
344
345fn press_position(event: &Event, cursor: mouse::Cursor) -> Option<Point> {
347 match event {
348 Event::Mouse(mouse::Event::ButtonPressed(_)) => cursor.position(),
349 Event::Touch(touch::Event::FingerPressed { position, .. }) => Some(*position),
350 _ => None,
351 }
352}
353
354fn for_field(event: &Event, on_field: bool) -> bool {
356 match event {
357 Event::Window(_) | Event::InputMethod(_) => true,
358 Event::Keyboard(keyboard::Event::KeyPressed { .. }) => false,
359 Event::Keyboard(_) => true,
360 Event::Mouse(mouse::Event::ButtonPressed(_)) | Event::Touch(_) => on_field,
361 Event::Mouse(_) => true,
362 }
363}
364
365impl<Message: Clone> List<'_, Message> {
366 fn has_field(&self) -> bool {
368 self.search.as_ref().is_some_and(|search| !search.on_anchor)
369 }
370
371 fn field_on_anchor(&self) -> bool {
372 self.search.as_ref().is_some_and(|search| search.on_anchor)
373 }
374
375 fn first_row(&self) -> usize {
376 usize::from(self.has_field())
377 }
378
379 fn search_height(&self) -> f32 {
380 if self.has_field() { SEARCH_HEIGHT } else { 0.0 }
381 }
382
383 fn shows_notice(&self, state: &ListState) -> bool {
386 state.rejected && !state.shown.is_empty()
387 }
388
389 fn top(&self, state: &ListState) -> f32 {
391 let notice = if self.shows_notice(state) {
392 NOTICE_HEIGHT
393 } else {
394 0.0
395 };
396 self.search_height() + notice
397 }
398
399 fn filters(&self) -> bool {
400 self.search.as_ref().is_some_and(|search| search.filters)
401 }
402
403 fn offers_custom(&self) -> bool {
404 self.search
405 .as_ref()
406 .is_some_and(|search| search.on_custom.is_some())
407 }
408
409 fn prefers_custom(&self) -> bool {
410 self.search
411 .as_ref()
412 .is_some_and(|search| search.prefer_custom)
413 }
414
415 fn commits_on_leave(&self) -> bool {
416 self.search
417 .as_ref()
418 .is_some_and(|search| search.commit_on_leave)
419 }
420
421 fn shown_for(&self, query: &str) -> Vec<usize> {
422 if self.filters() {
423 matching::filter(&self.labels, query)
424 } else {
425 (0..self.rows.len()).collect()
426 }
427 }
428
429 fn field(&self, state: &ListState) -> Option<Element<'static, String>> {
431 let search = self.search.as_ref().filter(|search| !search.on_anchor)?;
432 Some(field(
433 &search.placeholder,
434 &state.query,
435 state.rejected,
436 search.shortcuts,
437 ))
438 }
439
440 fn offers_typed(&self, state: &ListState) -> bool {
442 self.offers_custom()
443 && !state.rejected
444 && state.shown.is_empty()
445 && !state.query.trim().is_empty()
446 }
447
448 fn choice(&self, option: Option<usize>) -> Option<Message> {
449 option.and_then(|option| self.choices.get(option).cloned().flatten())
450 }
451
452 fn custom_message(&self, state: &ListState) -> Option<Message> {
454 let on_custom = self.search.as_ref()?.on_custom.as_ref()?;
455 on_custom(state.query.trim().to_owned())
456 }
457
458 fn custom(&self, state: &mut ListState) -> Outcome<Message> {
460 if !self.offers_custom() {
461 return Outcome::Used;
462 }
463 match self.custom_message(state) {
464 Some(message) => Outcome::Chosen(message),
465 None => {
466 state.rejected = true;
467 Outcome::Used
468 }
469 }
470 }
471
472 fn submit(&self, state: &mut ListState) -> Outcome<Message> {
478 let typed = !state.query.trim().is_empty();
479 if !typed || !self.offers_custom() {
480 return self
481 .choice(state.highlight)
482 .map_or(Outcome::Used, Outcome::Chosen);
483 }
484 let matched = if self.filters() {
485 state.highlight.filter(|_| !state.shown.is_empty())
486 } else {
487 None
488 };
489 let exact = matching::exact(&self.labels, &state.query);
490 if self.prefers_custom() && !state.steered {
491 if let Some(message) = self
492 .choice(exact)
493 .or_else(|| self.custom_message(state))
494 .or_else(|| self.choice(matched))
495 {
496 return Outcome::Chosen(message);
497 }
498 state.rejected = true;
499 return Outcome::Used;
500 }
501 let option = if self.filters() { matched } else { exact };
502 match self.choice(option) {
503 Some(message) => Outcome::Chosen(message),
504 None => self.custom(state),
505 }
506 }
507
508 fn leave(&self, state: &mut ListState) -> Outcome<Message> {
513 if !self.commits_on_leave() || state.query.trim().is_empty() {
514 return Outcome::Ignored;
515 }
516 match self.submit(state) {
517 Outcome::Chosen(message) => Outcome::Chosen(message),
518 _ if state.rejected => Outcome::Used,
519 _ => Outcome::Ignored,
520 }
521 }
522
523 fn set_query(&self, state: &mut ListState, query: String) {
525 state.edit(query);
526 self.refilter(state);
527 }
528
529 fn refilter(&self, state: &mut ListState) {
532 state.refilter = false;
533 state.shown = self.shown_for(&state.query);
534 if self.filters() {
535 state.highlight = state.shown.first().copied();
536 state.offset = 0.0;
537 }
538 state.reveal = Some(Reveal::Nearest);
539 }
540
541 fn message(&self, state: &ListState) -> String {
543 if self.offers_typed(state) {
544 return format!("Use \u{201c}{}\u{201d}", state.query.trim());
545 }
546 if state.rejected {
547 self.not_valid.clone()
548 } else if self.rows.is_empty() {
549 self.empty.clone()
550 } else {
551 self.no_results.clone()
552 }
553 }
554
555 fn notice_bounds(&self, layout: Layout<'_>) -> Rectangle {
557 let bounds = layout.bounds();
558 Rectangle::new(
559 Point::new(bounds.x + TEXT_X, bounds.y + self.search_height()),
560 Size::new((bounds.width - 2.0 * TEXT_X).max(0.0), NOTICE_HEIGHT),
561 )
562 }
563
564 fn key(
565 &self,
566 state: &mut ListState,
567 key: &Key,
568 modifiers: Modifiers,
569 text: Option<&str>,
570 ) -> Outcome<Message> {
571 let searching = self.search.is_some();
572 let plain = !(modifiers.control() || modifiers.alt() || modifiers.logo());
573 if let Key::Named(named) = key
574 && moves(*named)
575 && plain
576 && !modifiers.shift()
577 && !(searching && matches!(named, Named::Home | Named::End))
579 {
580 let position = state.position(state.highlight);
581 let next = step(position, state.shown.len(), state.page_rows(), *named);
582 state.highlight = next.and_then(|position| state.shown.get(position).copied());
583 state.reveal = Some(Reveal::Nearest);
584 state.steered = true;
585 state.typed.clear();
586 return Outcome::Used;
587 }
588 match key {
589 Key::Named(Named::Enter) if plain => return self.submit(state),
590 Key::Named(Named::Tab) => return self.leave(state),
591 Key::Named(Named::Escape) => return Outcome::Ignored,
592 _ if searching => return Outcome::Field,
593 _ if !plain => return Outcome::Ignored,
594 Key::Named(Named::Space) if !state.typed.is_typing(state.frame, self.pause) => {
595 return self
596 .choice(state.highlight)
597 .map_or(Outcome::Used, Outcome::Chosen);
598 }
599 _ => {}
600 }
601 let text = match key {
602 Key::Named(Named::Space) => Some(" "),
603 _ => text,
604 };
605 let Some(text) =
606 text.filter(|text| !text.is_empty() && !text.chars().any(char::is_control))
607 else {
608 return Outcome::Ignored;
609 };
610 let labels: Vec<&str> = state
611 .shown
612 .iter()
613 .filter_map(|&option| self.labels.get(option).map(String::as_str))
614 .collect();
615 let position = state.position(state.highlight);
616 let found = state
617 .typed
618 .type_text(text, state.frame, self.pause, &labels, position);
619 if let Some(option) = found.and_then(|position| state.shown.get(position).copied()) {
620 state.highlight = Some(option);
621 state.reveal = Some(Reveal::Nearest);
622 }
623 Outcome::Used
624 }
625
626 fn area(&self, layout: Layout<'_>, state: &ListState) -> Rectangle {
628 let bounds = layout.bounds();
629 let top = self.top(state);
630 Rectangle::new(
631 Point::new(bounds.x, bounds.y + top),
632 Size::new(bounds.width, state.viewport),
633 )
634 }
635
636 fn track(&self, layout: Layout<'_>, state: &ListState) -> Option<Rectangle> {
638 if state.content <= state.viewport {
639 return None;
640 }
641 let area = self.area(layout, state);
642 Some(Rectangle::new(
643 Point::new(
644 area.x + area.width - BAR_MARGIN - THICKNESS,
645 area.y + BAR_MARGIN,
646 ),
647 Size::new(THICKNESS, (area.height - 2.0 * BAR_MARGIN).max(0.0)),
648 ))
649 }
650
651 fn thumb_bounds(&self, layout: Layout<'_>, state: &ListState) -> Option<Rectangle> {
652 let track = self.track(layout, state)?;
653 let (top, height) = thumb(state.offset, state.content, state.viewport, track.height)?;
654 Some(Rectangle::new(
655 Point::new(track.x, track.y + top),
656 Size::new(track.width, height),
657 ))
658 }
659
660 fn on_field(&self, layout: Layout<'_>, point: Point) -> bool {
661 self.has_field()
662 && layout
663 .children()
664 .next()
665 .is_some_and(|field| field.bounds().contains(point))
666 }
667
668 fn target_at(&self, layout: Layout<'_>, state: &ListState, point: Point) -> Option<Target> {
670 let area = self.area(layout, state);
671 if !area.contains(point) {
672 return None;
673 }
674 if state.shown.is_empty() {
675 return self.offers_typed(state).then_some(Target::Custom);
676 }
677 let inside = point + Vector::new(0.0, state.offset);
678 let first = self.first_row();
679 state
680 .shown
681 .iter()
682 .copied()
683 .find(|&option| {
684 layout
685 .children()
686 .nth(first + option)
687 .is_some_and(|row| row.bounds().contains(inside))
688 })
689 .map(Target::Row)
690 }
691
692 fn hover(&self, layout: Layout<'_>, state: &mut ListState, point: Point) {
694 if state.grab.is_some() || state.over_bar {
695 return;
696 }
697 if let Some(Target::Row(option)) = self.target_at(layout, state, point) {
698 state.highlight = Some(option);
699 }
700 }
701
702 fn span(&self, layout: Layout<'_>, state: &ListState, option: usize) -> Option<(f32, f32)> {
704 let row = layout.children().nth(self.first_row() + option)?;
705 let top = row.bounds().y - layout.bounds().y - self.top(state);
706 Some((top, top + row.bounds().height))
707 }
708
709 fn reveal_now(&self, layout: Layout<'_>, state: &mut ListState) {
713 let reveal = match state.reveal {
714 Some(Reveal::Centre) => Some(Reveal::Centre),
715 _ => state.reveal.take(),
716 };
717 let Some(reveal) = reveal else {
718 return;
719 };
720 let span = state
721 .highlight
722 .filter(|option| state.shown.contains(option))
723 .and_then(|option| self.span(layout, state, option));
724 if let Some((top, bottom)) = span {
725 state.offset = match reveal {
726 Reveal::Centre => {
727 let centred = centred_offset(top, bottom, state.content, state.viewport);
728 (centred / ROW_HEIGHT).round() * ROW_HEIGHT
729 }
730 Reveal::Nearest => reveal_offset(state.offset, state.viewport, top, bottom),
731 };
732 }
733 state.offset = clamp_offset(state.offset, state.content, state.viewport);
734 }
735
736 fn press_outside(
742 &self,
743 state: &mut ListState,
744 position: Point,
745 shell: &mut Shell<'_, Message>,
746 ) {
747 let in_field =
748 self.field_on_anchor() && state.anchor.is_some_and(|anchor| anchor.contains(position));
749 if in_field {
750 return;
751 }
752 if self.field_on_anchor() {
754 shell.invalidate_layout();
755 }
756 match self.leave(state) {
757 Outcome::Chosen(message) => shell.publish(message),
758 Outcome::Used => shell.capture_event(),
759 _ => {}
760 }
761 }
762
763 fn choose(&self, target: Target, state: &mut ListState) -> Outcome<Message> {
764 match target {
765 Target::Row(option) => self
766 .choice(Some(option))
767 .map_or(Outcome::Used, Outcome::Chosen),
768 Target::Custom => self.custom(state),
769 }
770 }
771
772 #[allow(clippy::too_many_arguments)]
774 fn update_field(
775 &self,
776 tree: &mut Tree,
777 event: &Event,
778 layout: Layout<'_>,
779 cursor: mouse::Cursor,
780 renderer: &Renderer,
781 clipboard: &mut dyn Clipboard,
782 shell: &mut Shell<'_, Message>,
783 viewport: &Rectangle,
784 ) -> bool {
785 let state = tree.state.downcast_mut::<ListState>();
786 let (Some(mut field), Some(field_layout), Some(field_tree)) = (
787 self.field(state),
788 layout.children().next(),
789 tree.children.first_mut(),
790 ) else {
791 return false;
792 };
793 let mut typed = Vec::new();
794 let mut inner = Shell::new(&mut typed);
795 field.as_widget_mut().update(
796 field_tree,
797 event,
798 field_layout,
799 cursor,
800 renderer,
801 clipboard,
802 &mut inner,
803 viewport,
804 );
805 relay(shell, &inner);
806 field
808 .as_widget_mut()
809 .operate(field_tree, field_layout, renderer, &mut FocusField);
810 let Some(query) = typed.pop() else {
811 return false;
812 };
813 self.set_query(state, query);
814 true
815 }
816
817 fn draw_field(
819 &self,
820 tree: &Tree,
821 renderer: &mut Renderer,
822 theme: &Theme,
823 style: &renderer::Style,
824 layout: Layout<'_>,
825 cursor: mouse::Cursor,
826 ) {
827 let state = tree.state.downcast_ref::<ListState>();
828 let (Some(field), Some(field_layout), Some(field_tree)) = (
829 self.field(state),
830 layout.children().next(),
831 tree.children.first(),
832 ) else {
833 return;
834 };
835 let bounds = layout.bounds();
836 field.as_widget().draw(
837 field_tree,
838 renderer,
839 theme,
840 style,
841 field_layout,
842 cursor,
843 &bounds,
844 );
845 let tokens = Tokens::of(theme);
846 let rule = if state.rejected {
847 tokens.destructive
848 } else {
849 tokens.border
850 };
851 fill(
853 renderer,
854 Rectangle::new(
855 Point::new(bounds.x + 1.0, bounds.y + ROW_HEIGHT),
856 Size::new((bounds.width - 2.0).max(0.0), 1.0),
857 ),
858 rule,
859 0.0,
860 );
861 }
862
863 fn draw_message(
866 &self,
867 state: &ListState,
868 renderer: &mut Renderer,
869 tokens: &Tokens,
870 area: Rectangle,
871 ) {
872 if self.offers_typed(state) {
873 let row = Rectangle::new(
875 Point::new(area.x + space::XS, area.y),
876 Size::new((area.width - 2.0 * space::XS).max(0.0), ROW_HEIGHT),
877 );
878 let style = menu::row_style(tokens, RowStatus::Highlighted, false);
879 if let Some(background) = style.background {
880 fill(renderer, row, background, radius::SM);
881 }
882 let label = self.message(state);
883 let text = Rectangle::new(
884 Point::new(row.x + space::SM, row.y),
885 Size::new((row.width - 2.0 * space::SM).max(0.0), row.height),
886 );
887 draw_text(
888 renderer,
889 &label,
890 text,
891 style.text,
892 core_text::Alignment::Left,
893 );
894 return;
895 }
896 let colour = if state.rejected {
897 tokens.destructive_text
898 } else {
899 tokens.muted_foreground
900 };
901 draw_text(
902 renderer,
903 &self.message(state),
904 area,
905 colour,
906 core_text::Alignment::Center,
907 );
908 }
909}
910
911fn draw_text(
915 renderer: &mut Renderer,
916 content: &str,
917 bounds: Rectangle,
918 colour: Color,
919 align: core_text::Alignment,
920) {
921 let (x, width) = match align {
922 core_text::Alignment::Center => (bounds.center_x(), bounds.width),
923 _ => (bounds.x, f32::INFINITY),
924 };
925 <Renderer as core_text::Renderer>::fill_text(
926 renderer,
927 core_text::Text {
928 content: content.to_owned(),
929 bounds: Size::new(width, bounds.height),
930 size: Pixels(text_size::SM),
931 line_height: LineHeight::Absolute(Pixels(menu::LINE_HEIGHT)),
932 font: theme::font(),
933 align_x: align,
934 align_y: Vertical::Center,
935 shaping: Shaping::Advanced,
936 wrapping: Wrapping::None,
937 },
938 Point::new(x, bounds.center_y()),
939 colour,
940 bounds,
941 );
942}
943
944fn fill(renderer: &mut Renderer, bounds: Rectangle, colour: Color, corner: f32) {
945 <Renderer as renderer::Renderer>::fill_quad(
946 renderer,
947 renderer::Quad {
948 bounds,
949 border: Border {
950 radius: corner.into(),
951 ..Border::default()
952 },
953 ..renderer::Quad::default()
954 },
955 Background::Color(colour),
956 );
957}
958
959impl<Message: Clone> Widget<Message, Theme, Renderer> for List<'_, Message> {
960 fn size(&self) -> Size<Length> {
961 Size::new(Length::Fill, Length::Shrink)
962 }
963
964 fn tag(&self) -> tree::Tag {
965 tree::Tag::of::<ListState>()
966 }
967
968 fn state(&self) -> tree::State {
969 tree::State::new(ListState {
970 shown: (0..self.rows.len()).collect(),
971 highlight: self.selected,
972 reveal: Some(Reveal::Centre),
973 ..ListState::default()
974 })
975 }
976
977 fn children(&self) -> Vec<Tree> {
978 self.field(&ListState::default())
979 .iter()
980 .map(Tree::new)
981 .chain(self.rows.iter().map(Tree::new))
982 .collect()
983 }
984
985 fn diff(&self, tree: &mut Tree) {
986 if tree.children.len() != self.first_row() + self.rows.len() {
987 tree.children = self.children();
988 return;
989 }
990 let state = tree.state.downcast_ref::<ListState>();
991 let field = self.field(state);
992 let (field_tree, row_trees) = tree.children.split_at_mut(self.first_row());
993 if let (Some(field), Some(field_tree)) = (field, field_tree.first_mut()) {
994 field_tree.diff(field.as_widget());
995 }
996 for (row, row_tree) in self.rows.iter().zip(row_trees) {
997 row_tree.diff(row.as_widget());
998 }
999 }
1000
1001 fn layout(
1002 &mut self,
1003 tree: &mut Tree,
1004 renderer: &Renderer,
1005 limits: &layout::Limits,
1006 ) -> layout::Node {
1007 let first = self.first_row();
1008 let width = limits
1009 .resolve(Length::Fill, Length::Shrink, Size::ZERO)
1010 .width;
1011 let state = tree.state.downcast_mut::<ListState>();
1012 if state.refilter {
1013 self.refilter(state);
1014 } else {
1015 state.shown = self.shown_for(&state.query);
1016 }
1017 let search_height = self.top(state);
1018 if state
1019 .highlight
1020 .is_some_and(|option| !state.shown.contains(&option))
1021 {
1022 state.highlight = state.shown.first().copied();
1023 }
1024 let shown = state.shown.clone();
1025 let field = self.field(state);
1026 let (field_tree, row_trees) = tree.children.split_at_mut(first);
1027
1028 let mut lay_out = |width: f32| {
1029 let mut visible = vec![false; self.rows.len()];
1030 for &option in &shown {
1031 if let Some(slot) = visible.get_mut(option) {
1032 *slot = true;
1033 }
1034 }
1035 let row_limits =
1036 layout::Limits::new(Size::new(width, 0.0), Size::new(width, f32::INFINITY));
1037 let mut y = 0.0;
1038 let mut heights = Vec::with_capacity(shown.len());
1039 let nodes: Vec<layout::Node> = self
1040 .rows
1041 .iter_mut()
1042 .zip(row_trees.iter_mut())
1043 .zip(visible)
1044 .map(|((row, tree), visible)| {
1045 if !visible {
1046 return layout::Node::new(Size::ZERO).move_to((0.0, search_height));
1047 }
1048 let node = row
1049 .as_widget_mut()
1050 .layout(tree, renderer, &row_limits)
1051 .move_to((0.0, search_height + y));
1052 y += node.size().height;
1053 heights.push(node.size().height);
1054 node
1055 })
1056 .collect();
1057 (nodes, y, heights)
1058 };
1059
1060 let (mut nodes, mut content, heights) = lay_out(width);
1061 let room = (limits.max().height - search_height).max(0.0);
1062 let viewport = match self.max_rows {
1063 _ if shown.is_empty() => MESSAGE_HEIGHT,
1064 None => content,
1065 Some(rows) => {
1066 let cap: f32 = heights.iter().take(rows.max(1)).sum();
1067 content.min(cap).min(room)
1068 }
1069 };
1070 if content > viewport + 0.5 {
1071 (nodes, content, _) = lay_out((width - GUTTER).max(0.0));
1072 }
1073
1074 let mut children = Vec::with_capacity(nodes.len() + first);
1075 if let (Some(mut field), Some(field_tree)) = (field, field_tree.first_mut()) {
1076 let size = Size::new(width, ROW_HEIGHT);
1077 let node = field.as_widget_mut().layout(
1078 field_tree,
1079 renderer,
1080 &layout::Limits::new(size, size),
1081 );
1082 field.as_widget_mut().operate(
1083 field_tree,
1084 Layout::new(&node),
1085 renderer,
1086 &mut FocusField,
1087 );
1088 children.push(node);
1089 }
1090 children.extend(nodes);
1091
1092 let state = tree.state.downcast_mut::<ListState>();
1093 state.viewport = viewport;
1094 state.content = if shown.is_empty() { 0.0 } else { content };
1095 let node =
1096 layout::Node::with_children(Size::new(width, search_height + viewport), children);
1097 self.reveal_now(Layout::new(&node), state);
1098 node
1099 }
1100
1101 fn draw(
1102 &self,
1103 tree: &Tree,
1104 renderer: &mut Renderer,
1105 theme: &Theme,
1106 style: &renderer::Style,
1107 layout: Layout<'_>,
1108 cursor: mouse::Cursor,
1109 _viewport: &Rectangle,
1110 ) {
1111 let state = tree.state.downcast_ref::<ListState>();
1112 let tokens = Tokens::of(theme);
1113 self.draw_field(tree, renderer, theme, style, layout, cursor);
1114 if self.shows_notice(state) {
1115 draw_text(
1116 renderer,
1117 &self.not_valid,
1118 self.notice_bounds(layout),
1119 tokens.destructive_text,
1120 core_text::Alignment::Left,
1121 );
1122 }
1123 let area = self.area(layout, state);
1124 if state.shown.is_empty() {
1125 self.draw_message(state, renderer, &tokens, area);
1126 return;
1127 }
1128
1129 let offset = state.offset;
1130 let first = self.first_row();
1131 let inner_cursor = match cursor.position() {
1132 Some(position) if area.contains(position) => {
1133 mouse::Cursor::Available(position + Vector::new(0.0, offset))
1134 }
1135 _ => mouse::Cursor::Unavailable,
1136 };
1137 let inner_viewport = area + Vector::new(0.0, offset);
1138 let highlight = menu::row_style(&tokens, RowStatus::Highlighted, false);
1139 let idle = menu::row_style(&tokens, RowStatus::Idle, false);
1140
1141 <Renderer as renderer::Renderer>::with_layer(renderer, area, |renderer| {
1142 <Renderer as renderer::Renderer>::with_translation(
1143 renderer,
1144 Vector::new(0.0, -offset),
1145 |renderer| {
1146 for &option in &state.shown {
1147 let (Some(row), Some(row_tree), Some(element)) = (
1148 layout.children().nth(first + option),
1149 tree.children.get(first + option),
1150 self.rows.get(option),
1151 ) else {
1152 continue;
1153 };
1154 if !row.bounds().intersects(&inner_viewport) {
1155 continue;
1156 }
1157 let highlighted = state.highlight == Some(option);
1158 if highlighted && let Some(background) = highlight.background {
1159 let inner = row.children().next().map_or(row.bounds(), |b| b.bounds());
1160 fill(renderer, inner, background, radius::SM);
1161 }
1162 let text_color = if highlighted {
1163 highlight.text
1164 } else {
1165 idle.text
1166 };
1167 element.as_widget().draw(
1168 row_tree,
1169 renderer,
1170 theme,
1171 &renderer::Style { text_color },
1172 row,
1173 inner_cursor,
1174 &inner_viewport,
1175 );
1176 }
1177 },
1178 );
1179 });
1180
1181 if let Some(bar) = self.thumb_bounds(layout, state) {
1182 let interaction = if state.grab.is_some() {
1183 Interaction::Dragged
1184 } else if state.over_bar {
1185 Interaction::Hovered
1186 } else {
1187 Interaction::Idle
1188 };
1189 fill(
1190 renderer,
1191 bar,
1192 scroll_area::scroller_colour(&tokens, interaction),
1193 radius::FULL,
1194 );
1195 }
1196 }
1197
1198 fn operate(
1199 &mut self,
1200 tree: &mut Tree,
1201 layout: Layout<'_>,
1202 renderer: &Renderer,
1203 operation: &mut dyn Operation,
1204 ) {
1205 let first = self.first_row();
1206 let Tree {
1207 state, children, ..
1208 } = tree;
1209 let state = state.downcast_mut::<ListState>();
1210 let mut field = self.field(state);
1211 let area = self.area(layout, state);
1212 let content = Rectangle::new(area.position(), Size::new(area.width, state.content));
1213 let translation = Vector::new(0.0, state.offset);
1214 let shown = state.shown.clone();
1215 let notice = self.shows_notice(state).then(|| self.notice_bounds(layout));
1217 let message = shown.is_empty().then(|| self.message(state));
1218 let (field_tree, row_trees) = children.split_at_mut(first);
1219 operation.container(Some(&list_id()), layout.bounds());
1220 operation.traverse(&mut |operation| {
1221 if let (Some(field), Some(field_tree), Some(field_layout)) = (
1222 field.as_mut(),
1223 field_tree.first_mut(),
1224 layout.children().next(),
1225 ) {
1226 field
1227 .as_widget_mut()
1228 .operate(field_tree, field_layout, renderer, operation);
1229 }
1230 if let Some(bounds) = notice {
1231 operation.text(None, bounds, &self.not_valid);
1232 }
1233 if let Some(message) = &message {
1234 operation.text(None, area, message);
1235 }
1236 operation.scrollable(None, area, content, translation, state);
1237 operation.traverse(&mut |operation| {
1240 for &option in &shown {
1241 let (Some(row), Some(row_tree), Some(row_layout)) = (
1242 self.rows.get_mut(option),
1243 row_trees.get_mut(option),
1244 layout.children().nth(first + option),
1245 ) else {
1246 continue;
1247 };
1248 row.as_widget_mut()
1249 .operate(row_tree, row_layout, renderer, operation);
1250 }
1251 });
1252 });
1253 }
1254
1255 fn update(
1256 &mut self,
1257 tree: &mut Tree,
1258 event: &Event,
1259 layout: Layout<'_>,
1260 cursor: mouse::Cursor,
1261 renderer: &Renderer,
1262 clipboard: &mut dyn Clipboard,
1263 shell: &mut Shell<'_, Message>,
1264 viewport: &Rectangle,
1265 ) {
1266 let state = tree.state.downcast_mut::<ListState>();
1267 let before = (
1268 state.highlight,
1269 state.offset,
1270 state.over_bar,
1271 state.query.len(),
1272 state.rejected,
1273 );
1274 let mut outcome = Outcome::Ignored;
1275 if matches!(
1276 event,
1277 Event::Keyboard(_) | Event::Mouse(_) | Event::Touch(_)
1278 ) && state.reveal == Some(Reveal::Centre)
1279 {
1280 state.reveal = None;
1281 }
1282 if let Some(position) = press_position(event, cursor)
1284 && !layout.bounds().expand(space::XS).contains(position)
1285 {
1286 self.press_outside(state, position, shell);
1287 if state.rejected != before.4 {
1288 shell.invalidate_layout();
1289 shell.request_redraw();
1290 }
1291 return;
1292 }
1293
1294 match event {
1295 Event::Window(window::Event::RedrawRequested(now)) => {
1296 state.frame = Some(*now);
1297 if let Some(stamped) = state.typed.stamp(*now) {
1299 shell.request_redraw_at(stamped + self.pause);
1300 }
1301 }
1302 Event::Keyboard(keyboard::Event::KeyPressed {
1303 key,
1304 modifiers,
1305 text,
1306 ..
1307 }) => {
1308 if self.field_on_anchor() && *key == Key::Named(Named::Escape) {
1311 shell.invalidate_layout();
1312 }
1313 outcome = self.key(state, key, *modifiers, text.as_deref());
1314 self.reveal_now(layout, state);
1315 }
1316 Event::Mouse(mouse::Event::CursorMoved { position }) => {
1317 if let (Some(grab), Some(track)) = (state.grab, self.track(layout, state)) {
1318 state.offset = offset_for_thumb(
1319 position.y - grab - track.y,
1320 state.content,
1321 state.viewport,
1322 track.height,
1323 );
1324 }
1325 state.over_bar = self
1326 .track(layout, state)
1327 .is_some_and(|track| track.expand(BAR_MARGIN).contains(*position));
1328 self.hover(layout, state, *position);
1329 }
1330 Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) => {
1331 let Some(position) = cursor.position_over(layout.bounds()) else {
1332 return;
1333 };
1334 if self.on_field(layout, position) {
1335 outcome = Outcome::Field;
1336 } else if let Some(track) = self.track(layout, state)
1337 && track.expand(BAR_MARGIN).contains(position)
1338 {
1339 let thumb = self.thumb_bounds(layout, state).unwrap_or(track);
1340 let grab = if thumb.contains(position) {
1341 position.y - thumb.y
1342 } else {
1343 thumb.height / 2.0
1344 };
1345 state.grab = Some(grab);
1346 state.offset = offset_for_thumb(
1347 position.y - grab - track.y,
1348 state.content,
1349 state.viewport,
1350 track.height,
1351 );
1352 shell.capture_event();
1353 } else {
1354 state.press = self.target_at(layout, state, position);
1355 shell.capture_event();
1356 }
1357 }
1358 Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) => {
1359 state.grab = None;
1360 let pressed = state.press.take();
1361 let released = cursor
1362 .position()
1363 .and_then(|position| self.target_at(layout, state, position));
1364 if let Some(target) = pressed.filter(|target| Some(*target) == released) {
1365 outcome = self.choose(target, state);
1366 }
1367 }
1368 Event::Mouse(mouse::Event::WheelScrolled { delta }) => {
1369 let Some(position) = cursor.position_over(layout.bounds()) else {
1370 return;
1371 };
1372 let dy = match delta {
1373 mouse::ScrollDelta::Lines { y, .. } => y * WHEEL_LINE,
1374 mouse::ScrollDelta::Pixels { y, .. } => *y,
1375 };
1376 state.offset = clamp_offset(state.offset - dy, state.content, state.viewport);
1377 self.hover(layout, state, position);
1378 shell.capture_event();
1379 }
1380 Event::Touch(touch::Event::FingerPressed { id, position }) => {
1381 if !self.area(layout, state).contains(*position) {
1382 outcome = Outcome::Field;
1383 } else {
1384 state.finger = Some(Finger {
1385 id: *id,
1386 y: position.y,
1387 offset: state.offset,
1388 target: self.target_at(layout, state, *position),
1389 moved: false,
1390 });
1391 shell.capture_event();
1392 }
1393 }
1394 Event::Touch(touch::Event::FingerMoved { id, position }) => {
1395 let Some(finger) = state.finger.as_mut().filter(|finger| finger.id == *id) else {
1396 return;
1397 };
1398 let dy = position.y - finger.y;
1399 finger.moved |= dy.abs() > TOUCH_SLOP;
1400 if finger.moved {
1401 let offset = finger.offset - dy;
1402 state.offset = clamp_offset(offset, state.content, state.viewport);
1403 }
1404 shell.capture_event();
1405 }
1406 Event::Touch(touch::Event::FingerLifted { id, position }) => {
1407 let Some(finger) = state.finger.take().filter(|finger| finger.id == *id) else {
1408 return;
1409 };
1410 if !finger.moved
1411 && let Some(target) = finger.target
1412 && self.target_at(layout, state, *position) == Some(target)
1413 {
1414 outcome = self.choose(target, state);
1415 }
1416 }
1417 Event::Touch(touch::Event::FingerLost { .. }) => {
1418 state.finger = None;
1419 }
1420 _ => {}
1421 }
1422
1423 let pointer = matches!(event, Event::Mouse(_) | Event::Touch(_));
1424 let on_field = cursor
1425 .position()
1426 .is_some_and(|position| self.on_field(layout, position));
1427 let to_field = matches!(outcome, Outcome::Field) || for_field(event, on_field);
1428 match outcome {
1429 Outcome::Used if !pointer => shell.capture_event(),
1432 Outcome::Chosen(message) => {
1433 shell.publish(message);
1434 if pointer {
1435 shell.capture_event();
1436 }
1437 }
1438 _ => {}
1439 }
1440 let edited = to_field
1441 && self.update_field(
1442 tree, event, layout, cursor, renderer, clipboard, shell, viewport,
1443 );
1444 if edited {
1445 shell.invalidate_layout();
1446 }
1447
1448 let state = tree.state.downcast_ref::<ListState>();
1449 let after = (
1450 state.highlight,
1451 state.offset,
1452 state.over_bar,
1453 state.query.len(),
1454 state.rejected,
1455 );
1456 if after.4 != before.4 {
1457 shell.invalidate_layout();
1458 }
1459 if edited || before != after {
1460 shell.request_redraw();
1461 }
1462 }
1463
1464 fn mouse_interaction(
1465 &self,
1466 tree: &Tree,
1467 layout: Layout<'_>,
1468 cursor: mouse::Cursor,
1469 _viewport: &Rectangle,
1470 _renderer: &Renderer,
1471 ) -> mouse::Interaction {
1472 let state = tree.state.downcast_ref::<ListState>();
1473 let Some(position) = cursor.position() else {
1474 return mouse::Interaction::default();
1475 };
1476 if state.grab.is_some() || state.over_bar {
1477 return mouse::Interaction::Idle;
1478 }
1479 if self.target_at(layout, state, position).is_some() {
1480 return mouse::Interaction::Pointer;
1481 }
1482 if self.on_field(layout, position) {
1483 return mouse::Interaction::Text;
1484 }
1485 mouse::Interaction::default()
1486 }
1487}
1488
1489#[cfg(test)]
1490mod tests {
1491 use super::*;
1492
1493 #[derive(Debug, Clone, PartialEq)]
1494 enum Message {
1495 Pick(usize),
1496 Custom(String),
1497 }
1498
1499 const DAYS: [&str; 7] = [
1500 "Monday",
1501 "Tuesday",
1502 "Wednesday",
1503 "Thursday",
1504 "Friday",
1505 "Saturday",
1506 "Sunday",
1507 ];
1508
1509 fn list<'a>(filters: bool, custom: bool, accepts: bool) -> List<'a, Message> {
1510 with_custom(filters, custom, move |text| {
1511 accepts.then_some(Message::Custom(text))
1512 })
1513 }
1514
1515 fn with_custom<'a>(
1516 filters: bool,
1517 custom: bool,
1518 on_custom: impl Fn(String) -> Option<Message> + 'a,
1519 ) -> List<'a, Message> {
1520 let search = (filters || custom).then(|| Search {
1521 filters,
1522 on_custom: custom
1523 .then(|| Box::new(on_custom) as Box<dyn Fn(String) -> Option<Message> + 'a>),
1524 placeholder: "Search".to_owned(),
1525 shortcuts: Shortcuts::all(),
1526 on_anchor: false,
1527 prefer_custom: false,
1528 commit_on_leave: false,
1529 });
1530 List {
1531 rows: DAYS.iter().map(|_| iced::widget::space().into()).collect(),
1532 labels: matching::lowercase(&DAYS),
1533 choices: (0..DAYS.len())
1534 .map(|index| Some(Message::Pick(index)))
1535 .collect(),
1536 selected: Some(2),
1537 max_rows: Some(8),
1538 search,
1539 pause: Duration::from_secs(1),
1540 empty: "No options".to_owned(),
1541 no_results: "No results found.".to_owned(),
1542 not_valid: "Not valid".to_owned(),
1543 }
1544 }
1545
1546 fn open(list: &List<'_, Message>) -> ListState {
1547 ListState {
1548 shown: (0..list.rows.len()).collect(),
1549 highlight: list.selected,
1550 viewport: 96.0,
1551 content: 224.0,
1552 ..ListState::default()
1553 }
1554 }
1555
1556 fn press(
1557 list: &List<'_, Message>,
1558 state: &mut ListState,
1559 key: Key,
1560 text: Option<&str>,
1561 ) -> Outcome<Message> {
1562 list.key(state, &key, Modifiers::empty(), text)
1563 }
1564
1565 fn named(list: &List<'_, Message>, state: &mut ListState, key: Named) -> Outcome<Message> {
1566 press(list, state, Key::Named(key), None)
1567 }
1568
1569 fn typed(list: &List<'_, Message>, state: &mut ListState, text: &str) -> Outcome<Message> {
1570 press(list, state, Key::Character(text.into()), Some(text))
1571 }
1572
1573 #[test]
1574 fn arrows_and_pages_move_the_highlight_and_ask_for_a_reveal() {
1575 let list = list(false, false, false);
1576 let mut state = open(&list);
1577 assert_eq!(named(&list, &mut state, Named::ArrowDown), Outcome::Used);
1578 assert_eq!(state.highlight, Some(3));
1579 assert_eq!(state.reveal, Some(Reveal::Nearest));
1580 named(&list, &mut state, Named::PageDown);
1581 assert_eq!(
1582 state.highlight,
1583 Some(6),
1584 "three rows to a page, stopping at the end"
1585 );
1586 named(&list, &mut state, Named::PageUp);
1587 assert_eq!(state.highlight, Some(3));
1588 named(&list, &mut state, Named::Home);
1589 assert_eq!(state.highlight, Some(0));
1590 }
1591
1592 #[test]
1593 fn enter_or_space_choose_the_highlight_and_leave_the_key() {
1594 let list = list(false, false, false);
1595 let mut state = open(&list);
1596 assert_eq!(
1597 named(&list, &mut state, Named::Enter),
1598 Outcome::Chosen(Message::Pick(2))
1599 );
1600 assert_eq!(
1601 named(&list, &mut state, Named::Space),
1602 Outcome::Chosen(Message::Pick(2))
1603 );
1604 assert_eq!(named(&list, &mut state, Named::Tab), Outcome::Ignored);
1605 assert_eq!(named(&list, &mut state, Named::Escape), Outcome::Ignored);
1606 }
1607
1608 #[test]
1609 fn typing_without_search_jumps_to_a_match() {
1610 let list = list(false, false, false);
1611 let mut state = open(&list);
1612 assert_eq!(typed(&list, &mut state, "t"), Outcome::Used);
1613 assert_eq!(state.highlight, Some(3), "the next T after Wednesday");
1614 typed(&list, &mut state, "u");
1615 assert_eq!(state.highlight, Some(1), "Tu");
1616 assert_eq!(
1617 named(&list, &mut state, Named::Space),
1618 Outcome::Used,
1619 "a space while typing is part of the search"
1620 );
1621 assert!(state.query.is_empty(), "type-ahead has no query");
1622 }
1623
1624 #[test]
1625 fn with_a_search_field_typing_and_editing_keys_go_to_the_field() {
1626 let list = list(true, false, false);
1627 let mut state = open(&list);
1628 assert_eq!(typed(&list, &mut state, "s"), Outcome::Field);
1629 assert_eq!(named(&list, &mut state, Named::Space), Outcome::Field);
1630 assert_eq!(named(&list, &mut state, Named::Backspace), Outcome::Field);
1631 assert_eq!(named(&list, &mut state, Named::Home), Outcome::Field);
1632 let chord = list.key(
1633 &mut state,
1634 &Key::Character("v".into()),
1635 Modifiers::CTRL,
1636 Some("v"),
1637 );
1638 assert_eq!(chord, Outcome::Field, "paste and the editing shortcuts");
1639 assert_eq!(named(&list, &mut state, Named::ArrowDown), Outcome::Used);
1640 assert_eq!(named(&list, &mut state, Named::Escape), Outcome::Ignored);
1641 assert_eq!(named(&list, &mut state, Named::Tab), Outcome::Ignored);
1642 }
1643
1644 #[test]
1645 fn search_filters_and_highlights_the_first_match() {
1646 let list = list(true, false, false);
1647 let mut state = open(&list);
1648 list.set_query(&mut state, "Sa".to_owned());
1649 assert_eq!(state.shown, vec![5]);
1650 assert_eq!(state.highlight, Some(5));
1651 assert_eq!(
1652 named(&list, &mut state, Named::Enter),
1653 Outcome::Chosen(Message::Pick(5))
1654 );
1655 list.set_query(&mut state, "S".to_owned());
1656 assert_eq!(state.shown, vec![1, 2, 3, 5, 6], "every day with an S");
1657 list.set_query(&mut state, "Sx".to_owned());
1658 assert!(state.shown.is_empty());
1659 assert_eq!(
1660 named(&list, &mut state, Named::Enter),
1661 Outcome::Used,
1662 "nothing to choose"
1663 );
1664 }
1665
1666 #[test]
1667 fn a_typed_value_is_offered_when_nothing_matches() {
1668 let list = list(true, true, true);
1669 let mut state = open(&list);
1670 list.set_query(&mut state, "09:40".to_owned());
1671 assert!(list.offers_typed(&state));
1672 assert_eq!(
1673 named(&list, &mut state, Named::Enter),
1674 Outcome::Chosen(Message::Custom("09:40".to_owned()))
1675 );
1676 let mut state = open(&list);
1677 list.set_query(&mut state, "fri".to_owned());
1678 assert_eq!(
1679 named(&list, &mut state, Named::Enter),
1680 Outcome::Chosen(Message::Pick(4)),
1681 "a match wins over the typed value"
1682 );
1683 }
1684
1685 #[test]
1686 fn a_rejected_value_stays_with_the_invalid_look_until_edited() {
1687 let list = list(true, true, false);
1688 let mut state = open(&list);
1689 list.set_query(&mut state, "25:00".to_owned());
1690 assert_eq!(named(&list, &mut state, Named::Enter), Outcome::Used);
1691 assert!(state.rejected);
1692 assert!(!list.offers_typed(&state), "not offered again");
1693 assert_eq!(state.query, "25:00", "the text is kept");
1694 list.set_query(&mut state, "25:0".to_owned());
1695 assert!(!state.rejected);
1696 }
1697
1698 #[test]
1699 fn custom_values_without_search_keep_every_row_and_the_highlight() {
1700 let list = list(false, true, true);
1701 let mut state = open(&list);
1702 list.set_query(&mut state, "Fr".to_owned());
1703 assert_eq!(state.shown.len(), DAYS.len(), "nothing is filtered");
1704 assert_eq!(state.highlight, Some(2), "typing does not move it");
1705 assert_eq!(
1706 named(&list, &mut state, Named::Enter),
1707 Outcome::Chosen(Message::Custom("Fr".to_owned())),
1708 "only a whole label chooses an option"
1709 );
1710 list.set_query(&mut state, "friday".to_owned());
1711 assert_eq!(
1712 named(&list, &mut state, Named::Enter),
1713 Outcome::Chosen(Message::Pick(4))
1714 );
1715 }
1716
1717 fn preferring(accepts: &'static [&'static str]) -> List<'static, Message> {
1718 let mut list = with_custom(true, true, move |text| {
1719 accepts
1720 .contains(&text.as_str())
1721 .then_some(Message::Custom(text))
1722 });
1723 if let Some(search) = list.search.as_mut() {
1724 search.prefer_custom = true;
1725 search.commit_on_leave = true;
1726 }
1727 list
1728 }
1729
1730 #[test]
1731 fn preferring_custom_values_asks_the_app_before_the_highlight() {
1732 let list = preferring(&["s"]);
1733 let mut state = open(&list);
1734 list.set_query(&mut state, "s".to_owned());
1735 assert_eq!(state.highlight, Some(1), "Tuesday matches first");
1736 assert_eq!(
1737 named(&list, &mut state, Named::Enter),
1738 Outcome::Chosen(Message::Custom("s".to_owned()))
1739 );
1740 list.set_query(&mut state, "sat".to_owned());
1741 assert_eq!(
1742 named(&list, &mut state, Named::Enter),
1743 Outcome::Chosen(Message::Pick(5)),
1744 "turned down, so the highlight"
1745 );
1746 list.set_query(&mut state, "sunday".to_owned());
1747 assert_eq!(
1748 named(&list, &mut state, Named::Enter),
1749 Outcome::Chosen(Message::Pick(6)),
1750 "a whole label is that option"
1751 );
1752 list.set_query(&mut state, "zz".to_owned());
1753 assert_eq!(named(&list, &mut state, Named::Enter), Outcome::Used);
1754 assert!(state.rejected, "nothing to fall back to");
1755 }
1756
1757 #[test]
1758 fn a_highlight_moved_by_the_keys_wins_over_a_preferred_custom_value() {
1759 let list = preferring(&["s"]);
1760 let mut state = open(&list);
1761 list.set_query(&mut state, "s".to_owned());
1762 named(&list, &mut state, Named::ArrowDown);
1763 assert_eq!(
1764 named(&list, &mut state, Named::Enter),
1765 Outcome::Chosen(Message::Pick(2))
1766 );
1767 list.set_query(&mut state, "s".to_owned());
1768 assert!(!state.steered, "editing hands it back to the text");
1769 }
1770
1771 #[test]
1772 fn leaving_enters_typed_text_only_when_asked() {
1773 let committing = preferring(&["s"]);
1774 let mut state = open(&committing);
1775 assert_eq!(
1776 named(&committing, &mut state, Named::Tab),
1777 Outcome::Ignored,
1778 "nothing typed"
1779 );
1780 committing.set_query(&mut state, "s".to_owned());
1781 assert_eq!(
1782 named(&committing, &mut state, Named::Tab),
1783 Outcome::Chosen(Message::Custom("s".to_owned()))
1784 );
1785 committing.set_query(&mut state, "zz".to_owned());
1786 assert_eq!(named(&committing, &mut state, Named::Tab), Outcome::Used);
1787 assert!(state.rejected);
1788
1789 let plain = list_with_search(true, true);
1790 let mut state = open(&plain);
1791 plain.set_query(&mut state, "zz".to_owned());
1792 assert_eq!(
1793 plain.leave(&mut state),
1794 Outcome::Ignored,
1795 "text that chooses nothing is dropped"
1796 );
1797 let off = list(true, true, true);
1798 let mut state = open(&off);
1799 off.set_query(&mut state, "s".to_owned());
1800 assert_eq!(off.leave(&mut state), Outcome::Ignored, "off by default");
1801 }
1802
1803 fn list_with_search(filters: bool, commit: bool) -> List<'static, Message> {
1804 let mut list = list(filters, false, false);
1805 if let Some(search) = list.search.as_mut() {
1806 search.commit_on_leave = commit;
1807 }
1808 list
1809 }
1810
1811 #[test]
1812 fn the_not_valid_line_shows_above_rows_and_in_place_of_none() {
1813 let custom = list(false, true, false);
1814 let mut state = open(&custom);
1815 assert_eq!(custom.top(&state), SEARCH_HEIGHT);
1816 custom.set_query(&mut state, "x".to_owned());
1817 named(&custom, &mut state, Named::Enter);
1818 assert!(custom.shows_notice(&state), "rows still show");
1819 assert_eq!(custom.top(&state), SEARCH_HEIGHT + NOTICE_HEIGHT);
1820 let filtering = list_with_search(true, false);
1821 let mut state = open(&filtering);
1822 filtering.set_query(&mut state, "x".to_owned());
1823 state.rejected = true;
1824 assert!(!filtering.shows_notice(&state), "said in place of rows");
1825 assert_eq!(filtering.message(&state), "Not valid");
1826 }
1827
1828 #[test]
1829 fn the_line_in_place_of_rows_says_why() {
1830 let list = list(true, true, true);
1831 let mut state = open(&list);
1832 list.set_query(&mut state, "9:40".to_owned());
1833 assert_eq!(list.message(&state), "Use \u{201c}9:40\u{201d}");
1834 let plain = list_with_search(true, false);
1835 let mut state = open(&plain);
1836 plain.set_query(&mut state, "x".to_owned());
1837 assert_eq!(plain.message(&state), "No results found.");
1838 let mut empty = list_with_search(true, false);
1839 empty.rows.clear();
1840 empty.labels.clear();
1841 assert_eq!(empty.message(&ListState::default()), "No options");
1842 }
1843
1844 #[test]
1845 fn a_field_on_the_closed_control_leaves_the_list_without_one() {
1846 let mut list = list(true, true, true);
1847 if let Some(search) = list.search.as_mut() {
1848 search.on_anchor = true;
1849 }
1850 assert!(!list.has_field());
1851 assert_eq!(list.first_row(), 0);
1852 assert_eq!(list.search_height(), 0.0);
1853 let mut state = open(&list);
1854 assert_eq!(typed(&list, &mut state, "s"), Outcome::Field);
1855 state.edit("sa".to_owned());
1856 assert!(state.refilter, "filtered on the next layout");
1857 assert_eq!(state.edited_query(), Some("sa"));
1858 list.refilter(&mut state);
1859 assert_eq!(state.shown, vec![5]);
1860 }
1861
1862 #[test]
1863 fn without_a_search_field_chords_are_left_alone() {
1864 let list = list(false, false, false);
1865 let mut state = open(&list);
1866 let outcome = list.key(
1867 &mut state,
1868 &Key::Character("a".into()),
1869 Modifiers::CTRL,
1870 Some("a"),
1871 );
1872 assert_eq!(outcome, Outcome::Ignored);
1873 assert_eq!(state.highlight, Some(2));
1874 }
1875
1876 #[test]
1877 fn the_field_text_turns_red_once_rejected() {
1878 let tokens = Tokens::of(&crate::theme::light());
1879 assert_eq!(field_style(&tokens, false, true).value, tokens.foreground);
1880 assert_eq!(
1881 field_style(&tokens, true, true).value,
1882 tokens.destructive_text
1883 );
1884 assert_eq!(
1885 field_style(&tokens, false, true).background,
1886 Background::Color(Color::TRANSPARENT)
1887 );
1888 assert_eq!(
1889 field_style(&tokens, false, false).value,
1890 fade(tokens.foreground, 0.5)
1891 );
1892 }
1893
1894 #[test]
1895 fn only_some_events_reach_the_field() {
1896 let press = Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left));
1897 assert!(for_field(&press, true));
1898 assert!(
1899 !for_field(&press, false),
1900 "presses on rows stay with the list"
1901 );
1902 let moved = Event::Mouse(mouse::Event::CursorMoved {
1903 position: Point::ORIGIN,
1904 });
1905 assert!(
1906 for_field(&moved, false),
1907 "a drag selecting text follows the pointer"
1908 );
1909 let key = Event::Keyboard(keyboard::Event::ModifiersChanged(Modifiers::SHIFT));
1910 assert!(for_field(&key, false));
1911 }
1912
1913 #[test]
1914 fn programmatic_scrolls_stay_in_range() {
1915 let mut state = ListState {
1916 viewport: 100.0,
1917 content: 400.0,
1918 ..ListState::default()
1919 };
1920 state.scroll_to(AbsoluteOffset {
1921 x: None,
1922 y: Some(1000.0),
1923 });
1924 assert_eq!(state.offset, 300.0);
1925 state.snap_to(RelativeOffset {
1926 x: None,
1927 y: Some(0.5),
1928 });
1929 assert_eq!(state.offset, 150.0);
1930 state.scroll_by(
1931 AbsoluteOffset { x: 0.0, y: -500.0 },
1932 Rectangle::default(),
1933 Rectangle::default(),
1934 );
1935 assert_eq!(state.offset, 0.0);
1936 }
1937}