Skip to main content

xrack_layout/
choice.rs

1use crate::{
2    LayoutNode, Point, Rect, Size, Target, TextMeasurer, input::valid, place_in_direction,
3    popup::PopupTypography, window_safe_area,
4};
5use std::borrow::Cow;
6use std::sync::atomic::{AtomicU64, Ordering};
7use std::time::{Duration, Instant};
8use unicode_bidi::BidiInfo;
9use unicode_segmentation::UnicodeSegmentation;
10use xrack_runtime::{
11    ChoiceIdentity, ComboOptionInput, ComboPopupHandle, LayoutDirection, Node, RowKey,
12    choice_enabled, choice_identity, combo_count, combo_editable, combo_find_enabled_label,
13    combo_index, combo_label, combo_labels, combo_row_index, combo_row_key, combo_text,
14    search_suggestion, search_suggestions,
15};
16
17const ROW_HEIGHT: f32 = 28.0;
18pub(crate) const MAX_ROWS: usize = 8;
19
20/// The exact candidate and draft boundary displayed for one focused control.
21#[derive(Clone, Debug, PartialEq, Eq)]
22pub struct ComboCompletion {
23    pub(crate) target: Target,
24    pub(crate) value: String,
25    pub(crate) draft_len: usize,
26}
27
28impl ComboCompletion {
29    pub fn suffix(&self) -> &str {
30        &self.value[self.draft_len..]
31    }
32
33    pub(crate) fn continues_left(&self) -> bool {
34        BidiInfo::new(&self.value[..self.draft_len], None)
35            .paragraphs
36            .first()
37            .is_some_and(|paragraph| paragraph.level.is_rtl())
38    }
39}
40
41pub(crate) fn completion_value<'a>(node: &'a Node, draft: &str) -> Option<Cow<'a, str>> {
42    if draft.is_empty() || combo_find_enabled_label(node, 0, |value| value == draft).is_some() {
43        return None;
44    }
45    let index = combo_find_enabled_label(node, 0, |value| {
46        value.strip_prefix(draft).is_some_and(|suffix| {
47            suffix.chars().all(|ch| !ch.is_control())
48                && value
49                    .grapheme_indices(true)
50                    .any(|(index, _)| index == draft.len())
51        })
52    })?;
53    combo_label(node, index)
54}
55
56#[cfg(test)]
57mod tests {
58    use super::{LayoutDirection, Node, PopupTypography, Rect, completion_value, geometry};
59
60    #[test]
61    fn completion_skips_partial_graphemes_and_single_line_control_characters() {
62        let mut node = xrack_runtime::Node::new("ComboBox", None);
63        node.properties.insert(
64            "model",
65            vec!["e\u{301}lan".into(), "edit\n".into(), "editor".into()].into(),
66        );
67        assert_eq!(completion_value(&node, "e").as_deref(), Some("editor"));
68        node.properties
69            .insert("model", vec!["editor".into(), "e".into()].into());
70        assert_eq!(completion_value(&node, "e"), None);
71    }
72
73    #[test]
74    fn popup_reduces_padding_in_tight_space_before_overlapping_the_anchor() {
75        let mut combo = Node::new("ComboBox", None);
76        combo
77            .properties
78            .insert("model", vec!["one".to_owned(); 10].into());
79        let mut style = Node::new("ComboPopup", None);
80        for (name, value) in [
81            ("max-height", 120.0),
82            ("row-height", 32.0),
83            ("padding", 8.0),
84        ] {
85            style
86                .properties
87                .insert(name, xrack_runtime::Length(value).into());
88        }
89        combo.children.push(style);
90        let popup = geometry(
91            &combo,
92            Rect::new(10.0, 10.0, 100.0, 35.0),
93            Rect::new(0.0, 0.0, 180.0, 80.0),
94            LayoutDirection::LeftToRight,
95            PopupTypography::default(),
96            None,
97        )
98        .unwrap();
99        assert_eq!(popup.bounds, Rect::new(10.0, 45.0, 100.0, 35.0));
100        assert_eq!(popup.visible, 1);
101        assert_eq!(popup.rows.height, 32.0);
102
103        let style = &mut combo.children[0];
104        style
105            .properties
106            .insert("width", xrack_runtime::Percent(1.25).into());
107        style
108            .properties
109            .insert("max-height", xrack_runtime::Percent(0.5).into());
110        let popup = geometry(
111            &combo,
112            Rect::new(10.0, 10.0, 100.0, 20.0),
113            Rect::new(0.0, 0.0, 180.0, 80.0),
114            LayoutDirection::LeftToRight,
115            PopupTypography::default(),
116            None,
117        )
118        .unwrap();
119        assert_eq!(popup.bounds, Rect::new(10.0, 30.0, 125.0, 40.0));
120        assert_eq!(popup.rows.height, 32.0);
121    }
122
123    #[test]
124    fn choice_popup_moves_sideways_when_it_can_fit_more_complete_rows() {
125        let mut combo = Node::new("ComboBox", None);
126        combo
127            .properties
128            .insert("model", vec!["one".to_owned(); 10].into());
129        let viewport = Rect::new(0.0, 0.0, 400.0, 210.0);
130        let anchor = Rect::new(120.0, 60.0, 100.0, 40.0);
131        let keyboard = Rect::new(140.0, 30.0, 160.0, 160.0);
132        let popup = geometry(
133            &combo,
134            anchor,
135            viewport,
136            LayoutDirection::LeftToRight,
137            PopupTypography::default(),
138            Some(keyboard),
139        )
140        .unwrap();
141        assert!(popup.bounds.x + popup.bounds.width <= keyboard.x);
142        assert_eq!(popup.bounds.y, anchor.y + anchor.height);
143        assert_eq!(popup.bounds.width, anchor.width);
144        assert_eq!(popup.visible, 3);
145    }
146}
147
148#[derive(Clone, Copy, Debug, PartialEq, Eq)]
149pub enum ChoiceKey {
150    Open,
151    Up,
152    Down,
153    Home,
154    End,
155    PageUp,
156    PageDown,
157    Accept,
158    Escape,
159}
160
161#[derive(Clone, Debug, Default)]
162pub(crate) struct Typeahead {
163    prefix: String,
164    last: Option<Instant>,
165}
166
167impl Typeahead {
168    pub fn find(
169        &mut self,
170        node: &Node,
171        text: &str,
172        now: Instant,
173        current: Option<usize>,
174    ) -> Option<usize> {
175        self.find_with(text, now, current, |start, prefix| {
176            combo_find_enabled_label(node, start, |label| matches_prefix(label, prefix))
177        })
178    }
179
180    pub(crate) fn find_with(
181        &mut self,
182        text: &str,
183        now: Instant,
184        current: Option<usize>,
185        find: impl Fn(usize, &str) -> Option<usize>,
186    ) -> Option<usize> {
187        if text.is_empty() || text.chars().any(char::is_control) {
188            return None;
189        }
190        let text: String = text.chars().flat_map(char::to_lowercase).collect();
191        let continuing = self
192            .last
193            .is_some_and(|last| now.saturating_duration_since(last) <= Duration::from_millis(800));
194        self.last = Some(now);
195        if continuing && self.prefix != text && self.prefix.len() + text.len() <= 128 {
196            self.prefix.push_str(&text);
197            if let Some(index) = find(current.unwrap_or(0), &self.prefix) {
198                return Some(index);
199            }
200        }
201        self.prefix = text;
202        find(current.map_or(0, |index| index + 1), &self.prefix)
203    }
204}
205
206pub(crate) fn matches_prefix(label: &str, prefix: &str) -> bool {
207    let mut label = label.chars().flat_map(char::to_lowercase);
208    prefix
209        .chars()
210        .all(|character| label.next() == Some(character))
211}
212
213pub(crate) fn next_choice(
214    node: &Node,
215    current: Option<usize>,
216    key: ChoiceKey,
217    page: usize,
218) -> Option<usize> {
219    let count = choice_count(node);
220    let last = count.checked_sub(1)?;
221    let enabled = |&index: &usize| choice_enabled(node, index);
222    match key {
223        ChoiceKey::Up => (0..current.unwrap_or(count)).rev().find(enabled),
224        ChoiceKey::Down => (current.map_or(0, |index| index + 1)..count).find(enabled),
225        ChoiceKey::Home => (0..count).find(enabled),
226        ChoiceKey::End => (0..count).rev().find(enabled),
227        ChoiceKey::PageUp => {
228            let Some(current) = current else {
229                return (0..count).find(enabled);
230            };
231            let target = current.saturating_sub(page);
232            (0..=target)
233                .rev()
234                .find(enabled)
235                .or_else(|| (target..current).find(enabled))
236        }
237        ChoiceKey::PageDown => {
238            let target = current.map_or(0, |index| (index + page).min(last));
239            (target..count).find(enabled).or_else(|| {
240                (current.map_or(0, |index| index + 1)..target)
241                    .rev()
242                    .find(enabled)
243            })
244        }
245        _ => None,
246    }
247}
248
249pub struct ComboGeometry {
250    pub entry: Rect,
251    pub trigger: Rect,
252}
253
254impl ComboGeometry {
255    const TRIGGER_WIDTH: f32 = 28.0;
256    const LABEL_INSET: f32 = 8.0;
257
258    pub fn new(bounds: Rect) -> Self {
259        Self::with_layout_direction(bounds, LayoutDirection::LeftToRight)
260    }
261
262    /// Default arrow geometry. For a control with replacement artwork, use `for_control`.
263    pub fn for_layout(layout: &LayoutNode) -> Self {
264        Self::with_layout_direction(layout.bounds, layout.layout_direction)
265    }
266
267    pub fn with_layout_direction(bounds: Rect, direction: LayoutDirection) -> Self {
268        Self::with_indicator(bounds, direction, None)
269    }
270
271    /// Measure the replacement artwork against the same bounds used by painting and input.
272    pub fn for_control(node: &Node, bounds: Rect, direction: LayoutDirection) -> Self {
273        let indicator = node
274            .control_part("ComboIndicator")
275            .map(Self::indicator_size);
276        Self::with_indicator(bounds, direction, indicator)
277    }
278
279    fn indicator_size(indicator: &Node) -> Size {
280        Size::new(
281            indicator.length("width").unwrap_or(16.0).max(0.0),
282            indicator.length("height").unwrap_or(16.0).max(0.0),
283        )
284    }
285
286    pub(crate) fn preferred_size(
287        node: &Node,
288        available: Size,
289        text: &mut impl TextMeasurer,
290    ) -> Size {
291        let indicator = node
292            .control_part("ComboIndicator")
293            .map(Self::indicator_size);
294        let trigger = Self::trigger_width(indicator);
295        let content = node.combo_content().map_or_else(Size::default, |content| {
296            let available = Size::new(
297                (available.width - trigger - Self::LABEL_INSET).max(0.0),
298                available.height,
299            );
300            crate::linear::measure_replacement_content(content, available, text)
301        });
302        let (entry_width, vertical_padding) = if xrack_runtime::combo_editable(node) {
303            let padding = crate::linear::Padding::for_editor(node).size();
304            (116.0 + padding.width, padding.height)
305        } else {
306            (128.0, 10.0)
307        };
308        Size::new(
309            trigger + entry_width.max(content.width + Self::LABEL_INSET),
310            (text.font_size(node) * 1.4 + vertical_padding)
311                .max(34.0)
312                .max(indicator.map_or(0.0, |size| size.height + 8.0))
313                .max(content.height),
314        )
315    }
316
317    /// The inset used by the selected label and replacement content.
318    #[doc(hidden)]
319    pub fn label_bounds(&self, direction: LayoutDirection) -> Rect {
320        let entry = self.entry;
321        let inset = entry.width.min(Self::LABEL_INSET);
322        let x = if direction == LayoutDirection::RightToLeft {
323            entry.x
324        } else {
325            entry.x + inset
326        };
327        Rect::new(x, entry.y, entry.width - inset, entry.height)
328    }
329
330    fn trigger_width(indicator: Option<Size>) -> f32 {
331        Self::TRIGGER_WIDTH.max(indicator.map_or(0.0, |size| size.width + 12.0))
332    }
333
334    fn with_indicator(bounds: Rect, direction: LayoutDirection, indicator: Option<Size>) -> Self {
335        let trigger = bounds.width.min(Self::trigger_width(indicator));
336        let entry = bounds.width - trigger;
337        let mirror = |rect| place_in_direction(rect, bounds, direction);
338        Self {
339            entry: mirror(Rect::new(bounds.x, bounds.y, entry, bounds.height)),
340            trigger: mirror(Rect::new(
341                bounds.x + entry,
342                bounds.y,
343                trigger,
344                bounds.height,
345            )),
346        }
347    }
348
349    pub(crate) fn indicator_bounds(&self, part: &Node) -> Rect {
350        let size = Self::indicator_size(part);
351        let width = size.width.min(self.trigger.width);
352        let height = size.height.min(self.trigger.height);
353        Rect::new(
354            self.trigger.x + (self.trigger.width - width) * 0.5,
355            self.trigger.y + (self.trigger.height - height) * 0.5,
356            width,
357            height,
358        )
359    }
360}
361
362pub struct ChoiceMenu<'a> {
363    pub control: &'a Node,
364    pub bounds: Rect,
365    pub layout_direction: LayoutDirection,
366    pub rows: Cow<'a, [String]>,
367    pub first: usize,
368    pub highlighted: Option<usize>,
369    pub selected: Option<usize>,
370    pub font_size: f32,
371    rows_bounds: Rect,
372    metrics: PopupMetrics,
373}
374
375impl ChoiceMenu<'_> {
376    #[doc(hidden)]
377    pub fn popup_style(&self) -> Option<&Node> {
378        popup_style(self.control)
379    }
380
381    pub fn rows_bounds(&self) -> Rect {
382        self.rows_bounds
383    }
384
385    pub fn scroll_indicator(&self) -> Option<Rect> {
386        let metrics = &self.metrics;
387        let total = choice_count(self.control);
388        let visible = self.rows.len();
389        if !metrics.scroll_indicator || visible == 0 || visible >= total {
390            return None;
391        }
392        let inner = metrics.interior(self.bounds);
393        let gutter = PopupMetrics::gutter(inner.width);
394        let width = (gutter * 0.5).min(4.0);
395        let height = (inner.height * visible as f32 / total as f32)
396            .max(10.0)
397            .min(inner.height);
398        let offset = self.first as f32 / (total - visible) as f32;
399        let x = inner.x + inner.width - (gutter + width) * 0.5;
400        let thumb = Rect::new(x, inner.y + (inner.height - height) * offset, width, height);
401        Some(place_in_direction(thumb, inner, self.layout_direction))
402    }
403
404    #[doc(hidden)]
405    pub fn option_input(&self, offset: usize) -> Option<ComboOptionInput> {
406        let text = self.rows.get(offset)?.clone();
407        let index = self.first + offset;
408        Some(ComboOptionInput::new(
409            self.control,
410            index,
411            text,
412            self.selected == Some(index),
413            self.highlighted == Some(index),
414        ))
415    }
416
417    pub fn row_enabled(&self, offset: usize) -> bool {
418        offset < self.rows.len() && choice_enabled(self.control, self.first + offset)
419    }
420
421    #[doc(hidden)]
422    pub fn can_scroll(&self, backward: bool) -> bool {
423        if backward {
424            self.first > 0
425        } else {
426            self.first + self.rows.len() < choice_count(self.control)
427        }
428    }
429
430    pub fn row_bounds(&self, offset: usize) -> Rect {
431        let rows = self.rows_bounds();
432        let height = rows.height / self.rows.len() as f32;
433        Rect::new(rows.x, rows.y + height * offset as f32, rows.width, height)
434    }
435}
436
437fn popup_style(node: &Node) -> Option<&Node> {
438    (node.kind == "ComboBox")
439        .then(|| node.control_part("ComboPopup"))
440        .flatten()
441}
442
443struct PopupMetrics {
444    row_height: f32,
445    padding: f32,
446    scroll_indicator: bool,
447}
448
449impl PopupMetrics {
450    fn new(style: Option<&Node>, font_size: f32, scale: f32) -> Self {
451        let positive = |name| {
452            style
453                .and_then(|style| style.length(name))
454                .filter(|&value| value > 0.0)
455        };
456        let height = positive("row-height").unwrap_or(ROW_HEIGHT);
457        let row_height = if scale > 1.0 {
458            (height * scale).max(font_size * 1.4 + 8.0)
459        } else {
460            height.max(1.0)
461        };
462        let padding = positive("padding").unwrap_or(0.0);
463        Self {
464            row_height,
465            padding,
466            scroll_indicator: style.is_some_and(|style| style.boolean("scroll-indicator", false)),
467        }
468    }
469
470    fn vertical_padding(&self, height: f32) -> f32 {
471        self.padding.min((height - self.row_height).max(0.0) * 0.5)
472    }
473
474    fn interior(&self, bounds: Rect) -> Rect {
475        let x = self.padding.min((bounds.width - 1.0).max(0.0) * 0.5);
476        let y = self.vertical_padding(bounds.height);
477        Rect::new(
478            bounds.x + x,
479            bounds.y + y,
480            bounds.width - 2.0 * x,
481            bounds.height - 2.0 * y,
482        )
483    }
484
485    fn gutter(width: f32) -> f32 {
486        (width * 0.25).min(10.0)
487    }
488
489    fn rows(&self, bounds: Rect, scrolling: bool, direction: LayoutDirection) -> Rect {
490        let inner = self.interior(bounds);
491        let width = if self.scroll_indicator && scrolling {
492            inner.width - Self::gutter(inner.width)
493        } else {
494            inner.width
495        };
496        place_in_direction(
497            Rect::new(inner.x, inner.y, width, inner.height),
498            inner,
499            direction,
500        )
501    }
502}
503
504pub(crate) struct ChoiceGeometry {
505    bounds: Rect,
506    rows: Rect,
507    visible: usize,
508    direction: LayoutDirection,
509    metrics: PopupMetrics,
510    font_size: f32,
511}
512
513impl ChoiceGeometry {
514    fn row_at(&self, point: Point) -> Option<usize> {
515        if !self.rows.contains(point) {
516            return None;
517        }
518        let offset = ((point.y - self.rows.y) / self.rows.height * self.visible as f32) as usize;
519        (offset < self.visible).then_some(offset)
520    }
521}
522
523fn geometry(
524    node: &Node,
525    anchor: Rect,
526    viewport: Rect,
527    direction: LayoutDirection,
528    typography: PopupTypography,
529    floating_keyboard: Option<Rect>,
530) -> Option<ChoiceGeometry> {
531    let len = choice_count(node);
532    if len == 0 || viewport.width <= 0.0 || viewport.height <= 0.0 {
533        return None;
534    }
535    let style = popup_style(node);
536    let font_size = typography.size(node, 14.0);
537    let metrics = PopupMetrics::new(style, font_size, typography.scale);
538    let dimension = |name, reference| {
539        style
540            .and_then(|style| style.relative_length(name, reference))
541            .filter(|&value| value > 0.0)
542    };
543    let limit = dimension("max-height", viewport.height)
544        .unwrap_or(metrics.row_height * MAX_ROWS as f32 + 2.0 * metrics.padding)
545        .min(viewport.height);
546    let desired =
547        (metrics.row_height * len as f32 + 2.0 * metrics.vertical_padding(limit)).min(limit);
548    let width = dimension("width", anchor.width)
549        .unwrap_or_else(|| anchor.width.max(96.0) * typography.scale.max(1.0))
550        .min(viewport.width);
551    let aligned_x = if direction == LayoutDirection::RightToLeft {
552        anchor.x + anchor.width - width
553    } else {
554        anchor.x
555    };
556    let place = |area: Rect, avoid_anchor: bool| {
557        if area.width < width || area.height <= 0.0 {
558            return None;
559        }
560        let bottom = area.y + area.height;
561        let below = (bottom - (anchor.y + anchor.height).max(area.y)).max(0.0);
562        let above = (anchor.y.min(bottom) - area.y).max(0.0);
563        let down = below >= desired || below >= above;
564        let space = if down { below } else { above };
565        let min_row = metrics.row_height.min(limit);
566        if avoid_anchor && space < min_row {
567            return None;
568        }
569        let available = space.min(limit).max(min_row);
570        let padding = 2.0 * metrics.vertical_padding(available);
571        let visible = (((available - padding) / metrics.row_height) as usize).clamp(1, len);
572        let height = (visible as f32 * metrics.row_height + padding).min(available);
573        let x = aligned_x.clamp(area.x, area.x + (area.width - width));
574        let y = if down {
575            anchor.y + anchor.height
576        } else {
577            anchor.y - height
578        };
579        let y = y.clamp(area.y, area.y + (area.height - height).max(0.0));
580        Some((Rect::new(x, y, width, height), visible))
581    };
582    let (original, visible) = place(viewport, false)?;
583    let keyboard = floating_keyboard.map(|keyboard| keyboard.intersect(viewport));
584    let (bounds, visible) = if let Some(keyboard) = keyboard.filter(|keyboard| {
585        let covered = original.intersect(*keyboard);
586        covered.width > 0.0 && covered.height > 0.0
587    }) {
588        let right = keyboard.x + keyboard.width;
589        let bottom = keyboard.y + keyboard.height;
590        let free_areas = [
591            Rect::new(
592                viewport.x,
593                viewport.y,
594                viewport.width,
595                keyboard.y - viewport.y,
596            ),
597            Rect::new(
598                viewport.x,
599                bottom,
600                viewport.width,
601                viewport.y + viewport.height - bottom,
602            ),
603            Rect::new(
604                viewport.x,
605                viewport.y,
606                keyboard.x - viewport.x,
607                viewport.height,
608            ),
609            Rect::new(
610                right,
611                viewport.y,
612                viewport.x + viewport.width - right,
613                viewport.height,
614            ),
615        ];
616        let distance = |bounds: Rect| (bounds.x - original.x).abs() + (bounds.y - original.y).abs();
617        free_areas
618            .into_iter()
619            .filter_map(|area| place(area, true))
620            .max_by(|(left, left_rows), (right, right_rows)| {
621                left_rows
622                    .cmp(right_rows)
623                    .then_with(|| distance(*right).total_cmp(&distance(*left)))
624            })?
625    } else {
626        (original, visible)
627    };
628    Some(ChoiceGeometry {
629        bounds,
630        rows: metrics.rows(bounds, len > visible, direction),
631        visible,
632        direction,
633        metrics,
634        font_size,
635    })
636}
637
638#[derive(Clone, Debug)]
639pub(crate) struct ChoicePopup {
640    pub target: Target,
641    kind: &'static str,
642    highlight: Option<usize>,
643    highlighted_value: Option<String>,
644    highlighted_row: Option<RowKey>,
645    first: usize,
646    press: Option<(usize, ChoiceIdentity)>,
647    handle: Option<ComboPopupHandle>,
648    session: u64,
649}
650
651#[derive(Clone, Debug)]
652pub(crate) struct ChoicePan {
653    session: u64,
654    remainder: f32,
655}
656
657impl ChoicePan {
658    pub(crate) fn advance(
659        &mut self,
660        popup: &mut ChoicePopup,
661        scene: &Node,
662        layout: &LayoutNode,
663        delta: f32,
664    ) -> bool {
665        if self.session != popup.session {
666            return false;
667        }
668        let Some((_, geometry)) = popup.resolve(scene, layout) else {
669            return false;
670        };
671        let row_height = geometry.rows.height / geometry.visible as f32;
672        self.remainder += delta;
673        let rows = (self.remainder / row_height).trunc() as isize;
674        self.remainder %= row_height;
675        rows != 0 && popup.scroll(scene, layout, rows)
676    }
677}
678
679impl ChoicePopup {
680    pub(crate) fn artwork_dirty(&self, scene: &Node, layout: &LayoutNode) -> bool {
681        self.node(scene, layout)
682            .and_then(|node| node.combo_option_renderer.as_ref())
683            .is_some_and(|renderer| renderer.artwork_dirty())
684    }
685
686    pub fn open(target: Target, scene: &Node, layout: &LayoutNode) -> Option<Self> {
687        static NEXT_SESSION: AtomicU64 = AtomicU64::new(1);
688        let kind = scene.at_path(&target.path)?.kind;
689        if !matches!(kind, "ComboBox" | "SearchField") {
690            return None;
691        }
692        let mut popup = Self {
693            target,
694            kind,
695            highlight: None,
696            highlighted_value: None,
697            highlighted_row: None,
698            first: 0,
699            press: None,
700            handle: None,
701            session: NEXT_SESSION.fetch_add(1, Ordering::Relaxed),
702        };
703        let node = popup.node(scene, layout)?;
704        if node.kind == "SearchField" {
705            return popup.reconcile(scene, layout).then_some(popup);
706        }
707        let current = combo_index(node);
708        let index = node
709            .text("edit-text")
710            .filter(|draft| combo_editable(node) && !draft.is_empty())
711            .filter(|draft| combo_text(node) != *draft)
712            .and_then(|draft| {
713                combo_find_enabled_label(node, 0, |item| item == draft)
714                    .or_else(|| combo_find_enabled_label(node, 0, |item| item.starts_with(draft)))
715            })
716            .or_else(|| current.filter(|&index| choice_enabled(node, index)))
717            .or_else(|| combo_find_enabled_label(node, current.unwrap_or(0), |_| true));
718        if let Some(index) = index {
719            popup.highlight(node, index);
720        }
721        popup.reconcile(scene, layout).then_some(popup)
722    }
723
724    pub(crate) fn mounted(&mut self, scene: &Node) {
725        if let Some(node) = scene.at_path(&self.target.path) {
726            self.handle = node.combo_popup_handle.clone();
727            self.publish(node);
728        }
729    }
730
731    pub(crate) fn closed(self) {
732        if let Some(handle) = self.handle {
733            handle.publish(false, None);
734        }
735    }
736
737    fn publish(&self, node: &Node) {
738        if let Some(handle) = &self.handle {
739            handle.publish(true, self.highlighted(node));
740        }
741    }
742
743    fn node<'a>(&self, scene: &'a Node, layout: &LayoutNode) -> Option<&'a Node> {
744        if !valid(&self.target, scene, layout) {
745            return None;
746        }
747        scene.at_path(&self.target.path).filter(|node| {
748            node.kind == self.kind
749                && self
750                    .handle
751                    .as_ref()
752                    .is_none_or(|handle| node.combo_popup_handle.as_ref() == Some(handle))
753        })
754    }
755
756    fn resolve<'a>(
757        &self,
758        scene: &'a Node,
759        layout: &LayoutNode,
760    ) -> Option<(&'a Node, ChoiceGeometry)> {
761        let node = self.node(scene, layout)?;
762        let item = layout.at_path(&self.target.path)?;
763        let anchor = item.window_bounds(item.bounds);
764        Some((
765            node,
766            geometry(
767                node,
768                anchor,
769                window_safe_area(scene, layout.bounds),
770                item.layout_direction,
771                layout.popup_typography(),
772                layout.floating_keyboard(),
773            )?,
774        ))
775    }
776
777    pub(crate) fn pan_at(
778        &self,
779        scene: &Node,
780        layout: &LayoutNode,
781        point: Point,
782    ) -> Option<ChoicePan> {
783        let (_, geometry) = self.resolve(scene, layout)?;
784        geometry.bounds.contains(point).then_some(ChoicePan {
785            session: self.session,
786            remainder: 0.0,
787        })
788    }
789
790    pub fn view<'a>(&self, scene: &'a Node, layout: &LayoutNode) -> Option<ChoiceMenu<'a>> {
791        let (node, geo) = self.resolve(scene, layout)?;
792        let first = self.first.min(choice_count(node) - geo.visible);
793        let range = first..first + geo.visible;
794        Some(ChoiceMenu {
795            control: node,
796            bounds: geo.bounds,
797            layout_direction: geo.direction,
798            rows: if node.kind == "SearchField" {
799                Cow::Borrowed(&search_suggestions(node)[range])
800            } else {
801                combo_labels(node, range)
802            },
803            first,
804            highlighted: self.highlighted(node),
805            selected: (node.kind == "ComboBox")
806                .then(|| combo_index(node))
807                .flatten(),
808            font_size: geo.font_size,
809            rows_bounds: geo.rows,
810            metrics: geo.metrics,
811        })
812    }
813
814    pub fn reconcile(&mut self, scene: &Node, layout: &LayoutNode) -> bool {
815        let Some((node, geo)) = self.resolve(scene, layout) else {
816            return false;
817        };
818        let len = choice_count(node);
819        self.highlight = self.highlighted(node);
820        self.first = self.first.min(len - geo.visible);
821        if let Some(highlight) = self.highlight {
822            if highlight < self.first {
823                self.first = highlight;
824            } else if highlight >= self.first + geo.visible {
825                self.first = highlight + 1 - geo.visible;
826            }
827        }
828        self.publish(node);
829        true
830    }
831
832    fn highlighted(&self, node: &Node) -> Option<usize> {
833        let index = self.highlight?;
834        if node.kind == "SearchField" {
835            (search_suggestion(node, index) == self.highlighted_value.as_deref()
836                && self.highlighted_value.is_some())
837            .then_some(index)
838        } else {
839            let index = match self.highlighted_row {
840                Some(key) => combo_row_index(node, key)?,
841                None => index.min(choice_count(node).saturating_sub(1)),
842            };
843            choice_enabled(node, index).then_some(index)
844        }
845    }
846
847    fn highlight(&mut self, node: &Node, index: usize) {
848        if node.kind == "SearchField" {
849            self.highlighted_value = search_suggestion(node, index).map(str::to_owned);
850            self.highlight = self.highlighted_value.as_ref().map(|_| index);
851        } else {
852            self.highlighted_row = combo_row_key(node, index);
853            self.highlight = Some(index);
854        }
855        self.publish(node);
856    }
857
858    fn pick<'a>(
859        &self,
860        scene: &'a Node,
861        layout: &LayoutNode,
862        point: Point,
863    ) -> Option<(&'a Node, usize)> {
864        let (node, geo) = self.resolve(scene, layout)?;
865        let offset = geo.row_at(point)?;
866        let first = self.first.min(choice_count(node) - geo.visible);
867        Some((node, first + offset))
868    }
869
870    pub fn hover(&mut self, scene: &Node, layout: &LayoutNode, point: Point) -> bool {
871        let Some((node, index)) = self.pick(scene, layout, point) else {
872            return false;
873        };
874        if !choice_enabled(node, index) {
875            return false;
876        }
877        let previous = self.highlighted(node);
878        self.highlight(node, index);
879        previous != self.highlight
880    }
881
882    pub fn press(&mut self, scene: &Node, layout: &LayoutNode, point: Point) -> bool {
883        self.press = None;
884        let Some((node, geo)) = self.resolve(scene, layout) else {
885            return false;
886        };
887        if let Some(offset) = geo.row_at(point) {
888            let index = self.first.min(choice_count(node) - geo.visible) + offset;
889            if choice_enabled(node, index) {
890                self.highlight(node, index);
891                self.press = choice_identity(node, index).map(|identity| (index, identity));
892            }
893        }
894        geo.bounds.contains(point)
895    }
896
897    pub fn release(&mut self, scene: &Node, layout: &LayoutNode, point: Point) -> Option<usize> {
898        let (pressed, previous) = self.press.take()?;
899        let (node, index) = self.pick(scene, layout, point)?;
900        (index == pressed
901            && choice_enabled(node, index)
902            && choice_identity(node, index).as_ref() == Some(&previous))
903        .then_some(index)
904    }
905
906    pub fn move_highlight(&mut self, scene: &Node, layout: &LayoutNode, key: ChoiceKey) {
907        let Some((node, geo)) = self.resolve(scene, layout) else {
908            return;
909        };
910        if let Some(index) = next_choice(node, self.highlighted(node), key, geo.visible) {
911            self.highlight(node, index);
912            self.reconcile(scene, layout);
913        }
914    }
915
916    pub fn typeahead(
917        &mut self,
918        scene: &Node,
919        layout: &LayoutNode,
920        search: &mut Typeahead,
921        text: &str,
922        now: Instant,
923    ) {
924        let Some(node) = self.node(scene, layout) else {
925            return;
926        };
927        if let Some(index) = search.find(node, text, now, self.highlighted(node)) {
928            self.highlight(node, index);
929            self.reconcile(scene, layout);
930        }
931    }
932
933    pub fn selected(&self, scene: &Node, layout: &LayoutNode) -> Option<usize> {
934        self.highlighted(self.resolve(scene, layout)?.0)
935    }
936
937    pub fn scroll(&mut self, scene: &Node, layout: &LayoutNode, rows: isize) -> bool {
938        let Some((node, geo)) = self.resolve(scene, layout) else {
939            return false;
940        };
941        let before = self.first;
942        self.first = self
943            .first
944            .saturating_add_signed(rows)
945            .min(choice_count(node) - geo.visible);
946        if let Some(highlight) = self.highlighted(node) {
947            let end = self.first + geo.visible;
948            let index = if highlight >= end {
949                (self.first..end)
950                    .rev()
951                    .find(|&index| choice_enabled(node, index))
952            } else {
953                (highlight.max(self.first)..end).find(|&index| choice_enabled(node, index))
954            };
955            if let Some(index) = index {
956                self.highlight(node, index);
957            } else {
958                self.highlight = None;
959            }
960        }
961        self.press = None;
962        self.publish(node);
963        self.first != before
964    }
965}
966
967fn choice_count(node: &Node) -> usize {
968    if node.kind == "SearchField" {
969        search_suggestions(node).len()
970    } else {
971        combo_count(node)
972    }
973}