1use nativeview_abi::NodeId;
5use nativeview_store::NodeStore;
6use nativeview_tables::interaction::{resolve_focus_visible, FocusModality};
7use nativeview_tables::semantics::SemanticStyleOracle;
8use nativeview_tables::tables::Interaction;
9
10pub use crate::focus_query::{
11 first_focusable_in_subtree, first_matching_in_subtree, is_composite_aria_group,
12 is_focusable_node, is_focusable_self, is_subtree_closed_overlay, is_subtree_disabled,
13 is_tabbable_self, is_text_entry_node, is_within_subtree, topmost_open_modal,
14};
15use crate::focus_query::{is_open_modal, pick_modal_initial_focus, MAX_TREE_DEPTH};
16
17const PRE_MODAL_STACK_CAP: usize = 8;
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22struct ModalStackEntry {
23 modal: NodeId,
24 return_focus: NodeId,
25}
26
27impl Default for ModalStackEntry {
28 #[inline]
29 fn default() -> Self {
30 Self {
31 modal: NodeId::NULL,
32 return_focus: NodeId::NULL,
33 }
34 }
35}
36
37#[derive(Debug, Clone, Default)]
40pub struct FocusAnchor {
41 pub focused: Option<NodeId>,
42 pub prev_sibling: Option<NodeId>,
43 pub next_sibling: Option<NodeId>,
44 pub trail: Vec<(NodeId, usize)>,
46 modal_stack: [ModalStackEntry; PRE_MODAL_STACK_CAP],
48 pub active_modal: Option<NodeId>,
50 pub composite_group: Option<NodeId>,
52 pub was_roving_active: bool,
54 pub was_text_entry: bool,
55 pub modality: FocusModality,
56}
57
58impl FocusAnchor {
59 #[inline]
60 pub fn clear(&mut self) {
61 self.focused = None;
62 self.prev_sibling = None;
63 self.next_sibling = None;
64 self.trail.clear();
65 self.modal_stack = [ModalStackEntry::default(); PRE_MODAL_STACK_CAP];
66 self.active_modal = None;
67 self.composite_group = None;
68 self.was_roving_active = false;
69 self.was_text_entry = false;
70 self.modality = FocusModality::Pointer;
71 }
72
73 #[inline]
74 fn modal_stack_index(&self, modal: NodeId) -> Option<usize> {
75 if modal.is_null() {
76 return None;
77 }
78 self.modal_stack.iter().position(|e| e.modal == modal)
79 }
80
81 #[inline]
82 fn push_modal(&mut self, modal: NodeId, return_focus: Option<NodeId>) {
83 if modal.is_null() || self.modal_stack_index(modal).is_some() {
84 return;
85 }
86 let entry = ModalStackEntry {
87 modal,
88 return_focus: return_focus.unwrap_or(NodeId::NULL),
89 };
90 if let Some(slot) = self.modal_stack.iter_mut().find(|e| e.modal.is_null()) {
91 *slot = entry;
92 } else {
93 self.modal_stack.copy_within(1..PRE_MODAL_STACK_CAP, 0);
94 self.modal_stack[PRE_MODAL_STACK_CAP - 1] = entry;
95 }
96 }
97
98 #[inline]
99 fn unwind_modals_above<O: SemanticStyleOracle + ?Sized>(
100 &mut self,
101 target_modal: Option<NodeId>,
102 store: &NodeStore,
103 oracle: &O,
104 scope_root: NodeId,
105 ) -> Option<NodeId> {
106 let stop_len = target_modal
107 .and_then(|m| self.modal_stack_index(m))
108 .map_or(0, |idx| idx + 1);
109 let mut returned = None;
110 for idx in (stop_len..PRE_MODAL_STACK_CAP).rev() {
111 let entry = self.modal_stack[idx];
112 if entry.modal.is_null() {
113 continue;
114 }
115 self.modal_stack[idx] = ModalStackEntry::default();
116 if returned.is_none()
117 && !entry.return_focus.is_null()
118 && is_focusable_node(store, oracle, entry.return_focus)
119 && is_within_subtree(store, entry.return_focus, scope_root)
120 {
121 returned = Some(entry.return_focus);
122 }
123 }
124 returned
125 }
126
127 #[inline]
128 fn prune_closed_top_modals<O: SemanticStyleOracle + ?Sized>(
129 &mut self,
130 store: &NodeStore,
131 oracle: &O,
132 exclude_subtree: NodeId,
133 ) -> Option<NodeId> {
134 let mut carried = None;
135 for idx in (0..PRE_MODAL_STACK_CAP).rev() {
136 let entry = self.modal_stack[idx];
137 if entry.modal.is_null() {
138 continue;
139 }
140 if is_open_modal(store, oracle, entry.modal) {
141 break;
142 }
143 self.modal_stack[idx] = ModalStackEntry::default();
144 if carried.is_none()
145 && !entry.return_focus.is_null()
146 && is_focusable_node(store, oracle, entry.return_focus)
147 && !is_within_subtree(store, entry.return_focus, exclude_subtree)
148 {
149 carried = Some(entry.return_focus);
150 }
151 }
152 carried
153 }
154}
155
156#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158pub enum FocusRecoveryResult {
159 Unchanged,
161 Moved {
163 previous: Option<NodeId>,
164 next: NodeId,
165 modality: FocusModality,
166 focus_visible: bool,
167 },
168 Cleared { previous: NodeId },
170}
171
172
173pub fn snapshot_focus_anchor<O: SemanticStyleOracle + ?Sized>(
176 store: &NodeStore,
177 oracle: &O,
178 anchor: &mut FocusAnchor,
179 focused: Option<NodeId>,
180 modality: FocusModality,
181 dfs_scratch: &mut Vec<NodeId>,
182) {
183 anchor.focused = focused;
184 anchor.modality = modality;
185 anchor.prev_sibling = None;
186 anchor.next_sibling = None;
187 anchor.trail.clear();
188 anchor.composite_group = None;
189 anchor.was_roving_active = false;
190 anchor.was_text_entry = focused.is_some_and(|id| is_text_entry_node(store, id));
191 let topmost = topmost_open_modal(store, oracle, dfs_scratch);
192 anchor.active_modal = topmost;
193 if let Some(m) = topmost {
194 anchor.push_modal(m, None);
195 }
196
197 let Some(id) = focused else {
198 return;
199 };
200 if !store.is_live(id) {
201 return;
202 }
203
204 let mut cur = id;
205 for depth in 0..MAX_TREE_DEPTH {
206 let Some(parent) = store.parent(cur) else {
207 break;
208 };
209 if parent == cur {
210 break;
211 }
212 let children = store.children(parent);
213 let idx = children.iter().position(|&c| c == cur).unwrap_or(0);
214 if depth == 0 {
215 anchor.next_sibling = children[idx.saturating_add(1).min(children.len())..]
216 .iter()
217 .copied()
218 .find(|&c| is_focusable_node(store, oracle, c));
219 anchor.prev_sibling = children[..idx]
220 .iter()
221 .rev()
222 .copied()
223 .find(|&c| is_focusable_node(store, oracle, c));
224 }
225 anchor.trail.push((parent, idx));
226 if anchor.composite_group.is_none() && is_composite_aria_group(store, parent) {
227 anchor.composite_group = Some(parent);
228 }
229 cur = parent;
230 }
231 anchor.was_roving_active = anchor.composite_group.is_some()
232 && store
233 .try_row::<Interaction>(id)
234 .and_then(|i| i.tab_index())
235 == Some(0);
236}
237
238fn recover_from_trail<O: SemanticStyleOracle + ?Sized>(
239 store: &NodeStore,
240 oracle: &O,
241 anchor: &FocusAnchor,
242 scope_root: NodeId,
243 dfs_scratch: &mut Vec<NodeId>,
244) -> Option<NodeId> {
245 if let Some(next) = anchor.next_sibling
246 && is_focusable_node(store, oracle, next)
247 && is_within_subtree(store, next, scope_root)
248 {
249 return Some(next);
250 }
251 if let Some(prev) = anchor.prev_sibling
252 && is_focusable_node(store, oracle, prev)
253 && is_within_subtree(store, prev, scope_root)
254 {
255 return Some(prev);
256 }
257 for &(anc, old_idx) in &anchor.trail {
258 if !store.is_live(anc)
259 || oracle.is_subtree_display_none(store, anc)
260 || is_subtree_closed_overlay(store, anc)
261 || is_subtree_disabled(store, anc)
262 || !is_within_subtree(store, anc, scope_root)
263 {
264 continue;
265 }
266 let children = store.children(anc);
267 let split = old_idx.min(children.len());
268 for &child in &children[split..] {
269 if let Some(found) = first_focusable_in_subtree(store, oracle, child, dfs_scratch) {
270 return Some(found);
271 }
272 }
273 for &child in children[..split].iter().rev() {
274 if let Some(found) = first_focusable_in_subtree(store, oracle, child, dfs_scratch) {
275 return Some(found);
276 }
277 }
278 if is_focusable_self(store, anc) {
280 return Some(anc);
281 }
282 }
283 first_matching_in_subtree(store, oracle, scope_root, dfs_scratch, is_tabbable_self)
284 .or_else(|| first_focusable_in_subtree(store, oracle, scope_root, dfs_scratch))
285}
286
287pub fn resolve_focus_recovery<O: SemanticStyleOracle + ?Sized>(
299 store: &NodeStore,
300 oracle: &O,
301 anchor: &mut FocusAnchor,
302 last_input: FocusModality,
303 current_focused: Option<NodeId>,
304 explicit_return_focus: Option<NodeId>,
305 dfs_scratch: &mut Vec<NodeId>,
306) -> FocusRecoveryResult {
307 let prev_modal = anchor.active_modal;
308 let new_modal = topmost_open_modal(store, oracle, dfs_scratch);
309 let prev_focus = current_focused.or(anchor.focused);
310 let prev_modal_closed =
311 prev_modal.is_some_and(|pm| {
312 new_modal != Some(pm) && !is_open_modal(store, oracle, pm)
313 });
314 let closing_to_underlying = prev_modal_closed
315 && (new_modal.is_none()
316 || new_modal.is_some_and(|nm| anchor.modal_stack_index(nm).is_some()));
317
318 if let Some(closed_modal) = prev_modal
320 && closing_to_underlying
321 {
322 anchor.active_modal = new_modal;
323 let scope_root = new_modal.unwrap_or(NodeId::ROOT);
324 let popped_return = anchor.unwind_modals_above(new_modal, store, oracle, scope_root);
325 let needs_return = prev_focus.is_none_or(|p| {
326 !is_focusable_node(store, oracle, p)
327 || !is_within_subtree(store, p, scope_root)
328 || is_within_subtree(store, p, closed_modal)
329 });
330 if needs_return {
331 let target = explicit_return_focus
332 .filter(|&id| is_focusable_node(store, oracle, id) && is_within_subtree(store, id, scope_root))
333 .or(popped_return)
334 .or_else(|| recover_from_trail(store, oracle, anchor, scope_root, dfs_scratch));
335 if let Some(next) = target {
336 let fv = resolve_focus_visible(
337 FocusModality::Programmatic,
338 last_input,
339 is_text_entry_node(store, next),
340 );
341 snapshot_focus_anchor(store, oracle,
342 anchor,
343 Some(next),
344 FocusModality::Programmatic,
345 dfs_scratch,
346 );
347 return FocusRecoveryResult::Moved {
348 previous: prev_focus,
349 next,
350 modality: FocusModality::Programmatic,
351 focus_visible: fv,
352 };
353 }
354 anchor.focused = None;
355 return match prev_focus {
356 Some(previous) => FocusRecoveryResult::Cleared { previous },
357 None => FocusRecoveryResult::Unchanged,
358 };
359 }
360 } else if let Some(modal_id) = new_modal
361 && new_modal != prev_modal
362 {
363 let carried_return = anchor.prune_closed_top_modals(store, oracle, modal_id);
365 let saved_return = if prev_modal_closed {
366 carried_return.or_else(|| {
369 prev_focus.filter(|&id| {
370 is_focusable_node(store, oracle, id)
371 && !is_within_subtree(store, id, modal_id)
372 && prev_modal.is_none_or(|pm| !is_within_subtree(store, id, pm))
373 })
374 })
375 } else {
376 current_focused
380 .filter(|&id| store.is_live(id) && !is_within_subtree(store, id, modal_id))
381 .or_else(|| {
382 anchor
383 .focused
384 .filter(|&id| store.is_live(id) && !is_within_subtree(store, id, modal_id))
385 })
386 };
387 anchor.push_modal(modal_id, saved_return);
388 anchor.active_modal = Some(modal_id);
389 if let Some(cur) = current_focused
390 && is_focusable_node(store, oracle, cur)
391 && is_within_subtree(store, cur, modal_id)
392 {
393 snapshot_focus_anchor(store, oracle, anchor, Some(cur), anchor.modality, dfs_scratch);
394 return FocusRecoveryResult::Unchanged;
395 }
396 if let Some(next) = pick_modal_initial_focus(store, oracle, modal_id, dfs_scratch) {
397 let fv = resolve_focus_visible(
398 FocusModality::Programmatic,
399 last_input,
400 is_text_entry_node(store, next),
401 );
402 snapshot_focus_anchor(store, oracle,
403 anchor,
404 Some(next),
405 FocusModality::Programmatic,
406 dfs_scratch,
407 );
408 return FocusRecoveryResult::Moved {
409 previous: prev_focus,
410 next,
411 modality: FocusModality::Programmatic,
412 focus_visible: fv,
413 };
414 }
415 anchor.focused = None;
416 return match prev_focus {
417 Some(previous) => FocusRecoveryResult::Cleared { previous },
418 None => FocusRecoveryResult::Unchanged,
419 };
420 }
421
422 anchor.active_modal = new_modal;
423 let scope_root = new_modal.unwrap_or(NodeId::ROOT);
424
425 let Some(prev_id) = prev_focus else {
426 return FocusRecoveryResult::Unchanged;
427 };
428
429 if is_focusable_node(store, oracle, prev_id) && is_within_subtree(store, prev_id, scope_root) {
431 if anchor.was_roving_active
432 && let Some(group) = anchor.composite_group
433 && store.is_live(group)
434 && is_within_subtree(store, group, scope_root)
435 && store
436 .try_row::<Interaction>(prev_id)
437 .and_then(|i| i.tab_index())
438 == Some(-1)
439 && let Some(next) = first_matching_in_subtree(store, oracle, group, dfs_scratch, |s, id| {
440 id != prev_id
441 && is_focusable_self(s, id)
442 && s.try_row::<Interaction>(id).and_then(|i| i.tab_index()) == Some(0)
443 })
444 {
445 let fv = resolve_focus_visible(
446 FocusModality::Programmatic,
447 last_input,
448 is_text_entry_node(store, next),
449 );
450 snapshot_focus_anchor(store, oracle,
451 anchor,
452 Some(next),
453 FocusModality::Programmatic,
454 dfs_scratch,
455 );
456 return FocusRecoveryResult::Moved {
457 previous: Some(prev_id),
458 next,
459 modality: FocusModality::Programmatic,
460 focus_visible: fv,
461 };
462 }
463 snapshot_focus_anchor(store, oracle, anchor, Some(prev_id), anchor.modality, dfs_scratch);
464 return FocusRecoveryResult::Unchanged;
465 }
466
467 if let Some(next) = recover_from_trail(store, oracle, anchor, scope_root, dfs_scratch) {
469 let fv = resolve_focus_visible(
470 FocusModality::Programmatic,
471 last_input,
472 is_text_entry_node(store, next),
473 );
474 snapshot_focus_anchor(store, oracle,
475 anchor,
476 Some(next),
477 FocusModality::Programmatic,
478 dfs_scratch,
479 );
480 FocusRecoveryResult::Moved {
481 previous: Some(prev_id),
482 next,
483 modality: FocusModality::Programmatic,
484 focus_visible: fv,
485 }
486 } else {
487 anchor.focused = None;
488 anchor.prev_sibling = None;
489 anchor.next_sibling = None;
490 anchor.trail.clear();
491 FocusRecoveryResult::Cleared { previous: prev_id }
492 }
493}