Skip to main content

day_pieces/
combobox.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Core editable combo box. Protocol types live in `day-spec`; each supported toolkit owns
5//! its native renderer and any required C++ or Java shim.
6//!
7//! A combo box: free-form text entry plus a dropdown of suggestions, as the platform's
8//! native combo control: `NSComboBox` (AppKit), `GtkComboBoxText` with an entry (GTK), an
9//! editable `QComboBox` (Qt), `AutoCompleteTextView` (Android), an editable `ComboBox` (XAML).
10//! Because a typed value need not be in the list, the value is the text: a `Signal<String>`
11//! bound two-way, exactly like `search_field` (typing sets the signal; setting the signal
12//! patches the control, echo-guarded). Picking a dropdown item is just another way to set the
13//! text; every backend reports it through the same `Event::TextChanged`. The suggestion list
14//! is reactive: `items` is a `Signal<Vec<String>>` and changes patch the native list live.
15//!
16//! iOS has no native combo-box control, so this piece carries **no uikit renderer**; day
17//! renders its placeholder leaf there (docs/combobox.md).
18//!
19//! ```ignore
20//! let flavor = Signal::new(String::new());
21//! combo_box(flavors, flavor).placeholder(res::str::combo_placeholder())
22//! ```
23
24use crate::Decorated;
25use crate::{IntoText, TextSource};
26use day_core::{BuildCx, Flex, Piece, RNode, with_tree};
27use day_reactive::{Signal, bind_seeded};
28use day_spec::Event;
29use std::cell::RefCell;
30use std::rc::Rc;
31
32pub use day_spec::controls::combobox::*;
33
34/// A native combo box bound two-way to `text`, with a reactive dropdown of `items`.
35pub struct ComboBox {
36    items: Signal<Vec<String>>,
37    text: Signal<String>,
38    placeholder: Option<TextSource>,
39}
40
41/// `combo_box(items, text)`: free-form text entry plus a native dropdown of suggestions.
42/// Typing (or picking an item) writes `text`; setting either signal patches the control.
43pub fn combo_box(items: Signal<Vec<String>>, text: Signal<String>) -> ComboBox {
44    ComboBox {
45        items,
46        text,
47        placeholder: None,
48    }
49}
50
51#[crate::builder(ComboBoxBuilder)]
52impl ComboBox {
53    /// The empty-state prompt shown while the entry has no text (a constant, `Signal<String>`, or
54    /// closure, evaluated once for the initial value; not reactive after build).
55    pub fn placeholder<M>(mut self, t: impl IntoText<M>) -> Self {
56        self.placeholder = Some(t.into_text());
57        self
58    }
59}
60
61impl Piece for ComboBox {
62    fn build(self, cx: &mut BuildCx) -> RNode {
63        let ComboBox {
64            items,
65            text,
66            placeholder,
67        } = self;
68        let initial_items = items.get_untracked();
69        let initial_text = text.get_untracked();
70        let ph = placeholder.map(|p| p.initial()).unwrap_or_default();
71        let node = cx.leaf(
72            KIND,
73            &ComboProps {
74                items: initial_items.clone(),
75                text: initial_text.clone(),
76                placeholder: ph,
77            },
78            // A text entry fills the available width and keeps its natural (single-line) height.
79            Flex {
80                grow_w: true,
81                ..Default::default()
82            },
83        );
84        bind_seeded(
85            initial_items,
86            move || items.get(),
87            move |v: &Vec<String>| {
88                with_tree(|t| t.patch(node, Box::new(ComboPatch::Items(v.clone())), true));
89            },
90        );
91        // Controlled input with origin tracking (§4.4): the echo guard remembers the last value
92        // that arrived from the native control so bind_seeded does not patch it straight back.
93        let guard: Rc<RefCell<Option<String>>> = Rc::new(RefCell::new(None));
94        let g = guard.clone();
95        bind_seeded(
96            initial_text,
97            move || text.get(),
98            move |t: &String| {
99                let from_native = g.borrow_mut().take().as_deref() == Some(t.as_str());
100                if !from_native {
101                    with_tree(|tr| tr.patch(node, Box::new(ComboPatch::SetText(t.clone())), false));
102                }
103            },
104        );
105        cx.on(node, move |ev| match ev {
106            Event::TextChanged(t) => {
107                *guard.borrow_mut() = Some(t.clone());
108                text.set(t.clone());
109            }
110            // Menu-driven selection by index. Native backends report picks as TextChanged (the
111            // pick sets the entry text), so this arm serves the synthetic path (dayscript's
112            // `select` step), mapping the index through the current items. No guard poke: the
113            // native control did not originate this, so the SetText patch must reach it.
114            Event::SelectionChanged(i) => {
115                if *i >= 0
116                    && let Some(t) = items.get_untracked().get(*i as usize)
117                {
118                    text.set(t.clone());
119                }
120            }
121            _ => {}
122        });
123        node
124    }
125}
126
127// ---------------------------------------------------------------------------
128// Per-toolkit native renderers, one file per backend, in the house `#[cfg]`/`#[path]` gates.
129// No uikit arm: iOS has no native combo-box control (day renders its placeholder leaf there).
130// ---------------------------------------------------------------------------
131
132// --- Typed builders, forwarded through `Decorated` (docs/api-style.md) ---
133
134/// The combo box's conformance cases (docs/testing.md).
135#[cfg(feature = "conformance")]
136pub mod conformance {
137    use crate::*;
138    use day_core::conformance::{Case, Drive};
139    use day_reactive::Signal;
140
141    use super::{KIND, combo_box};
142
143    fn page() -> impl day_core::Piece {
144        let items = Signal::new(vec![
145            "Vanilla".to_string(),
146            "Chocolate".into(),
147            "Pistachio".into(),
148        ]);
149        let text = Signal::new(String::new());
150        column((
151            label(move || format!("chose {}", text.get())).id(day_core::id!(combobox::chose)),
152            combo_box(items, text)
153                .placeholder("Flavor")
154                .id(day_core::id!(combobox::combo)),
155        ))
156    }
157
158    /// Choosing from the menu writes the item's text.
159    #[day_macros::test(day_core)]
160    fn combobox_menu_selects() -> Case {
161        Case::new()
162            .proves(KIND)
163            .page(page)
164            .drive(|d: Drive| async move {
165                d.select("combobox::combo", 2).await?;
166                d.assert_text("combobox::chose", "chose Pistachio").await
167            })
168    }
169
170    /// Typing writes free-form text that is in no menu item.
171    #[day_macros::test(day_core)]
172    fn combobox_free_text() -> Case {
173        Case::new()
174            .proves(KIND)
175            .page(page)
176            .drive(|d: Drive| async move {
177                d.input("combobox::combo", "Stracciatella").await?;
178                d.assert_text("combobox::chose", "chose Stracciatella")
179                    .await
180            })
181    }
182}
183
184/// Whether the selected toolkit implements this control.
185pub fn support() -> day_spec::Support {
186    day_core::capability(day_spec::Cap::ComboBox)
187}