xrack-runtime 0.6.0

Runtime types, properties, models, and controls for generated XRack UI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
use crate::{ChangeSignal, ControlAction, InputRoute, Node, RowKey, Value, VecModel};
use std::{borrow::Cow, cell::Cell, fmt, ops::Range, rc::Rc};

trait Rows {
    fn structure(&self) -> (u64, u64);
    fn len(&self) -> usize;
    fn label(&self, index: usize) -> Option<String>;
    fn value(&self, index: usize) -> Option<Value>;
    fn enabled(&self, index: usize) -> bool;
    fn key(&self, index: usize) -> Option<RowKey>;
    fn index(&self, key: RowKey) -> Option<usize>;
    fn find_label(
        &self,
        range: Range<usize>,
        enabled_only: bool,
        predicate: &mut dyn FnMut(&str) -> bool,
    ) -> Option<usize>;
    fn find_value(&self, value: &Value) -> Option<usize>;
}

type LabelProjection<T> = dyn Fn(&T) -> &str;
type ValueProjection<T> = dyn Fn(&T) -> Value;
type EnabledProjection<T> = dyn Fn(&T) -> bool;

struct RecordRows<T> {
    model: VecModel<T>,
    label: Rc<LabelProjection<T>>,
    value: Rc<ValueProjection<T>>,
    enabled: Rc<EnabledProjection<T>>,
}

impl<T> Rows for RecordRows<T> {
    fn structure(&self) -> (u64, u64) {
        self.model.structure_stamp()
    }
    fn len(&self) -> usize {
        self.model.len()
    }
    fn label(&self, index: usize) -> Option<String> {
        self.model
            .project_row_untracked(index, |row| (self.label)(row).to_owned())
    }
    fn value(&self, index: usize) -> Option<Value> {
        self.model
            .project_row_untracked(index, |row| (self.value)(row))
    }
    fn enabled(&self, index: usize) -> bool {
        self.model
            .project_row_untracked(index, |row| (self.enabled)(row))
            .unwrap_or(false)
    }
    fn key(&self, index: usize) -> Option<RowKey> {
        self.model.row_key(index)
    }
    fn index(&self, key: RowKey) -> Option<usize> {
        self.model.row_index(key)
    }
    fn find_label(
        &self,
        range: Range<usize>,
        enabled_only: bool,
        predicate: &mut dyn FnMut(&str) -> bool,
    ) -> Option<usize> {
        self.model.position_untracked(range, |row| {
            (!enabled_only || (self.enabled)(row)) && predicate((self.label)(row))
        })
    }
    fn find_value(&self, value: &Value) -> Option<usize> {
        self.model
            .position_untracked(0..self.model.len(), |row| (self.value)(row) == *value)
    }
}

/// A typed record projection shared by snapshots of a ComboBox.
#[doc(hidden)]
#[derive(Clone)]
pub struct ComboItems {
    rows: Rc<dyn Rows>,
    changes: Rc<ChangeSignal>,
    revision: Rc<Cell<u64>>,
}

impl ComboItems {
    pub fn new<T: 'static>(
        model: VecModel<T>,
        label: impl Fn(&T) -> &str + 'static,
        value: impl Fn(&T) -> Value + 'static,
    ) -> Self {
        Self::with_enabled(model, label, value, |_| true)
    }

    pub fn with_enabled<T: 'static>(
        model: VecModel<T>,
        label: impl Fn(&T) -> &str + 'static,
        value: impl Fn(&T) -> Value + 'static,
        enabled: impl Fn(&T) -> bool + 'static,
    ) -> Self {
        let label: Rc<LabelProjection<T>> = Rc::new(label);
        let value: Rc<ValueProjection<T>> = Rc::new(value);
        let enabled: Rc<EnabledProjection<T>> = Rc::new(enabled);
        let revision = Rc::new(Cell::new(0_u64));
        let changes = model.observe_projection_changes(usize::MAX, {
            let label = label.clone();
            let value = value.clone();
            let enabled = enabled.clone();
            let revision = revision.clone();
            move |_, before, after| {
                let changed = enabled(before) != enabled(after)
                    || label(before) != label(after)
                    || value(before) != value(after);
                if changed {
                    revision.set(revision.get().wrapping_add(1));
                }
                changed
            }
        });
        Self {
            rows: Rc::new(RecordRows {
                model,
                label,
                value,
                enabled,
            }),
            changes,
            revision,
        }
    }

    pub fn snapshot(&self, index: i64, value: Option<&Value>) -> ComboModel {
        self.changes.track();
        let structure = self.rows.structure();
        let index = match value {
            Some(value) => self.rows.find_value(value),
            None => usize::try_from(index).ok(),
        };
        let selected = index.and_then(|index| Some((index, self.rows.label(index)?)));
        ComboModel {
            items: self.clone(),
            structure,
            revision: self.revision.get(),
            selected,
        }
    }

    /// Use the selection already read for the scene when projecting record options.
    #[doc(hidden)]
    pub fn populate_scene(&self, node: &mut Node) {
        let index = node.int("current-index").unwrap_or(0);
        let snapshot = self.snapshot(index, node.properties.get("current-value"));
        node.properties.insert("model", Value::ComboModel(snapshot));
    }
}

