Skip to main content

xrack_runtime/
combo.rs

1use crate::{ChangeSignal, ControlAction, InputRoute, Node, Property, RowKey, Value, VecModel};
2use std::{
3    any::Any,
4    borrow::Cow,
5    cell::{Cell, RefCell},
6    fmt,
7    ops::Range,
8    rc::Rc,
9};
10
11#[derive(Clone, Default)]
12#[doc(hidden)]
13pub struct ComboPopupHandle(Rc<ComboPopupState>);
14
15#[derive(Default)]
16struct ComboPopupState {
17    open: Property<bool>,
18    highlighted: Property<i64>,
19}
20
21impl ComboPopupHandle {
22    pub fn popup_open(&self) -> bool {
23        self.0.open.get(|| false)
24    }
25
26    pub fn highlighted_index(&self) -> i64 {
27        self.0.highlighted.get(|| -1)
28    }
29
30    pub fn publish(&self, open: bool, highlighted: Option<usize>) {
31        self.0.open.set_if_changed(open);
32        self.0
33            .highlighted
34            .set_if_changed(highlighted.map_or(-1, |index| index as i64));
35    }
36}
37
38impl PartialEq for ComboPopupHandle {
39    fn eq(&self, other: &Self) -> bool {
40        Rc::ptr_eq(&self.0, &other.0)
41    }
42}
43
44impl fmt::Debug for ComboPopupHandle {
45    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
46        formatter
47            .debug_struct("ComboPopupHandle")
48            .finish_non_exhaustive()
49    }
50}
51
52#[doc(hidden)]
53pub struct ComboOptionInput {
54    pub text: String,
55    pub index: i64,
56    pub enabled: bool,
57    pub selected: bool,
58    pub highlighted: bool,
59    pub displacement: f64,
60    pub progress: f64,
61    numeric: bool,
62    record_rows: Option<Rc<dyn Rows>>,
63}
64
65impl ComboOptionInput {
66    pub fn new(node: &Node, index: usize, text: String, selected: bool, highlighted: bool) -> Self {
67        Self {
68            text,
69            index: index as i64,
70            enabled: choice_enabled(node, index),
71            selected,
72            highlighted,
73            displacement: 0.0,
74            progress: 0.5,
75            numeric: false,
76            record_rows: model(node).map(|model| model.items.rows.clone()),
77        }
78    }
79
80    pub(crate) fn for_tumbler(
81        index: usize,
82        text: String,
83        selected: bool,
84        enabled: bool,
85        displacement: f64,
86        numeric: bool,
87        records: Option<&ComboItems>,
88    ) -> Self {
89        Self {
90            index: index as i64,
91            text,
92            selected,
93            enabled,
94            highlighted: false,
95            displacement,
96            progress: 0.5,
97            numeric,
98            record_rows: records.map(|items| items.rows.clone()),
99        }
100    }
101
102    /// Fetch the row in its original representation and observe this row's changes.
103    pub fn record_data<T: Clone + 'static>(&self) -> Option<T> {
104        let rows = self.record_rows.as_ref()?;
105        let model = rows.source().downcast_ref::<VecModel<T>>()?;
106        model.row(self.index as usize)
107    }
108}
109
110#[derive(Clone, Copy)]
111#[doc(hidden)]
112pub enum ComboOptionParameter {
113    Data,
114    Text,
115    Index,
116    Enabled,
117    Selected,
118    Highlighted,
119    Displacement,
120    Progress,
121}
122
123impl ComboOptionParameter {
124    pub fn parse(name: &str) -> Option<Self> {
125        Some(match name {
126            "option-data" => Self::Data,
127            "option-text" => Self::Text,
128            "option-index" => Self::Index,
129            "option-enabled" => Self::Enabled,
130            "option-selected" => Self::Selected,
131            "option-highlighted" => Self::Highlighted,
132            "option-displacement" => Self::Displacement,
133            "option-progress" => Self::Progress,
134            _ => return None,
135        })
136    }
137
138    pub fn read(self, input: &ComboOptionInput) -> Value {
139        match self {
140            Self::Data if input.numeric => input.index.into(),
141            Self::Data => input
142                .record_data::<crate::RecordValue>()
143                .map_or_else(|| input.text.clone().into(), Value::Record),
144            Self::Text => input.text.clone().into(),
145            Self::Index => input.index.into(),
146            Self::Enabled => input.enabled.into(),
147            Self::Selected => input.selected.into(),
148            Self::Highlighted => input.highlighted.into(),
149            Self::Displacement => input.displacement.into(),
150            Self::Progress => input.progress.into(),
151        }
152    }
153}
154
155type RenderOption = dyn Fn(ComboOptionInput) -> Option<Node>;
156
157struct OptionArtwork {
158    render: Box<RenderOption>,
159    reads: RefCell<Option<Property<()>>>,
160}
161
162/// Produces artwork for a visible choice option.
163#[derive(Clone)]
164#[doc(hidden)]
165pub struct ComboOptionRenderer(Rc<OptionArtwork>);
166
167impl ComboOptionRenderer {
168    pub fn new(render: impl Fn(ComboOptionInput) -> Option<Node> + 'static) -> Self {
169        Self(Rc::new(OptionArtwork {
170            render: Box::new(render),
171            reads: RefCell::default(),
172        }))
173    }
174
175    pub fn render(&self, input: ComboOptionInput) -> Option<Node> {
176        (self.0.render)(input)
177    }
178
179    pub fn render_visible(
180        &self,
181        inputs: impl Iterator<Item = ComboOptionInput>,
182    ) -> Vec<Option<Node>> {
183        let reads = Property::default();
184        let mut options = Vec::new();
185        reads.get(|| options = inputs.map(self.0.render.as_ref()).collect());
186        // Keep the observed dependencies alive between frames.
187        self.0.reads.replace(Some(reads));
188        options
189    }
190
191    pub fn artwork_dirty(&self) -> bool {
192        self.0
193            .reads
194            .borrow()
195            .as_ref()
196            .is_some_and(Property::is_dirty)
197    }
198}
199
200impl PartialEq for ComboOptionRenderer {
201    fn eq(&self, other: &Self) -> bool {
202        Rc::ptr_eq(&self.0, &other.0)
203    }
204}
205
206impl fmt::Debug for ComboOptionRenderer {
207    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
208        formatter
209            .debug_struct("ComboOptionRenderer")
210            .finish_non_exhaustive()
211    }
212}
213
214trait Rows {
215    fn source(&self) -> &dyn Any;
216    fn structure(&self) -> (u64, u64);
217    fn len(&self) -> usize;
218    fn label(&self, index: usize) -> Option<String>;
219    fn value(&self, index: usize) -> Option<Value>;
220    fn enabled(&self, index: usize) -> bool;
221    fn key(&self, index: usize) -> Option<RowKey>;
222    fn index(&self, key: RowKey) -> Option<usize>;
223    fn find_label(
224        &self,
225        range: Range<usize>,
226        enabled_only: bool,
227        predicate: &mut dyn FnMut(&str) -> bool,
228    ) -> Option<usize>;
229    fn find_value(&self, value: &Value) -> Option<usize>;
230}
231
232type LabelProjection<T> = dyn Fn(&T) -> &str;
233type ValueProjection<T> = dyn Fn(&T) -> Value;
234type EnabledProjection<T> = dyn Fn(&T) -> bool;
235
236struct RecordRows<T> {
237    model: VecModel<T>,
238    label: Rc<LabelProjection<T>>,
239    value: Rc<ValueProjection<T>>,
240    enabled: Rc<EnabledProjection<T>>,
241}
242
243impl<T: 'static> Rows for RecordRows<T> {
244    fn source(&self) -> &dyn Any {
245        &self.model
246    }
247
248    fn structure(&self) -> (u64, u64) {
249        self.model.structure_stamp()
250    }
251    fn len(&self) -> usize {
252        self.model.len()
253    }
254    fn label(&self, index: usize) -> Option<String> {
255        self.model
256            .project_row_untracked(index, |row| (self.label)(row).to_owned())
257    }
258    fn value(&self, index: usize) -> Option<Value> {
259        self.model
260            .project_row_untracked(index, |row| (self.value)(row))
261    }
262    fn enabled(&self, index: usize) -> bool {
263        self.model
264            .project_row_untracked(index, |row| (self.enabled)(row))
265            .unwrap_or(false)
266    }
267    fn key(&self, index: usize) -> Option<RowKey> {
268        self.model.row_key(index)
269    }
270    fn index(&self, key: RowKey) -> Option<usize> {
271        self.model.row_index(key)
272    }
273    fn find_label(
274        &self,
275        range: Range<usize>,
276        enabled_only: bool,
277        predicate: &mut dyn FnMut(&str) -> bool,
278    ) -> Option<usize> {
279        self.model.position_untracked(range, |row| {
280            (!enabled_only || (self.enabled)(row)) && predicate((self.label)(row))
281        })
282    }
283    fn find_value(&self, value: &Value) -> Option<usize> {
284        self.model
285            .position_untracked(0..self.model.len(), |row| (self.value)(row) == *value)
286    }
287}
288
289/// A typed record projection shared by snapshots of choice controls.
290#[doc(hidden)]
291#[derive(Clone)]
292pub struct ComboItems {
293    rows: Rc<dyn Rows>,
294    changes: Rc<ChangeSignal>,
295    revision: Rc<Cell<u64>>,
296}
297
298impl ComboItems {
299    pub fn new<T: 'static>(
300        model: VecModel<T>,
301        label: impl Fn(&T) -> &str + 'static,
302        value: impl Fn(&T) -> Value + 'static,
303    ) -> Self {
304        Self::with_enabled(model, label, value, |_| true)
305    }
306
307    pub fn with_enabled<T: 'static>(
308        model: VecModel<T>,
309        label: impl Fn(&T) -> &str + 'static,
310        value: impl Fn(&T) -> Value + 'static,
311        enabled: impl Fn(&T) -> bool + 'static,
312    ) -> Self {
313        let label: Rc<LabelProjection<T>> = Rc::new(label);
314        let value: Rc<ValueProjection<T>> = Rc::new(value);
315        let enabled: Rc<EnabledProjection<T>> = Rc::new(enabled);
316        let revision = Rc::new(Cell::new(0_u64));
317        let changes = model.observe_projection_changes(usize::MAX, {
318            let label = label.clone();
319            let value = value.clone();
320            let enabled = enabled.clone();
321            let revision = revision.clone();
322            move |_, before, after| {
323                let changed = enabled(before) != enabled(after)
324                    || label(before) != label(after)
325                    || value(before) != value(after);
326                if changed {
327                    revision.set(revision.get().wrapping_add(1));
328                }
329                changed
330            }
331        });
332        Self {
333            rows: Rc::new(RecordRows {
334                model,
335                label,
336                value,
337                enabled,
338            }),
339            changes,
340            revision,
341        }
342    }
343
344    pub fn snapshot(&self, index: i64, value: Option<&Value>) -> ComboModel {
345        self.changes.track();
346        let structure = self.rows.structure();
347        let index = self.selected_index(index, value);
348        let selected = index.and_then(|index| Some((index, self.rows.label(index)?)));
349        ComboModel {
350            items: self.clone(),
351            structure,
352            revision: self.revision.get(),
353            selected,
354        }
355    }
356
357    pub fn count(&self) -> usize {
358        self.rows.len()
359    }
360
361    pub(crate) fn stamp(&self) -> ((u64, u64), u64) {
362        self.changes.track();
363        (self.rows.structure(), self.revision.get())
364    }
365
366    pub(crate) fn same_projection(&self, other: &Self) -> bool {
367        Rc::ptr_eq(&self.rows, &other.rows)
368    }
369
370    pub(crate) fn row_key(&self, index: usize) -> Option<RowKey> {
371        self.rows.key(index)
372    }
373
374    pub fn selected_index(&self, index: i64, value: Option<&Value>) -> Option<usize> {
375        if let Some(value) = value {
376            self.changes.track();
377            self.rows.structure();
378            self.rows.find_value(value)
379        } else {
380            usize::try_from(index)
381                .ok()
382                .filter(|&index| index < self.rows.len())
383        }
384    }
385
386    pub(crate) fn selected_text(&self, index: usize) -> Option<String> {
387        self.changes.track();
388        self.rows.structure();
389        self.rows.label(index)
390    }
391
392    pub(crate) fn selected_value(&self, index: usize) -> Option<Value> {
393        self.changes.track();
394        self.rows.structure();
395        self.rows.value(index)
396    }
397
398    /// Use the selection already read for the scene when projecting record options.
399    #[doc(hidden)]
400    pub fn populate_scene(&self, node: &mut Node) {
401        let index = node.int("current-index").unwrap_or(0);
402        let snapshot = self.snapshot(index, node.properties.get("current-value"));
403        node.properties.insert("model", Value::ComboModel(snapshot));
404    }
405}
406
407#[doc(hidden)]
408#[derive(Clone)]
409pub struct ComboModel {
410    items: ComboItems,
411    structure: (u64, u64),
412    revision: u64,
413    selected: Option<(usize, String)>,
414}
415
416impl fmt::Debug for ComboModel {
417    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
418        f.debug_struct("ComboModel")
419            .field("structure", &self.structure)
420            .field("revision", &self.revision)
421            .field("selected", &self.selected)
422            .finish()
423    }
424}
425
426impl PartialEq for ComboModel {
427    fn eq(&self, other: &Self) -> bool {
428        Rc::ptr_eq(&self.items.rows, &other.items.rows)
429            && self.structure == other.structure
430            && self.revision == other.revision
431            && self.selected == other.selected
432    }
433}
434
435fn model(node: &Node) -> Option<&ComboModel> {
436    match node.properties.get("model") {
437        Some(Value::ComboModel(model)) => Some(model),
438        _ => None,
439    }
440}
441
442pub fn combo_index(node: &Node) -> Option<usize> {
443    if let Some(model) = model(node) {
444        return model.selected.as_ref().map(|(index, _)| *index);
445    }
446    let model = node.strings("model");
447    if let Some(value) = node.text("current-value") {
448        model.iter().position(|item| item == value)
449    } else {
450        let index = usize::try_from(node.int("current-index").unwrap_or(0)).ok()?;
451        (index < model.len()).then_some(index)
452    }
453}
454
455fn string_combo_index(model: &VecModel<String>, index: i64, value: Option<&str>) -> Option<usize> {
456    if let Some(value) = value {
457        model.contents_stamp();
458        model.position_untracked(0..model.len(), |item| item == value)
459    } else {
460        usize::try_from(index)
461            .ok()
462            .filter(|&index| index < model.len())
463    }
464}
465
466/// Live model access for declarative reads that do not require a rendered node.
467#[doc(hidden)]
468pub enum ComboStateModel {
469    Strings(VecModel<String>),
470    Records(ComboItems),
471    Tumbler(ComboItems),
472}
473
474impl ComboStateModel {
475    fn exact_enabled_selection(&self, text: &str) -> Option<ComboSelection> {
476        let (index, value) = match self {
477            Self::Strings(model) => {
478                model.contents_stamp();
479                let index = model.position_untracked(0..model.len(), |label| label == text)?;
480                (index, Value::String(text.to_owned()))
481            }
482            Self::Records(items) => {
483                items.stamp();
484                let index = items
485                    .rows
486                    .find_label(0..items.rows.len(), true, &mut |label| label == text)?;
487                (index, items.rows.value(index)?)
488            }
489            Self::Tumbler(_) => return None,
490        };
491        Some(ComboSelection {
492            index,
493            value,
494            label: text.to_owned(),
495        })
496    }
497
498    pub fn count(&self) -> usize {
499        match self {
500            Self::Strings(model) => model.len(),
501            Self::Records(model) => model.count(),
502            Self::Tumbler(model) => model.wheel_count(),
503        }
504    }
505
506    pub fn selected_index(&self, index: i64, value: Option<&Value>) -> Option<usize> {
507        match self {
508            Self::Strings(model) => {
509                let value = match value {
510                    Some(Value::String(text)) => Some(text.as_str()),
511                    None => None,
512                    _ => return None,
513                };
514                string_combo_index(model, index, value)
515            }
516            Self::Records(model) => model.selected_index(index, value),
517            Self::Tumbler(model) => model.wheel_index(index, value),
518        }
519    }
520
521    pub fn text_at(&self, index: usize) -> Option<String> {
522        match self {
523            Self::Strings(model) => model.row(index),
524            Self::Records(model) | Self::Tumbler(model) => model.selected_text(index),
525        }
526    }
527
528    pub fn value_at(&self, index: usize) -> Option<Value> {
529        match self {
530            Self::Strings(model) => model.row(index).map(Value::String),
531            Self::Records(model) | Self::Tumbler(model) => model.selected_value(index),
532        }
533    }
534}
535
536pub fn combo_text(node: &Node) -> &str {
537    if let Some(model) = model(node) {
538        return model.selected.as_ref().map_or("", |(_, label)| label);
539    }
540    combo_index(node).map_or("", |index| node.strings("model")[index].as_str())
541}
542
543pub fn combo_count(node: &Node) -> usize {
544    model(node).map_or_else(
545        || node.strings("model").len(),
546        |model| model.items.rows.len(),
547    )
548}
549
550pub fn combo_label(node: &Node, index: usize) -> Option<Cow<'_, str>> {
551    match model(node) {
552        Some(model) => model.items.rows.label(index).map(Cow::Owned),
553        None => node
554            .strings("model")
555            .get(index)
556            .map(|label| Cow::Borrowed(label.as_str())),
557    }
558}
559
560pub fn combo_labels(node: &Node, range: Range<usize>) -> Cow<'_, [String]> {
561    match model(node) {
562        Some(model) => Cow::Owned(
563            range
564                .filter_map(|index| model.items.rows.label(index))
565                .collect(),
566        ),
567        None => Cow::Borrowed(&node.strings("model")[range]),
568    }
569}
570
571pub fn combo_find_label(node: &Node, mut predicate: impl FnMut(&str) -> bool) -> Option<usize> {
572    match model(node) {
573        Some(model) => {
574            model
575                .items
576                .rows
577                .find_label(0..model.items.rows.len(), false, &mut predicate)
578        }
579        None => node
580            .strings("model")
581            .iter()
582            .position(|text| predicate(text)),
583    }
584}
585
586/// Search enabled rows from a model index, wrapping to the beginning once.
587pub fn combo_find_enabled_label(
588    node: &Node,
589    start: usize,
590    mut predicate: impl FnMut(&str) -> bool,
591) -> Option<usize> {
592    let len = combo_count(node);
593    let start = start.min(len);
594    [start..len, 0..start].into_iter().find_map(|range| {
595        if let Some(model) = model(node) {
596            model.items.rows.find_label(range, true, &mut predicate)
597        } else {
598            let start = range.start;
599            node.strings("model")[range]
600                .iter()
601                .position(|text| predicate(text))
602                .map(|offset| start + offset)
603        }
604    })
605}
606
607#[doc(hidden)]
608pub struct ComboSubmission {
609    pub text: String,
610    pub index: Option<usize>,
611}
612
613/// Interpret the text in an editable ComboBox snapshot. A disabled record cannot be
614/// submitted as free text. Keep the selected record when its label still matches.
615#[doc(hidden)]
616pub fn combo_submission(node: &Node) -> Option<ComboSubmission> {
617    if !crate::combo_editable(node) {
618        return None;
619    }
620
621    let draft = crate::text_input_value(node);
622    let index = if model(node).is_some() {
623        let index = combo_index(node)
624            .filter(|&index| choice_enabled(node, index) && combo_text(node) == draft)
625            .or_else(|| combo_find_enabled_label(node, 0, |label| label == draft));
626        if index.is_none() && combo_find_label(node, |label| label == draft).is_some() {
627            return None;
628        }
629        index
630    } else {
631        node.strings("model").iter().position(|item| item == draft)
632    };
633    Some(ComboSubmission {
634        text: draft.to_owned(),
635        index,
636    })
637}
638
639#[doc(hidden)]
640pub struct ComboSelection {
641    pub index: usize,
642    pub label: String,
643    pub value: Value,
644}
645
646#[doc(hidden)]
647pub enum ComboInput {
648    Select {
649        selection: ComboSelection,
650        editable: bool,
651    },
652    Accept {
653        text: String,
654        selection: Option<ComboSelection>,
655    },
656}
657
658#[derive(Clone, Copy)]
659#[doc(hidden)]
660pub enum ComboEditor {
661    None,
662    Default,
663    Explicit,
664}
665
666#[doc(hidden)]
667pub enum ComboUpdate<'a> {
668    Select(&'a ComboSelection),
669    ClearIndex,
670    SetFreeText(&'a str),
671    SetEditText(&'a str),
672    ResetEditText,
673    FinishEdit { text: &'a str, accepted: bool },
674    Selected(&'a str),
675    ValueSelected(&'a Value),
676    Accepted(&'a str),
677}
678
679impl ComboInput {
680    pub fn accepts_unmatched_text(&self) -> bool {
681        matches!(
682            self,
683            Self::Accept {
684                selection: None,
685                ..
686            }
687        )
688    }
689
690    /// Commit selection and edit text before publishing callbacks.
691    pub fn try_apply<E>(
692        self,
693        editor: ComboEditor,
694        by_value: bool,
695        records: bool,
696        mut update: impl FnMut(ComboUpdate<'_>) -> Result<bool, E>,
697    ) -> Result<bool, E> {
698        use ComboUpdate::*;
699
700        match self {
701            Self::Select {
702                selection,
703                editable,
704            } => {
705                if !update(Select(&selection))? {
706                    return Ok(false);
707                }
708                if editable {
709                    match editor {
710                        ComboEditor::None => {}
711                        ComboEditor::Default => {
712                            update(ResetEditText)?;
713                        }
714                        ComboEditor::Explicit => {
715                            update(SetEditText(&selection.label))?;
716                        }
717                    }
718                    update(FinishEdit {
719                        text: &selection.label,
720                        accepted: false,
721                    })?;
722                }
723                update(Selected(&selection.label))?;
724                if records {
725                    update(ValueSelected(&selection.value))?;
726                }
727            }
728            Self::Accept { text, selection } => {
729                if matches!(editor, ComboEditor::None) {
730                    return Ok(false);
731                }
732                if let Some(selection) = selection {
733                    if !update(Select(&selection))? {
734                        return Ok(false);
735                    }
736                    if matches!(editor, ComboEditor::Default) {
737                        update(ResetEditText)?;
738                    }
739                    update(FinishEdit {
740                        text: &text,
741                        accepted: true,
742                    })?;
743                    if records {
744                        update(ValueSelected(&selection.value))?;
745                    }
746                } else {
747                    if !by_value {
748                        update(ClearIndex)?;
749                    } else if !records {
750                        update(SetFreeText(&text))?;
751                    }
752                    if matches!(editor, ComboEditor::Default) {
753                        update(SetEditText(&text))?;
754                    }
755                    update(FinishEdit {
756                        text: &text,
757                        accepted: true,
758                    })?;
759                }
760                update(Accepted(&text))?;
761            }
762        }
763        Ok(true)
764    }
765
766    pub fn apply(
767        self,
768        editor: ComboEditor,
769        by_value: bool,
770        records: bool,
771        mut update: impl FnMut(ComboUpdate<'_>) -> bool,
772    ) -> bool {
773        self.try_apply(editor, by_value, records, |event| {
774            Ok::<_, std::convert::Infallible>(update(event))
775        })
776        .unwrap_or_else(|error| match error {})
777    }
778}
779
780fn same_combo_value(left: &Value, right: &Value) -> bool {
781    left == right
782        || matches!((left, right), (Value::Float(a), Value::Float(b)) if a.is_nan() && b.is_nan())
783}
784
785/// Run the accepted handler before checking a fresh model for newly inserted text.
786/// The editor can keep its existing free-text state or let the handler supply a selection.
787#[doc(hidden)]
788pub fn try_resolve_combo_after_accept<E>(
789    text: &str,
790    mut state: impl FnMut() -> Result<Option<Value>, E>,
791    accepted: impl FnOnce() -> Result<(), E>,
792    available: impl FnOnce() -> Result<bool, E>,
793    model: impl FnOnce() -> Result<ComboStateModel, E>,
794) -> Result<Option<ComboSelection>, E> {
795    let before = state()?;
796    accepted()?;
797    let Some(before) = before else {
798        return Ok(None);
799    };
800    crate::property::watch_reads(|reads| {
801        if !available()?
802            || !state()?.is_some_and(|after| same_combo_value(&before, &after))
803            || reads.changed()
804        {
805            return Ok(None);
806        }
807        let selection = model()?.exact_enabled_selection(text);
808        Ok(selection.filter(|_| !reads.changed()))
809    })
810}
811
812#[doc(hidden)]
813pub fn resolve_combo_after_accept(
814    text: &str,
815    mut state: impl FnMut() -> Option<Value>,
816    accepted: impl FnOnce(),
817    available: impl FnOnce() -> bool,
818    model: impl FnOnce() -> ComboStateModel,
819) -> Option<ComboSelection> {
820    try_resolve_combo_after_accept(
821        text,
822        || Ok::<_, std::convert::Infallible>(state()),
823        || Ok(accepted()),
824        || Ok(available()),
825        || Ok(model()),
826    )
827    .unwrap_or_else(|error| match error {})
828}
829
830fn combo_selection(node: &Node, index: usize) -> Option<ComboSelection> {
831    if !choice_enabled(node, index) {
832        return None;
833    }
834    let label = combo_label(node, index)?.into_owned();
835    let value = if model(node).is_some() {
836        combo_value(node, index)?
837    } else {
838        Value::String(label.clone())
839    };
840    Some(ComboSelection {
841        index,
842        label,
843        value,
844    })
845}
846
847/// Check live bindings before resolving the choice or draft from the input scene.
848#[doc(hidden)]
849pub fn try_prepare_combo_input<E>(
850    node: &Node,
851    action: ControlAction,
852    available: impl FnOnce() -> Result<bool, E>,
853    editable: impl FnOnce() -> Result<bool, E>,
854    model_current: impl FnOnce() -> Result<bool, E>,
855) -> Result<Option<ComboInput>, E> {
856    try_prepare_combo_input_with_draft(node, action, available, editable, model_current, || {
857        Ok(None)
858    })
859}
860
861#[doc(hidden)]
862pub fn try_prepare_combo_input_with_draft<E>(
863    node: &Node,
864    action: ControlAction,
865    available: impl FnOnce() -> Result<bool, E>,
866    editable: impl FnOnce() -> Result<bool, E>,
867    model_current: impl FnOnce() -> Result<bool, E>,
868    linked_draft: impl FnOnce() -> Result<Option<String>, E>,
869) -> Result<Option<ComboInput>, E> {
870    try_prepare_combo_input_with_live_draft(
871        node,
872        action,
873        available,
874        editable,
875        model_current,
876        || Ok(linked_draft()?.is_none_or(|draft| draft == crate::text_input_value(node))),
877    )
878}
879
880#[doc(hidden)]
881pub fn try_prepare_combo_input_with_live_draft<E>(
882    node: &Node,
883    action: ControlAction,
884    available: impl FnOnce() -> Result<bool, E>,
885    editable: impl FnOnce() -> Result<bool, E>,
886    model_current: impl FnOnce() -> Result<bool, E>,
887    draft_current: impl FnOnce() -> Result<bool, E>,
888) -> Result<Option<ComboInput>, E> {
889    if !matches!(
890        action,
891        ControlAction::Select(_) | ControlAction::AcceptComboText
892    ) {
893        return Ok(None);
894    }
895    crate::property::watch_reads(|reads| {
896        if !available()? || reads.changed() {
897            return Ok(None);
898        }
899        let editable = editable()?;
900        if (action == ControlAction::AcceptComboText && !editable)
901            || reads.changed()
902            || !model_current()?
903            || reads.changed()
904        {
905            return Ok(None);
906        }
907        Ok(match action {
908            ControlAction::Select(index) => {
909                combo_selection(node, index).map(|selection| ComboInput::Select {
910                    selection,
911                    editable,
912                })
913            }
914            ControlAction::AcceptComboText => {
915                if !draft_current()? || reads.changed() {
916                    return Ok(None);
917                }
918                let Some(submission) = combo_submission(node) else {
919                    return Ok(None);
920                };
921                let selection = if let Some(index) = submission.index {
922                    let Some(selection) = combo_selection(node, index) else {
923                        return Ok(None);
924                    };
925                    Some(selection)
926                } else {
927                    None
928                };
929                Some(ComboInput::Accept {
930                    text: submission.text,
931                    selection,
932                })
933            }
934            _ => None,
935        })
936    })
937}
938
939#[doc(hidden)]
940pub fn prepare_combo_input_with_live_draft(
941    node: &Node,
942    action: ControlAction,
943    available: impl FnOnce() -> bool,
944    editable: impl FnOnce() -> bool,
945    model_current: impl FnOnce() -> bool,
946    draft_current: impl FnOnce() -> bool,
947) -> Option<ComboInput> {
948    try_prepare_combo_input_with_live_draft(
949        node,
950        action,
951        || Ok::<_, std::convert::Infallible>(available()),
952        || Ok(editable()),
953        || Ok(model_current()),
954        || Ok(draft_current()),
955    )
956    .unwrap_or_else(|error| match error {})
957}
958
959#[doc(hidden)]
960pub fn prepare_combo_input(
961    node: &Node,
962    action: ControlAction,
963    available: impl FnOnce() -> bool,
964    editable: impl FnOnce() -> bool,
965    model_current: impl FnOnce() -> bool,
966) -> Option<ComboInput> {
967    try_prepare_combo_input(
968        node,
969        action,
970        || Ok::<_, std::convert::Infallible>(available()),
971        || Ok(editable()),
972        || Ok(model_current()),
973    )
974    .unwrap_or_else(|error| match error {})
975}
976
977#[doc(hidden)]
978pub fn prepare_combo_input_with_draft(
979    node: &Node,
980    action: ControlAction,
981    available: impl FnOnce() -> bool,
982    editable: impl FnOnce() -> bool,
983    model_current: impl FnOnce() -> bool,
984    linked_draft: impl FnOnce() -> Option<String>,
985) -> Option<ComboInput> {
986    try_prepare_combo_input_with_draft(
987        node,
988        action,
989        || Ok::<_, std::convert::Infallible>(available()),
990        || Ok(editable()),
991        || Ok(model_current()),
992        || Ok(linked_draft()),
993    )
994    .unwrap_or_else(|error| match error {})
995}
996
997pub fn choice_enabled(node: &Node, index: usize) -> bool {
998    if node.kind == "SearchField" {
999        return crate::search_suggestion(node, index).is_some();
1000    }
1001    model(node).map_or_else(
1002        || index < node.strings("model").len(),
1003        |model| model.items.rows.enabled(index),
1004    )
1005}
1006
1007impl Node {
1008    /// Only read the model and selection when the editor is displaying a label.
1009    #[doc(hidden)]
1010    pub fn try_combo_draft_is_current<E>(
1011        &self,
1012        draft: Option<String>,
1013        selection: impl FnOnce() -> Result<bool, E>,
1014    ) -> Result<bool, E> {
1015        let shown = crate::text_input_value(self);
1016        match draft {
1017            Some(draft) => Ok(draft == shown),
1018            None => Ok(shown == combo_text(self) && selection()?),
1019        }
1020    }
1021
1022    #[doc(hidden)]
1023    pub fn combo_draft_is_current(
1024        &self,
1025        draft: Option<String>,
1026        selection: impl FnOnce() -> bool,
1027    ) -> bool {
1028        self.try_combo_draft_is_current(draft, || Ok::<_, std::convert::Infallible>(selection()))
1029            .unwrap_or_else(|error| match error {})
1030    }
1031
1032    #[doc(hidden)]
1033    pub fn combo_selection_is_current(&self, property: &str, value: &Value) -> bool {
1034        self.properties
1035            .get(property)
1036            .is_some_and(|shown| same_combo_value(shown, value))
1037    }
1038
1039    #[doc(hidden)]
1040    pub fn try_prepare_combo_edit<E>(
1041        &self,
1042        input: InputRoute<'_>,
1043        editable: impl FnOnce() -> Result<bool, E>,
1044        draft_current: impl FnOnce() -> Result<bool, E>,
1045    ) -> Result<bool, E> {
1046        Ok(input.try_available(editable)? && draft_current()? && input.is_current())
1047    }
1048
1049    #[doc(hidden)]
1050    pub fn prepare_combo_edit(
1051        &self,
1052        input: InputRoute<'_>,
1053        editable: impl FnOnce() -> bool,
1054        draft_current: impl FnOnce() -> bool,
1055    ) -> bool {
1056        self.try_prepare_combo_edit(
1057            input,
1058            || Ok::<_, std::convert::Infallible>(editable()),
1059            || Ok(draft_current()),
1060        )
1061        .unwrap_or_else(|error| match error {})
1062    }
1063
1064    #[doc(hidden)]
1065    pub fn set_string_combo_model(&mut self, source: VecModel<String>) {
1066        self.standard_list_stamp = Some(source.edit_stamp());
1067        self.properties.insert("model", source.into());
1068    }
1069}
1070
1071#[doc(hidden)]
1072pub fn combo_model_is_current<T>(node: &Node, source: &VecModel<T>) -> bool {
1073    if let Some(model) = model(node) {
1074        model.items.changes.track();
1075        model.structure == source.structure_stamp() && model.revision == model.items.revision.get()
1076    } else {
1077        node.standard_list_stamp == Some(source.contents_stamp())
1078    }
1079}
1080
1081#[doc(hidden)]
1082pub fn combo_value(node: &Node, index: usize) -> Option<Value> {
1083    model(node)?.items.rows.value(index)
1084}
1085
1086pub fn combo_row_key(node: &Node, index: usize) -> Option<RowKey> {
1087    model(node)?.items.rows.key(index)
1088}
1089
1090pub fn combo_row_index(node: &Node, key: RowKey) -> Option<usize> {
1091    model(node)?.items.rows.index(key)
1092}
1093
1094/// A pressed or projected option must still identify the same record and business value.
1095#[derive(Clone, Debug, PartialEq)]
1096pub struct ChoiceIdentity {
1097    pub label: String,
1098    pub record: Option<(RowKey, Value)>,
1099}
1100
1101pub fn choice_identity(node: &Node, index: usize) -> Option<ChoiceIdentity> {
1102    if node.kind == "SearchField" {
1103        return Some(ChoiceIdentity {
1104            label: crate::search_suggestion(node, index)?.to_owned(),
1105            record: None,
1106        });
1107    }
1108    let label = combo_label(node, index)?.into_owned();
1109    let record = match model(node) {
1110        Some(model) => Some((model.items.rows.key(index)?, model.items.rows.value(index)?)),
1111        None => None,
1112    };
1113    Some(ChoiceIdentity { label, record })
1114}