cranpose_ui/layout/
semantics_labels.rs1use std::borrow::Cow;
2
3use super::{SemanticsNode, SemanticsRole, SemanticsWidgetRole};
4
5impl SemanticsNode {
6 pub fn merges_accessibility_descendants(&self) -> bool {
9 self.merge_descendants
10 || !self.actions.is_empty()
11 || self.editable_text
12 || self.password
13 || self.focusable
14 || !self.custom_actions.is_empty()
15 || self.set_progress.is_some()
16 || self.set_text.is_some()
17 || self.set_selection.is_some()
18 || self.on_long_click.is_some()
19 || self.on_magic_tap.is_some()
20 || self.expand.is_some()
21 || self.collapse.is_some()
22 || self.dismiss.is_some()
23 }
24
25 pub fn is_accessibility_boundary(&self) -> bool {
28 self.merges_accessibility_descendants()
29 || self.vertical_scroll.is_some()
30 || self.horizontal_scroll.is_some()
31 || self.selectable_group
32 || self.pane_title.is_some()
33 || matches!(
34 self.widget_role,
35 Some(
36 SemanticsWidgetRole::Dialog
37 | SemanticsWidgetRole::Toolbar
38 | SemanticsWidgetRole::Menu
39 | SemanticsWidgetRole::TabBar
40 | SemanticsWidgetRole::List
41 )
42 )
43 }
44
45 pub fn accessibility_children(&self) -> Vec<&Self> {
48 let mut children: Vec<_> = self.children.iter().collect();
49 let index = |node: &&Self| {
50 if node.traversal_index.is_finite() {
51 node.traversal_index
52 } else {
53 0.0
54 }
55 };
56 if children.iter().any(|child| index(child) != 0.0) {
57 children.sort_by(|left, right| {
58 index(left)
59 .partial_cmp(&index(right))
60 .unwrap_or(std::cmp::Ordering::Equal)
61 });
62 }
63 children
64 }
65
66 pub fn accessibility_label(&self) -> Option<Cow<'_, str>> {
71 if self.hidden {
72 return None;
73 }
74 let own = self
75 .description
76 .as_deref()
77 .filter(|label| !label.trim().is_empty())
78 .or_else(|| match &self.role {
79 SemanticsRole::Text { value } if !value.trim().is_empty() => Some(value.as_str()),
80 _ => None,
81 });
82 if self.password {
83 return Some(Cow::Borrowed(
84 self.description
85 .as_deref()
86 .filter(|label| {
87 !label.trim().is_empty() && Some(*label) != self.text.as_deref()
88 })
89 .unwrap_or("password"),
90 ));
91 }
92 own.map(Cow::Borrowed)
93 .or_else(|| {
94 if !self.merges_accessibility_descendants() {
95 return None;
96 }
97 let mut words = Vec::new();
98 self.collect_accessibility_words(&mut words);
99 (!words.is_empty()).then(|| Cow::Owned(words.join(", ")))
100 })
101 .or_else(|| self.editable_text.then_some(Cow::Borrowed("")))
102 }
103
104 fn collect_accessibility_words<'a>(&'a self, words: &mut Vec<&'a str>) {
105 for child in self.accessibility_children() {
106 if child.hidden || child.is_accessibility_boundary() {
107 continue;
108 }
109 match child.accessibility_label() {
110 Some(Cow::Borrowed(label)) if !label.trim().is_empty() => words.push(label),
111 _ => child.collect_accessibility_words(words),
112 }
113 }
114 }
115}
116
117#[cfg(test)]
118#[path = "tests/semantics_labels.rs"]
119mod tests;