#[doc(hidden)]
#[derive(Clone)]
pub struct ComboModel {
    items: ComboItems,
    structure: (u64, u64),
    revision: u64,
    selected: Option<(usize, String)>,
}

impl fmt::Debug for ComboModel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ComboModel")
            .field("structure", &self.structure)
            .field("revision", &self.revision)
            .field("selected", &self.selected)
            .finish()
    }
}

impl PartialEq for ComboModel {
    fn eq(&self, other: &Self) -> bool {
        Rc::ptr_eq(&self.items.rows, &other.items.rows)
            && self.structure == other.structure
            && self.revision == other.revision
            && self.selected == other.selected
    }
}

fn model(node: &Node) -> Option<&ComboModel> {
    match node.properties.get("model") {
        Some(Value::ComboModel(model)) => Some(model),
        _ => None,
    }
}

pub fn combo_index(node: &Node) -> Option<usize> {
    if let Some(model) = model(node) {
        return model.selected.as_ref().map(|(index, _)| *index);
    }
    let model = node.strings("model");
    if let Some(value) = node.text("current-value") {
        model.iter().position(|item| item == value)
    } else {
        let index = usize::try_from(node.int("current-index").unwrap_or(0)).ok()?;
        (index < model.len()).then_some(index)
    }
}

pub fn combo_text(node: &Node) -> &str {
    if let Some(model) = model(node) {
        return model.selected.as_ref().map_or("", |(_, label)| label);
    }
    combo_index(node).map_or("", |index| node.strings("model")[index].as_str())
}

pub fn combo_count(node: &Node) -> usize {
    model(node).map_or_else(
        || node.strings("model").len(),
        |model| model.items.rows.len(),
    )
}

pub fn combo_label(node: &Node, index: usize) -> Option<Cow<'_, str>> {
    match model(node) {
        Some(model) => model.items.rows.label(index).map(Cow::Owned),
        None => node
            .strings("model")
            .get(index)
            .map(|label| Cow::Borrowed(label.as_str())),
    }
}

pub fn combo_labels(node: &Node, range: Range<usize>) -> Cow<'_, [String]> {
    match model(node) {
        Some(model) => Cow::Owned(
            range
                .filter_map(|index| model.items.rows.label(index))
                .collect(),
        ),
        None => Cow::Borrowed(&node.strings("model")[range]),
    }
}

pub fn combo_find_label(node: &Node, mut predicate: impl FnMut(&str) -> bool) -> Option<usize> {
    match model(node) {
        Some(model) => {
            model
                .items
                .rows
                .find_label(0..model.items.rows.len(), false, &mut predicate)
        }
        None => node
            .strings("model")
            .iter()
            .position(|text| predicate(text)),
    }
}

/// Search enabled rows from a model index, wrapping to the beginning once.
pub fn combo_find_enabled_label(
    node: &Node,
    start: usize,
    mut predicate: impl FnMut(&str) -> bool,
) -> Option<usize> {
    let len = combo_count(node);
    let start = start.min(len);
    [start..len, 0..start].into_iter().find_map(|range| {
        if let Some(model) = model(node) {
            model.items.rows.find_label(range, true, &mut predicate)
        } else {
            let start = range.start;
            node.strings("model")[range]
                .iter()
                .position(|text| predicate(text))
                .map(|offset| start + offset)
        }
    })
}

