Skip to main content

xrack_runtime/
combo.rs

1use crate::{ChangeSignal, ControlAction, 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
146#[doc(hidden)]
147#[derive(Clone)]
148pub struct ComboModel {
149    items: ComboItems,
150    structure: (u64, u64),
151    revision: u64,
152    selected: Option<(usize, String)>,
153}
154
155impl fmt::Debug for ComboModel {
156    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157        f.debug_struct("ComboModel")
158            .field("structure", &self.structure)
159            .field("revision", &self.revision)
160            .field("selected", &self.selected)
161            .finish()
162    }
163}
164
165impl PartialEq for ComboModel {
166    fn eq(&self, other: &Self) -> bool {
167        Rc::ptr_eq(&self.items.rows, &other.items.rows)
168            && self.structure == other.structure
169            && self.revision == other.revision
170            && self.selected == other.selected
171    }
172}
173
174fn model(node: &Node) -> Option<&ComboModel> {
175    match node.properties.get("model") {
176        Some(Value::ComboModel(model)) => Some(model),
177        _ => None,
178    }
179}
180
181pub fn combo_index(node: &Node) -> Option<usize> {
182    if let Some(model) = model(node) {
183        return model.selected.as_ref().map(|(index, _)| *index);
184    }
185    let model = node.strings("model");
186    if let Some(value) = node.text("current-value") {
187        model.iter().position(|item| item == value)
188    } else {
189        let index = usize::try_from(node.int("current-index").unwrap_or(0)).ok()?;
190        (index < model.len()).then_some(index)
191    }
192}
193
194pub fn combo_text(node: &Node) -> &str {
195    if let Some(model) = model(node) {
196        return model.selected.as_ref().map_or("", |(_, label)| label);
197    }
198    combo_index(node).map_or("", |index| node.strings("model")[index].as_str())
199}
200
201pub fn combo_count(node: &Node) -> usize {
202    model(node).map_or_else(
203        || node.strings("model").len(),
204        |model| model.items.rows.len(),
205    )
206}
207
208pub fn combo_label(node: &Node, index: usize) -> Option<Cow<'_, str>> {
209    match model(node) {
210        Some(model) => model.items.rows.label(index).map(Cow::Owned),
211        None => node
212            .strings("model")
213            .get(index)
214            .map(|label| Cow::Borrowed(label.as_str())),
215    }
216}
217
218pub fn combo_labels(node: &Node, range: Range<usize>) -> Cow<'_, [String]> {
219    match model(node) {
220        Some(model) => Cow::Owned(
221            range
222                .filter_map(|index| model.items.rows.label(index))
223                .collect(),
224        ),
225        None => Cow::Borrowed(&node.strings("model")[range]),
226    }
227}
228
229pub fn combo_find_label(node: &Node, mut predicate: impl FnMut(&str) -> bool) -> Option<usize> {
230    match model(node) {
231        Some(model) => {
232            model
233                .items
234                .rows
235                .find_label(0..model.items.rows.len(), false, &mut predicate)
236        }
237        None => node
238            .strings("model")
239            .iter()
240            .position(|text| predicate(text)),
241    }
242}
243
244/// Search enabled rows from a model index, wrapping to the beginning once.
245pub fn combo_find_enabled_label(
246    node: &Node,
247    start: usize,
248    mut predicate: impl FnMut(&str) -> bool,
249) -> Option<usize> {
250    let len = combo_count(node);
251    let start = start.min(len);
252    [start..len, 0..start].into_iter().find_map(|range| {
253        if let Some(model) = model(node) {
254            model.items.rows.find_label(range, true, &mut predicate)
255        } else {
256            let start = range.start;
257            node.strings("model")[range]
258                .iter()
259                .position(|text| predicate(text))
260                .map(|offset| start + offset)
261        }
262    })
263}
264
265#[doc(hidden)]
266pub struct ComboSubmission {
267    pub text: String,
268    pub index: Option<usize>,
269}
270
271/// Interpret the text in an editable ComboBox snapshot. A disabled record cannot be
272/// submitted as free text. Keep the selected record when its label still matches.
273#[doc(hidden)]
274pub fn combo_submission(node: &Node) -> Option<ComboSubmission> {
275    if !crate::combo_editable(node) {
276        return None;
277    }
278
279    let draft = crate::text_input_value(node);
280    let index = if model(node).is_some() {
281        let index = combo_index(node)
282            .filter(|&index| choice_enabled(node, index) && combo_text(node) == draft)
283            .or_else(|| combo_find_enabled_label(node, 0, |label| label == draft));
284        if index.is_none() && combo_find_label(node, |label| label == draft).is_some() {
285            return None;
286        }
287        index
288    } else {
289        node.strings("model").iter().position(|item| item == draft)
290    };
291    Some(ComboSubmission {
292        text: draft.to_owned(),
293        index,
294    })
295}
296
297#[doc(hidden)]
298pub struct ComboSelection {
299    pub index: usize,
300    pub label: String,
301    pub value: Value,
302}
303
304#[doc(hidden)]
305pub enum ComboInput {
306    Select {
307        selection: ComboSelection,
308        editable: bool,
309    },
310    Accept {
311        text: String,
312        selection: Option<ComboSelection>,
313    },
314}
315
316#[derive(Clone, Copy)]
317#[doc(hidden)]
318pub enum ComboEditor {
319    None,
320    Default,
321    Explicit,
322}
323
324#[doc(hidden)]
325pub enum ComboUpdate<'a> {
326    Select(&'a ComboSelection),
327    ClearIndex,
328    SetFreeText(&'a str),
329    SetEditText(&'a str),
330    ResetEditText,
331    Selected(&'a str),
332    ValueSelected(&'a Value),
333    Accepted(&'a str),
334}
335
336impl ComboInput {
337    /// Commit selection and edit text before publishing callbacks.
338    pub fn try_apply<E>(
339        self,
340        editor: ComboEditor,
341        by_value: bool,
342        records: bool,
343        mut update: impl FnMut(ComboUpdate<'_>) -> Result<bool, E>,
344    ) -> Result<bool, E> {
345        use ComboUpdate::*;
346
347        match self {
348            Self::Select {
349                selection,
350                editable,
351            } => {
352                if !update(Select(&selection))? {
353                    return Ok(false);
354                }
355                if editable {
356                    match editor {
357                        ComboEditor::None => {}
358                        ComboEditor::Default => {
359                            update(ResetEditText)?;
360                        }
361                        ComboEditor::Explicit => {
362                            update(SetEditText(&selection.label))?;
363                        }
364                    }
365                }
366                update(Selected(&selection.label))?;
367                if records {
368                    update(ValueSelected(&selection.value))?;
369                }
370            }
371            Self::Accept { text, selection } => {
372                if matches!(editor, ComboEditor::None) {
373                    return Ok(false);
374                }
375                if let Some(selection) = selection {
376                    if !update(Select(&selection))? {
377                        return Ok(false);
378                    }
379                    if matches!(editor, ComboEditor::Default) {
380                        update(ResetEditText)?;
381                    }
382                    if records {
383                        update(ValueSelected(&selection.value))?;
384                    }
385                } else {
386                    if !by_value {
387                        update(ClearIndex)?;
388                    } else if !records {
389                        update(SetFreeText(&text))?;
390                    }
391                    if matches!(editor, ComboEditor::Default) {
392                        update(SetEditText(&text))?;
393                    }
394                }
395                update(Accepted(&text))?;
396            }
397        }
398        Ok(true)
399    }
400
401    pub fn apply(
402        self,
403        editor: ComboEditor,
404        by_value: bool,
405        records: bool,
406        mut update: impl FnMut(ComboUpdate<'_>) -> bool,
407    ) -> bool {
408        self.try_apply(editor, by_value, records, |event| {
409            Ok::<_, std::convert::Infallible>(update(event))
410        })
411        .unwrap_or_else(|error| match error {})
412    }
413}
414
415fn combo_selection(node: &Node, index: usize) -> Option<ComboSelection> {
416    if !choice_enabled(node, index) {
417        return None;
418    }
419    let label = combo_label(node, index)?.into_owned();
420    let value = if model(node).is_some() {
421        combo_value(node, index)?
422    } else {
423        Value::String(label.clone())
424    };
425    Some(ComboSelection {
426        index,
427        label,
428        value,
429    })
430}
431
432/// Check live bindings before resolving the choice or draft from the input scene.
433#[doc(hidden)]
434pub fn try_prepare_combo_input<E>(
435    node: &Node,
436    action: ControlAction,
437    available: impl FnOnce() -> Result<bool, E>,
438    editable: impl FnOnce() -> Result<bool, E>,
439    model_current: impl FnOnce() -> Result<bool, E>,
440) -> Result<Option<ComboInput>, E> {
441    if !matches!(
442        action,
443        ControlAction::Select(_) | ControlAction::AcceptComboText
444    ) {
445        return Ok(None);
446    }
447    crate::property::watch_reads(|reads| {
448        if !available()? || reads.changed() {
449            return Ok(None);
450        }
451        let editable = editable()?;
452        if (action == ControlAction::AcceptComboText && !editable)
453            || reads.changed()
454            || !model_current()?
455            || reads.changed()
456        {
457            return Ok(None);
458        }
459        Ok(match action {
460            ControlAction::Select(index) => {
461                combo_selection(node, index).map(|selection| ComboInput::Select {
462                    selection,
463                    editable,
464                })
465            }
466            ControlAction::AcceptComboText => {
467                let Some(submission) = combo_submission(node) else {
468                    return Ok(None);
469                };
470                let selection = if let Some(index) = submission.index {
471                    let Some(selection) = combo_selection(node, index) else {
472                        return Ok(None);
473                    };
474                    Some(selection)
475                } else {
476                    None
477                };
478                Some(ComboInput::Accept {
479                    text: submission.text,
480                    selection,
481                })
482            }
483            _ => None,
484        })
485    })
486}
487
488#[doc(hidden)]
489pub fn prepare_combo_input(
490    node: &Node,
491    action: ControlAction,
492    available: impl FnOnce() -> bool,
493    editable: impl FnOnce() -> bool,
494    model_current: impl FnOnce() -> bool,
495) -> Option<ComboInput> {
496    try_prepare_combo_input(
497        node,
498        action,
499        || Ok::<_, std::convert::Infallible>(available()),
500        || Ok(editable()),
501        || Ok(model_current()),
502    )
503    .unwrap_or_else(|error| match error {})
504}
505
506pub fn choice_enabled(node: &Node, index: usize) -> bool {
507    if node.kind == "SearchField" {
508        return crate::search_suggestion(node, index).is_some();
509    }
510    model(node).map_or_else(
511        || index < node.strings("model").len(),
512        |model| model.items.rows.enabled(index),
513    )
514}
515
516impl Node {
517    #[doc(hidden)]
518    pub fn set_string_combo_model(&mut self, source: VecModel<String>) {
519        self.standard_list_stamp = Some(source.edit_stamp());
520        self.properties.insert("model", source.into());
521    }
522}
523
524#[doc(hidden)]
525pub fn combo_model_is_current<T>(node: &Node, source: &VecModel<T>) -> bool {
526    if let Some(model) = model(node) {
527        model.items.changes.track();
528        model.structure == source.structure_stamp() && model.revision == model.items.revision.get()
529    } else {
530        node.standard_list_stamp == Some(source.edit_stamp())
531    }
532}
533
534#[doc(hidden)]
535pub fn combo_value(node: &Node, index: usize) -> Option<Value> {
536    model(node)?.items.rows.value(index)
537}
538
539pub fn combo_row_key(node: &Node, index: usize) -> Option<RowKey> {
540    model(node)?.items.rows.key(index)
541}
542
543pub fn combo_row_index(node: &Node, key: RowKey) -> Option<usize> {
544    model(node)?.items.rows.index(key)
545}
546
547/// A pressed or projected option must still identify the same record and business value.
548#[derive(Clone, Debug, PartialEq)]
549pub struct ChoiceIdentity {
550    pub label: String,
551    pub record: Option<(RowKey, Value)>,
552}
553
554pub fn choice_identity(node: &Node, index: usize) -> Option<ChoiceIdentity> {
555    if node.kind == "SearchField" {
556        return Some(ChoiceIdentity {
557            label: crate::search_suggestion(node, index)?.to_owned(),
558            record: None,
559        });
560    }
561    let label = combo_label(node, index)?.into_owned();
562    let record = match model(node) {
563        Some(model) => Some((model.items.rows.key(index)?, model.items.rows.value(index)?)),
564        None => None,
565    };
566    Some(ChoiceIdentity { label, record })
567}