Skip to main content

cranpose_foundation/modifier/
semantics_configuration.rs

1use super::{
2    CanvasSemanticsNode, CollectionInfo, LiveRegionMode, ProgressBarRangeInfo, ScrollAxisRange,
3    SemanticsCustomAction, SemanticsDismiss, SemanticsExpand, SemanticsLongClick,
4    SemanticsMagicTap, SemanticsScrollBy, SemanticsScrollToIndex, SemanticsSetProgress,
5    SemanticsSetSelection, SemanticsSetText, SemanticsWidgetRole, ToggleableState,
6};
7
8/// Semantics configuration for accessibility.
9#[derive(Clone, Debug, PartialEq)]
10pub struct SemanticsConfiguration {
11    /// What a screen reader reads as the name of the node. Compose's `contentDescription`.
12    pub content_description: Option<String>,
13    /// Compose's `stateDescription`.
14    pub state_description: Option<String>,
15    /// Compose's `onClick(label = …)`; implies clickable.
16    pub on_click_label: Option<String>,
17    /// Activation callback for controls whose pointer gesture is handled separately.
18    /// Invoked by keyboard and native accessibility activation after validation.
19    pub on_click: Option<SemanticsCustomAction>,
20    /// What this control does when a screen reader asks for its long press.
21    /// Compose's `onLongClick`.
22    pub on_long_click: Option<SemanticsLongClick>,
23    /// What the long press does, as a verb phrase a reader reads out:
24    /// "Remove receipt". Compose's `onLongClick(label = …)`.
25    pub on_long_click_label: Option<String>,
26    /// What this control does on VoiceOver's magic tap, and on the other
27    /// platforms as an action listed by [`Self::on_magic_tap_label`].
28    /// SwiftUI's `accessibilityAction(.magicTap)`.
29    pub on_magic_tap: Option<SemanticsMagicTap>,
30    /// What the magic tap does, as a verb phrase a reader reads out: "Take
31    /// the photo".
32    pub on_magic_tap_label: Option<String>,
33    /// The short names a person says to Voice Control to reach this control,
34    /// when the name a reader hears is too long to say. SwiftUI's
35    /// `accessibilityInputLabels`; iOS only.
36    pub input_labels: Vec<String>,
37    /// The language of this control's text as a BCP 47 tag, "de" or "pt-BR",
38    /// so a reader picks the right voice for it. SwiftUI's
39    /// `accessibilityLanguage`, ARIA's `lang`.
40    pub language: Option<String>,
41    /// Compose's `Role`.
42    pub role: Option<SemanticsWidgetRole>,
43    /// Whether the control is selected. `None` means the control has no selected state.
44    pub selected: Option<bool>,
45    /// Whether the control is on, off or partly on. Compose's
46    /// `toggleableState`.
47    pub toggled: Option<ToggleableState>,
48    /// Whether the control accepts input. A disabled control is announced as such.
49    pub enabled: bool,
50    /// Whether the control reacts to a click.
51    pub is_clickable: bool,
52    /// Whether the node is a text field a user edits.
53    pub is_editable_text: bool,
54    /// Whether an editable field accepts line breaks, independent of its current text.
55    pub multiline: bool,
56    /// The text an editable field holds, read as its value. Compose's
57    /// `editableText`.
58    pub text: Option<String>,
59    /// The selection or the caret of an editable field, as byte offsets into its text.
60    pub text_selection: Option<crate::text::TextRange>,
61    /// Named actions that a screen reader lists in its actions menu for the node.
62    pub custom_actions: Vec<SemanticsCustomAction>,
63    /// Controls this node drew itself instead of laying out. See
64    /// [`CanvasSemanticsNode`].
65    pub canvas_children: Vec<CanvasSemanticsNode>,
66    /// Whether this node takes over the screen: everything outside it is
67    /// inert, and a screen reader keeps its traversal inside.
68    pub is_modal: bool,
69    /// Whether a screen reader skips this node and everything under it: a
70    /// decorative image, or a placeholder drawn under a named field. Compose's
71    /// `hideFromAccessibility`.
72    pub hidden: bool,
73    /// Whether a screen reader takes this node and the text under it as one
74    /// stop, the way it does for a button: a row whose name, count and price
75    /// belong together. Compose's `mergeDescendants`.
76    pub merge_descendants: bool,
77    /// Whether the selectable controls under this node form one group, so a
78    /// screen reader says which of how many a tab or a radio button is.
79    /// Compose's `selectableGroup`.
80    pub selectable_group: bool,
81    /// The title of the screen or pane this node is the root of, read out when
82    /// the app moves to it. Compose's `paneTitle`.
83    pub pane_title: Option<String>,
84    /// Why the control's content is wrong, read after its state: "invalid,
85    /// the amount needs a number". Compose's `error`.
86    pub error: Option<String>,
87    /// What using the control does or what it wants, read after its other
88    /// words: "double tap to choose a color". Compose's `hintText`.
89    pub hint_text: Option<String>,
90    /// Whether this field holds a secret, so screen readers never receive its
91    /// text and native editors use protected input. Compose's `password`.
92    pub password: bool,
93    /// Where a screen reader visits this node among the ones beside it: a
94    /// smaller number comes first, and nodes left at zero keep the order the
95    /// app laid them out in. Compose's `traversalIndex`.
96    pub traversal_index: f32,
97    /// A name tests find this node by. Screen readers never read it. UI test
98    /// tools find it in the platform's accessibility tree: the accessibility
99    /// identifier on iOS and macOS, the UI Automation `AutomationId` on
100    /// Windows, the AT-SPI accessible id on Linux, the `id` of the web
101    /// mirror's node, and on Android the view id resource name where
102    /// [`Self::test_tags_as_resource_id`] holds. Only a node a screen reader
103    /// reaches carries it there. Compose's `testTag`.
104    pub test_tag: Option<String>,
105    /// Whether Android publishes the test tags of this node and of the nodes
106    /// under it as their view id resource names, where UI Automator's
107    /// `By.res` finds them. `None` takes the value of the nearest node above
108    /// that sets one, and a tree that sets none keeps the tags off. Compose's
109    /// `testTagsAsResourceId`.
110    pub test_tags_as_resource_id: Option<bool>,
111    /// Compose's `liveRegion`. When set, a screen reader reads this node again
112    /// whenever its text changes, without the user moving to it.
113    pub live_region: Option<LiveRegionMode>,
114    /// Compose's `progressBarRangeInfo`. A control with it is adjustable: a
115    /// screen reader offers its own way to move the value.
116    pub progress: Option<ProgressBarRangeInfo>,
117    /// What the control does when a screen reader moves its value. Compose's
118    /// `setProgress`.
119    pub set_progress: Option<SemanticsSetProgress>,
120    /// What this field does when a screen reader or a voice tool hands it
121    /// text. Compose's `setText`.
122    pub set_text: Option<SemanticsSetText>,
123    /// What this field does when a screen reader moves its caret or picks a
124    /// stretch of its text. Compose's `setSelection`.
125    pub set_selection: Option<SemanticsSetSelection>,
126    /// What this control does when a screen reader asks it to open. A control
127    /// that says so reads as closed. Compose's `expand`.
128    pub expand: Option<SemanticsExpand>,
129    /// What this control does when a screen reader asks to send it away: a row
130    /// a sighted person swipes off, a sheet a sighted person taps outside of.
131    /// Compose's `dismiss`.
132    pub dismiss: Option<SemanticsDismiss>,
133    /// What this control does when a screen reader asks it to close. A control
134    /// that says so reads as open. Compose's `collapse`.
135    pub collapse: Option<SemanticsExpand>,
136    /// How far this container scrolled up and down. Compose's
137    /// `verticalScrollAxisRange`.
138    pub vertical_scroll: Option<ScrollAxisRange>,
139    /// How far this container scrolled left and right. Compose's
140    /// `horizontalScrollAxisRange`.
141    pub horizontal_scroll: Option<ScrollAxisRange>,
142    /// What this container does when a screen reader pages it. Compose's
143    /// `scrollBy`.
144    pub scroll_by: Option<SemanticsScrollBy>,
145    /// What this list does when a screen reader asks for the row at an index,
146    /// so a reader reaches row 300 without paging to it. Compose's
147    /// `scrollToIndex`.
148    pub scroll_to_index: Option<SemanticsScrollToIndex>,
149    /// How many rows and columns this list holds. Compose's `collectionInfo`.
150    pub collection: Option<CollectionInfo>,
151}
152
153impl Default for SemanticsConfiguration {
154    fn default() -> Self {
155        Self {
156            content_description: None,
157            state_description: None,
158            on_click_label: None,
159            on_click: None,
160            on_long_click: None,
161            on_long_click_label: None,
162            on_magic_tap: None,
163            on_magic_tap_label: None,
164            input_labels: Vec::new(),
165            language: None,
166            role: None,
167            selected: None,
168            toggled: None,
169            enabled: true,
170            is_clickable: false,
171            is_editable_text: false,
172            multiline: false,
173            text: None,
174            text_selection: None,
175            custom_actions: Vec::new(),
176            canvas_children: Vec::new(),
177            is_modal: false,
178            hidden: false,
179            merge_descendants: false,
180            selectable_group: false,
181            pane_title: None,
182            error: None,
183            hint_text: None,
184            password: false,
185            traversal_index: 0.0,
186            test_tag: None,
187            test_tags_as_resource_id: None,
188            live_region: None,
189            progress: None,
190            set_progress: None,
191            set_text: None,
192            set_selection: None,
193            expand: None,
194            dismiss: None,
195            collapse: None,
196            vertical_scroll: None,
197            horizontal_scroll: None,
198            scroll_by: None,
199            scroll_to_index: None,
200            collection: None,
201        }
202    }
203}
204
205/// One value that says what a screen reader reads for a node, built up with
206/// the methods below and handed to `Modifier::semantics_spec`.
207///
208/// Compose has no such value: it takes a receiver lambda, which Kotlin makes
209/// read well and Rust has no match for. `SemanticsSpec::new().content_description("Save")`
210/// reads better than `|config| config.content_description = Some("Save".into())`,
211/// it is one chain element rather than one per property, and two specs can be
212/// compared. The closure form stays as `Modifier::semantics` for parity.
213pub type SemanticsSpec = SemanticsConfiguration;
214
215impl SemanticsConfiguration {
216    /// An empty spec to build on. Every field is what it is with no semantics
217    /// declared at all.
218    pub fn new() -> Self {
219        Self::default()
220    }
221
222    /// The name a screen reader reads for the control. Compose's
223    /// `contentDescription`.
224    pub fn content_description(mut self, name: impl Into<String>) -> Self {
225        self.content_description = Some(name.into());
226        self
227    }
228
229    /// A name tests find this node by. Screen readers never receive it.
230    /// Compose's `testTag`.
231    pub fn test_tag(mut self, tag: impl Into<String>) -> Self {
232        self.test_tag = Some(tag.into());
233        self
234    }
235
236    /// What the control says about itself after its name. Compose's
237    /// `stateDescription`.
238    pub fn state_description(mut self, state: impl Into<String>) -> Self {
239        self.state_description = Some(state.into());
240        self
241    }
242
243    /// A screen reader offers to activate the control. Compose's `onClick`.
244    pub fn clickable(mut self) -> Self {
245        self.is_clickable = true;
246        self
247    }
248
249    /// Handles keyboard and screen-reader activation without adding a pointer gesture.
250    /// An empty label uses the platform's default activation instruction.
251    pub fn on_click(mut self, label: impl Into<String>, action: impl Fn() + 'static) -> Self {
252        self.on_click = Some(SemanticsCustomAction::new(label, action));
253        self
254    }
255
256    /// What the control does when a screen reader asks for its long press,
257    /// and the verb phrase a reader reads out for it. Compose's
258    /// `onLongClick(label) { … }`.
259    pub fn on_long_click(
260        mut self,
261        label: impl Into<String>,
262        action: impl Fn() -> bool + 'static,
263    ) -> Self {
264        self.on_long_click_label = Some(label.into());
265        self.on_long_click = Some(SemanticsLongClick::new(action));
266        self
267    }
268
269    /// What the control does on VoiceOver's magic tap, and the verb phrase
270    /// the other platforms list it under. SwiftUI's
271    /// `accessibilityAction(.magicTap)`.
272    pub fn on_magic_tap(
273        mut self,
274        label: impl Into<String>,
275        action: impl Fn() -> bool + 'static,
276    ) -> Self {
277        self.on_magic_tap_label = Some(label.into());
278        self.on_magic_tap = Some(SemanticsMagicTap::new(action));
279        self
280    }
281
282    /// The short names a person says to Voice Control to reach the control.
283    /// SwiftUI's `accessibilityInputLabels`.
284    pub fn input_labels<S: Into<String>>(mut self, labels: impl IntoIterator<Item = S>) -> Self {
285        self.input_labels = labels.into_iter().map(Into::into).collect();
286        self
287    }
288
289    /// The language of the control's text, as a BCP 47 tag. SwiftUI's
290    /// `accessibilityLanguage`, ARIA's `lang`.
291    pub fn language(mut self, tag: impl Into<String>) -> Self {
292        self.language = Some(tag.into());
293        self
294    }
295
296    /// Whether the control is on, off or partly on. Compose's
297    /// `toggleableState`; a `bool` is on or off.
298    pub fn toggled(mut self, toggled: impl Into<ToggleableState>) -> Self {
299        self.toggled = Some(toggled.into());
300        self
301    }
302
303    /// Whether the control is the one picked out of a group. Compose's
304    /// `selected`.
305    pub fn selected(mut self, selected: bool) -> Self {
306        self.selected = Some(selected);
307        self
308    }
309
310    /// What kind of control a screen reader reads this as. Compose's `Role`.
311    pub fn role(mut self, role: SemanticsWidgetRole) -> Self {
312        self.role = Some(role);
313        self
314    }
315
316    /// Reads as a heading, so a reader can jump between the headings of a
317    /// screen. Compose's `heading()`.
318    pub fn heading(self) -> Self {
319        self.role(SemanticsWidgetRole::Header)
320    }
321
322    /// Why the control's content is wrong. Compose's `error`.
323    pub fn error(mut self, message: impl Into<String>) -> Self {
324        self.error = Some(message.into());
325        self
326    }
327
328    /// What using the control does or what it wants. Compose's `hintText`.
329    pub fn hint_text(mut self, hint: impl Into<String>) -> Self {
330        self.hint_text = Some(hint.into());
331        self
332    }
333
334    /// Holds a secret, so no reader reads the text out. Compose's `password`.
335    pub fn password(mut self) -> Self {
336        self.password = true;
337        self
338    }
339
340    /// Names the screen or pane this node is the root of. Compose's
341    /// `paneTitle`.
342    pub fn pane_title(mut self, title: impl Into<String>) -> Self {
343        self.pane_title = Some(title.into());
344        self
345    }
346
347    /// Where a reader visits this node among the ones beside it. Compose's
348    /// `traversalIndex`.
349    pub fn traversal_index(mut self, index: f32) -> Self {
350        self.traversal_index = index;
351        self
352    }
353
354    /// Skips this node and everything under it. Compose's
355    /// `hideFromAccessibility`.
356    pub fn hidden(mut self) -> Self {
357        self.hidden = true;
358        self
359    }
360
361    /// Takes this node and the text under it as one stop. Compose's
362    /// `mergeDescendants`.
363    pub fn merge_descendants(mut self) -> Self {
364        self.merge_descendants = true;
365        self
366    }
367
368    /// Makes the selectable controls under this node one group. Compose's
369    /// `selectableGroup`.
370    pub fn selectable_group(mut self) -> Self {
371        self.selectable_group = true;
372        self
373    }
374
375    /// Reads this node again whenever its text changes. Compose's
376    /// `liveRegion`.
377    pub fn live_region(mut self, mode: LiveRegionMode) -> Self {
378        self.live_region = Some(mode);
379        self
380    }
381    /// Folds `other` into this configuration. A value that `other` sets replaces the value here.
382    /// `enabled` stays true only when both are enabled, the boolean flags turn true when either is
383    /// true, and the lists are appended.
384    pub fn merge(&mut self, other: &Self) {
385        if let Some(description) = &other.content_description {
386            self.content_description = Some(description.clone());
387        }
388        if let Some(state) = &other.state_description {
389            self.state_description = Some(state.clone());
390        }
391        if let Some(label) = &other.on_click_label {
392            self.on_click_label = Some(label.clone());
393        }
394        if let Some(label) = &other.on_long_click_label {
395            self.on_long_click_label = Some(label.clone());
396        }
397        if let Some(label) = &other.on_magic_tap_label {
398            self.on_magic_tap_label = Some(label.clone());
399        }
400        if !other.input_labels.is_empty() {
401            self.input_labels.clone_from(&other.input_labels);
402        }
403        if let Some(language) = &other.language {
404            self.language = Some(language.clone());
405        }
406        if let Some(role) = other.role {
407            self.role = Some(role);
408        }
409        if let Some(selected) = other.selected {
410            self.selected = Some(selected);
411        }
412        if let Some(toggled) = other.toggled {
413            self.toggled = Some(toggled);
414        }
415        self.enabled &= other.enabled;
416        self.is_clickable |= other.is_clickable;
417        self.is_editable_text |= other.is_editable_text;
418        self.multiline |= other.multiline;
419        if let Some(text) = &other.text {
420            self.text = Some(text.clone());
421        }
422        self.is_modal |= other.is_modal;
423        self.hidden |= other.hidden;
424        self.merge_descendants |= other.merge_descendants;
425        self.selectable_group |= other.selectable_group;
426        self.password |= other.password;
427        if other.traversal_index != 0.0 {
428            self.traversal_index = other.traversal_index;
429        }
430        if let Some(live_region) = other.live_region {
431            self.live_region = Some(live_region);
432        }
433        self.test_tags_as_resource_id = other
434            .test_tags_as_resource_id
435            .or(self.test_tags_as_resource_id);
436        self.merge_words(other);
437        self.merge_actions(other);
438        self.merge_ranges(other);
439    }
440
441    fn merge_words(&mut self, other: &Self) {
442        if let Some(title) = &other.pane_title {
443            self.pane_title = Some(title.clone());
444        }
445        if let Some(error) = &other.error {
446            self.error = Some(error.clone());
447        }
448        if let Some(hint) = &other.hint_text {
449            self.hint_text = Some(hint.clone());
450        }
451        if let Some(tag) = &other.test_tag {
452            self.test_tag = Some(tag.clone());
453        }
454    }
455
456    fn merge_actions(&mut self, other: &Self) {
457        if let Some(on_click) = &other.on_click {
458            self.on_click = Some(on_click.clone());
459        }
460        self.custom_actions
461            .extend(other.custom_actions.iter().cloned());
462        self.canvas_children
463            .extend(other.canvas_children.iter().cloned());
464        if let Some(set_progress) = &other.set_progress {
465            self.set_progress = Some(set_progress.clone());
466        }
467        if let Some(set_text) = &other.set_text {
468            self.set_text = Some(set_text.clone());
469        }
470        if let Some(set_selection) = &other.set_selection {
471            self.set_selection = Some(set_selection.clone());
472        }
473        if let Some(expand) = &other.expand {
474            self.expand = Some(expand.clone());
475        }
476        if let Some(collapse) = &other.collapse {
477            self.collapse = Some(collapse.clone());
478        }
479        if let Some(dismiss) = &other.dismiss {
480            self.dismiss = Some(dismiss.clone());
481        }
482        if let Some(long_click) = &other.on_long_click {
483            self.on_long_click = Some(long_click.clone());
484        }
485        if let Some(magic_tap) = &other.on_magic_tap {
486            self.on_magic_tap = Some(magic_tap.clone());
487        }
488        if let Some(scroll_by) = &other.scroll_by {
489            self.scroll_by = Some(scroll_by.clone());
490        }
491        if let Some(scroll_to_index) = &other.scroll_to_index {
492            self.scroll_to_index = Some(scroll_to_index.clone());
493        }
494    }
495
496    fn merge_ranges(&mut self, other: &Self) {
497        if let Some(selection) = other.text_selection {
498            self.text_selection = Some(selection);
499        }
500        if let Some(progress) = other.progress {
501            self.progress = Some(progress);
502        }
503        if let Some(range) = other.vertical_scroll {
504            self.vertical_scroll = Some(range);
505        }
506        if let Some(range) = other.horizontal_scroll {
507            self.horizontal_scroll = Some(range);
508        }
509        if let Some(collection) = other.collection {
510            self.collection = Some(collection);
511        }
512    }
513
514    /// Whether a screen reader should offer activation. A named click label is
515    /// how Compose declares `onClick`, so it implies the action the same way.
516    pub fn is_activatable(&self) -> bool {
517        self.is_clickable || self.on_click_label.is_some() || self.on_click.is_some()
518    }
519}