Skip to main content

nativeview_layout/scene/focus_traversal/
tab_order.rs

1//! Default zero-sized HTML sequential focus-navigation policy ([`TabOrderPolicy`]).
2
3use nativeview_abi::FocusMove;
4use nativeview_engine::is_focusable_self;
5use nativeview_store::NodeId;
6use nativeview_tables::tables::Interaction;
7
8use super::{
9    FocusTraversalCtx, FocusTraversalOutcome, FocusTraversalPolicy, FocusTraverseFlags,
10    walk_active_scope,
11};
12
13/// Zero-sized default HTML sequential focus-navigation policy.
14#[derive(Debug, Clone, Copy, Default)]
15pub struct TabOrderPolicy;
16
17impl FocusTraversalPolicy for TabOrderPolicy {
18    fn traverse(
19        &mut self,
20        ctx: &mut FocusTraversalCtx<'_>,
21        current: Option<NodeId>,
22        direction: FocusMove,
23        flags: FocusTraverseFlags,
24    ) -> FocusTraversalOutcome {
25        let trapped = ctx.topmost_modal().is_some();
26        if matches!(
27            direction,
28            FocusMove::Up | FocusMove::Down | FocusMove::Left | FocusMove::Right
29        ) {
30            return FocusTraversalOutcome {
31                target: None,
32                trapped,
33                scrolled: false,
34                wrapped: false,
35            };
36        }
37
38        let store = ctx.store;
39        let cascade = &ctx.cascade;
40        let overlays = ctx.overlays;
41        let scratch = &mut *ctx.scratch;
42        scratch.positive_buf.clear();
43        scratch.natural_buf.clear();
44
45        let mut cur_in_dfs = false;
46        let mut nat_pos_at_cur = 0usize;
47
48        walk_active_scope(
49            store,
50            cascade,
51            overlays,
52            &mut scratch.dfs_stack,
53            &mut |s, id, eff_hidden, _ov| {
54                if current == Some(id) {
55                    cur_in_dfs = true;
56                    nat_pos_at_cur = scratch.natural_buf.len();
57                }
58                if eff_hidden || !is_focusable_self(s, id) {
59                    return;
60                }
61                let tab_index = s.try_row::<Interaction>(id).and_then(|i| i.tab_index());
62                match tab_index {
63                    Some(ti) if ti < 0 => {}
64                    Some(ti) if ti > 0 => scratch.positive_buf.push((ti, id)),
65                    _ => scratch.natural_buf.push(id),
66                }
67            },
68        );
69
70        stable_sort_positive(&mut scratch.positive_buf, &mut scratch.positive_sort_buf);
71
72        let pos_len = scratch.positive_buf.len();
73        let nat_len = scratch.natural_buf.len();
74        let total = pos_len + nat_len;
75        if total == 0 {
76            return FocusTraversalOutcome {
77                target: None,
78                trapped,
79                scrolled: false,
80                wrapped: false,
81            };
82        }
83
84        let combined_at = |idx: usize| -> NodeId {
85            if idx < pos_len {
86                scratch.positive_buf[idx].1
87            } else {
88                scratch.natural_buf[idx - pos_len]
89            }
90        };
91
92        let wrap_allowed = trapped || !flags.contains(FocusTraverseFlags::NO_WRAP);
93
94        let (target, wrapped) = match direction {
95            FocusMove::First => (Some(combined_at(0)), false),
96            FocusMove::Last => (Some(combined_at(total - 1)), false),
97            FocusMove::Next | FocusMove::Prev => {
98                let forward = direction == FocusMove::Next;
99                let current_idx = current.and_then(|cur| {
100                    scratch
101                        .positive_buf
102                        .iter()
103                        .position(|&(_, id)| id == cur)
104                        .or_else(|| {
105                            scratch
106                                .natural_buf
107                                .iter()
108                                .position(|&id| id == cur)
109                                .map(|i| pos_len + i)
110                        })
111                });
112                if let Some(idx) = current_idx {
113                    if forward {
114                        if idx + 1 < total {
115                            (Some(combined_at(idx + 1)), false)
116                        } else if wrap_allowed {
117                            (Some(combined_at(0)), true)
118                        } else {
119                            (None, false)
120                        }
121                    } else if idx > 0 {
122                        (Some(combined_at(idx - 1)), false)
123                    } else if wrap_allowed {
124                        (Some(combined_at(total - 1)), true)
125                    } else {
126                        (None, false)
127                    }
128                } else if cur_in_dfs {
129                    if forward {
130                        if nat_pos_at_cur < nat_len {
131                            (Some(scratch.natural_buf[nat_pos_at_cur]), false)
132                        } else if wrap_allowed {
133                            (Some(combined_at(0)), true)
134                        } else {
135                            (None, false)
136                        }
137                    } else if nat_pos_at_cur > 0 {
138                        (Some(scratch.natural_buf[nat_pos_at_cur - 1]), false)
139                    } else if pos_len > 0 {
140                        (Some(scratch.positive_buf[pos_len - 1].1), false)
141                    } else if wrap_allowed {
142                        (Some(combined_at(total - 1)), true)
143                    } else {
144                        (None, false)
145                    }
146                } else if forward {
147                    (Some(combined_at(0)), false)
148                } else {
149                    (Some(combined_at(total - 1)), false)
150                }
151            }
152            FocusMove::Up | FocusMove::Down | FocusMove::Left | FocusMove::Right => unreachable!(),
153        };
154
155        FocusTraversalOutcome {
156            target,
157            trapped,
158            scrolled: false,
159            wrapped,
160        }
161    }
162}
163
164/// Zero-allocation stable sort by ascending `tab_index` (reusing `scratch` when `len > 32`).
165fn stable_sort_positive(buf: &mut [(i16, NodeId)], scratch: &mut Vec<(i16, NodeId)>) {
166    let n = buf.len();
167    if n <= 1 {
168        return;
169    }
170    if n <= 32 {
171        for i in 1..n {
172            let key = buf[i];
173            let mut j = i;
174            while j > 0 && buf[j - 1].0 > key.0 {
175                buf[j] = buf[j - 1];
176                j -= 1;
177            }
178            buf[j] = key;
179        }
180        return;
181    }
182    scratch.clear();
183    scratch.resize(n, (0, NodeId::NULL));
184    let mut width = 1usize;
185    let mut src_is_buf = true;
186    type TabEntry = (i16, NodeId);
187    while width < n {
188        let (src, dst): (&[TabEntry], &mut [TabEntry]) = if src_is_buf {
189            (buf, scratch.as_mut_slice())
190        } else {
191            (scratch.as_slice(), buf)
192        };
193        let mut left = 0usize;
194        while left < n {
195            let mid = (left + width).min(n);
196            let right = (left + 2 * width).min(n);
197            let (mut i, mut j, mut k) = (left, mid, left);
198            while i < mid && j < right {
199                if src[i].0 <= src[j].0 {
200                    dst[k] = src[i];
201                    i += 1;
202                } else {
203                    dst[k] = src[j];
204                    j += 1;
205                }
206                k += 1;
207            }
208            if i < mid {
209                dst[k..k + (mid - i)].copy_from_slice(&src[i..mid]);
210            } else if j < right {
211                dst[k..k + (right - j)].copy_from_slice(&src[j..right]);
212            }
213            left = right;
214        }
215        src_is_buf = !src_is_buf;
216        width *= 2;
217    }
218    if !src_is_buf {
219        buf.copy_from_slice(&scratch[..n]);
220    }
221}