#[doc(hidden)]
pub struct ComboSubmission {
    pub text: String,
    pub index: Option<usize>,
}

/// Interpret the text in an editable ComboBox snapshot. A disabled record cannot be
/// submitted as free text. Keep the selected record when its label still matches.
#[doc(hidden)]
pub fn combo_submission(node: &Node) -> Option<ComboSubmission> {
    if !crate::combo_editable(node) {
        return None;
    }

    let draft = crate::text_input_value(node);
    let index = if model(node).is_some() {
        let index = combo_index(node)
            .filter(|&index| choice_enabled(node, index) && combo_text(node) == draft)
            .or_else(|| combo_find_enabled_label(node, 0, |label| label == draft));
        if index.is_none() && combo_find_label(node, |label| label == draft).is_some() {
            return None;
        }
        index
    } else {
        node.strings("model").iter().position(|item| item == draft)
    };
    Some(ComboSubmission {
        text: draft.to_owned(),
        index,
    })
}

#[doc(hidden)]
pub struct ComboSelection {
    pub index: usize,
    pub label: String,
    pub value: Value,
}

#[doc(hidden)]
pub enum ComboInput {
    Select {
        selection: ComboSelection,
        editable: bool,
    },
    Accept {
        text: String,
        selection: Option<ComboSelection>,
    },
}

#[derive(Clone, Copy)]
#[doc(hidden)]
pub enum ComboEditor {
    None,
    Default,
    Explicit,
}

