Skip to main content

cranpose_ui/layout/
semantics_labels.rs

1use std::borrow::Cow;
2
3use super::{SemanticsNode, SemanticsRole, SemanticsWidgetRole};
4
5impl SemanticsNode {
6    /// Whether this node combines its static descendants into one reader stop.
7    /// Independently operable descendants remain separate stops.
8    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    /// Whether an ancestor must leave this node and its content as a separate
26    /// reader stop or container instead of including it in its own label.
27    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    /// Children in screen-reader order. Equal indices retain composition order;
46    /// non-finite indices are treated as the default index, zero.
47    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    /// The accessible name, including merged static descendants in reading
67    /// order. Hidden content and independent controls contribute no text to an
68    /// ancestor. Password values never become names. An unnamed editable field
69    /// returns an empty name so it remains reachable by assistive technology.
70    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;