Skip to main content

xrack_runtime/
combo.rs

1use crate::{ChangeSignal, ControlAction, InputRoute, Node, RowKey, Value, VecModel};
2use std::{borrow::Cow, cell::Cell, fmt, ops::Range, rc::Rc};
3
4trait Rows {
5    fn structure(&self) -> (u64, u64);
6    fn len(&self) -> usize;
7    fn label(&self, index: usize) -> Option<String>;
8    fn value(&self, index: usize) -> Option<Value>;
9    fn enabled(&self, index: usize) -> bool;
10    fn key(&self, index: usize) -> Option<RowKey>;
11    fn index(&self, key: RowKey) -> Option<usize>;
12    fn find_label(
13        &self,
14        range: Range<usize>,
15        enabled_only: bool,
16        predicate: &mut dyn FnMut(&str) -> bool,
17    ) -> Option<usize>;
18    fn find_value(&self, value: &Value) -> Option<usize>;
19}
20
21type LabelProjection<T> = dyn Fn(&T) -> &str;
22type ValueProjection<T> = dyn Fn(&T) -> Value;
23type EnabledProjection<T> = dyn Fn(&T) -> bool;
24
25struct RecordRows<T> {
26    model: VecModel<T>,
27    label: Rc<LabelProjection<T>>,
28    value: Rc<ValueProjection<T>>,
29    enabled: Rc<EnabledProjection<T>>,
30}
31
32impl<T> Rows for RecordRows<T> {
33    fn structure(&self) -> (u64, u64) {
34        self.model.structure_stamp()
35    }
36    fn len(&self) -> usize {
37        self.model.len()
38    }
39    fn label(&self, index: usize) -> Option<String> {
40        self.model
41            .project_row_untracked(index, |row| (self.label)(row).to_owned())
42    }
43    fn value(&self, index: usize) -> Option<Value> {
44        self.model
45            .project_row_untracked(index, |row| (self.value)(row))
46    }
47    fn enabled(&self, index: usize) -> bool {
48        self.model
49            .project_row_untracked(index, |row| (self.enabled)(row))
50            .unwrap_or(false)
51    }
52    fn key(&self, index: usize) -> Option<RowKey> {
53        self.model.row_key(index)
54    }
55    fn index(&self, key: RowKey) -> Option<usize> {
56        self.model.row_index(key)
57    }
58    fn find_label(
59        &self,
60        range: Range<usize>,
61        enabled_only: bool,
62        predicate: &mut dyn FnMut(&str) -> bool,
63    ) -> Option<usize> {
64        self.model.position_untracked(range, |row| {
65            (!enabled_only || (self.enabled)(row)) && predicate((self.label)(row))
66        })
67    }
68    fn find_value(&self, value: &Value) -> Option<usize> {
69        self.model
70            .position_untracked(0..self.model.len(), |row| (self.value)(row) == *value)
71    }
72}
73
74/// A typed record projection shared by snapshots of a ComboBox.
75#[doc(hidden)]
76#[derive(Clone)]
77pub struct ComboItems {
78    rows: Rc<dyn Rows>,
79    changes: Rc<ChangeSignal>,
80    revision: Rc<Cell<u64>>,
81}
82
83impl ComboItems {
84    pub fn new<T: 'static>(
85        model: VecModel<T>,
86        label: impl Fn(&T) -> &str + 'static,
87        value: impl Fn(&T) -> Value + 'static,
88    ) -> Self {
89        Self::with_enabled(model, label, value, |_| true)
90    }
91
92    pub fn with_enabled<T: 'static>(
93        model: VecModel<T>,
94        label: impl Fn(&T) -> &str + 'static,
95        value: impl Fn(&T) -> Value + 'static,
96        enabled: impl Fn(&T) -> bool + 'static,
97    ) -> Self {
98        let label: Rc<LabelProjection<T>> = Rc::new(label);
99        let value: Rc<ValueProjection<T>> = Rc::new(value);
100        let enabled: Rc<EnabledProjection<T>> = Rc::new(enabled);
101        let revision = Rc::new(Cell::new(0_u64));
102        let changes = model.observe_projection_changes(usize::MAX, {
103            let label = label.clone();
104            let value = value.clone();
105            let enabled = enabled.clone();
106            let revision = revision.clone();
107            move |_, before, after| {
108                let changed = enabled(before) != enabled(after)
109                    || label(before) != label(after)
110                    || value(before) != value(after);
111                if changed {
112                    revision.set(revision.get().wrapping_add(1));
113                }
114                changed
115            }
116        });
117        Self {
118            rows: Rc::new(RecordRows {
119                model,
120                label,
121                value,
122                enabled,
123            }),
124            changes,
125            revision,
126        }
127    }
128
129    pub fn snapshot(&self, index: i64, value: Option<&Value>) -> ComboModel {
130        self.changes.track();
131        let structure = self.rows.structure();
132        let index = match value {
133            Some(value) => self.rows.find_value(value),
134            None => usize::try_from(index).ok(),
135        };
136        let selected = index.and_then(|index| Some((index, self.rows.label(index)?)));
137        ComboModel {
138            items: self.clone(),
139            structure,
140            revision: self.revision.get(),
141            selected,
142        }
143    }
144
145    /// Use the selection already read for the scene when projecting record options.
146    #[doc(hidden)]
147    pub fn populate_scene(&self, node: &mut Node) {
148        let index = node.int("current-index").unwrap_or(0);
149        let snapshot = self.snapshot(index, node.properties.get("current-value"));
150        node.properties.insert("model", Value::ComboModel(snapshot));
151    }
152}
153
154#[doc(hidden)]
155#[derive(Clone)]
156pub struct ComboModel {
157    items: ComboItems,
158    structure: (u64, u64),
159    revision: u64,
160    selected: Option<(usize, String)>,
161}
162
163impl fmt::Debug for ComboModel {
164    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165        f.debug_struct("ComboModel")
166            .field("structure", &self.structure)
167            .field("revision", &self.revision)
168            .field("selected", &self.selected)
169            .finish()
170    }
171}
172
173impl PartialEq for ComboModel {
174    fn eq(&self, other: &Self) -> bool {
175        Rc::ptr_eq(&self.items.rows, &other.items.rows)
176            && self.structure == other.structure
177            && self.revision == other.revision
178            && self.selected == other.selected
179    }
180}
181
182fn model(node: &Node) -> Option<&ComboModel> {
183    match node.properties.get("model") {
184        Some(Value::ComboModel(model)) => Some(model),
185        _ => None,
186    }
187}
188
189pub fn combo_index(node: &Node) -> Option<usize> {
190    if let Some(model) = model(node) {
191        return model.selected.as_ref().map(|(index, _)| *index);
192    }
193    let model = node.strings("model");
194    if let Some(value) = node.text("current-value") {
195        model.iter().position(|item| item == value)
196    } else {
197        let index = usize::try_from(node.int("current-index").unwrap_or(0)).ok()?;
198        (index < model.len()).then_some(index)
199    }
200}
201
202pub fn combo_text(node: &Node) -> &str {
203    if let Some(model) = model(node) {
204        return model.selected.as_ref().map_or("", |(_, label)| label);
205    }
206    combo_index(node).map_or("", |index| node.strings("model")[index].as_str())
207}
208
209pub fn combo_count(node: &Node) -> usize {
210    model(node).map_or_else(
211        || node.strings("model").len(),
212        |model| model.items.rows.len(),
213    )
214}
215
216pub fn combo_label(node: &Node, index: usize) -> Option<Cow<'_, str>> {
217    match model(node) {
218        Some(model) => model.items.rows.label(index).map(Cow::Owned),
219        None => node
220            .strings("model")
221            .get(index)
222            .map(|label| Cow::Borrowed(label.as_str())),
223    }
224}
225
226pub fn combo_labels(node: &Node, range: Range<usize>) -> Cow<'_, [String]> {
227    match model(node) {
228        Some(model) => Cow::Owned(
229            range
230                .filter_map(|index| model.items.rows.label(index))
231                .collect(),
232        ),
233        None => Cow::Borrowed(&node.strings("model")[range]),
234    }
235}
236
237pub fn combo_find_label(node: &Node, mut predicate: impl FnMut(&str) -> bool) -> Option<usize> {
238    match model(node) {
239        Some(model) => {
240            model
241                .items
242                .rows
243                .find_label(0..model.items.rows.len(), false, &mut predicate)
244        }
245        None => node
246            .strings("model")
247            .iter()
248            .position(|text| predicate(text)),
249    }
250}
251
252/// Search enabled rows from a model index, wrapping to the beginning once.
253pub fn combo_find_enabled_label(
254    node: &Node,
255    start: usize,
256    mut predicate: impl FnMut(&str) -> bool,
257) -> Option<usize> {
258    let len = combo_count(node);
259    let start = start.min(len);
260    [start..len, 0..start].into_iter().find_map(|range| {
261        if let Some(model) = model(node) {
262            model.items.rows.find_label(range, true, &mut predicate)
263        } else {
264            let start = range.start;
265            node.strings("model")[range]
266                .iter()
267                .position(|text| predicate(text))
268                .map(|offset| start + offset)
269        }
270    })
271}
272
273#[doc(hidden)]
274pub struct ComboSubmission {
275    pub text: String,
276    pub index: Option<usize>,
277}
278
279/// Interpret the text in an editable ComboBox snapshot. A disabled record cannot be
280/// submitted as free text. Keep the selected record when its label still matches.
281#[doc(hidden)]
282pub fn combo_submission(node: &Node) -> Option<ComboSubmission> {
283    if !crate::combo_editable(node) {
284        return None;
285    }
286
287    let draft = crate::text_input_value(node);
288    let index = if model(node).is_some() {
289        let index = combo_index(node)
290            .filter(|&index| choice_enabled(node, index) && combo_text(node) == draft)
291            .or_else(|| combo_find_enabled_label(node, 0, |label| label == draft));
292        if index.is_none() && combo_find_label(node, |label| label == draft).is_some() {
293            return None;
294        }
295        index
296    } else {
297        node.strings("model").iter().position(|item| item == draft)
298    };
299    Some(ComboSubmission {
300        text: draft.to_owned(),
301        index,
302    })
303}
304
305#[doc(hidden)]
306pub struct ComboSelection {
307    pub index: usize,
308    pub label: String,
309    pub value: Value,
310}
311
312#[doc(hidden)]
313pub enum ComboInput {
314    Select {
315        selection: ComboSelection,
316        editable: bool,
317    },
318    Accept {
319        text: String,
320        selection: Option<ComboSelection>,
321    },
322}
323
324#[derive(Clone, Copy)]
325#[doc(hidden)]
326pub enum ComboEditor {
327    None,
328    Default,
329    Explicit,
330}
331
332#[doc(hidden)]
333pub enum ComboUpdate<'a> {
334    Select(&'a ComboSelection),
335    ClearIndex,
336    SetFreeText(&'a str),
337    SetEditText(&'a str),
338    ResetEditText,
339    Selected(&'a str),
340    ValueSelected(&'a Value),
341    Accepted(&'a str),
342}
343
344impl ComboInput {
345    /// Commit selection and edit text before publishing callbacks.
346    pub fn try_apply<E>(
347        self,
348        editor: ComboEditor,
349        by_value: bool,
350        records: bool,
351        mut update: impl FnMut(ComboUpdate<'_>) -> Result<bool, E>,
352    ) -> Result<bool, E> {
353        use ComboUpdate::*;
354
355        match self {
356            Self::Select {
357                selection,
358                editable,
359            } => {
360                if !update(Select(&selection))? {
361                    return Ok(false);
362                }
363                if editable {
364                    match editor {
365                        ComboEditor::None => {}
366                        ComboEditor::Default => {
367                            update(ResetEditText)?;
368                        }
369                        ComboEditor::Explicit => {
370                            update(SetEditText(&selection.label))?;
371                        }
372                    }
373                }
374                update(Selected(&selection.label))?;
375                if records {
376                    update(ValueSelected(&selection.value))?;
377                }
378            }
379            Self::Accept { text, selection } => {
380                if matches!(editor, ComboEditor::None) {
381                    return Ok(false);
382                }
383                if let Some(selection) = selection {
384                    if !update(Select(&selection))? {
385                        return Ok(false);
386                    }
387                    if matches!(editor, ComboEditor::Default) {
388                        update(ResetEditText)?;
389                    }
390                    if records {
391                        update(ValueSelected(&selection.value))?;
392                    }
393                } else {
394                    if !by_value {
395                        update(ClearIndex)?;
396                    } else if !records {
397                        update(SetFreeText(&text))?;
398                    }
399                    if matches!(editor, ComboEditor::Default) {
400                        update(SetEditText(&text))?;
401                    }
402                }
403                update(Accepted(&text))?;
404            }
405        }
406        Ok(true)
407    }
408
409    pub fn apply(
410        self,
411        editor: ComboEditor,
412        by_value: bool,
413        records: bool,
414        mut update: impl FnMut(ComboUpdate<'_>) -> bool,
415    ) -> bool {
416        self.try_apply(editor, by_value, records, |event| {
417            Ok::<_, std::convert::Infallible>(update(event))
418        })
419        .unwrap_or_else(|error| match error {})
420    }
421}
422
423fn combo_selection(node: &Node, index: usize) -> Option<ComboSelection> {
424    if !choice_enabled(node, index) {
425        return None;
426    }
427    let label = combo_label(node, index)?.into_owned();
428    let value = if model(node).is_some() {
429        combo_value(node, index)?
430    } else {
431        Value::String(label.clone())
432    };
433    Some(ComboSelection {
434        index,
435        label,
436        value,
437    })
438}
439
440/// Check live bindings before resolving the choice or draft from the input scene.
441#[doc(hidden)]
442pub fn try_prepare_combo_input<E>(
443    node: &Node,
444    action: ControlAction,
445    available: impl FnOnce() -> Result<bool, E>,
446    editable: impl FnOnce() -> Result<bool, E>,
447    model_current: impl FnOnce() -> Result<bool, E>,
448) -> Result<Option<ComboInput>, E> {
449    try_prepare_combo_input_with_draft(node, action, available, editable, model_current, || {
450        Ok(None)
451    })
452}
453
454#[doc(hidden)]
455pub fn try_prepare_combo_input_with_draft<E>(
456    node: &Node,
457    action: ControlAction,
458    available: impl FnOnce() -> Result<bool, E>,
459    editable: impl FnOnce() -> Result<bool, E>,
460    model_current: impl FnOnce() -> Result<bool, E>,
461    linked_draft: impl FnOnce() -> Result<Option<String>, E>,
462) -> Result<Option<ComboInput>, E> {
463    try_prepare_combo_input_with_live_draft(
464        node,
465        action,
466        available,
467        editable,
468        model_current,
469        || Ok(linked_draft()?.is_none_or(|draft| draft == crate::text_input_value(node))),
470    )
471}
472
473#[doc(hidden)]
474pub fn try_prepare_combo_input_with_live_draft<E>(
475    node: &Node,
476    action: ControlAction,
477    available: impl FnOnce() -> Result<bool, E>,
478    editable: impl FnOnce() -> Result<bool, E>,
479    model_current: impl FnOnce() -> Result<bool, E>,
480    draft_current: impl FnOnce() -> Result<bool, E>,
481) -> Result<Option<ComboInput>, E> {
482    if !matches!(
483        action,
484        ControlAction::Select(_) | ControlAction::AcceptComboText
485    ) {
486        return Ok(None);
487    }
488    crate::property::watch_reads(|reads| {
489        if !available()? || reads.changed() {
490            return Ok(None);
491        }
492        let editable = editable()?;
493        if (action == ControlAction::AcceptComboText && !editable)
494            || reads.changed()
495            || !model_current()?
496            || reads.changed()
497        {
498            return Ok(None);
499        }
500        Ok(match action {
501            ControlAction::Select(index) => {
502                combo_selection(node, index).map(|selection| ComboInput::Select {
503                    selection,
504                    editable,
505                })
506            }
507            ControlAction::AcceptComboText => {
508                if !draft_current()? || reads.changed() {
509                    return Ok(None);
510                }
511                let Some(submission) = combo_submission(node) else {
512                    return Ok(None);
513                };
514                let selection = if let Some(index) = submission.index {
515                    let Some(selection) = combo_selection(node, index) else {
516                        return Ok(None);
517                    };
518                    Some(selection)
519                } else {
520                    None
521                };
522                Some(ComboInput::Accept {
523                    text: submission.text,
524                    selection,
525                })
526            }
527            _ => None,
528        })
529    })
530}
531
532#[doc(hidden)]
533pub fn prepare_combo_input_with_live_draft(
534    node: &Node,
535    action: ControlAction,
536    available: impl FnOnce() -> bool,
537    editable: impl FnOnce() -> bool,
538    model_current: impl FnOnce() -> bool,
539    draft_current: impl FnOnce() -> bool,
540) -> Option<ComboInput> {
541    try_prepare_combo_input_with_live_draft(
542        node,
543        action,
544        || Ok::<_, std::convert::Infallible>(available()),
545        || Ok(editable()),
546        || Ok(model_current()),
547        || Ok(draft_current()),
548    )
549    .unwrap_or_else(|error| match error {})
550}
551
552#[doc(hidden)]
553pub fn prepare_combo_input(
554    node: &Node,
555    action: ControlAction,
556    available: impl FnOnce() -> bool,
557    editable: impl FnOnce() -> bool,
558    model_current: impl FnOnce() -> bool,
559) -> Option<ComboInput> {
560    try_prepare_combo_input(
561        node,
562        action,
563        || Ok::<_, std::convert::Infallible>(available()),
564        || Ok(editable()),
565        || Ok(model_current()),
566    )
567    .unwrap_or_else(|error| match error {})
568}
569
570#[doc(hidden)]
571pub fn prepare_combo_input_with_draft(
572    node: &Node,
573    action: ControlAction,
574    available: impl FnOnce() -> bool,
575    editable: impl FnOnce() -> bool,
576    model_current: impl FnOnce() -> bool,
577    linked_draft: impl FnOnce() -> Option<String>,
578) -> Option<ComboInput> {
579    try_prepare_combo_input_with_draft(
580        node,
581        action,
582        || Ok::<_, std::convert::Infallible>(available()),
583        || Ok(editable()),
584        || Ok(model_current()),
585        || Ok(linked_draft()),
586    )
587    .unwrap_or_else(|error| match error {})
588}
589
590pub fn choice_enabled(node: &Node, index: usize) -> bool {
591    if node.kind == "SearchField" {
592        return crate::search_suggestion(node, index).is_some();
593    }
594    model(node).map_or_else(
595        || index < node.strings("model").len(),
596        |model| model.items.rows.enabled(index),
597    )
598}
599
600impl Node {
601    /// Only read the model and selection when the editor is displaying a label.
602    #[doc(hidden)]
603    pub fn try_combo_draft_is_current<E>(
604        &self,
605        draft: Option<String>,
606        selection: impl FnOnce() -> Result<bool, E>,
607    ) -> Result<bool, E> {
608        let shown = crate::text_input_value(self);
609        match draft {
610            Some(draft) => Ok(draft == shown),
611            None => Ok(shown == combo_text(self) && selection()?),
612        }
613    }
614
615    #[doc(hidden)]
616    pub fn combo_draft_is_current(
617        &self,
618        draft: Option<String>,
619        selection: impl FnOnce() -> bool,
620    ) -> bool {
621        self.try_combo_draft_is_current(draft, || Ok::<_, std::convert::Infallible>(selection()))
622            .unwrap_or_else(|error| match error {})
623    }
624
625    #[doc(hidden)]
626    pub fn combo_selection_is_current(&self, property: &str, value: &Value) -> bool {
627        match (self.properties.get(property), value) {
628            (Some(Value::Float(shown)), Value::Float(live)) if shown.is_nan() => live.is_nan(),
629            (shown, live) => shown == Some(live),
630        }
631    }
632
633    #[doc(hidden)]
634    pub fn try_prepare_combo_edit<E>(
635        &self,
636        input: InputRoute<'_>,
637        editable: impl FnOnce() -> Result<bool, E>,
638        draft_current: impl FnOnce() -> Result<bool, E>,
639    ) -> Result<bool, E> {
640        Ok(input.try_available(editable)? && draft_current()? && input.is_current())
641    }
642
643    #[doc(hidden)]
644    pub fn prepare_combo_edit(
645        &self,
646        input: InputRoute<'_>,
647        editable: impl FnOnce() -> bool,
648        draft_current: impl FnOnce() -> bool,
649    ) -> bool {
650        self.try_prepare_combo_edit(
651            input,
652            || Ok::<_, std::convert::Infallible>(editable()),
653            || Ok(draft_current()),
654        )
655        .unwrap_or_else(|error| match error {})
656    }
657
658    #[doc(hidden)]
659    pub fn set_string_combo_model(&mut self, source: VecModel<String>) {
660        self.standard_list_stamp = Some(source.edit_stamp());
661        self.properties.insert("model", source.into());
662    }
663}
664
665#[doc(hidden)]
666pub fn combo_model_is_current<T>(node: &Node, source: &VecModel<T>) -> bool {
667    if let Some(model) = model(node) {
668        model.items.changes.track();
669        model.structure == source.structure_stamp() && model.revision == model.items.revision.get()
670    } else {
671        node.standard_list_stamp == Some(source.contents_stamp())
672    }
673}
674
675#[doc(hidden)]
676pub fn combo_value(node: &Node, index: usize) -> Option<Value> {
677    model(node)?.items.rows.value(index)
678}
679
680pub fn combo_row_key(node: &Node, index: usize) -> Option<RowKey> {
681    model(node)?.items.rows.key(index)
682}
683
684pub fn combo_row_index(node: &Node, key: RowKey) -> Option<usize> {
685    model(node)?.items.rows.index(key)
686}
687
688/// A pressed or projected option must still identify the same record and business value.
689#[derive(Clone, Debug, PartialEq)]
690pub struct ChoiceIdentity {
691    pub label: String,
692    pub record: Option<(RowKey, Value)>,
693}
694
695pub fn choice_identity(node: &Node, index: usize) -> Option<ChoiceIdentity> {
696    if node.kind == "SearchField" {
697        return Some(ChoiceIdentity {
698            label: crate::search_suggestion(node, index)?.to_owned(),
699            record: None,
700        });
701    }
702    let label = combo_label(node, index)?.into_owned();
703    let record = match model(node) {
704        Some(model) => Some((model.items.rows.key(index)?, model.items.rows.value(index)?)),
705        None => None,
706    };
707    Some(ChoiceIdentity { label, record })
708}