#[doc(hidden)]
pub enum ComboUpdate<'a> {
    Select(&'a ComboSelection),
    ClearIndex,
    SetFreeText(&'a str),
    SetEditText(&'a str),
    ResetEditText,
    Selected(&'a str),
    ValueSelected(&'a Value),
    Accepted(&'a str),
}

impl ComboInput {
    /// Commit selection and edit text before publishing callbacks.
    pub fn try_apply<E>(
        self,
        editor: ComboEditor,
        by_value: bool,
        records: bool,
        mut update: impl FnMut(ComboUpdate<'_>) -> Result<bool, E>,
    ) -> Result<bool, E> {
        use ComboUpdate::*;

        match self {
            Self::Select {
                selection,
                editable,
            } => {
                if !update(Select(&selection))? {
                    return Ok(false);
                }
                if editable {
                    match editor {
                        ComboEditor::None => {}
                        ComboEditor::Default => {
                            update(ResetEditText)?;
                        }
                        ComboEditor::Explicit => {
                            update(SetEditText(&selection.label))?;
                        }
                    }
                }
                update(Selected(&selection.label))?;
                if records {
                    update(ValueSelected(&selection.value))?;
                }
            }
            Self::Accept { text, selection } => {
                if matches!(editor, ComboEditor::None) {
                    return Ok(false);
                }
                if let Some(selection) = selection {
                    if !update(Select(&selection))? {
                        return Ok(false);
                    }
                    if matches!(editor, ComboEditor::Default) {
                        update(ResetEditText)?;
                    }
                    if records {
                        update(ValueSelected(&selection.value))?;
                    }
                } else {
                    if !by_value {
                        update(ClearIndex)?;
                    } else if !records {
                        update(SetFreeText(&text))?;
                    }
                    if matches!(editor, ComboEditor::Default) {
                        update(SetEditText(&text))?;
                    }
                }
                update(Accepted(&text))?;
            }
        }
        Ok(true)
    }

    pub fn apply(
        self,
        editor: ComboEditor,
        by_value: bool,
        records: bool,
        mut update: impl FnMut(ComboUpdate<'_>) -> bool,
    ) -> bool {
        self.try_apply(editor, by_value, records, |event| {
            Ok::<_, std::convert::Infallible>(update(event))
        })
        .unwrap_or_else(|error| match error {})
    }
}

fn combo_selection(node: &Node, index: usize) -> Option<ComboSelection> {
    if !choice_enabled(node, index) {
        return None;
    }
    let label = combo_label(node, index)?.into_owned();
    let value = if model(node).is_some() {
        combo_value(node, index)?
    } else {
        Value::String(label.clone())
    };
    Some(ComboSelection {
        index,
        label,
        value,
    })
}

/// Check live bindings before resolving the choice or draft from the input scene.
#[doc(hidden)]
pub fn try_prepare_combo_input<E>(
    node: &Node,
    action: ControlAction,
    available: impl FnOnce() -> Result<bool, E>,
    editable: impl FnOnce() -> Result<bool, E>,
    model_current: impl FnOnce() -> Result<bool, E>,
) -> Result<Option<ComboInput>, E> {
    try_prepare_combo_input_with_draft(node, action, available, editable, model_current, || {
        Ok(None)
    })
}

#[doc(hidden)]
pub fn try_prepare_combo_input_with_draft<E>(
    node: &Node,
    action: ControlAction,
    available: impl FnOnce() -> Result<bool, E>,
    editable: impl FnOnce() -> Result<bool, E>,
    model_current: impl FnOnce() -> Result<bool, E>,
    linked_draft: impl FnOnce() -> Result<Option<String>, E>,
) -> Result<Option<ComboInput>, E> {
    try_prepare_combo_input_with_live_draft(
        node,
        action,
        available,
        editable,
        model_current,
        || Ok(linked_draft()?.is_none_or(|draft| draft == crate::text_input_value(node))),
    )
}

#[doc(hidden)]
pub fn try_prepare_combo_input_with_live_draft<E>(
    node: &Node,
    action: ControlAction,
    available: impl FnOnce() -> Result<bool, E>,
    editable: impl FnOnce() -> Result<bool, E>,
    model_current: impl FnOnce() -> Result<bool, E>,
    draft_current: impl FnOnce() -> Result<bool, E>,
) -> Result<Option<ComboInput>, E> {
    if !matches!(
        action,
        ControlAction::Select(_) | ControlAction::AcceptComboText
    ) {
        return Ok(None);
    }
    crate::property::watch_reads(|reads| {
        if !available()? || reads.changed() {
            return Ok(None);
        }
        let editable = editable()?;
        if (action == ControlAction::AcceptComboText && !editable)
            || reads.changed()
            || !model_current()?
            || reads.changed()
        {
            return Ok(None);
        }
        Ok(match action {
            ControlAction::Select(index) => {
                combo_selection(node, index).map(|selection| ComboInput::Select {
                    selection,
                    editable,
                })
            }
            ControlAction::AcceptComboText => {
                if !draft_current()? || reads.changed() {
                    return Ok(None);
                }
                let Some(submission) = combo_submission(node) else {
                    return Ok(None);
                };
                let selection = if let Some(index) = submission.index {
                    let Some(selection) = combo_selection(node, index) else {
                        return Ok(None);
                    };
                    Some(selection)
                } else {
                    None
                };
                Some(ComboInput::Accept {
                    text: submission.text,
                    selection,
                })
            }
            _ => None,
        })
    })
}

#[doc(hidden)]
pub fn prepare_combo_input_with_live_draft(
    node: &Node,
    action: ControlAction,
    available: impl FnOnce() -> bool,
    editable: impl FnOnce() -> bool,
    model_current: impl FnOnce() -> bool,
    draft_current: impl FnOnce() -> bool,
) -> Option<ComboInput> {
    try_prepare_combo_input_with_live_draft(
        node,
        action,
        || Ok::<_, std::convert::Infallible>(available()),
        || Ok(editable()),
        || Ok(model_current()),
        || Ok(draft_current()),
    )
    .unwrap_or_else(|error| match error {})
}

#[doc(hidden)]
pub fn prepare_combo_input(
    node: &Node,
    action: ControlAction,
    available: impl FnOnce() -> bool,
    editable: impl FnOnce() -> bool,
    model_current: impl FnOnce() -> bool,
) -> Option<ComboInput> {
    try_prepare_combo_input(
        node,
        action,
        || Ok::<_, std::convert::Infallible>(available()),
        || Ok(editable()),
        || Ok(model_current()),
    )
    .unwrap_or_else(|error| match error {})
}

#[doc(hidden)]
pub fn prepare_combo_input_with_draft(
    node: &Node,
    action: ControlAction,
    available: impl FnOnce() -> bool,
    editable: impl FnOnce() -> bool,
    model_current: impl FnOnce() -> bool,
    linked_draft: impl FnOnce() -> Option<String>,
) -> Option<ComboInput> {
    try_prepare_combo_input_with_draft(
        node,
        action,
        || Ok::<_, std::convert::Infallible>(available()),
        || Ok(editable()),
        || Ok(model_current()),
        || Ok(linked_draft()),
    )
    .unwrap_or_else(|error| match error {})
}

pub fn choice_enabled(node: &Node, index: usize) -> bool {
    if node.kind == "SearchField" {
        return crate::search_suggestion(node, index).is_some();
    }
    model(node).map_or_else(
        || index < node.strings("model").len(),
        |model| model.items.rows.enabled(index),
    )
}

impl Node {
    /// Only read the model and selection when the editor is displaying a label.
    #[doc(hidden)]
    pub fn try_combo_draft_is_current<E>(
        &self,
        draft: Option<String>,
        selection: impl FnOnce() -> Result<bool, E>,
    ) -> Result<bool, E> {
        let shown = crate::text_input_value(self);
        match draft {
            Some(draft) => Ok(draft == shown),
            None => Ok(shown == combo_text(self) && selection()?),
        }
    }

    #[doc(hidden)]
    pub fn combo_draft_is_current(
        &self,
        draft: Option<String>,
        selection: impl FnOnce() -> bool,
    ) -> bool {
        self.try_combo_draft_is_current(draft, || Ok::<_, std::convert::Infallible>(selection()))
            .unwrap_or_else(|error| match error {})
    }

    #[doc(hidden)]
    pub fn combo_selection_is_current(&self, property: &str, value: &Value) -> bool {
        match (self.properties.get(property), value) {
            (Some(Value::Float(shown)), Value::Float(live)) if shown.is_nan() => live.is_nan(),
            (shown, live) => shown == Some(live),
        }
    }

    #[doc(hidden)]
    pub fn try_prepare_combo_edit<E>(
        &self,
        input: InputRoute<'_>,
        editable: impl FnOnce() -> Result<bool, E>,
        draft_current: impl FnOnce() -> Result<bool, E>,
    ) -> Result<bool, E> {
        Ok(input.try_available(editable)? && draft_current()? && input.is_current())
    }

    #[doc(hidden)]
    pub fn prepare_combo_edit(
        &self,
        input: InputRoute<'_>,
        editable: impl FnOnce() -> bool,
        draft_current: impl FnOnce() -> bool,
    ) -> bool {
        self.try_prepare_combo_edit(
            input,
            || Ok::<_, std::convert::Infallible>(editable()),
            || Ok(draft_current()),
        )
        .unwrap_or_else(|error| match error {})
    }

    #[doc(hidden)]
    pub fn set_string_combo_model(&mut self, source: VecModel<String>) {
        self.standard_list_stamp = Some(source.edit_stamp());
        self.properties.insert("model", source.into());
    }
}

#[doc(hidden)]
pub fn combo_model_is_current<T>(node: &Node, source: &VecModel<T>) -> bool {
    if let Some(model) = model(node) {
        model.items.changes.track();
        model.structure == source.structure_stamp() && model.revision == model.items.revision.get()
    } else {
        node.standard_list_stamp == Some(source.contents_stamp())
    }
}

#[doc(hidden)]
pub fn combo_value(node: &Node, index: usize) -> Option<Value> {
    model(node)?.items.rows.value(index)
}

pub fn combo_row_key(node: &Node, index: usize) -> Option<RowKey> {
    model(node)?.items.rows.key(index)
}

pub fn combo_row_index(node: &Node, key: RowKey) -> Option<usize> {
    model(node)?.items.rows.index(key)
}

/// A pressed or projected option must still identify the same record and business value.
#[derive(Clone, Debug, PartialEq)]
pub struct ChoiceIdentity {
    pub label: String,
    pub record: Option<(RowKey, Value)>,
}

pub fn choice_identity(node: &Node, index: usize) -> Option<ChoiceIdentity> {
    if node.kind == "SearchField" {
        return Some(ChoiceIdentity {
            label: crate::search_suggestion(node, index)?.to_owned(),
            record: None,
        });
    }
    let label = combo_label(node, index)?.into_owned();
    let record = match model(node) {
        Some(model) => Some((model.items.rows.key(index)?, model.items.rows.value(index)?)),
        None => None,
    };
    Some(ChoiceIdentity { label, record })
}