Skip to main content

euv_core/system/a11y/
impl.rs

1use super::*;
2
3/// Native OS role mapping for `A11yRole` across all 7 platforms.
4impl A11yRole {
5    /// Resolves the canonical native accessibility role or trait identifier for `platform`.
6    ///
7    /// # Arguments
8    ///
9    /// - `&Self` - Semantic accessibility role.
10    /// - `PlatformKind` - Target execution platform.
11    ///
12    /// # Returns
13    ///
14    /// - `&'static str` - Native OS role identifier (NSAccessibility, UIAccessibility, UIA, AT-SPI2, Android, or ARIA).
15    #[must_use]
16    pub const fn native_role_name(&self, platform: PlatformKind) -> &'static str {
17        match platform {
18            PlatformKind::MacOs => match *self {
19                Self::Window => "NSAccessibilityWindowRole",
20                Self::Region | Self::Navigation | Self::Group => ROLE_MAC_GROUP,
21                Self::Heading | Self::Text => ROLE_MAC_STATIC_TEXT,
22                Self::Button => "NSAccessibilityButtonRole",
23                Self::TextInput => "NSAccessibilityTextFieldRole",
24                Self::Checkbox | Self::Switch => "NSAccessibilityCheckBoxRole",
25                Self::Slider => "NSAccessibilitySliderRole",
26                Self::Tab => "NSAccessibilityRadioButtonRole",
27                Self::TabList => "NSAccessibilityTabGroupRole",
28                Self::List => "NSAccessibilityListRole",
29                Self::ListItem => "NSAccessibilityRowRole",
30                Self::Dialog | Self::Alert => "NSAccessibilitySheetRole",
31                Self::ProgressBar => "NSAccessibilityProgressIndicatorRole",
32                Self::Image | Self::Canvas => "NSAccessibilityImageRole",
33                Self::ScrollView => "NSAccessibilityScrollAreaRole",
34                Self::Link => "NSAccessibilityLinkRole",
35                Self::Menu => "NSAccessibilityMenuRole",
36                Self::MenuItem => "NSAccessibilityMenuItemRole",
37            },
38            PlatformKind::Ios | PlatformKind::IpadOs => match *self {
39                Self::Button | Self::Tab | Self::MenuItem => "UIAccessibilityTraitButton",
40                Self::Heading => "UIAccessibilityTraitHeader",
41                Self::Link => "UIAccessibilityTraitLink",
42                Self::Image | Self::Canvas => "UIAccessibilityTraitImage",
43                Self::Slider | Self::ProgressBar => "UIAccessibilityTraitAdjustable",
44                Self::Text | Self::Alert => "UIAccessibilityTraitStaticText",
45                _ => "UIAccessibilityTraitNone",
46            },
47            PlatformKind::Windows => match *self {
48                Self::Window | Self::Dialog => "UIA_WindowControlTypeId",
49                Self::Button => "UIA_ButtonControlTypeId",
50                Self::TextInput => "UIA_EditControlTypeId",
51                Self::Checkbox | Self::Switch => "UIA_CheckBoxControlTypeId",
52                Self::Slider => "UIA_SliderControlTypeId",
53                Self::Tab => "UIA_TabItemControlTypeId",
54                Self::TabList => "UIA_TabControlTypeId",
55                Self::List => "UIA_ListControlTypeId",
56                Self::ListItem => "UIA_ListItemControlTypeId",
57                Self::ProgressBar => "UIA_ProgressBarControlTypeId",
58                Self::Image | Self::Canvas => "UIA_ImageControlTypeId",
59                Self::Link => "UIA_HyperlinkControlTypeId",
60                Self::Menu => "UIA_MenuControlTypeId",
61                Self::MenuItem => "UIA_MenuItemControlTypeId",
62                Self::Text | Self::Heading | Self::Alert => "UIA_TextControlTypeId",
63                Self::ScrollView => "UIA_PaneControlTypeId",
64                Self::Group | Self::Region | Self::Navigation => "UIA_GroupControlTypeId",
65            },
66            PlatformKind::Linux => match *self {
67                Self::Window => "ATK_ROLE_FRAME",
68                Self::Dialog => "ATK_ROLE_DIALOG",
69                Self::Alert => "ATK_ROLE_ALERT",
70                Self::Button => "ATK_ROLE_PUSH_BUTTON",
71                Self::TextInput => "ATK_ROLE_ENTRY",
72                Self::Checkbox => "ATK_ROLE_CHECK_BOX",
73                Self::Switch => "ATK_ROLE_TOGGLE_BUTTON",
74                Self::Slider => "ATK_ROLE_SLIDER",
75                Self::Tab => "ATK_ROLE_PAGE_TAB",
76                Self::TabList => "ATK_ROLE_PAGE_TAB_LIST",
77                Self::List => "ATK_ROLE_LIST",
78                Self::ListItem => "ATK_ROLE_LIST_ITEM",
79                Self::ProgressBar => "ATK_ROLE_PROGRESS_BAR",
80                Self::Image | Self::Canvas => "ATK_ROLE_IMAGE",
81                Self::ScrollView => "ATK_ROLE_SCROLL_PANE",
82                Self::Link => "ATK_ROLE_LINK",
83                Self::Menu => "ATK_ROLE_MENU",
84                Self::MenuItem => "ATK_ROLE_MENU_ITEM",
85                Self::Heading => "ATK_ROLE_HEADING",
86                Self::Text => "ATK_ROLE_LABEL",
87                Self::Group | Self::Region | Self::Navigation => "ATK_ROLE_PANEL",
88            },
89            PlatformKind::Android => match *self {
90                Self::Button | Self::MenuItem => "android.widget.Button",
91                Self::TextInput => "android.widget.EditText",
92                Self::Checkbox => "android.widget.CheckBox",
93                Self::Switch => "android.widget.Switch",
94                Self::Slider => "android.widget.SeekBar",
95                Self::ProgressBar => "android.widget.ProgressBar",
96                Self::Image | Self::Canvas => "android.widget.ImageView",
97                Self::ScrollView => "android.widget.ScrollView",
98                Self::List => "android.widget.ListView",
99                Self::Text | Self::Heading | Self::Alert | Self::Link => "android.widget.TextView",
100                _ => "android.view.View",
101            },
102            PlatformKind::Web | PlatformKind::Headless => match *self {
103                Self::Window => "application",
104                Self::Region | Self::ScrollView => ROLE_ARIA_REGION,
105                Self::Navigation => "navigation",
106                Self::Heading => "heading",
107                Self::Text => "paragraph",
108                Self::Button => "button",
109                Self::TextInput => "textbox",
110                Self::Checkbox => "checkbox",
111                Self::Switch => "switch",
112                Self::Slider => "slider",
113                Self::Tab => "tab",
114                Self::TabList => "tablist",
115                Self::List => "list",
116                Self::ListItem => "listitem",
117                Self::Dialog => "dialog",
118                Self::Alert => "alert",
119                Self::ProgressBar => "progressbar",
120                Self::Image | Self::Canvas => "img",
121                Self::Link => "link",
122                Self::Menu => "menu",
123                Self::MenuItem => "menuitem",
124                Self::Group => "group",
125            },
126        }
127    }
128}
129
130/// Optional accessor helpers for `A11yProps`.
131impl A11yProps {
132    /// Returns the optional checked state (`Some(true)`, `Some(false)`, or `None`).
133    ///
134    /// # Arguments
135    ///
136    /// - `&Self` - Accessibility properties reference.
137    ///
138    /// # Returns
139    ///
140    /// - `Option<bool>` - Checked state if applicable.
141    #[must_use]
142    pub fn checked_state(&self) -> Option<bool> {
143        let Self { checked, .. } = self;
144        *checked
145    }
146}
147
148/// Tree compilation and lookup methods for `A11yTree`.
149impl A11yTree {
150    /// Compiles an `A11yTree` snapshot directly from a laid-out `SceneTree`.
151    ///
152    /// # Arguments
153    ///
154    /// - `&SceneTree` - Retained UI scene tree.
155    ///
156    /// # Returns
157    ///
158    /// - `Self` - Compiled accessibility tree ready for native OS bridges.
159    #[must_use]
160    pub fn from_scene(tree: &SceneTree) -> Self {
161        let root: NodeId = tree.get_root();
162        let focused_id: Option<NodeId> = tree.get_focus().focused_node();
163        let initial_cap: usize = (tree.live_node_count() / 2).max(1);
164        let mut nodes: Vec<A11yNode> = Vec::with_capacity(initial_cap);
165        Self::collect_node(tree, root, root, focused_id, &mut nodes);
166        Self::new(root, nodes, focused_id)
167    }
168
169    /// Returns `true` when `node` is visible (`Display != None`) and not marked `hidden` in explicit accessibility extras.
170    ///
171    /// # Arguments
172    ///
173    /// - `&SceneNode` - Candidate scene node reference.
174    ///
175    /// # Returns
176    ///
177    /// - `bool` - Whether the node should be exposed in `A11yTree`.
178    #[must_use]
179    #[inline(always)]
180    fn is_node_exposed(node: &SceneNode) -> bool {
181        if node.style_ref().layout_ref().get_display() == Display::None {
182            return false;
183        }
184        !node.a11y_props_ref().is_some_and(A11yProps::get_hidden)
185    }
186
187    /// Recursively collects visible, non-hidden nodes into the flat accessibility list without cloning styles or child vectors.
188    ///
189    /// # Arguments
190    ///
191    /// - `&SceneTree` - Retained UI scene tree.
192    /// - `NodeId` - Current node handle.
193    /// - `NodeId` - Scene root node handle.
194    /// - `Option<NodeId>` - Active focused node identifier.
195    /// - `&mut Vec<A11yNode>` - Output accessible node vector.
196    fn collect_node(
197        tree: &SceneTree,
198        node_id: NodeId,
199        root: NodeId,
200        focused_id: Option<NodeId>,
201        out: &mut Vec<A11yNode>,
202    ) {
203        let Some(node) = tree.get_node(node_id) else {
204            return;
205        };
206        if node.style_ref().layout_ref().get_display() == Display::None {
207            return;
208        }
209        let explicit_ref: Option<&A11yProps> = node.a11y_props_ref();
210        if explicit_ref.is_some_and(A11yProps::get_hidden) {
211            return;
212        }
213        let props: A11yProps = match explicit_ref {
214            Some(explicit) => explicit.clone(),
215            None => {
216                let mut inferred: A11yProps = match node.get_kind() {
217                    NodeKind::Text(t) => A11yProps::new(A11yRole::Text, t.clone()),
218                    NodeKind::Input(state) => {
219                        let mut p: A11yProps =
220                            A11yProps::new(A11yRole::TextInput, state.get_placeholder().clone());
221                        p.set_value(state.get_value().clone())
222                            .set_disabled(state.get_disabled());
223                        p
224                    }
225                    NodeKind::Image(_) => A11yProps::new(A11yRole::Image, String::new()),
226                    NodeKind::Canvas => A11yProps::new(A11yRole::Canvas, String::new()),
227                    NodeKind::ScrollView => A11yProps::new(A11yRole::ScrollView, String::new()),
228                    NodeKind::Portal => A11yProps::new(A11yRole::Dialog, String::new()),
229                    NodeKind::View | NodeKind::Fragment => {
230                        let role: A11yRole = if node_id == root {
231                            A11yRole::Window
232                        } else if node
233                            .get_handlers()
234                            .handler_for(&UiEventKind::Click(Point::default()))
235                            .is_some()
236                        {
237                            A11yRole::Button
238                        } else {
239                            A11yRole::Group
240                        };
241                        A11yProps::new(role, String::new())
242                    }
243                };
244                if node.get_interaction().get_focused() {
245                    inferred.set_live_region(A11yLiveRegion::Polite);
246                }
247                inferred
248            }
249        };
250        let raw_children: &[NodeId] = node.get_children().as_slice();
251        let visible_children: Vec<NodeId> = if raw_children.is_empty() {
252            Vec::new()
253        } else {
254            let mut vis: Vec<NodeId> = Vec::with_capacity(raw_children.len());
255            for &cid in raw_children {
256                if tree.get_node(cid).is_some_and(Self::is_node_exposed) {
257                    vis.push(cid);
258                }
259            }
260            vis
261        };
262        out.push(A11yNode::new(
263            node_id,
264            props,
265            node.get_layout_box().get_bounds(),
266            focused_id == Some(node_id),
267            visible_children,
268        ));
269        for &child_id in raw_children {
270            Self::collect_node(tree, child_id, root, focused_id, out);
271        }
272    }
273
274    /// Finds an `A11yNode` by its `NodeId`.
275    ///
276    /// # Arguments
277    ///
278    /// - `&Self` - Accessibility tree reference.
279    /// - `NodeId` - Target scene node identifier.
280    ///
281    /// # Returns
282    ///
283    /// - `Option<&A11yNode>` - Matching accessibility node, if exposed.
284    #[must_use]
285    pub fn find(&self, id: NodeId) -> Option<&A11yNode> {
286        self.get_nodes()
287            .iter()
288            .find(|node: &&A11yNode| node.get_id() == id)
289    }
290
291    /// Returns the currently focused node identifier, if any.
292    ///
293    /// # Arguments
294    ///
295    /// - `&Self` - Accessibility tree reference.
296    ///
297    /// # Returns
298    ///
299    /// - `Option<NodeId>` - Focused accessible node identifier.
300    #[must_use]
301    pub fn focused_node(&self) -> Option<NodeId> {
302        let Self { focused_id, .. } = self;
303        *focused_id
304    }
305
306    /// Formats a compact ARIA-compatible semantic summary for Web synchronization and diagnostics.
307    ///
308    /// # Arguments
309    ///
310    /// - `&Self` - Accessibility tree reference.
311    /// - `PlatformKind` - Platform whose native role identifiers should be emitted.
312    ///
313    /// # Returns
314    ///
315    /// - `String` - Newline-delimited semantic role summary.
316    #[must_use]
317    pub fn format_summary(&self, platform: PlatformKind) -> String {
318        let mut out: String = String::with_capacity(self.get_nodes().len().saturating_mul(24));
319        for node in self.get_nodes().iter() {
320            let role: &str = node.get_props().get_role().native_role_name(platform);
321            let label: &str = node.get_props().get_label().as_str();
322            out.push_str(role);
323            if !label.is_empty() {
324                out.push_str(": ");
325                out.push_str(label);
326            }
327            out.push('\n');
328        }
329        out
330    }
331}