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`.
35#[must_use]
36pub struct ComboBox {
37    items: Signal<Vec<String>>,
38    text: Signal<String>,
39    placeholder: Option<TextSource>,
40}
41
42/// `combo_box(items, text)`: free-form text entry plus a native dropdown of suggestions.
43/// Typing (or picking an item) writes `text`; setting either signal patches the control.
44pub fn combo_box(items: Signal<Vec<String>>, text: Signal<String>) -> ComboBox {
45    ComboBox {
46        items,
47        text,
48        placeholder: None,
49    }
50}
51
52#[crate::builder(ComboBoxBuilder)]
53impl ComboBox {
54    /// The empty-state prompt shown while the entry has no text (a constant, `Signal<String>`, or
55    /// closure, evaluated once for the initial value; not reactive after build).
56    pub fn placeholder<M>(mut self, t: impl IntoText<M>) -> Self {
57        self.placeholder = Some(t.into_text());
58        self
59    }
60}
61
62impl Piece for ComboBox {
63    fn build(self, cx: &mut BuildCx) -> RNode {
64        let ComboBox {
65            items,
66            text,
67            placeholder,
68        } = self;
69        let initial_items = items.get_untracked();
70        let initial_text = text.get_untracked();
71        let ph = placeholder.map_or_default(|p| p.initial());
72        let node = cx.leaf(
73            KIND,
74            &ComboProps {
75                items: initial_items.clone(),
76                text: initial_text.clone(),
77                placeholder: ph,
78            },
79            // A text entry fills the available width and keeps its natural (single-line) height.
80            Flex {
81                grow_w: true,
82                ..Default::default()
83            },
84        );
85        bind_seeded(
86            initial_items,
87            move || items.get(),
88            move |v: &Vec<String>| {
89                with_tree(|t| t.patch(node, Box::new(ComboPatch::Items(v.clone())), true));
90            },
91        );
92        // Controlled input with origin tracking (§4.4): the echo guard remembers the last value
93        // that arrived from the native control so bind_seeded does not patch it straight back.
94        let guard: Rc<RefCell<Option<String>>> = Rc::new(RefCell::new(None));
95        let g = guard.clone();
96        bind_seeded(
97            initial_text,
98            move || text.get(),
99            move |t: &String| {
100                let from_native = g.borrow_mut().take().as_deref() == Some(t.as_str());
101                if !from_native {
102                    with_tree(|tr| tr.patch(node, Box::new(ComboPatch::SetText(t.clone())), false));
103                }
104            },
105        );
106        cx.on(node, move |ev| match ev {
107            Event::TextChanged(t) => {
108                *guard.borrow_mut() = Some(t.clone());
109                text.set(t.clone());
110            }
111            // Menu-driven selection by index. Native backends report picks as TextChanged (the
112            // pick sets the entry text), so this arm serves the synthetic path (dayscript's
113            // `select` step), mapping the index through the current items. No guard poke: the
114            // native control did not originate this, so the SetText patch must reach it.
115            Event::SelectionChanged(i) => {
116                if *i >= 0
117                    && let Some(t) = items.get_untracked().get(*i as usize)
118                {
119                    text.set(t.clone());
120                }
121            }
122            _ => {}
123        });
124        node
125    }
126}
127
128// ---------------------------------------------------------------------------
129// Per-toolkit native renderers, one file per backend, in the house `#[cfg]`/`#[path]` gates.
130// No uikit arm: iOS has no native combo-box control (day renders its placeholder leaf there).
131// ---------------------------------------------------------------------------
132
133// --- Typed builders, forwarded through `Decorated` (docs/api-style.md) ---
134
135/// The combo box's conformance cases (docs/testing.md).
136#[cfg(feature = "conformance")]
137pub mod conformance {
138    use crate::*;
139    use day_core::conformance::{Case, Drive};
140    use day_reactive::Signal;
141
142    use super::{KIND, combo_box};
143
144    fn page() -> impl day_core::Piece {
145        let items = Signal::new(vec![
146            "Vanilla".to_string(),
147            "Chocolate".into(),
148            "Pistachio".into(),
149        ]);
150        let text = Signal::new(String::new());
151        column((
152            label(move || format!("chose {}", text.get())).id(day_core::id!(combobox::chose)),
153            combo_box(items, text)
154                .placeholder("Flavor")
155                .id(day_core::id!(combobox::combo)),
156        ))
157    }
158
159    /// Choosing from the menu writes the item's text.
160    #[day_macros::test(day_core)]
161    fn combobox_menu_selects() -> Case {
162        Case::new()
163            .proves(KIND)
164            .page(page)
165            .drive(|d: Drive| async move {
166                d.select("combobox::combo", 2).await?;
167                d.assert_text("combobox::chose", "chose Pistachio").await
168            })
169    }
170
171    /// Typing writes free-form text that is in no menu item.
172    #[day_macros::test(day_core)]
173    fn combobox_free_text() -> Case {
174        Case::new()
175            .proves(KIND)
176            .page(page)
177            .drive(|d: Drive| async move {
178                d.input("combobox::combo", "Stracciatella").await?;
179                d.assert_text("combobox::chose", "chose Stracciatella")
180                    .await
181            })
182    }
183}
184
185/// Whether the selected toolkit implements this control.
186#[must_use]
187pub fn support() -> day_spec::Support {
188    day_core::capability(day_spec::Cap::ComboBox)
189}