Skip to main content

xrack_runtime/
controls.rs

1use crate::{
2    DecimalSpinRange, InputRoute, ListModel, Node, Property, RoutedEvent, RowKey, SpinDecimal,
3    TableRows, Value,
4};
5use std::{
6    rc::Rc,
7    sync::{
8        Arc,
9        atomic::{AtomicU64, Ordering},
10    },
11};
12
13/// Identity shared by all presentations of one component instance's Action.
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub struct ActionKey(u64);
16
17impl ActionKey {
18    #[doc(hidden)]
19    pub fn present_with(
20        self,
21        node: &mut Node,
22        checkable: impl FnOnce() -> bool,
23        enabled: impl FnOnce() -> bool,
24        checked: impl FnOnce(bool) -> bool,
25    ) {
26        self.try_present_with(
27            node,
28            || Ok::<_, std::convert::Infallible>(checkable()),
29            || Ok(enabled()),
30            |checkable| Ok(checked(checkable)),
31        )
32        .unwrap_or_else(|error| match error {});
33    }
34
35    /// Resolve presentation bindings in their render order.
36    #[doc(hidden)]
37    pub fn try_present_with<E>(
38        self,
39        node: &mut Node,
40        checkable: impl FnOnce() -> Result<bool, E>,
41        enabled: impl FnOnce() -> Result<bool, E>,
42        checked: impl FnOnce(bool) -> Result<bool, E>,
43    ) -> Result<bool, E> {
44        let checkable = checkable()?;
45        let enabled = enabled()?;
46        let checked = checked(checkable)?;
47        self.present(node, enabled, checkable, checked);
48        Ok(enabled)
49    }
50
51    #[doc(hidden)]
52    pub fn present(self, node: &mut crate::Node, enabled: bool, checkable: bool, checked: bool) {
53        node.action = Some(self);
54        node.properties.insert("enabled", enabled.into());
55        node.properties.insert("checkable", checkable.into());
56        node.properties.insert("checked", checked.into());
57    }
58}
59
60/// Return a pending checked update only while the activation bindings remain current.
61#[doc(hidden)]
62pub fn try_prepare_action_activation<E>(
63    enabled: impl FnOnce() -> Result<bool, E>,
64    checkable: impl FnOnce() -> Result<bool, E>,
65    checked: impl FnOnce() -> Result<bool, E>,
66) -> Result<Option<Option<bool>>, E> {
67    crate::property::watch_reads(|reads| {
68        if !enabled()? || reads.changed() {
69            return Ok(None);
70        }
71        let checkable = checkable()?;
72        if reads.changed() {
73            return Ok(None);
74        }
75        let next = if checkable { Some(!checked()?) } else { None };
76        Ok((!reads.changed()).then_some(next))
77    })
78}
79
80#[doc(hidden)]
81pub fn prepare_action_activation(
82    enabled: impl FnOnce() -> bool,
83    checkable: impl FnOnce() -> bool,
84    checked: impl FnOnce() -> bool,
85) -> Option<Option<bool>> {
86    try_prepare_action_activation(
87        || Ok::<_, std::convert::Infallible>(enabled()),
88        || Ok(checkable()),
89        || Ok(checked()),
90    )
91    .unwrap_or_else(|error| match error {})
92}
93
94/// Read the next expansion state while the group and its input route remain current.
95#[doc(hidden)]
96pub fn try_prepare_group_box_toggle<E>(
97    input: Option<InputRoute<'_>>,
98    checkable: impl FnOnce() -> Result<bool, E>,
99    checked: impl FnOnce() -> Result<bool, E>,
100) -> Result<Option<bool>, E> {
101    if input.is_some_and(|input| !input.is_current()) {
102        return Ok(None);
103    }
104    Ok(
105        try_prepare_action_activation(|| Ok(true), checkable, checked)?
106            .flatten()
107            .filter(|_| input.is_none_or(InputRoute::is_current)),
108    )
109}
110
111#[doc(hidden)]
112pub fn prepare_group_box_toggle(
113    input: Option<InputRoute<'_>>,
114    checkable: impl FnOnce() -> bool,
115    checked: impl FnOnce() -> bool,
116) -> Option<bool> {
117    try_prepare_group_box_toggle(
118        input,
119        || Ok::<_, std::convert::Infallible>(checkable()),
120        || Ok(checked()),
121    )
122    .unwrap_or_else(|error| match error {})
123}
124
125/// Resolve a toggle or explicit expansion without acting on an old input route.
126#[doc(hidden)]
127pub fn try_prepare_expander_change<E>(
128    input: Option<InputRoute<'_>>,
129    requested: Option<bool>,
130    expanded: impl FnOnce() -> Result<bool, E>,
131) -> Result<Option<bool>, E> {
132    if input.is_some_and(|input| !input.is_current()) {
133        return Ok(None);
134    }
135    crate::property::watch_reads(|reads| {
136        let current = expanded()?;
137        let next = requested.unwrap_or(!current);
138        Ok(
139            (next != current && !reads.changed() && input.is_none_or(InputRoute::is_current))
140                .then_some(next),
141        )
142    })
143}
144
145#[doc(hidden)]
146pub fn prepare_expander_change(
147    input: Option<InputRoute<'_>>,
148    requested: Option<bool>,
149    expanded: impl FnOnce() -> bool,
150) -> Option<bool> {
151    try_prepare_expander_change(input, requested, || {
152        Ok::<_, std::convert::Infallible>(expanded())
153    })
154    .unwrap_or_else(|error| match error {})
155}
156
157/// Resolve an activation target without allowing bindings to invalidate it mid-read.
158#[doc(hidden)]
159pub fn try_prepare_action_view<T, E>(
160    read: impl FnOnce() -> Result<Option<T>, E>,
161) -> Result<Option<T>, E> {
162    crate::property::watch_reads(|reads| Ok(read()?.filter(|_| !reads.changed())))
163}
164
165#[doc(hidden)]
166pub fn prepare_action_view<T>(read: impl FnOnce() -> Option<T>) -> Option<T> {
167    try_prepare_action_view(|| Ok::<_, std::convert::Infallible>(read()))
168        .unwrap_or_else(|error| match error {})
169}
170
171impl crate::CheckState {
172    /// Compute a toggle while its state and settings still describe the same input.
173    #[doc(hidden)]
174    pub fn try_prepare_toggle<E>(
175        input: Option<InputRoute<'_>>,
176        current: impl FnOnce() -> Result<Self, E>,
177        tristate: impl FnOnce() -> Result<bool, E>,
178    ) -> Result<Option<Self>, E> {
179        let route_current = || input.is_none_or(InputRoute::is_current);
180        if !route_current() {
181            return Ok(None);
182        }
183        crate::property::watch_reads(|reads| {
184            let current = current()?;
185            if reads.changed() || !route_current() {
186                return Ok(None);
187            }
188            let next = if let Some(crate::RoutedEvent::Control(ControlAction::SetSwitch(checked))) =
189                input.map(InputRoute::event)
190            {
191                let desired = Self::from(*checked);
192                (desired != current).then_some(desired)
193            } else {
194                Some(current.next(tristate()?))
195            };
196            Ok(next.filter(|_| !reads.changed() && route_current()))
197        })
198    }
199
200    #[doc(hidden)]
201    pub fn prepare_toggle(
202        input: Option<InputRoute<'_>>,
203        current: impl FnOnce() -> Self,
204        tristate: impl FnOnce() -> bool,
205    ) -> Option<Self> {
206        Self::try_prepare_toggle(
207            input,
208            || Ok::<_, std::convert::Infallible>(current()),
209            || Ok(tristate()),
210        )
211        .unwrap_or_else(|error| match error {})
212    }
213}
214
215/// Sample toggle settings before history, with the same input guard as the write.
216#[doc(hidden)]
217pub fn try_prepare_row_toggle<E>(
218    node: &Node,
219    input: crate::InputRoute<'_>,
220    tristate: Option<impl FnOnce() -> Result<bool, E>>,
221    history: impl FnOnce() -> Result<bool, E>,
222) -> Result<Option<bool>, E> {
223    try_prepare_row_toggle_matching(node, input, tristate, || true, history)
224}
225
226/// Revalidate the displayed field after reading settings and before recording history.
227#[doc(hidden)]
228pub fn try_prepare_row_toggle_matching<E>(
229    node: &Node,
230    input: crate::InputRoute<'_>,
231    tristate: Option<impl FnOnce() -> Result<bool, E>>,
232    field_current: impl FnOnce() -> bool,
233    history: impl FnOnce() -> Result<bool, E>,
234) -> Result<Option<bool>, E> {
235    input.try_prepare(
236        || match tristate {
237            Some(read) => Ok(read()? == node.boolean("tristate", false)),
238            None => Ok(true),
239        },
240        || {
241            if !field_current() {
242                return Ok(None);
243            }
244            history().map(Some)
245        },
246    )
247}
248
249#[doc(hidden)]
250pub fn prepare_row_toggle(
251    node: &Node,
252    input: crate::InputRoute<'_>,
253    tristate: Option<impl FnOnce() -> bool>,
254    history: impl FnOnce() -> bool,
255) -> Option<bool> {
256    prepare_row_toggle_matching(node, input, tristate, || true, history)
257}
258
259#[doc(hidden)]
260pub fn prepare_row_toggle_matching(
261    node: &Node,
262    input: crate::InputRoute<'_>,
263    tristate: Option<impl FnOnce() -> bool>,
264    field_current: impl FnOnce() -> bool,
265    history: impl FnOnce() -> bool,
266) -> Option<bool> {
267    try_prepare_row_toggle_matching(
268        node,
269        input,
270        tristate.map(|read| move || Ok::<_, std::convert::Infallible>(read())),
271        field_current,
272        || Ok(history()),
273    )
274    .unwrap_or_else(|error| match error {})
275}
276
277/// Resolve an index only while the control and its options remain current.
278#[doc(hidden)]
279pub fn try_prepare_index_selection<E>(
280    index: usize,
281    available: impl FnOnce() -> Result<bool, E>,
282    contains: impl FnOnce(i64) -> Result<bool, E>,
283    current: impl FnOnce() -> Result<i64, E>,
284) -> Result<Option<i64>, E> {
285    let Ok(index) = i64::try_from(index) else {
286        return Ok(None);
287    };
288    crate::property::watch_reads(|reads| {
289        if !available()? || reads.changed() || !contains(index)? || reads.changed() {
290            return Ok(None);
291        }
292        Ok((current()? != index && !reads.changed()).then_some(index))
293    })
294}
295
296#[doc(hidden)]
297pub fn prepare_index_selection(
298    index: usize,
299    available: impl FnOnce() -> bool,
300    contains: impl FnOnce(i64) -> bool,
301    current: impl FnOnce() -> i64,
302) -> Option<i64> {
303    try_prepare_index_selection(
304        index,
305        || Ok::<_, std::convert::Infallible>(available()),
306        |index| Ok(contains(index)),
307        || Ok(current()),
308    )
309    .unwrap_or_else(|error| match error {})
310}
311
312/// Resolve a source row and discard the selection if its projection changes during the cursor read.
313#[doc(hidden)]
314pub fn try_prepare_source_selection<E>(
315    resolve: impl FnOnce() -> Result<Option<usize>, E>,
316    current: impl FnOnce() -> Result<i64, E>,
317) -> Result<Option<i64>, E> {
318    try_prepare_action_view(|| {
319        let Some(index) = resolve()?.and_then(|index| i64::try_from(index).ok()) else {
320            return Ok(None);
321        };
322        Ok((current()? != index).then_some(index))
323    })
324}
325
326#[doc(hidden)]
327pub fn prepare_source_selection(
328    resolve: impl FnOnce() -> Option<usize>,
329    current: impl FnOnce() -> i64,
330) -> Option<i64> {
331    try_prepare_source_selection(
332        || Ok::<_, std::convert::Infallible>(resolve()),
333        || Ok(current()),
334    )
335    .unwrap_or_else(|error| match error {})
336}
337
338impl Node {
339    /// A disabled Action forces its presentation's state-controlled enabled value.
340    #[doc(hidden)]
341    pub fn action_state_override(&self, property: &str) -> Option<crate::Value> {
342        (property == "enabled" && self.action.is_some() && !self.boolean("enabled", true))
343            .then_some(crate::Value::Bool(false))
344    }
345}
346
347impl Default for ActionKey {
348    #[expect(
349        clippy::expect_used,
350        reason = "action IDs must remain unique across all action instances"
351    )]
352    fn default() -> Self {
353        static NEXT_ACTION: AtomicU64 = AtomicU64::new(1);
354        let id = NEXT_ACTION
355            .try_update(Ordering::Relaxed, Ordering::Relaxed, |next| {
356                next.checked_add(1)
357            })
358            .expect("Action keys exhausted");
359        Self(id)
360    }
361}
362
363#[derive(Clone, Copy, Debug, PartialEq, Eq)]
364pub enum SpinAction {
365    Increase,
366    Decrease,
367    Step(i64),
368    Minimum,
369    Maximum,
370    Commit(i64),
371    CommitIfCurrent {
372        original: i64,
373        value: i64,
374    },
375    CommitDecimal(SpinDecimal),
376    CommitDecimalIfCurrent {
377        original: Option<SpinDecimal>,
378        value: SpinDecimal,
379    },
380    #[doc(hidden)]
381    StepFromIntegerDraft {
382        original: Option<i64>,
383        draft: i64,
384        steps: i64,
385    },
386    #[doc(hidden)]
387    StepFromDecimalDraft {
388        original: Option<SpinDecimal>,
389        draft: SpinDecimal,
390        steps: i64,
391    },
392}
393
394impl SpinAction {
395    /// Read the live control value when applying an action based on an earlier draft.
396    #[doc(hidden)]
397    pub fn try_accepts_current<E>(
398        self,
399        current: impl FnOnce() -> Result<Value, E>,
400    ) -> Result<bool, E> {
401        Ok(match self {
402            Self::CommitIfCurrent { original, .. }
403            | Self::StepFromIntegerDraft {
404                original: Some(original),
405                ..
406            } => {
407                matches!(current()?, Value::Int(value) if value == original)
408            }
409            Self::CommitDecimalIfCurrent { original, .. }
410            | Self::StepFromDecimalDraft { original, .. } => {
411                matches!(current()?, Value::Float(value) if SpinDecimal::new(value) == original)
412            }
413            _ => true,
414        })
415    }
416
417    #[doc(hidden)]
418    pub fn accepts_current(self, current: impl FnOnce() -> Value) -> bool {
419        self.try_accepts_current(|| Ok::<_, std::convert::Infallible>(current()))
420            .unwrap_or_else(|error| match error {})
421    }
422}
423
424#[derive(Clone, Copy, Debug, PartialEq, Eq)]
425pub enum ControlAction {
426    Spin(SpinAction),
427    SetSwitch(bool),
428    Expander(bool),
429    Calendar(crate::CalendarAction),
430    Select(usize),
431    ActivateRadioOption,
432    MoveTab(TabMove),
433    CloseTab(TabClose),
434    PickTumbler {
435        index: usize,
436        row: crate::RowKey,
437    },
438    TableSelection(crate::TableSelectionAction),
439    Tree(crate::TreeAction),
440    Dialog(DialogRole),
441    DialogCommand(DialogCommand),
442    Drawer(bool),
443    Popup(bool),
444    SwipeDelegate(SwipeSide),
445    DelayButton(bool),
446    StackBack {
447        revision: u64,
448    },
449    ActivateMenuItem,
450    TextCommand(crate::TextCommand),
451    ActivateTextLink(usize),
452    ActivateAction,
453    ActivateShortcut,
454    AmbiguousShortcut,
455    AcceptComboText,
456    #[doc(hidden)]
457    ValidateTextSubmission,
458    SubmitSearch,
459    ClearSearch,
460    SortColumn(usize),
461    ResizeColumn {
462        column: usize,
463        width: u32,
464    },
465    ResizeRow {
466        row: usize,
467        key: crate::RowKey,
468        height: u32,
469    },
470    MoveColumn {
471        from: usize,
472        to: usize,
473    },
474    MoveRow {
475        from: usize,
476        to: usize,
477        row: crate::RowKey,
478        stamp: (u64, u64),
479    },
480}
481
482pub fn is_modal_overlay(kind: &str) -> bool {
483    matches!(kind, "Dialog" | "Drawer")
484}
485
486pub fn is_window_overlay(kind: &str) -> bool {
487    is_modal_overlay(kind) || kind == "PopupWindow"
488}
489
490/// A swipe may reveal a panel only if it was visible in the displayed scene
491/// and is still visible after reading the live open side.
492#[doc(hidden)]
493pub fn try_prepare_swipe_side<E>(
494    node: &Node,
495    side: SwipeSide,
496    input: InputRoute<'_>,
497    current: impl FnOnce() -> Result<SwipeSide, E>,
498    panel_visible: impl FnOnce(&str) -> Result<bool, E>,
499) -> Result<bool, E> {
500    crate::property::watch_reads(|reads| {
501        if !input.is_current()
502            || !node.accepts_swipe_side(current()?, side)
503            || reads.changed()
504            || !input.is_current()
505        {
506            return Ok(false);
507        }
508        if let Some(panel) = side.panel()
509            && !panel_visible(panel)?
510        {
511            return Ok(false);
512        }
513        Ok(!reads.changed() && input.is_current())
514    })
515}
516
517#[doc(hidden)]
518pub fn prepare_swipe_side(
519    node: &Node,
520    side: SwipeSide,
521    input: InputRoute<'_>,
522    current: impl FnOnce() -> SwipeSide,
523    panel_visible: impl FnOnce(&str) -> bool,
524) -> bool {
525    try_prepare_swipe_side(
526        node,
527        side,
528        input,
529        || Ok::<_, std::convert::Infallible>(current()),
530        |panel| Ok(panel_visible(panel)),
531    )
532    .unwrap_or_else(|error| match error {})
533}
534
535#[doc(hidden)]
536pub fn try_set_overlay_open<E>(
537    open: bool,
538    input: Option<InputRoute<'_>>,
539    current: impl FnOnce() -> Result<bool, E>,
540    set_open: impl FnOnce(bool) -> Result<(), E>,
541    notify: impl FnOnce(bool) -> Result<(), E>,
542) -> Result<bool, E> {
543    let route_current = || input.is_none_or(InputRoute::is_current);
544    let should_set = crate::property::watch_reads(|reads| {
545        Ok(route_current() && current()? != open && !reads.changed() && route_current())
546    })?;
547    if !should_set {
548        return Ok(false);
549    }
550    set_open(open)?;
551    notify(open)?;
552    Ok(true)
553}
554
555#[doc(hidden)]
556pub fn set_overlay_open(
557    open: bool,
558    input: Option<InputRoute<'_>>,
559    current: impl FnOnce() -> bool,
560    set_open: impl FnOnce(bool),
561    notify: impl FnOnce(bool),
562) -> bool {
563    try_set_overlay_open(
564        open,
565        input,
566        || Ok::<_, std::convert::Infallible>(current()),
567        |open| {
568            set_open(open);
569            Ok(())
570        },
571        |open| {
572            notify(open);
573            Ok(())
574        },
575    )
576    .unwrap_or_else(|error| match error {})
577}
578
579#[doc(hidden)]
580pub fn is_pane(kind: &str) -> bool {
581    matches!(kind, "Pane" | "ControlFrame")
582}
583
584#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
585pub enum PopupPlacement {
586    #[default]
587    Below,
588    Above,
589    Left,
590    Right,
591    Offset,
592}
593
594#[derive(Clone, Copy, Debug, PartialEq, Eq)]
595pub struct TableSort {
596    pub column: usize,
597    pub descending: bool,
598}
599
600impl TableSort {
601    #[doc(hidden)]
602    pub fn from_index(column: i64, descending: bool) -> Option<Self> {
603        Some(Self {
604            column: usize::try_from(column).ok()?,
605            descending,
606        })
607    }
608
609    #[doc(hidden)]
610    pub fn column_index(sort: Option<Self>) -> i64 {
611        sort.map_or(-1, |sort| sort.column as i64)
612    }
613
614    #[doc(hidden)]
615    pub fn is_descending(sort: Option<Self>) -> bool {
616        sort.is_some_and(|sort| sort.descending)
617    }
618}
619
620/// Visual positions map to the declaration indices used by cells and model actions.
621#[derive(Clone, Debug, Default, PartialEq, Eq)]
622pub struct TableColumnOrder(Option<Arc<ColumnPermutation>>);
623
624#[derive(Debug, PartialEq, Eq)]
625struct ColumnPermutation {
626    columns: Vec<usize>,
627    positions: Vec<usize>,
628}
629
630impl TableColumnOrder {
631    pub fn as_slice(&self, count: usize) -> Option<&[usize]> {
632        self.0
633            .as_deref()
634            .filter(|order| order.columns.len() == count)
635            .map(|order| order.columns.as_slice())
636    }
637
638    pub fn iter(&self, count: usize) -> impl DoubleEndedIterator<Item = usize> + ExactSizeIterator {
639        let order = self.as_slice(count);
640        (0..count).map(move |visual| order.map_or(visual, |order| order[visual]))
641    }
642
643    pub fn visual_index(&self, count: usize, column: usize) -> Option<usize> {
644        if let Some(order) = self
645            .0
646            .as_deref()
647            .filter(|order| order.columns.len() == count)
648        {
649            order.positions.get(column).copied()
650        } else {
651            (column < count).then_some(column)
652        }
653    }
654
655    #[doc(hidden)]
656    pub fn moved(&self, count: usize, from: usize, to: usize) -> Option<(usize, Self)> {
657        if from >= count || to >= count || from == to {
658            return None;
659        }
660        let mut order: Vec<_> = self.iter(count).collect();
661        let column = order.remove(from);
662        order.insert(to, column);
663        let reordered = order.iter().copied().ne(0..count);
664        Some((
665            column,
666            Self(reordered.then(|| {
667                let mut positions = vec![0; count];
668                for (visual, &logical) in order.iter().enumerate() {
669                    positions[logical] = visual;
670                }
671                Arc::new(ColumnPermutation {
672                    columns: order,
673                    positions,
674                })
675            })),
676        ))
677    }
678}
679
680#[derive(Clone, Debug, PartialEq)]
681pub struct TableHeader {
682    pub columns: Vec<Node>,
683    pub sort: Option<TableSort>,
684    pub column_widths: Vec<Option<u32>>,
685}
686
687pub fn resizable_table_column(table: &Node, column: usize) -> Option<&Node> {
688    let definition = table.table_header.as_ref()?.columns.get(column)?;
689    (table.boolean("resizable-columns", false) && definition.boolean("resizable", true))
690        .then_some(definition)
691}
692
693#[doc(hidden)]
694pub fn resize_table_column(widths: &Property<Vec<Option<u32>>>, column: usize, width: u32) -> bool {
695    let mut next = widths.get(Vec::new);
696    if next.get(column) == Some(&Some(width)) {
697        return false;
698    }
699    if next.len() <= column {
700        next.resize(column + 1, None);
701    }
702    next[column] = Some(width);
703    widths.set(next);
704    true
705}
706
707/// Validate a drag against both the originating scene and the current bindings.
708#[doc(hidden)]
709pub fn try_table_drag_available<E>(
710    table: &Node,
711    input: InputRoute<'_>,
712    flag: impl FnOnce(&str) -> Result<bool, E>,
713    column_resizable: impl FnOnce(usize) -> Result<bool, E>,
714) -> Result<bool, E> {
715    let (property, column) = match *input.event() {
716        RoutedEvent::Control(ControlAction::ResizeColumn { column, .. }) => {
717            if resizable_table_column(table, column).is_none() {
718                return Ok(false);
719            }
720            ("resizable-columns", Some(column))
721        }
722        RoutedEvent::Control(ControlAction::ResizeRow { .. }) => ("resizable-rows", None),
723        RoutedEvent::Control(ControlAction::MoveColumn { .. }) => ("movable-columns", None),
724        RoutedEvent::Control(ControlAction::MoveRow { stamp, .. }) => {
725            if table.standard_list_stamp != Some(stamp) {
726                return Ok(false);
727            }
728            ("movable-rows", None)
729        }
730        _ => return Ok(true),
731    };
732    if !table.boolean(property, false) {
733        return Ok(false);
734    }
735    input.try_available(|| {
736        if !flag(property)? {
737            return Ok(false);
738        }
739        column.map_or(Ok(true), column_resizable)
740    })
741}
742
743#[doc(hidden)]
744pub fn table_drag_available(
745    table: &Node,
746    input: InputRoute<'_>,
747    flag: impl FnOnce(&str) -> bool,
748    column_resizable: impl FnOnce(usize) -> bool,
749) -> bool {
750    try_table_drag_available(
751        table,
752        input,
753        |name| Ok::<_, std::convert::Infallible>(flag(name)),
754        |column| Ok(column_resizable(column)),
755    )
756    .unwrap_or_else(|error| match error {})
757}
758
759#[doc(hidden)]
760pub enum TableHeaderAction {
761    Sort(TableSort),
762    MoveColumn {
763        from: usize,
764        to: usize,
765    },
766    ResizeColumn {
767        column: usize,
768        width: u32,
769    },
770    ResizeRow {
771        row: usize,
772        key: RowKey,
773        height: u32,
774    },
775}
776
777impl TableHeaderAction {
778    /// Reject stale header actions before reading the row projection.
779    pub fn try_prepare<M, E>(
780        node: &Node,
781        input: InputRoute<'_>,
782        action: ControlAction,
783        sort: impl FnOnce() -> Option<TableSort>,
784        order: impl FnOnce() -> TableColumnOrder,
785        rows: impl FnOnce() -> Result<TableRows<M>, E>,
786    ) -> Result<Option<(Self, TableRows<M>)>, E> {
787        let action = match action {
788            ControlAction::SortColumn(column) => {
789                let Some(sort) = node
790                    .table_header
791                    .as_ref()
792                    .and_then(|header| header.next_sort_if_current(column, sort()))
793                else {
794                    return Ok(None);
795                };
796                Self::Sort(sort)
797            }
798            ControlAction::MoveColumn { from, to } => {
799                if !node.table_column_move_is_current(from, to, &order()) {
800                    return Ok(None);
801                }
802                Self::MoveColumn { from, to }
803            }
804            ControlAction::ResizeColumn { column, width } => Self::ResizeColumn { column, width },
805            ControlAction::ResizeRow { row, key, height } => Self::ResizeRow { row, key, height },
806            _ => return Ok(None),
807        };
808        let rows = rows()?;
809        Ok(
810            (input.is_current() && node.standard_list_stamp == Some(rows.positions().stamp()))
811                .then_some((action, rows)),
812        )
813    }
814
815    pub fn prepare<M>(
816        node: &Node,
817        input: InputRoute<'_>,
818        action: ControlAction,
819        sort: impl FnOnce() -> Option<TableSort>,
820        order: impl FnOnce() -> TableColumnOrder,
821        rows: impl FnOnce() -> TableRows<M>,
822    ) -> Option<(Self, TableRows<M>)> {
823        Self::try_prepare(node, input, action, sort, order, || {
824            Ok::<_, std::convert::Infallible>(rows())
825        })
826        .unwrap_or_else(|error| match error {})
827    }
828}
829
830impl TableHeader {
831    pub fn next_sort(&self, column: usize) -> Option<TableSort> {
832        let definition = self.columns.get(column)?;
833        definition.boolean("sortable", true).then_some(TableSort {
834            column,
835            descending: self
836                .sort
837                .is_some_and(|sort| sort.column == column && !sort.descending),
838        })
839    }
840
841    /// Resolve a click using the sort indicator the user actually saw.
842    #[doc(hidden)]
843    pub fn next_sort_if_current(
844        &self,
845        column: usize,
846        current: Option<TableSort>,
847    ) -> Option<TableSort> {
848        if self.sort != current {
849            return None;
850        }
851        self.next_sort(column)
852    }
853}
854
855impl Node {
856    /// A column move uses visual positions from the originating scene.
857    #[doc(hidden)]
858    pub fn table_column_move_is_current(
859        &self,
860        from: usize,
861        to: usize,
862        current: &TableColumnOrder,
863    ) -> bool {
864        self.table_column_order == *current
865            && from != to
866            && self
867                .table_header
868                .as_ref()
869                .is_some_and(|header| from < header.columns.len() && to < header.columns.len())
870    }
871}
872
873#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
874pub enum DialogRole {
875    #[default]
876    Accept,
877    Reject,
878}
879
880#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
881pub enum SwipeSide {
882    #[default]
883    Closed,
884    Left,
885    Right,
886}
887
888impl SwipeSide {
889    pub fn panel(self) -> Option<&'static str> {
890        match self {
891            Self::Closed => None,
892            Self::Left => Some("SwipeLeft"),
893            Self::Right => Some("SwipeRight"),
894        }
895    }
896}
897
898#[derive(Clone, Copy, Debug, PartialEq, Eq)]
899pub enum DialogCommand {
900    Apply,
901    Reset,
902    Help,
903    Discard,
904}
905
906#[doc(hidden)]
907pub enum DialogEvent {
908    Accepted,
909    Rejected,
910    Applied,
911    Reset,
912    HelpRequested,
913    Discarded,
914}
915
916impl DialogEvent {
917    pub fn handler(&self) -> &'static str {
918        match self {
919            Self::Accepted => "accepted",
920            Self::Rejected => "rejected",
921            Self::Applied => "applied",
922            Self::Reset => "reset",
923            Self::HelpRequested => "help-requested",
924            Self::Discarded => "discarded",
925        }
926    }
927
928    pub fn try_deliver<E>(
929        action: ControlAction,
930        input: InputRoute<'_>,
931        open: impl FnOnce() -> Result<bool, E>,
932        close: impl FnOnce() -> Result<(), E>,
933        notify: impl FnOnce(Self) -> Result<(), E>,
934    ) -> Result<bool, E> {
935        if !open()? || !input.is_current() {
936            return Ok(false);
937        }
938        let event = match action {
939            ControlAction::Dialog(DialogRole::Accept) => Self::Accepted,
940            ControlAction::Dialog(DialogRole::Reject) => Self::Rejected,
941            ControlAction::DialogCommand(DialogCommand::Apply) => Self::Applied,
942            ControlAction::DialogCommand(DialogCommand::Reset) => Self::Reset,
943            ControlAction::DialogCommand(DialogCommand::Help) => Self::HelpRequested,
944            ControlAction::DialogCommand(DialogCommand::Discard) => Self::Discarded,
945            _ => return Ok(false),
946        };
947        if matches!(event, Self::Accepted | Self::Rejected | Self::Discarded) {
948            close()?;
949        }
950        notify(event)?;
951        Ok(true)
952    }
953
954    pub fn deliver(
955        action: ControlAction,
956        input: InputRoute<'_>,
957        open: impl FnOnce() -> bool,
958        close: impl FnOnce(),
959        notify: impl FnOnce(Self),
960    ) -> bool {
961        Self::try_deliver(
962            action,
963            input,
964            || Ok::<_, std::convert::Infallible>(open()),
965            || {
966                close();
967                Ok(())
968            },
969            |event| {
970                notify(event);
971                Ok(())
972            },
973        )
974        .unwrap_or_else(|error| match error {})
975    }
976}
977
978#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
979pub enum StandardButtonKind {
980    #[default]
981    Ok,
982    Open,
983    Save,
984    SaveAll,
985    Cancel,
986    Close,
987    Apply,
988    Reset,
989    RestoreDefaults,
990    Help,
991    Yes,
992    YesToAll,
993    No,
994    NoToAll,
995    Abort,
996    Retry,
997    Ignore,
998    Discard,
999}
1000
1001impl StandardButtonKind {
1002    #[doc(hidden)]
1003    pub fn accepts_message(self) -> bool {
1004        matches!(self, Self::Ok | Self::Yes)
1005    }
1006
1007    pub fn label(self) -> &'static str {
1008        match self {
1009            Self::Ok => "OK",
1010            Self::Open => "Open",
1011            Self::Save => "Save",
1012            Self::SaveAll => "Save All",
1013            Self::Cancel => "Cancel",
1014            Self::Close => "Close",
1015            Self::Apply => "Apply",
1016            Self::Reset => "Reset",
1017            Self::RestoreDefaults => "Restore Defaults",
1018            Self::Help => "Help",
1019            Self::Yes => "Yes",
1020            Self::YesToAll => "Yes to All",
1021            Self::No => "No",
1022            Self::NoToAll => "No to All",
1023            Self::Abort => "Abort",
1024            Self::Retry => "Retry",
1025            Self::Ignore => "Ignore",
1026            Self::Discard => "Discard",
1027        }
1028    }
1029
1030    fn dialog_action(self) -> ControlAction {
1031        match self {
1032            Self::Ok
1033            | Self::Open
1034            | Self::Save
1035            | Self::SaveAll
1036            | Self::Yes
1037            | Self::YesToAll
1038            | Self::Retry
1039            | Self::Ignore => ControlAction::Dialog(DialogRole::Accept),
1040            Self::Cancel | Self::Close | Self::No | Self::NoToAll | Self::Abort => {
1041                ControlAction::Dialog(DialogRole::Reject)
1042            }
1043            Self::Apply => ControlAction::DialogCommand(DialogCommand::Apply),
1044            Self::Reset | Self::RestoreDefaults => {
1045                ControlAction::DialogCommand(DialogCommand::Reset)
1046            }
1047            Self::Help => ControlAction::DialogCommand(DialogCommand::Help),
1048            Self::Discard => ControlAction::DialogCommand(DialogCommand::Discard),
1049        }
1050    }
1051}
1052
1053pub fn dialog_button_action(node: &Node) -> Option<ControlAction> {
1054    if node.kind == "DialogButton" {
1055        return Some(ControlAction::Dialog(node.dialog_role()));
1056    }
1057    node.standard_button_kind()
1058        .map(StandardButtonKind::dialog_action)
1059}
1060
1061pub fn is_button(kind: &str) -> bool {
1062    matches!(
1063        kind,
1064        "Button" | "ToolButton" | "RoundButton" | "DialogButton" | "DelayButton"
1065    )
1066}
1067
1068pub fn delay_millis(node: &Node) -> u64 {
1069    normalized_delay_millis(node.int("delay"))
1070}
1071
1072fn normalized_delay_millis(delay: Option<i64>) -> u64 {
1073    delay.unwrap_or(3_000).clamp(0, 60_000) as u64
1074}
1075
1076/// Confirm that a pending hold or reset still applies to the live button.
1077#[doc(hidden)]
1078pub fn try_delay_button_transition_is_current<E>(
1079    node: &Node,
1080    checked: bool,
1081    available: impl FnOnce() -> Result<bool, E>,
1082    delay: impl FnOnce() -> Result<Option<i64>, E>,
1083    current: impl FnOnce() -> Result<bool, E>,
1084) -> Result<bool, E> {
1085    crate::property::watch_reads(|reads| {
1086        if !available()? || reads.changed() {
1087            return Ok(false);
1088        }
1089        if checked && (normalized_delay_millis(delay()?) != delay_millis(node) || reads.changed()) {
1090            return Ok(false);
1091        }
1092        Ok(current()? != checked && !reads.changed())
1093    })
1094}
1095
1096#[doc(hidden)]
1097pub fn delay_button_transition_is_current(
1098    node: &Node,
1099    checked: bool,
1100    available: impl FnOnce() -> bool,
1101    delay: impl FnOnce() -> Option<i64>,
1102    current: impl FnOnce() -> bool,
1103) -> bool {
1104    try_delay_button_transition_is_current(
1105        node,
1106        checked,
1107        || Ok::<_, std::convert::Infallible>(available()),
1108        || Ok(delay()),
1109        || Ok(current()),
1110    )
1111    .unwrap_or_else(|error| match error {})
1112}
1113
1114pub fn button_text(node: &Node) -> &str {
1115    node.text("text").unwrap_or_else(|| {
1116        if let Some(kind) = node.standard_button_kind() {
1117            return kind.label();
1118        }
1119        match (node.kind, node.dialog_role()) {
1120            ("DialogButton", DialogRole::Accept) => "OK",
1121            ("DialogButton", DialogRole::Reject) => "Cancel",
1122            _ => "",
1123        }
1124    })
1125}
1126
1127pub struct SpinRange {
1128    min: i64,
1129    max: i64,
1130    value: i64,
1131    original: Option<i64>,
1132    step: i64,
1133    wrap: bool,
1134}
1135
1136impl SpinRange {
1137    pub fn from_node(node: &Node) -> Self {
1138        let min = node.int("minimum").unwrap_or(0);
1139        let max = node.int("maximum").unwrap_or(100).max(min);
1140        let original = node.int("value");
1141        Self {
1142            min,
1143            max,
1144            value: original.unwrap_or(min).clamp(min, max),
1145            original,
1146            step: node.int("step-size").unwrap_or(1).max(0),
1147            wrap: node.boolean("wrap", false),
1148        }
1149    }
1150
1151    pub fn value(&self) -> i64 {
1152        self.value
1153    }
1154
1155    pub fn apply(&self, action: SpinAction) -> Option<i64> {
1156        let next = match action {
1157            SpinAction::Increase
1158                if self.wrap
1159                    && self
1160                        .value
1161                        .checked_add(self.step)
1162                        .is_none_or(|value| value > self.max) =>
1163            {
1164                self.min
1165            }
1166            SpinAction::Decrease
1167                if self.wrap
1168                    && self
1169                        .value
1170                        .checked_sub(self.step)
1171                        .is_none_or(|value| value < self.min) =>
1172            {
1173                self.max
1174            }
1175            SpinAction::Increase => self.value.saturating_add(self.step),
1176            SpinAction::Decrease => self.value.saturating_sub(self.step),
1177            SpinAction::Step(steps) => {
1178                let next = i128::from(self.value) + i128::from(self.step) * i128::from(steps);
1179                let min = i128::from(self.min);
1180                let max = i128::from(self.max);
1181                let step = i128::from(self.step);
1182                let value = i128::from(self.value);
1183                if self.wrap && next > max {
1184                    let remaining = i128::from(steps) - (max - value) / step - 1;
1185                    (min + remaining % ((max - min) / step + 1) * step) as i64
1186                } else if self.wrap && next < min {
1187                    let remaining = -i128::from(steps) - (value - min) / step - 1;
1188                    (max - remaining % ((max - min) / step + 1) * step) as i64
1189                } else {
1190                    next.clamp(min, max) as i64
1191                }
1192            }
1193            SpinAction::Minimum => self.min,
1194            SpinAction::Maximum => self.max,
1195            SpinAction::Commit(value) => value,
1196            SpinAction::CommitIfCurrent { original, value } if self.original == Some(original) => {
1197                value
1198            }
1199            SpinAction::CommitIfCurrent { .. } => return None,
1200            SpinAction::StepFromIntegerDraft {
1201                original,
1202                draft,
1203                steps,
1204            } if original.is_none() || original == self.original => {
1205                let value = draft.clamp(self.min, self.max);
1206                let range = Self { value, ..*self };
1207                range.apply(SpinAction::Step(steps)).unwrap_or(value)
1208            }
1209            SpinAction::CommitDecimal(_)
1210            | SpinAction::CommitDecimalIfCurrent { .. }
1211            | SpinAction::StepFromIntegerDraft { .. }
1212            | SpinAction::StepFromDecimalDraft { .. } => {
1213                return None;
1214            }
1215        }
1216        .clamp(self.min, self.max);
1217        (next != self.value).then_some(next)
1218    }
1219}
1220
1221pub fn spin_value_after(node: &Node, action: SpinAction) -> Option<i64> {
1222    if node.boolean("read-only", false)
1223        || matches!(
1224            action,
1225            SpinAction::Commit(_)
1226                | SpinAction::CommitIfCurrent { .. }
1227                | SpinAction::StepFromIntegerDraft { .. }
1228        ) && !spin_editable(node)
1229    {
1230        return None;
1231    }
1232    SpinRange::from_node(node).apply(action)
1233}
1234
1235#[doc(hidden)]
1236pub const SPIN_VIEW_PROPERTIES: &[&str] = &[
1237    "read-only",
1238    "editable",
1239    "minimum",
1240    "maximum",
1241    "decimals",
1242    "decimal-separator",
1243    "step-size",
1244    "wrap",
1245];
1246
1247/// Check that the options used to interpret an input are still current.
1248#[doc(hidden)]
1249pub fn try_spin_view_is_current<E>(
1250    node: &Node,
1251    action: SpinAction,
1252    available: impl FnOnce() -> Result<bool, E>,
1253    current: impl FnOnce() -> Result<Value, E>,
1254    read: impl FnMut(&str) -> Result<Option<Value>, E>,
1255) -> Result<bool, E> {
1256    try_prepare_spin_view(node, action, available, current, read, || Ok(Some(())))
1257        .map(|prepared| prepared.is_some())
1258}
1259
1260#[doc(hidden)]
1261pub fn try_prepare_spin_view<T, E>(
1262    node: &Node,
1263    action: SpinAction,
1264    available: impl FnOnce() -> Result<bool, E>,
1265    current: impl FnOnce() -> Result<Value, E>,
1266    mut read: impl FnMut(&str) -> Result<Option<Value>, E>,
1267    prepare: impl FnOnce() -> Result<Option<T>, E>,
1268) -> Result<Option<T>, E> {
1269    let decimal = node.kind == "DoubleSpinBox";
1270    let commit = matches!(
1271        action,
1272        SpinAction::Commit(_)
1273            | SpinAction::CommitIfCurrent { .. }
1274            | SpinAction::CommitDecimal(_)
1275            | SpinAction::CommitDecimalIfCurrent { .. }
1276            | SpinAction::StepFromIntegerDraft { .. }
1277            | SpinAction::StepFromDecimalDraft { .. }
1278    );
1279    let step = matches!(
1280        action,
1281        SpinAction::Increase
1282            | SpinAction::Decrease
1283            | SpinAction::Step(_)
1284            | SpinAction::StepFromIntegerDraft { .. }
1285            | SpinAction::StepFromDecimalDraft { .. }
1286    );
1287    crate::property::watch_reads(|reads| {
1288        if !available()? || reads.changed() {
1289            return Ok(None);
1290        }
1291        for &name in SPIN_VIEW_PROPERTIES {
1292            let used = match name {
1293                "editable" => commit,
1294                "decimals" => decimal,
1295                "decimal-separator" => decimal && commit,
1296                "step-size" | "wrap" => step,
1297                _ => true,
1298            };
1299            if used && (read(name)?.as_ref() != node.properties.get(name) || reads.changed()) {
1300                return Ok(None);
1301            }
1302        }
1303        if !action.try_accepts_current(current)? || reads.changed() {
1304            return Ok(None);
1305        }
1306        Ok(prepare()?.filter(|_| !reads.changed()))
1307    })
1308}
1309
1310#[doc(hidden)]
1311pub fn spin_view_is_current(
1312    node: &Node,
1313    action: SpinAction,
1314    available: impl FnOnce() -> bool,
1315    current: impl FnOnce() -> Value,
1316    mut read: impl FnMut(&str) -> Option<Value>,
1317) -> bool {
1318    try_spin_view_is_current(
1319        node,
1320        action,
1321        || Ok::<_, std::convert::Infallible>(available()),
1322        || Ok(current()),
1323        |name| Ok(read(name)),
1324    )
1325    .unwrap_or_else(|error| match error {})
1326}
1327
1328#[doc(hidden)]
1329pub fn prepare_spin_view<T>(
1330    node: &Node,
1331    action: SpinAction,
1332    available: impl FnOnce() -> bool,
1333    current: impl FnOnce() -> Value,
1334    mut read: impl FnMut(&str) -> Option<Value>,
1335    prepare: impl FnOnce() -> Option<T>,
1336) -> Option<T> {
1337    try_prepare_spin_view(
1338        node,
1339        action,
1340        || Ok::<_, std::convert::Infallible>(available()),
1341        || Ok(current()),
1342        |name| Ok(read(name)),
1343        || Ok(prepare()),
1344    )
1345    .unwrap_or_else(|error| match error {})
1346}
1347
1348pub fn is_spin_box(kind: &str) -> bool {
1349    matches!(kind, "SpinBox" | "DoubleSpinBox")
1350}
1351
1352pub fn spin_editable(node: &Node) -> bool {
1353    is_spin_box(node.kind) && node.boolean("editable", true) && !node.boolean("read-only", false)
1354}
1355
1356pub fn spin_text(node: &Node) -> String {
1357    if node.kind == "DoubleSpinBox" {
1358        DecimalSpinRange::from_node(node).display()
1359    } else {
1360        SpinRange::from_node(node).value().to_string()
1361    }
1362}
1363
1364pub fn combo_editable(node: &Node) -> bool {
1365    node.kind == "ComboBox" && node.boolean("editable", false)
1366}
1367
1368pub fn text_input_value(node: &Node) -> &str {
1369    if combo_editable(node) {
1370        node.text("edit-text")
1371            .unwrap_or_else(|| crate::combo_text(node))
1372    } else {
1373        node.text("text").unwrap_or("")
1374    }
1375}
1376
1377/// Suggestions can be tagged with the query that produced them.
1378pub fn search_suggestions(node: &Node) -> &[String] {
1379    let text = text_input_value(node);
1380    if node.kind != "SearchField"
1381        || node.boolean("read-only", false)
1382        || text.is_empty()
1383        || node
1384            .text("suggestions-for")
1385            .is_some_and(|query| query != text)
1386    {
1387        &[]
1388    } else {
1389        node.strings("suggestions")
1390    }
1391}
1392
1393pub fn search_suggestion(node: &Node, index: usize) -> Option<&str> {
1394    let value = search_suggestions(node).get(index)?;
1395    (!value.is_empty() && !value.chars().any(char::is_control)).then_some(value.as_str())
1396}
1397
1398pub fn page_indicator_count(node: &Node) -> usize {
1399    usize::try_from(node.int("count").unwrap_or(0).max(0)).unwrap_or(usize::MAX)
1400}
1401
1402pub fn page_indicator_index(node: &Node) -> Option<usize> {
1403    let index = usize::try_from(node.int("current-index").unwrap_or(0)).ok()?;
1404    (index < page_indicator_count(node)).then_some(index)
1405}
1406
1407/// Select the adjacent page in logical order. An invalid selection starts at the first page.
1408#[doc(hidden)]
1409pub fn page_indicator_step(node: &Node, forward: bool) -> Option<usize> {
1410    if !node.boolean("interactive", false) || !node.boolean("enabled", true) {
1411        return None;
1412    }
1413    let last = page_indicator_count(node).checked_sub(1)?;
1414    let current = page_indicator_index(node);
1415    let next = current.map_or(0, |index| {
1416        if forward {
1417            (index + 1).min(last)
1418        } else {
1419            index.saturating_sub(1)
1420        }
1421    });
1422    (current != Some(next)).then_some(next)
1423}
1424
1425/// Resolve an eligible option without giving each option independent selection state.
1426fn navigation_item_kind(kind: &str) -> Option<&'static str> {
1427    match kind {
1428        "TabWidget" => Some("Tab"),
1429        "TabBar" => Some("TabButton"),
1430        "SwipeView" => Some("SwipePage"),
1431        _ => None,
1432    }
1433}
1434
1435fn group_item_available(item: &Node, expected: &str) -> bool {
1436    item.kind == expected && item.boolean("visible", true) && item.boolean("enabled", true)
1437}
1438
1439pub fn group_item(node: &Node, index: usize) -> Option<&Node> {
1440    let expected = if node.kind == "RadioGroup" {
1441        "RadioButton"
1442    } else {
1443        navigation_item_kind(node.kind)?
1444    };
1445    node.children
1446        .get(index)
1447        .filter(|item| group_item_available(item, expected))
1448}
1449
1450fn navigation_index(
1451    kind: &str,
1452    requested: Option<&str>,
1453    index: Option<i64>,
1454    items: &[Node],
1455) -> Option<usize> {
1456    if kind == "StackLayout" {
1457        return match requested {
1458            Some(value) => {
1459                resolve_navigation_value(value, items.iter().map(|item| item.text("value")))
1460            }
1461            None => usize::try_from(index.unwrap_or(0))
1462                .ok()
1463                .filter(|index| *index < items.len()),
1464        };
1465    }
1466    let expected = navigation_item_kind(kind)?;
1467    let eligible = |item: &Node| group_item_available(item, expected);
1468    if let Some(value) = requested {
1469        return resolve_navigation_value(
1470            value,
1471            items
1472                .iter()
1473                .map(|item| eligible(item).then(|| item.text("value")).flatten()),
1474        );
1475    }
1476    if kind == "TabWidget" {
1477        let slot = usize::try_from(index.unwrap_or(0)).ok()?;
1478        return items.get(slot).filter(|item| eligible(item)).map(|_| slot);
1479    }
1480    resolve_swipe_index(index, items.iter().map(eligible))
1481}
1482
1483#[doc(hidden)]
1484pub fn tab_is_closable(group: &Node, item: &Node) -> bool {
1485    matches!(
1486        (group.kind, item.kind),
1487        ("TabBar", "TabButton") | ("TabWidget", "Tab")
1488    ) && item.boolean("closable", group.boolean("tabs-closable", false))
1489}
1490
1491#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1492pub struct TabClose {
1493    pub index: usize,
1494    row: Option<crate::RowKey>,
1495    stamp: Option<(u64, u64)>,
1496}
1497
1498impl Node {
1499    #[doc(hidden)]
1500    pub fn tab_close(&self, index: usize) -> Option<TabClose> {
1501        let item = group_item(self, index)?;
1502        tab_is_closable(self, item).then_some(TabClose {
1503            index,
1504            row: item.row_key,
1505            stamp: self.standard_list_stamp,
1506        })
1507    }
1508}
1509
1510/// Validate an offered close target against the current model and its live bindings.
1511#[doc(hidden)]
1512pub fn try_prepare_tab_close<M, E>(
1513    node: &Node,
1514    request: TabClose,
1515    route: crate::InputRoute<'_>,
1516    model: impl FnOnce() -> Result<Option<M>, E>,
1517    read: impl FnOnce(&M, usize) -> Result<Option<String>, E>,
1518) -> Result<Option<String>, E> {
1519    if node.tab_close(request.index) != Some(request) {
1520        return Ok(None);
1521    }
1522    let expected = node
1523        .child_at(request.index)
1524        .and_then(|item| item.text("value"))
1525        .unwrap_or("");
1526    let mut label = None;
1527    let sample = || {
1528        if let Some(model) = model()? {
1529            label = read(&model, request.index)?.filter(|current| current == expected);
1530        }
1531        Ok(label.is_some())
1532    };
1533    let accepted = if route.checks_availability() {
1534        route.try_available(sample)?
1535    } else {
1536        sample()?
1537    };
1538    Ok(label.filter(|_| accepted && route.is_current()))
1539}
1540
1541#[doc(hidden)]
1542pub fn prepare_tab_close<M>(
1543    node: &Node,
1544    request: TabClose,
1545    route: crate::InputRoute<'_>,
1546    model: impl FnOnce() -> Option<M>,
1547    read: impl FnOnce(&M, usize, bool) -> Option<String>,
1548) -> Option<String> {
1549    try_prepare_tab_close(
1550        node,
1551        request,
1552        route,
1553        || Ok::<_, std::convert::Infallible>(model()),
1554        |model, slot| Ok(read(model, slot, true)),
1555    )
1556    .unwrap_or_else(|error| match error {})
1557}
1558
1559#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1560pub struct TabMove {
1561    pub from: usize,
1562    pub to: usize,
1563    source: crate::RowKey,
1564    destination: crate::RowKey,
1565    stamp: (u64, u64),
1566}
1567
1568#[doc(hidden)]
1569pub fn moved_navigation_index(from: usize, to: usize, index: i64) -> i64 {
1570    let Ok(slot) = usize::try_from(index) else {
1571        return index;
1572    };
1573    if slot == from {
1574        to as i64
1575    } else if from < slot && slot <= to {
1576        index - 1
1577    } else if to <= slot && slot < from {
1578        index + 1
1579    } else {
1580        index
1581    }
1582}
1583
1584impl TabMove {
1585    pub fn moved_index(self, index: i64) -> i64 {
1586        moved_navigation_index(self.from, self.to, index)
1587    }
1588
1589    #[doc(hidden)]
1590    pub fn matches_model(self, model: &impl ListModel) -> bool {
1591        self.stamp == model.contents_stamp()
1592            && model.key_at(self.from) == Some(self.source)
1593            && model.key_at(self.to) == Some(self.destination)
1594    }
1595}
1596
1597impl Node {
1598    #[doc(hidden)]
1599    pub fn tab_move(&self, from: usize, to: usize) -> Option<TabMove> {
1600        if !matches!(self.kind, "TabBar" | "TabWidget")
1601            || !self.boolean("reorderable", false)
1602            || from == to
1603        {
1604            return None;
1605        }
1606        Some(TabMove {
1607            from,
1608            to,
1609            source: group_item(self, from)?.row_key?,
1610            destination: group_item(self, to)?.row_key?,
1611            stamp: self.standard_list_stamp?,
1612        })
1613    }
1614}
1615
1616#[doc(hidden)]
1617pub fn try_prepare_tab_move<E>(
1618    node: &Node,
1619    movement: TabMove,
1620    input: crate::InputRoute<'_>,
1621    model: &impl ListModel,
1622    enabled: impl FnOnce() -> Result<bool, E>,
1623    mut available: impl FnMut(usize) -> Result<bool, E>,
1624) -> Result<bool, E> {
1625    if node.tab_move(movement.from, movement.to) != Some(movement) {
1626        return Ok(false);
1627    }
1628    Ok(input.try_available(|| {
1629        Ok(enabled()?
1630            && movement.matches_model(model)
1631            && available(movement.from)?
1632            && available(movement.to)?)
1633    })? && input.is_current()
1634        && movement.matches_model(model))
1635}
1636
1637#[doc(hidden)]
1638pub fn prepare_tab_move<M: ListModel>(
1639    node: &Node,
1640    movement: TabMove,
1641    input: crate::InputRoute<'_>,
1642    model: &Rc<M>,
1643    enabled: impl FnOnce() -> bool,
1644    mut option: impl FnMut(&Rc<M>, usize, bool) -> Option<String>,
1645) -> bool {
1646    try_prepare_tab_move(
1647        node,
1648        movement,
1649        input,
1650        model.as_ref(),
1651        || Ok::<_, std::convert::Infallible>(enabled()),
1652        |index| Ok(option(model, index, false).is_some()),
1653    )
1654    .unwrap_or_else(|error| match error {})
1655}
1656
1657/// Resolve a selectable option that is distinct from the scene's selected option.
1658#[doc(hidden)]
1659pub fn group_selection_item(node: &Node, index: usize) -> Option<&Node> {
1660    let item = group_item(node, index)?;
1661    (group_index(node) != Some(index)).then_some(item)
1662}
1663
1664/// The flattened range and model stamp for a single declaration in a RadioGroup.
1665#[derive(Clone, Debug, PartialEq)]
1666pub(crate) struct RadioOptionBlock {
1667    end: usize,
1668    stamp: Option<(u64, u64)>,
1669}
1670
1671impl Node {
1672    #[doc(hidden)]
1673    pub fn record_radio_option_block(&mut self) {
1674        self.push_radio_option_block(None);
1675    }
1676
1677    fn push_radio_option_block(&mut self, stamp: Option<(u64, u64)>) {
1678        let end = self.children.len();
1679        let blocks = self.radio_option_blocks.get_or_insert_with(Rc::default);
1680        let start = blocks.last().map_or(0, |block| block.end);
1681        let scope = blocks.len() as u64 + 1;
1682        Rc::make_mut(blocks).push(RadioOptionBlock { end, stamp });
1683        for (row, option) in self.children[start..end].iter_mut().enumerate() {
1684            if option.kind == "RadioButton" {
1685                // Keep both anonymous fixed options and repeat rows identifiable after a reflow.
1686                option.row_key.get_or_insert(crate::RowKey {
1687                    model: 0,
1688                    row: row as u64,
1689                    scope: 0,
1690                });
1691                option.row_scope = scope;
1692            }
1693        }
1694    }
1695
1696    /// Resolve the flattened scene position to a declaration and its local row.
1697    #[doc(hidden)]
1698    pub fn radio_option_location(&self, slot: usize) -> Option<(usize, usize)> {
1699        if slot >= self.children.len() {
1700            return None;
1701        }
1702        let Some(blocks) = &self.radio_option_blocks else {
1703            return Some((slot, 0));
1704        };
1705        let declaration = blocks.partition_point(|block| block.end <= slot);
1706        blocks.get(declaration)?;
1707        let start = declaration
1708            .checked_sub(1)
1709            .map_or(0, |previous| blocks[previous].end);
1710        Some((declaration, slot - start))
1711    }
1712
1713    #[doc(hidden)]
1714    pub fn radio_option_model_is_current(
1715        &self,
1716        declaration: usize,
1717        model: &impl ListModel,
1718    ) -> bool {
1719        self.radio_option_blocks
1720            .as_ref()
1721            .and_then(|blocks| blocks.get(declaration))
1722            .and_then(|block| block.stamp)
1723            == Some(model.contents_stamp())
1724    }
1725}
1726
1727/// Validate the displayed option against the live group before committing a selection.
1728#[doc(hidden)]
1729pub fn try_prepare_group_selection<E>(
1730    node: &Node,
1731    index: usize,
1732    route: crate::InputRoute<'_>,
1733    model_current: impl FnOnce() -> Result<bool, E>,
1734    current: impl FnOnce() -> Result<crate::ButtonGroupSelection, E>,
1735    mut option: impl FnMut(usize, bool) -> Result<Option<String>, E>,
1736) -> Result<Option<String>, E> {
1737    try_prepare_group_selection_with_model(
1738        node,
1739        index,
1740        route,
1741        || Ok((!route.checks_availability() || model_current()?).then_some(())),
1742        current,
1743        |_, slot, label| option(slot, label),
1744    )
1745}
1746
1747/// Validate the model once and use that sample for every option read.
1748#[doc(hidden)]
1749pub fn try_prepare_group_selection_with_model<M, E>(
1750    node: &Node,
1751    index: usize,
1752    route: crate::InputRoute<'_>,
1753    model: impl FnOnce() -> Result<Option<M>, E>,
1754    current: impl FnOnce() -> Result<crate::ButtonGroupSelection, E>,
1755    mut option: impl FnMut(&M, usize, bool) -> Result<Option<String>, E>,
1756) -> Result<Option<String>, E> {
1757    let Some(shown) = group_item(node, index) else {
1758        return Ok(None);
1759    };
1760    let by_navigation_value = matches!(node.kind, "TabBar" | "TabWidget" | "SwipeView")
1761        && node.text("current-value").is_some();
1762    let read_value = node.kind == "RadioGroup" || by_navigation_value;
1763    let mut sample = None;
1764    if !route.checks_availability() {
1765        sample = model()?;
1766    } else if !route.try_available(|| {
1767        sample = model()?;
1768        Ok(sample.is_some())
1769    })? {
1770        return Ok(None);
1771    }
1772    let Some(sample) = sample else {
1773        return Ok(None);
1774    };
1775    let mut option = |slot, label| option(&sample, slot, label);
1776    let Some(label) = option(index, read_value)? else {
1777        return Ok(None);
1778    };
1779    if !route.is_current() || (read_value && label != crate::radio_value(shown)) {
1780        return Ok(None);
1781    }
1782    if by_navigation_value {
1783        // A value addresses the first eligible option carrying it.
1784        for preceding in 0..index {
1785            if option(preceding, true)?.as_ref() == Some(&label) || !route.is_current() {
1786                return Ok(None);
1787            }
1788        }
1789    }
1790    let current = current()?;
1791    if !route.is_current() {
1792        return Ok(None);
1793    }
1794    let unchanged = match current {
1795        crate::ButtonGroupSelection::Value(value) => value == label,
1796        crate::ButtonGroupSelection::Index(current) => {
1797            let current = usize::try_from(current).ok();
1798            if current == Some(index) {
1799                true
1800            } else if matches!(node.kind, "TabBar" | "SwipeView") {
1801                let mut selected = false;
1802                let valid_current = if let Some(current) = current {
1803                    option(current, false)?.is_some()
1804                } else {
1805                    false
1806                };
1807                if !valid_current && route.is_current() {
1808                    selected = true;
1809                    for preceding in 0..index {
1810                        if option(preceding, false)?.is_some() || !route.is_current() {
1811                            selected = false;
1812                            break;
1813                        }
1814                    }
1815                }
1816                selected
1817            } else {
1818                false
1819            }
1820        }
1821    };
1822    Ok((!unchanged && route.is_current()).then_some(label))
1823}
1824
1825#[doc(hidden)]
1826pub fn prepare_group_selection_with_model<M>(
1827    node: &Node,
1828    index: usize,
1829    route: crate::InputRoute<'_>,
1830    model: impl FnOnce() -> Option<M>,
1831    current: impl FnOnce() -> crate::ButtonGroupSelection,
1832    mut option: impl FnMut(&M, usize, bool) -> Option<String>,
1833) -> Option<String> {
1834    try_prepare_group_selection_with_model(
1835        node,
1836        index,
1837        route,
1838        || Ok::<_, std::convert::Infallible>(model()),
1839        || Ok(current()),
1840        |model, slot, label| Ok(option(model, slot, label)),
1841    )
1842    .unwrap_or_else(|error| match error {})
1843}
1844
1845#[doc(hidden)]
1846pub fn prepare_group_selection(
1847    node: &Node,
1848    index: usize,
1849    route: crate::InputRoute<'_>,
1850    model_current: impl FnOnce() -> bool,
1851    current: impl FnOnce() -> crate::ButtonGroupSelection,
1852    mut option: impl FnMut(usize, bool) -> Option<String>,
1853) -> Option<String> {
1854    try_prepare_group_selection(
1855        node,
1856        index,
1857        route,
1858        || Ok::<_, std::convert::Infallible>(model_current()),
1859        || Ok(current()),
1860        |index, label| Ok(option(index, label)),
1861    )
1862    .unwrap_or_else(|error| match error {})
1863}
1864
1865#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
1866#[doc(hidden)]
1867pub enum PageIdentity {
1868    Row(RowKey),
1869    Named(Arc<str>),
1870    Slot(usize, &'static str),
1871}
1872
1873impl PageIdentity {
1874    pub fn of(page: &Node, slot: usize) -> Self {
1875        if let Some(key) = page.routing_row_key() {
1876            Self::Row(key)
1877        } else if let Some(id) = page.shared_element_id() {
1878            Self::Named(id)
1879        } else if let Some(id) = page.id {
1880            Self::Named(Arc::from(id))
1881        } else {
1882            Self::Slot(slot, page.kind)
1883        }
1884    }
1885}
1886
1887#[derive(Clone, Debug, PartialEq, Eq)]
1888struct SwipePreviewRequest {
1889    from: (usize, PageIdentity),
1890    to: (usize, PageIdentity),
1891}
1892
1893/// The host requests one neighboring page for painting during a SwipeView drag.
1894#[doc(hidden)]
1895#[derive(Clone, Default)]
1896pub struct SwipePreviewHandle(Rc<Property<Option<SwipePreviewRequest>>>);
1897
1898impl std::fmt::Debug for SwipePreviewHandle {
1899    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1900        f.debug_tuple("SwipePreviewHandle")
1901            .field(&Rc::as_ptr(&self.0))
1902            .finish()
1903    }
1904}
1905
1906impl PartialEq for SwipePreviewHandle {
1907    fn eq(&self, other: &Self) -> bool {
1908        Rc::ptr_eq(&self.0, &other.0)
1909    }
1910}
1911
1912impl SwipePreviewHandle {
1913    pub fn request(&self, from: (usize, PageIdentity), to: (usize, PageIdentity)) {
1914        self.0
1915            .set_if_changed(Some(SwipePreviewRequest { from, to }));
1916    }
1917
1918    pub fn clear(&self) {
1919        self.0.set_if_changed(None);
1920    }
1921
1922    fn slot(&self, active: Option<usize>, pages: &[Node]) -> Option<usize> {
1923        let request = self.0.get(|| None)?;
1924        let available = |(slot, id): &(usize, PageIdentity)| {
1925            pages.get(*slot).is_some_and(|page| {
1926                group_item_available(page, "SwipePage") && PageIdentity::of(page, *slot) == *id
1927            })
1928        };
1929        (active == Some(request.from.0)
1930            && request.from.0 != request.to.0
1931            && available(&request.from)
1932            && available(&request.to))
1933        .then_some(request.to.0)
1934    }
1935}
1936
1937#[doc(hidden)]
1938#[derive(Clone, Debug, PartialEq)]
1939pub struct SwipePreview {
1940    pub handle: SwipePreviewHandle,
1941    pub page: Option<(usize, Node)>,
1942}
1943
1944impl Node {
1945    #[doc(hidden)]
1946    pub fn enable_swipe_preview(&mut self, handle: SwipePreviewHandle) {
1947        self.swipe_preview = Some(Box::new(SwipePreview { handle, page: None }));
1948    }
1949}
1950
1951impl Node {
1952    #[doc(hidden)]
1953    pub fn try_append_group_options<M: ListModel, E>(
1954        &mut self,
1955        source: impl FnOnce() -> Result<Rc<M>, E>,
1956        render: impl FnOnce(&Rc<M>) -> Result<Vec<Node>, E>,
1957    ) -> Result<(), E> {
1958        let radio = self.kind == "RadioGroup";
1959        let mut stamp = None;
1960        let options = crate::try_render_rows_from_source(
1961            || {
1962                let model = source()?;
1963                if radio {
1964                    stamp = Some(model.contents_stamp());
1965                } else {
1966                    self.snapshot_group_options(&*model);
1967                }
1968                Ok(model)
1969            },
1970            |model| render(&model),
1971        )?;
1972        self.children.extend(options);
1973        if radio {
1974            self.push_radio_option_block(stamp);
1975        }
1976        Ok(())
1977    }
1978
1979    #[doc(hidden)]
1980    pub fn append_group_options<M: ListModel>(
1981        &mut self,
1982        source: impl FnOnce() -> Rc<M>,
1983        render: impl FnOnce(&Rc<M>) -> Vec<Node>,
1984    ) {
1985        self.try_append_group_options(
1986            || Ok::<_, std::convert::Infallible>(source()),
1987            |model| Ok(render(model)),
1988        )
1989        .unwrap_or_else(|error| match error {});
1990    }
1991
1992    #[doc(hidden)]
1993    pub fn try_append_navigation_pages<M: ListModel, E>(
1994        &mut self,
1995        source: impl FnOnce() -> Result<Rc<M>, E>,
1996        describe: impl FnMut(&Rc<M>, usize) -> Result<Node, E>,
1997        mount: impl FnOnce(&Rc<M>, Option<usize>) -> Result<Vec<Node>, E>,
1998    ) -> Result<(), E> {
1999        self.try_append_navigation_pages_with_preview(source, describe, |model, [active, _]| {
2000            mount(model, active)
2001        })
2002    }
2003
2004    #[doc(hidden)]
2005    pub fn append_navigation_pages<M: ListModel>(
2006        &mut self,
2007        source: impl FnOnce() -> Rc<M>,
2008        mut describe: impl FnMut(&Rc<M>, usize) -> Node,
2009        mount: impl FnOnce(&Rc<M>, Option<usize>) -> Vec<Node>,
2010    ) {
2011        self.try_append_navigation_pages(
2012            || Ok::<_, std::convert::Infallible>(source()),
2013            |model, slot| Ok(describe(model, slot)),
2014            |model, slot| Ok(mount(model, slot)),
2015        )
2016        .unwrap_or_else(|error| match error {});
2017    }
2018
2019    /// Project navigation metadata for every page and mount the selected row and any paint-only swipe preview.
2020    #[doc(hidden)]
2021    pub fn try_append_navigation_pages_with_preview<M: ListModel, E>(
2022        &mut self,
2023        source: impl FnOnce() -> Result<Rc<M>, E>,
2024        mut describe: impl FnMut(&Rc<M>, usize) -> Result<Node, E>,
2025        mount: impl FnOnce(&Rc<M>, [Option<usize>; 2]) -> Result<Vec<Node>, E>,
2026    ) -> Result<(), E> {
2027        let requested = self.text("current-value").map(str::to_owned);
2028        let index = self.int("current-index");
2029        let visible = self.is_visible();
2030        let kind = self.kind;
2031        let mut stamp = None;
2032        let preview_handle = self
2033            .swipe_preview
2034            .as_ref()
2035            .map(|preview| preview.handle.clone());
2036        let mut painted = None;
2037        let pages = crate::try_render_rows_from_source(
2038            || {
2039                let model = source()?;
2040                stamp = Some(model.contents_stamp());
2041                Ok(model)
2042            },
2043            |model| {
2044                let stamp = model.contents_stamp();
2045                let mut pages = crate::list::try_render_stable_rows(
2046                    model.as_ref(),
2047                    model.structure_stamp(),
2048                    0..model.row_count().min(4096),
2049                    |slot| {
2050                        let mut page = describe(&model, slot)?;
2051                        page.set_row_key(Some(model.row_key(slot)));
2052                        Ok(page)
2053                    },
2054                )?;
2055                let active = visible
2056                    .then(|| navigation_index(kind, requested.as_deref(), index, &pages))
2057                    .flatten();
2058                let preview_slot = preview_handle
2059                    .as_ref()
2060                    .and_then(|handle| handle.slot(active, &pages));
2061                let mut mounted = mount(&model, [active, preview_slot])?.into_iter();
2062                if model.contents_stamp() != stamp {
2063                    return Ok(Vec::new());
2064                }
2065                if let Some(slot) = active {
2066                    let Some(page) = mounted.next() else {
2067                        return Ok(Vec::new());
2068                    };
2069                    if page.row_key != pages[slot].row_key {
2070                        return Ok(Vec::new());
2071                    }
2072                    pages[slot] = page;
2073                }
2074                if let Some(slot) = preview_slot
2075                    && let Some(page) = mounted.next()
2076                    && page.row_key == pages[slot].row_key
2077                {
2078                    painted = Some((slot, page));
2079                }
2080                Ok(pages)
2081            },
2082        )?;
2083        if let Some(preview) = &mut self.swipe_preview {
2084            preview.page = if pages.is_empty() { None } else { painted };
2085        }
2086        self.standard_list_stamp = stamp;
2087        self.children.extend(pages);
2088        Ok(())
2089    }
2090
2091    #[doc(hidden)]
2092    pub fn append_navigation_pages_with_preview<M: ListModel>(
2093        &mut self,
2094        source: impl FnOnce() -> Rc<M>,
2095        mut describe: impl FnMut(&Rc<M>, usize) -> Node,
2096        mount: impl FnOnce(&Rc<M>, [Option<usize>; 2]) -> Vec<Node>,
2097    ) {
2098        self.try_append_navigation_pages_with_preview(
2099            || Ok::<_, std::convert::Infallible>(source()),
2100            |model, slot| Ok(describe(model, slot)),
2101            |model, slot| Ok(mount(model, slot)),
2102        )
2103        .unwrap_or_else(|error| match error {})
2104    }
2105
2106    #[doc(hidden)]
2107    pub fn snapshot_group_options(&mut self, model: &impl ListModel) {
2108        self.standard_list_stamp = Some(model.contents_stamp());
2109    }
2110
2111    #[doc(hidden)]
2112    pub fn group_options_are_current(&self, model: &impl ListModel) -> bool {
2113        self.standard_list_stamp == Some(model.contents_stamp())
2114    }
2115}
2116
2117pub fn group_index(node: &Node) -> Option<usize> {
2118    if node.kind == "StackLayout" || navigation_item_kind(node.kind).is_some() {
2119        return navigation_index(
2120            node.kind,
2121            node.text("current-value"),
2122            node.int("current-index"),
2123            &node.children,
2124        );
2125    }
2126    if node.kind == "RadioGroup" {
2127        let mut selection = node.text("current-value").map_or_else(
2128            || crate::ButtonGroupSelection::Index(node.int("current-index").unwrap_or(-1)),
2129            |value| crate::ButtonGroupSelection::Value(value.to_owned()),
2130        );
2131        return selection.select_radio_option(node.children.len(), |index, label| {
2132            group_item(node, index).map(|item| if label { crate::radio_value(item) } else { "" })
2133        });
2134    }
2135    let index = usize::try_from(node.int("current-index").unwrap_or(0)).ok()?;
2136    group_item(node, index).map(|_| index)
2137}
2138
2139impl Node {
2140    /// Mount the same SwipePage that layout will select from the rendered page properties.
2141    #[doc(hidden)]
2142    pub fn mount_active_swipe_page<T>(
2143        &mut self,
2144        mount: impl FnOnce(usize, &mut Node) -> T,
2145    ) -> Option<T> {
2146        if self.kind != "SwipeView" || !self.is_visible() {
2147            return None;
2148        }
2149        let index = group_index(self)?;
2150        Some(mount(index, &mut self.children[index]))
2151    }
2152
2153    /// Populate the adjacent page outside the live scene while a swipe is in progress.
2154    #[doc(hidden)]
2155    pub fn try_mount_swipe_pages<E>(
2156        &mut self,
2157        mut mount: impl FnMut(usize, &mut Node) -> Result<(), E>,
2158    ) -> Result<(), E> {
2159        self.mount_active_swipe_page(&mut mount).transpose()?;
2160        let active = self.is_visible().then(|| group_index(self)).flatten();
2161        let mut painted = None;
2162        if let Some(slot) = self
2163            .swipe_preview
2164            .as_ref()
2165            .and_then(|preview| preview.handle.slot(active, &self.children))
2166            && let Some(mut page) = self.children.get(slot).cloned()
2167        {
2168            mount(slot, &mut page)?;
2169            painted = Some((slot, page));
2170        }
2171        if let Some(preview) = &mut self.swipe_preview {
2172            preview.page = painted;
2173        }
2174        Ok(())
2175    }
2176
2177    #[doc(hidden)]
2178    pub fn mount_swipe_pages(&mut self, mut mount: impl FnMut(usize, &mut Node)) {
2179        self.try_mount_swipe_pages(|slot, node| {
2180            mount(slot, node);
2181            Ok::<_, std::convert::Infallible>(())
2182        })
2183        .unwrap_or_else(|error| match error {});
2184    }
2185}
2186
2187/// Find the first eligible option addressed by a navigation value.
2188#[doc(hidden)]
2189pub fn resolve_navigation_value<V: AsRef<str>>(
2190    requested: &str,
2191    options: impl IntoIterator<Item = Option<V>>,
2192) -> Option<usize> {
2193    try_resolve_navigation_value(
2194        requested,
2195        options.into_iter().map(Ok::<_, std::convert::Infallible>),
2196    )
2197    .unwrap_or_else(|error| match error {})
2198}
2199
2200#[doc(hidden)]
2201pub fn try_resolve_navigation_value<V: AsRef<str>, E>(
2202    requested: &str,
2203    options: impl IntoIterator<Item = Result<Option<V>, E>>,
2204) -> Result<Option<usize>, E> {
2205    for (index, option) in options.into_iter().enumerate() {
2206        if option?.is_some_and(|value| value.as_ref() == requested) {
2207            return Ok(Some(index));
2208        }
2209    }
2210    Ok(None)
2211}
2212
2213/// Preserve declared page indexes while falling back to the first available page.
2214#[doc(hidden)]
2215pub fn resolve_swipe_index(
2216    requested: Option<i64>,
2217    available: impl IntoIterator<Item = bool>,
2218) -> Option<usize> {
2219    try_resolve_swipe_index(
2220        requested,
2221        available.into_iter().map(Ok::<_, std::convert::Infallible>),
2222    )
2223    .unwrap_or_else(|error| match error {})
2224}
2225
2226#[doc(hidden)]
2227pub fn try_resolve_swipe_index<E>(
2228    requested: Option<i64>,
2229    available: impl IntoIterator<Item = Result<bool, E>>,
2230) -> Result<Option<usize>, E> {
2231    let requested = requested.and_then(|index| usize::try_from(index).ok());
2232    let mut first = None;
2233    for (index, available) in available.into_iter().enumerate() {
2234        if available? {
2235            if requested == Some(index) {
2236                return Ok(Some(index));
2237            }
2238            first.get_or_insert(index);
2239        }
2240    }
2241    Ok(first)
2242}
2243
2244#[cfg(test)]
2245mod tests {
2246    use super::*;
2247
2248    #[test]
2249    fn integer_steps_preserve_precision_and_handle_overflow() {
2250        let mut node = Node::new("SpinBox", None);
2251        node.properties.insert("value", (i64::MAX - 4).into());
2252        node.properties.insert("maximum", i64::MAX.into());
2253        node.properties.insert("step-size", 3_i64.into());
2254        assert_eq!(
2255            SpinRange::from_node(&node).apply(SpinAction::Increase),
2256            Some(i64::MAX - 1)
2257        );
2258        node.properties.insert("value", (i64::MAX - 1).into());
2259        assert_eq!(
2260            SpinRange::from_node(&node).apply(SpinAction::Increase),
2261            Some(i64::MAX)
2262        );
2263        node.properties.insert("wrap", true.into());
2264        assert_eq!(
2265            SpinRange::from_node(&node).apply(SpinAction::Increase),
2266            Some(0)
2267        );
2268    }
2269}