waft_rendering/semantics.rs
1//! Flutter counterpart: `semantics/semantics.dart`'s values that annotate a subtree:
2//! the handler typedefs, `AccessibilityFocusBlockType`, `SemanticsTag`,
3//! `CustomSemanticsAction`, `AttributedString`, `SemanticsHintOverrides`,
4//! `SemanticsProperties`, `SemanticsSortKey` and `OrdinalSortKey`.
5//!
6//! Flutter's `semantics` library sits between painting and rendering; Waft has no crate for
7//! it, so its values live in the lowest crate above painting. `SemanticsNode`,
8//! `SemanticsOwner`, `SemanticsConfiguration` and `SemanticsData` wait with the semantics
9//! tree: until it lands nothing reads these values, and they are kept as the widgets give them.
10
11use std::any::Any;
12use std::cmp::Ordering;
13use std::fmt::{self, Debug};
14use std::ops::Add;
15use std::rc::Rc;
16
17use indexmap::{IndexMap, IndexSet};
18use waft_embedder::{
19 SemanticsAction, SemanticsHitTestBehavior, SemanticsInputType, SemanticsRole,
20 SemanticsValidationResult, StringAttributeRef, TextDirection, TextRange, TextSelection,
21};
22use waft_foundation::{App, VoidCallback};
23
24/// Signature for `SemanticsAction`s that move the cursor.
25///
26/// If `extendSelection` is set to true the cursor movement should extend the
27/// current selection or (if nothing is currently selected) start a selection.
28pub type MoveCursorHandler = Rc<dyn Fn(&mut App, bool)>;
29
30/// Signature for the `SemanticsAction.setSelection` handlers to change the
31/// text selection (or re-position the cursor) to `selection`.
32pub type SetSelectionHandler = Rc<dyn Fn(&mut App, TextSelection)>;
33
34/// Signature for the `SemanticsAction.setText` handlers to replace the
35/// current text with the input `text`.
36pub type SetTextHandler = Rc<dyn Fn(&mut App, String)>;
37
38/// Controls how accessibility focus is blocked.
39///
40/// This is typically used to prevent screen readers from focusing on parts
41/// of the UI.
42///
43/// Setting this property also blocks the reporting of keyboard focusability
44/// for the semantics node, but it does not affect the actual keyboard focus
45/// handled by `FocusNode`.
46#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
47pub enum AccessibilityFocusBlockType {
48 /// Accessibility focus is **not blocked**.
49 None,
50
51 /// Blocks accessibility focus for the entire subtree.
52 BlockSubtree,
53
54 /// Blocks accessibility focus for the **current node only**. Its descendants
55 /// may still be focusable.
56 BlockNode,
57}
58
59/// A tag for a `SemanticsNode`.
60///
61/// Tags can be interpreted by the parent of a `SemanticsNode`
62/// and depending on the presence of a tag the parent can for example decide
63/// how to add the tagged node as a child. Tags are not sent to the engine.
64///
65/// The provided [`name`](Self::name) is only used for debugging. Two tags are identical only
66/// when they are the same object: held as `Rc<SemanticsTag>`, the `Rc`'s identity.
67pub struct SemanticsTag {
68 /// A human-readable name for this tag used for debugging.
69 ///
70 /// This string is not used to determine if two tags are identical.
71 pub name: String,
72}
73
74impl SemanticsTag {
75 /// Creates a [`SemanticsTag`].
76 pub fn new(name: impl Into<String>) -> Rc<SemanticsTag> {
77 Rc::new(SemanticsTag { name: name.into() })
78 }
79}
80
81impl Debug for SemanticsTag {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 write!(f, "SemanticsTag({})", self.name)
84 }
85}
86
87/// An identifier of a custom semantics action.
88///
89/// Custom semantics actions can be provided to make complex user
90/// interactions more accessible. For instance, if an application has a
91/// drag-and-drop list that requires the user to press and hold an item
92/// to move it, users interacting with the application using a hardware
93/// switch may have difficulty. This can be made accessible by creating custom
94/// actions and pairing them with handlers that move a list item up or down in
95/// the list.
96///
97/// In Android, these actions are presented in the local context menu. In iOS,
98/// these are presented in the radial context menu.
99///
100/// Localization and text direction do not automatically apply to the provided
101/// label or hint.
102///
103/// Dart's identifier registry (`getIdentifier`, `getAction`, `resetForTests`) waits with the
104/// semantics tree, which is what sends the identifiers.
105#[derive(Clone, PartialEq, Eq, Hash)]
106pub struct CustomSemanticsAction {
107 /// The user readable name of this custom semantics action.
108 pub label: Option<String>,
109
110 /// The hint description of this custom semantics action.
111 pub hint: Option<String>,
112
113 /// The standard semantics action this action replaces.
114 pub action: Option<SemanticsAction>,
115}
116
117impl CustomSemanticsAction {
118 /// Creates a new [`CustomSemanticsAction`].
119 ///
120 /// The `label` must not be empty.
121 pub fn new(label: impl Into<String>) -> CustomSemanticsAction {
122 let label = label.into();
123 debug_assert!(!label.is_empty());
124 CustomSemanticsAction {
125 label: Some(label),
126 hint: None,
127 action: None,
128 }
129 }
130
131 /// Creates a new [`CustomSemanticsAction`] that overrides a standard semantics
132 /// action.
133 ///
134 /// The `hint` must not be empty.
135 pub fn overriding_action(
136 hint: impl Into<String>,
137 action: SemanticsAction,
138 ) -> CustomSemanticsAction {
139 let hint = hint.into();
140 debug_assert!(!hint.is_empty());
141 CustomSemanticsAction {
142 label: None,
143 hint: Some(hint),
144 action: Some(action),
145 }
146 }
147}
148
149impl Debug for CustomSemanticsAction {
150 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151 write!(
152 f,
153 "CustomSemanticsAction(label:{:?}, hint:{:?}, action:{:?})",
154 self.label, self.hint, self.action
155 )
156 }
157}
158
159/// A string that carries a list of `StringAttribute`s.
160#[derive(Clone)]
161pub struct AttributedString {
162 /// The plain string stored in the attributed string.
163 pub string: String,
164
165 /// The attributes this string carries.
166 ///
167 /// The list must not be modified after this string is created.
168 pub attributes: Vec<StringAttributeRef>,
169}
170
171impl AttributedString {
172 /// Creates a attributed string.
173 pub fn new(string: impl Into<String>) -> AttributedString {
174 AttributedString {
175 string: string.into(),
176 attributes: Vec::new(),
177 }
178 }
179
180 /// Dart `AttributedString(attributes:)`.
181 ///
182 /// The `TextRange` in the `attributes` must be inside the length of the
183 /// `string`.
184 ///
185 /// The `attributes` must not be changed after the attributed string is
186 /// created.
187 pub fn attributes(mut self, attributes: Vec<StringAttributeRef>) -> AttributedString {
188 debug_assert!(!self.string.is_empty() || attributes.is_empty());
189 if cfg!(debug_assertions) {
190 let length = utf16_length(&self.string);
191 for attribute in &attributes {
192 debug_assert!(
193 length >= attribute.range().start && length >= attribute.range().end,
194 "The range in {attribute:?} is outside of the string {}",
195 self.string
196 );
197 }
198 }
199 self.attributes = attributes;
200 self
201 }
202}
203
204/// Dart's `String.length`: UTF-16 code units, the unit of a `TextRange`.
205fn utf16_length(string: &str) -> i32 {
206 string.encode_utf16().count() as i32
207}
208
209impl Add for AttributedString {
210 type Output = AttributedString;
211
212 /// Returns a new [`AttributedString`] by concatenate the operands
213 ///
214 /// The string attribute list of the returned [`AttributedString`] will contains
215 /// the string attributes from both operands with updated text ranges.
216 fn add(self, other: AttributedString) -> AttributedString {
217 if self.string.is_empty() {
218 return other;
219 }
220 if other.string.is_empty() {
221 return self;
222 }
223
224 // None of the strings is empty.
225 let new_string = self.string.clone() + &other.string;
226 let mut new_attributes = self.attributes.clone();
227 if !other.attributes.is_empty() {
228 let offset = utf16_length(&self.string);
229 for attribute in &other.attributes {
230 let new_range = TextRange::new(
231 attribute.range().start + offset,
232 attribute.range().end + offset,
233 );
234 let adjusted_attribute = attribute.copy(new_range);
235 new_attributes.push(adjusted_attribute);
236 }
237 }
238 AttributedString::new(new_string).attributes(new_attributes)
239 }
240}
241
242/// Two [`AttributedString`]s are equal if their string and attributes are; an attribute equals
243/// only itself.
244impl PartialEq for AttributedString {
245 fn eq(&self, other: &AttributedString) -> bool {
246 other.string == self.string
247 && other.attributes.len() == self.attributes.len()
248 && other
249 .attributes
250 .iter()
251 .zip(&self.attributes)
252 .all(|(a, b)| Rc::ptr_eq(a, b))
253 }
254}
255
256impl Debug for AttributedString {
257 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258 write!(
259 f,
260 "AttributedString('{}', attributes: {:?})",
261 self.string, self.attributes
262 )
263 }
264}
265
266/// Provides hint values which override the default hints on supported
267/// platforms.
268///
269/// On iOS, these values are always ignored.
270#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
271pub struct SemanticsHintOverrides {
272 /// The hint text for a tap action.
273 ///
274 /// If null, the standard hint is used instead.
275 ///
276 /// The hint should describe what happens when a tap occurs, not the
277 /// manner in which a tap is accomplished.
278 ///
279 /// Bad: 'Double tap to show movies'.
280 /// Good: 'show movies'.
281 pub on_tap_hint: Option<String>,
282
283 /// The hint text for a long press action.
284 ///
285 /// If null, the standard hint is used instead.
286 ///
287 /// The hint should describe what happens when a long press occurs, not
288 /// the manner in which the long press is accomplished.
289 ///
290 /// Bad: 'Double tap and hold to favorite'.
291 /// Good: 'favorite'.
292 pub on_long_press_hint: Option<String>,
293}
294
295impl SemanticsHintOverrides {
296 /// Creates a semantics hint overrides.
297 pub fn new() -> SemanticsHintOverrides {
298 SemanticsHintOverrides::default()
299 }
300
301 /// Dart `SemanticsHintOverrides(onTapHint:)`.
302 pub fn on_tap_hint(mut self, on_tap_hint: impl Into<String>) -> SemanticsHintOverrides {
303 let on_tap_hint = on_tap_hint.into();
304 debug_assert!(!on_tap_hint.is_empty());
305 self.on_tap_hint = Some(on_tap_hint);
306 self
307 }
308
309 /// Dart `SemanticsHintOverrides(onLongPressHint:)`.
310 pub fn on_long_press_hint(
311 mut self,
312 on_long_press_hint: impl Into<String>,
313 ) -> SemanticsHintOverrides {
314 let on_long_press_hint = on_long_press_hint.into();
315 debug_assert!(!on_long_press_hint.is_empty());
316 self.on_long_press_hint = Some(on_long_press_hint);
317 self
318 }
319
320 /// Whether there are any non-null hint values.
321 pub fn is_not_empty(&self) -> bool {
322 self.on_tap_hint.is_some() || self.on_long_press_hint.is_some()
323 }
324}
325
326/// Contains properties used by assistive technologies to make the application
327/// more accessible.
328///
329/// The properties of this class are used to generate a `SemanticsNode`s in the
330/// semantics tree.
331///
332/// Dart's class does not override `==`: a render object compares two by identity, so they are
333/// held as `Rc<SemanticsProperties>` and compared with `Rc::ptr_eq`.
334#[derive(Clone, Default)]
335pub struct SemanticsProperties {
336 /// If non-null, indicates that this subtree represents something that can be
337 /// in an enabled or disabled state.
338 ///
339 /// For example, a button that a user can currently interact with would set
340 /// this field to true. A button that currently does not respond to user
341 /// interactions would set this field to false.
342 pub enabled: Option<bool>,
343
344 /// If non-null, indicates that this subtree represents a checkbox
345 /// or similar widget with a "checked" state, and what its current
346 /// state is.
347 ///
348 /// When the `Checkbox.value` of a tristate Checkbox is null,
349 /// indicating a mixed-state, this value shall be false, in which
350 /// case, `mixed` will be true.
351 ///
352 /// This is mutually exclusive with `toggled` and `mixed`.
353 pub checked: Option<bool>,
354
355 /// If non-null, indicates that this subtree represents a checkbox
356 /// or similar widget with a "half-checked" state or similar, and
357 /// whether it is currently in this half-checked state.
358 ///
359 /// This must be null when `Checkbox.tristate` is false, or
360 /// when the widget is not a checkbox. When a tristate
361 /// checkbox is fully unchecked/checked, this value shall
362 /// be false.
363 ///
364 /// This is mutually exclusive with `checked` and `toggled`.
365 pub mixed: Option<bool>,
366
367 /// If non-null, indicates that this subtree represents something
368 /// that can be in an "expanded" or "collapsed" state.
369 ///
370 /// For example, if a `SubmenuButton` is opened, this property
371 /// should be set to true; otherwise, this property should be
372 /// false.
373 pub expanded: Option<bool>,
374
375 /// If non-null, indicates that this subtree represents a toggle switch
376 /// or similar widget with an "on" state, and what its current
377 /// state is.
378 ///
379 /// This is mutually exclusive with `checked` and `mixed`.
380 pub toggled: Option<bool>,
381
382 /// If non-null indicates that this subtree represents something that can be
383 /// in a selected or unselected state, and what its current state is.
384 ///
385 /// The active tab in a tab bar for example is considered "selected", whereas
386 /// all other tabs are unselected.
387 pub selected: Option<bool>,
388
389 /// If non-null, indicates that this subtree represents a button.
390 ///
391 /// TalkBack/VoiceOver provides users with the hint "button" when a button
392 /// is focused.
393 pub button: Option<bool>,
394
395 /// If non-null, indicates that this subtree represents a link.
396 ///
397 /// iOS's VoiceOver provides users with a unique hint when a link is focused.
398 /// Android's Talkback will announce a link hint the same way it does a
399 /// button.
400 pub link: Option<bool>,
401
402 /// If non-null, indicates that this subtree represents a header.
403 ///
404 /// A header is typically the top element of a page or section, such as a
405 /// page title or app bar title.
406 pub header: Option<bool>,
407
408 /// If non-null, indicates that this subtree represents a text field.
409 ///
410 /// TalkBack/VoiceOver provide special affordances to enter text into a
411 /// text field.
412 pub text_field: Option<bool>,
413
414 /// If non-null, indicates that this subtree represents a slider.
415 ///
416 /// Talkback/\VoiceOver provides users with the hint "slider" when a
417 /// slider is focused.
418 pub slider: Option<bool>,
419
420 /// If non-null, indicates that this subtree represents a keyboard key.
421 pub keyboard_key: Option<bool>,
422
423 /// If non-null, indicates that this subtree is read only.
424 ///
425 /// Only applicable when `textField` is true.
426 ///
427 /// TalkBack/VoiceOver will treat it as non-editable text field.
428 pub read_only: Option<bool>,
429
430 /// If non-null, whether the node is able to hold input focus.
431 ///
432 /// If `focusable` is set to false, then `focused` must not be true.
433 ///
434 /// Input focus indicates that the node will receive keyboard events. It is not
435 /// to be confused with accessibility focus. Accessibility focus is the
436 /// green/black rectangular highlight that TalkBack/VoiceOver draws around the
437 /// element it is reading, and is separate from input focus.
438 ///
439 /// Deprecated: use `focused` instead; setting `focused` automatically sets `focusable`.
440 pub focusable: Option<bool>,
441
442 /// If non-null, whether the node currently holds input focus.
443 ///
444 /// If null, the node is not focusable.
445 ///
446 /// At most one node in the tree should hold input focus at any point in time,
447 /// and it should not be set to true if `focusable` is false.
448 ///
449 /// Input focus indicates that the node will receive keyboard events. It is not
450 /// to be confused with accessibility focus. Accessibility focus is the
451 /// green/black rectangular highlight that TalkBack/VoiceOver draws around the
452 /// element it is reading, and is separate from input focus.
453 pub focused: Option<bool>,
454
455 /// If non-null, indicates if this subtree or current node is blocked in a11y focus.
456 ///
457 /// This is for accessibility focus, which is the focus used by screen readers
458 /// like TalkBack and VoiceOver. It is different from input focus, which is
459 /// usually held by the element that currently responds to keyboard inputs.
460 pub accessibility_focus_block_type: Option<AccessibilityFocusBlockType>,
461
462 /// If non-null, whether a semantic node is in a mutually exclusive group.
463 ///
464 /// For example, a radio button is in a mutually exclusive group because only
465 /// one radio button in that group can be marked as `checked`.
466 pub in_mutually_exclusive_group: Option<bool>,
467
468 /// If non-null, whether the node is considered hidden.
469 ///
470 /// Hidden elements are currently not visible on screen. They may be covered
471 /// by other elements or positioned outside of the visible area of a viewport.
472 ///
473 /// Hidden elements cannot gain accessibility focus though regular touch. The
474 /// only way they can be focused is by moving the focus to them via linear
475 /// navigation.
476 ///
477 /// Platforms are free to completely ignore hidden elements and new platforms
478 /// are encouraged to do so.
479 ///
480 /// Instead of marking an element as hidden it should usually be excluded from
481 /// the semantics tree altogether. Hidden elements are only included in the
482 /// semantics tree to work around platform limitations and they are mainly
483 /// used to implement accessibility scrolling on iOS.
484 pub hidden: Option<bool>,
485
486 /// If non-null, whether `value` should be obscured.
487 ///
488 /// This option is usually set in combination with `textField` to indicate
489 /// that the text field contains a password (or other sensitive information).
490 /// Doing so instructs screen readers to not read out the `value`.
491 pub obscured: Option<bool>,
492
493 /// Whether the `value` is coming from a field that supports multiline text
494 /// editing.
495 ///
496 /// This option is only meaningful when `textField` is true to indicate
497 /// whether it's a single-line or multiline text field.
498 ///
499 /// This option is null when `textField` is false.
500 pub multiline: Option<bool>,
501
502 /// If non-null, whether the node corresponds to the root of a subtree for
503 /// which a route name should be announced.
504 ///
505 /// Generally, this is set in combination with
506 /// `SemanticsConfiguration.explicitChildNodes`, since nodes with this flag
507 /// are not considered focusable by Android or iOS.
508 pub scopes_route: Option<bool>,
509
510 /// If non-null, whether the node contains the semantic label for a route.
511 pub names_route: Option<bool>,
512
513 /// If non-null, whether the node represents an image.
514 pub image: Option<bool>,
515
516 /// If non-null, whether the node should be considered a live region.
517 ///
518 /// A live region indicates that updates to semantics node are important.
519 /// Platforms may use this information to make polite announcements to the
520 /// user to inform them of updates to this node.
521 ///
522 /// An example of a live region is a `SnackBar` widget. On Android and iOS,
523 /// live region causes a polite announcement to be generated automatically,
524 /// even if the widget does not have accessibility focus. This announcement
525 /// may not be spoken if the OS accessibility services are already
526 /// announcing something else, such as reading the label of a focused widget
527 /// or providing a system announcement.
528 pub live_region: Option<bool>,
529
530 /// If non-null, whether the node should be considered required.
531 ///
532 /// If true, user input is required on the semantics node before a form can
533 /// be submitted. If false, the node is optional before a form can be
534 /// submitted. If null, the node does not have a required semantics.
535 ///
536 /// For example, a login form requires its email text field to be non-empty.
537 ///
538 /// On web, this will set a `aria-required` attribute on the DOM element
539 /// that corresponds to the semantics node.
540 pub is_required: Option<bool>,
541
542 /// The maximum number of characters that can be entered into an editable
543 /// text field.
544 ///
545 /// For the purpose of this function a character is defined as one Unicode
546 /// scalar value.
547 ///
548 /// This should only be set when `textField` is true. Defaults to null,
549 /// which means no limit is imposed on the text field.
550 pub max_value_length: Option<i32>,
551
552 /// The current number of characters that have been entered into an editable
553 /// text field.
554 ///
555 /// For the purpose of this function a character is defined as one Unicode
556 /// scalar value.
557 ///
558 /// This should only be set when `textField` is true. Must be set when
559 /// `maxValueLength` is set.
560 pub current_value_length: Option<i32>,
561
562 /// Provides an identifier for the semantics node in native accessibility hierarchy.
563 ///
564 /// This value is not exposed to the users of the app.
565 ///
566 /// It's usually used for UI testing with tools that work by querying the
567 /// native accessibility, like UIAutomator, XCUITest, or Appium. It can be
568 /// matched with `CommonFinders.bySemanticsIdentifier`.
569 ///
570 /// When set, this property implicitly forces the creation of a new
571 /// `SemanticsNode` (equivalent to setting `container` to true in
572 /// `Semantics`). This ensures the identifier is always attached to its
573 /// own node and is not merged into an ancestor.
574 ///
575 /// On Android, this is used for `AccessibilityNodeInfo.setViewIdResourceName`.
576 /// It'll be appear in accessibility hierarchy as `resource-id`.
577 ///
578 /// On iOS, this will set `UIAccessibilityElement.accessibilityIdentifier`.
579 ///
580 /// On web, this will set a `flt-semantics-identifier` attribute on the DOM element
581 /// that corresponds to the semantics node.
582 pub identifier: Option<String>,
583
584 /// Provides an identifier for establishing parent-child relationships in the semantics
585 /// traversal tree.
586 ///
587 /// This property is used to create a logical parent-child relationship between
588 /// semantics nodes that may not be directly connected in the widget tree. It's
589 /// primarily used with `OverlayPortal` to ensure proper accessibility traversal
590 /// order when overlay content needs to be semantically connected to its parent
591 /// widget.
592 ///
593 /// When a semantics node has a `traversalParentIdentifier`, it indicates that
594 /// this node can act as a parent for other nodes that reference this identifier
595 /// in their `traversalChildIdentifier`. This allows assistive technologies
596 /// to navigate the UI in the correct logical order.
597 ///
598 /// The `traversalParentIdentifier` must be unique in the semantics. No two
599 /// semantics node can have the same `traversalParentIdentifier`. This unique
600 /// identifier serves as the only reference for its traversal children. To
601 /// graft other nodes as the traversal children of this node, assign this same
602 /// value to their `traversalChildIdentifier`.
603 pub traversal_parent_identifier: Option<Rc<dyn Any>>,
604
605 /// Provides an identifier for establishing parent-child relationships in the semantics
606 /// traversal tree.
607 ///
608 /// This property is used to create a logical parent-child relationship between
609 /// semantics nodes that may not be directly connected in the widget tree. It's
610 /// primarily used with `OverlayPortal` to ensure proper accessibility traversal
611 /// order when overlay content needs to be semantically connected to its parent
612 /// widget.
613 ///
614 /// When a semantics node has a `traversalChildIdentifier`, it indicates that
615 /// this node should be treated as a child of another node that has this same
616 /// identifier as its `traversalParentIdentifier`. This allows assistive technologies
617 /// to navigate the UI in the correct logical order.
618 ///
619 /// The `traversalChildIdentifier` value may be duplicated across multiple
620 /// semantics nodes. To establish one or more nodes as the traversal children
621 /// of a parent node, assign this identifier the same value as the parent's
622 /// `traversalParentIdentifier`.
623 pub traversal_child_identifier: Option<Rc<dyn Any>>,
624
625 /// Provides a textual description of the widget.
626 ///
627 /// If a label is provided, there must either by an ambient `Directionality`
628 /// or an explicit `textDirection` should be provided.
629 ///
630 /// Callers must not provide both `label` and `attributedLabel`. One or both
631 /// must be null.
632 pub label: Option<String>,
633
634 /// Provides an `AttributedString` version of textual description of the widget.
635 ///
636 /// If a `attributedLabel` is provided, there must either by an ambient
637 /// `Directionality` or an explicit `textDirection` should be provided.
638 ///
639 /// Callers must not provide both `label` and `attributedLabel`. One or both
640 /// must be null.
641 pub attributed_label: Option<AttributedString>,
642
643 /// Provides a textual description of the value of the widget.
644 ///
645 /// If a value is provided, there must either by an ambient `Directionality`
646 /// or an explicit `textDirection` should be provided.
647 ///
648 /// Callers must not provide both `value` and `attributedValue`, One or both
649 /// must be null.
650 pub value: Option<String>,
651
652 /// Provides an `AttributedString` version of textual description of the value
653 /// of the widget.
654 ///
655 /// If a `attributedValue` is provided, there must either by an ambient
656 /// `Directionality` or an explicit `textDirection` should be provided.
657 ///
658 /// Callers must not provide both `value` and `attributedValue`, One or both
659 /// must be null.
660 pub attributed_value: Option<AttributedString>,
661
662 /// The value that `value` or `attributedValue` will become after a
663 /// `SemanticsAction.increase` action has been performed on this widget.
664 ///
665 /// If a value is provided, `onIncrease` must also be set and there must
666 /// either be an ambient `Directionality` or an explicit `textDirection`
667 /// must be provided.
668 ///
669 /// Callers must not provide both `increasedValue` and
670 /// `attributedIncreasedValue`, One or both must be null.
671 pub increased_value: Option<String>,
672
673 /// The `AttributedString` that `value` or `attributedValue` will become after
674 /// a `SemanticsAction.increase` action has been performed on this widget.
675 ///
676 /// If a `attributedIncreasedValue` is provided, `onIncrease` must also be set
677 /// and there must either be an ambient `Directionality` or an explicit
678 /// `textDirection` must be provided.
679 ///
680 /// Callers must not provide both `increasedValue` and
681 /// `attributedIncreasedValue`, One or both must be null.
682 pub attributed_increased_value: Option<AttributedString>,
683
684 /// The value that `value` or `attributedValue` will become after a
685 /// `SemanticsAction.decrease` action has been performed on this widget.
686 ///
687 /// If a value is provided, `onDecrease` must also be set and there must
688 /// either be an ambient `Directionality` or an explicit `textDirection`
689 /// must be provided.
690 ///
691 /// Callers must not provide both `decreasedValue` and
692 /// `attributedDecreasedValue`, One or both must be null.
693 pub decreased_value: Option<String>,
694
695 /// The `AttributedString` that `value` or `attributedValue` will become after
696 /// a `SemanticsAction.decrease` action has been performed on this widget.
697 ///
698 /// If a `attributedDecreasedValue` is provided, `onDecrease` must also be set
699 /// and there must either be an ambient `Directionality` or an explicit
700 /// `textDirection` must be provided.
701 ///
702 /// Callers must not provide both `decreasedValue` and
703 /// `attributedDecreasedValue`, One or both must be null/// provided.
704 pub attributed_decreased_value: Option<AttributedString>,
705
706 /// Provides a brief textual description of the result of an action performed
707 /// on the widget.
708 ///
709 /// If a hint is provided, there must either be an ambient `Directionality`
710 /// or an explicit `textDirection` should be provided.
711 ///
712 /// Callers must not provide both `hint` and `attributedHint`, One or both
713 /// must be null.
714 pub hint: Option<String>,
715
716 /// Provides an `AttributedString` version of brief textual description of the
717 /// result of an action performed on the widget.
718 ///
719 /// If a `attributedHint` is provided, there must either by an ambient
720 /// `Directionality` or an explicit `textDirection` should be provided.
721 ///
722 /// Callers must not provide both `hint` and `attributedHint`, One or both
723 /// must be null.
724 pub attributed_hint: Option<AttributedString>,
725
726 /// Provides a textual description of the widget's tooltip.
727 ///
728 /// In Android, this property sets the `AccessibilityNodeInfo.setTooltipText`.
729 /// In iOS, this property is appended to the end of the
730 /// `UIAccessibilityElement.accessibilityLabel`.
731 ///
732 /// If a `tooltip` is provided, there must either by an ambient
733 /// `Directionality` or an explicit `textDirection` should be provided.
734 pub tooltip: Option<String>,
735
736 /// The heading level in the document structure.
737 ///
738 /// A heading divides content into sections. For example, an address book
739 /// application might define headings A, B, C, etc. to divide the list of
740 /// alphabetically sorted contacts into sections.
741 ///
742 /// Screen readers use this value to determine which part of the page
743 /// structure this heading represents. A level 1 heading usually indicates
744 /// the main heading of a page, a level 2 heading the first subsection,
745 /// a level 3 is a subsection of that, and so on.
746 ///
747 /// On web, this sets the `aria-level` attribute (e.g., `aria-level="1"`).
748 /// On Android, this sets the `isHeading` property for accessibility.
749 pub heading_level: Option<i32>,
750
751 /// Overrides the default accessibility hints provided by the platform.
752 ///
753 /// This `hintOverrides` property does not affect how the platform processes hints;
754 /// it only sets the custom text that will be read by assistive technology.
755 ///
756 /// On Android, these overrides replace the default hints for semantics nodes
757 /// with tap or long-press actions. For example, if `SemanticsHintOverrides.onTapHint`
758 /// is provided, instead of saying `Double tap to activate`, the screen reader
759 /// will say `Double tap to <onTapHint>`.
760 ///
761 /// On iOS, this property is ignored, and default platform behavior applies.
762 ///
763 /// Example usage:
764 pub hint_overrides: Option<SemanticsHintOverrides>,
765
766 /// The reading direction of the `label`, `value`, `increasedValue`,
767 /// `decreasedValue`, and `hint`.
768 ///
769 /// Defaults to the ambient `Directionality`.
770 pub text_direction: Option<TextDirection>,
771
772 /// Determines the position of this node among its siblings in the traversal
773 /// sort order.
774 ///
775 /// This is used to describe the order in which the semantic node should be
776 /// traversed by the accessibility services on the platform (e.g. VoiceOver
777 /// on iOS and TalkBack on Android).
778 pub sort_key: Option<SemanticsSortKeyRef>,
779
780 /// A tag to be applied to the child `SemanticsNode`s of this widget.
781 ///
782 /// The tag is added to all child `SemanticsNode`s that pass through the
783 /// `RenderObject` corresponding to this widget while looking to be attached
784 /// to a parent SemanticsNode.
785 ///
786 /// Tags are used to communicate to a parent SemanticsNode that a child
787 /// SemanticsNode was passed through a particular RenderObject. The parent can
788 /// use this information to determine the shape of the semantics tree.
789 pub tag_for_children: Option<Rc<SemanticsTag>>,
790
791 /// The URL that this node links to.
792 ///
793 /// On the web, this is used to set the `href` attribute of the DOM element.
794 pub link_url: Option<String>,
795
796 /// The handler for `SemanticsAction.tap`.
797 ///
798 /// This is the semantic equivalent of a user briefly tapping the screen with
799 /// the finger without moving it. For example, a button should implement this
800 /// action.
801 ///
802 /// VoiceOver users on iOS and TalkBack users on Android *may* trigger this
803 /// action by double-tapping the screen while an element is focused.
804 ///
805 /// Note: different OSes or assistive technologies may decide to interpret
806 /// user inputs differently. Some may simulate real screen taps, while others
807 /// may call semantics tap. One way to handle taps properly is to provide the
808 /// same handler to both gesture tap and semantics tap.
809 pub on_tap: Option<VoidCallback>,
810
811 /// The handler for `SemanticsAction.longPress`.
812 ///
813 /// This is the semantic equivalent of a user pressing and holding the screen
814 /// with the finger for a few seconds without moving it.
815 ///
816 /// VoiceOver users on iOS and TalkBack users on Android *may* trigger this
817 /// action by double-tapping the screen without lifting the finger after the
818 /// second tap.
819 ///
820 /// Note: different OSes or assistive technologies may decide to interpret
821 /// user inputs differently. Some may simulate real long presses, while others
822 /// may call semantics long press. One way to handle long press properly is to
823 /// provide the same handler to both gesture long press and semantics long
824 /// press.
825 pub on_long_press: Option<VoidCallback>,
826
827 /// The handler for `SemanticsAction.scrollLeft`.
828 ///
829 /// This is the semantic equivalent of a user moving their finger across the
830 /// screen from right to left. It should be recognized by controls that are
831 /// horizontally scrollable.
832 ///
833 /// VoiceOver users on iOS can trigger this action by swiping left with three
834 /// fingers. TalkBack users on Android can trigger this action by swiping
835 /// right and then left in one motion path. On Android, `onScrollUp` and
836 /// `onScrollLeft` share the same gesture. Therefore, only on of them should
837 /// be provided.
838 pub on_scroll_left: Option<VoidCallback>,
839
840 /// The handler for `SemanticsAction.scrollRight`.
841 ///
842 /// This is the semantic equivalent of a user moving their finger across the
843 /// screen from left to right. It should be recognized by controls that are
844 /// horizontally scrollable.
845 ///
846 /// VoiceOver users on iOS can trigger this action by swiping right with three
847 /// fingers. TalkBack users on Android can trigger this action by swiping
848 /// left and then right in one motion path. On Android, `onScrollDown` and
849 /// `onScrollRight` share the same gesture. Therefore, only on of them should
850 /// be provided.
851 pub on_scroll_right: Option<VoidCallback>,
852
853 /// The handler for `SemanticsAction.scrollUp`.
854 ///
855 /// This is the semantic equivalent of a user moving their finger across the
856 /// screen from bottom to top. It should be recognized by controls that are
857 /// vertically scrollable.
858 ///
859 /// VoiceOver users on iOS can trigger this action by swiping up with three
860 /// fingers. TalkBack users on Android can trigger this action by swiping
861 /// right and then left in one motion path. On Android, `onScrollUp` and
862 /// `onScrollLeft` share the same gesture. Therefore, only on of them should
863 /// be provided.
864 pub on_scroll_up: Option<VoidCallback>,
865
866 /// The handler for `SemanticsAction.scrollDown`.
867 ///
868 /// This is the semantic equivalent of a user moving their finger across the
869 /// screen from top to bottom. It should be recognized by controls that are
870 /// vertically scrollable.
871 ///
872 /// VoiceOver users on iOS can trigger this action by swiping down with three
873 /// fingers. TalkBack users on Android can trigger this action by swiping
874 /// left and then right in one motion path. On Android, `onScrollDown` and
875 /// `onScrollRight` share the same gesture. Therefore, only on of them should
876 /// be provided.
877 pub on_scroll_down: Option<VoidCallback>,
878
879 /// The handler for `SemanticsAction.increase`.
880 ///
881 /// This is a request to increase the value represented by the widget. For
882 /// example, this action might be recognized by a slider control.
883 ///
884 /// If a `value` is set, `increasedValue` must also be provided and
885 /// `onIncrease` must ensure that `value` will be set to `increasedValue`.
886 ///
887 /// VoiceOver users on iOS can trigger this action by swiping up with one
888 /// finger. TalkBack users on Android can trigger this action by pressing the
889 /// volume up button.
890 pub on_increase: Option<VoidCallback>,
891
892 /// The handler for `SemanticsAction.decrease`.
893 ///
894 /// This is a request to decrease the value represented by the widget. For
895 /// example, this action might be recognized by a slider control.
896 ///
897 /// If a `value` is set, `decreasedValue` must also be provided and
898 /// `onDecrease` must ensure that `value` will be set to `decreasedValue`.
899 ///
900 /// VoiceOver users on iOS can trigger this action by swiping down with one
901 /// finger. TalkBack users on Android can trigger this action by pressing the
902 /// volume down button.
903 pub on_decrease: Option<VoidCallback>,
904
905 /// The handler for `SemanticsAction.copy`.
906 ///
907 /// This is a request to copy the current selection to the clipboard.
908 ///
909 /// TalkBack users on Android can trigger this action from the local context
910 /// menu of a text field, for example.
911 pub on_copy: Option<VoidCallback>,
912
913 /// The handler for `SemanticsAction.cut`.
914 ///
915 /// This is a request to cut the current selection and place it in the
916 /// clipboard.
917 ///
918 /// TalkBack users on Android can trigger this action from the local context
919 /// menu of a text field, for example.
920 pub on_cut: Option<VoidCallback>,
921
922 /// The handler for `SemanticsAction.paste`.
923 ///
924 /// This is a request to paste the current content of the clipboard.
925 ///
926 /// TalkBack users on Android can trigger this action from the local context
927 /// menu of a text field, for example.
928 pub on_paste: Option<VoidCallback>,
929
930 /// The handler for `SemanticsAction.moveCursorForwardByCharacter`.
931 ///
932 /// This handler is invoked when the user wants to move the cursor in a
933 /// text field forward by one character.
934 ///
935 /// TalkBack users can trigger this by pressing the volume up key while the
936 /// input focus is in a text field.
937 pub on_move_cursor_forward_by_character: Option<MoveCursorHandler>,
938
939 /// The handler for `SemanticsAction.moveCursorBackwardByCharacter`.
940 ///
941 /// This handler is invoked when the user wants to move the cursor in a
942 /// text field backward by one character.
943 ///
944 /// TalkBack users can trigger this by pressing the volume down key while the
945 /// input focus is in a text field.
946 pub on_move_cursor_backward_by_character: Option<MoveCursorHandler>,
947
948 /// The handler for `SemanticsAction.moveCursorForwardByWord`.
949 ///
950 /// This handler is invoked when the user wants to move the cursor in a
951 /// text field backward by one word.
952 ///
953 /// TalkBack users can trigger this by pressing the volume down key while the
954 /// input focus is in a text field.
955 pub on_move_cursor_forward_by_word: Option<MoveCursorHandler>,
956
957 /// The handler for `SemanticsAction.moveCursorBackwardByWord`.
958 ///
959 /// This handler is invoked when the user wants to move the cursor in a
960 /// text field backward by one word.
961 ///
962 /// TalkBack users can trigger this by pressing the volume down key while the
963 /// input focus is in a text field.
964 pub on_move_cursor_backward_by_word: Option<MoveCursorHandler>,
965
966 /// The handler for `SemanticsAction.setSelection`.
967 ///
968 /// This handler is invoked when the user either wants to change the currently
969 /// selected text in a text field or change the position of the cursor.
970 ///
971 /// TalkBack users can trigger this handler by selecting "Move cursor to
972 /// beginning/end" or "Select all" from the local context menu.
973 pub on_set_selection: Option<SetSelectionHandler>,
974
975 /// The handler for `SemanticsAction.setText`.
976 ///
977 /// This handler is invoked when the user wants to replace the current text in
978 /// the text field with a new text.
979 ///
980 /// Voice access users can trigger this handler by speaking `type <text>` to
981 /// their Android devices.
982 pub on_set_text: Option<SetTextHandler>,
983
984 /// The handler for `SemanticsAction.didGainAccessibilityFocus`.
985 ///
986 /// This handler is invoked when the node annotated with this handler gains
987 /// the accessibility focus. The accessibility focus is the
988 /// green (on Android with TalkBack) or black (on iOS with VoiceOver)
989 /// rectangle shown on screen to indicate what element an accessibility
990 /// user is currently interacting with.
991 ///
992 /// The accessibility focus is different from the input focus. The input focus
993 /// is usually held by the element that currently responds to keyboard inputs.
994 /// Accessibility focus and input focus can be held by two different nodes!
995 pub on_did_gain_accessibility_focus: Option<VoidCallback>,
996
997 /// The handler for `SemanticsAction.didLoseAccessibilityFocus`.
998 ///
999 /// This handler is invoked when the node annotated with this handler
1000 /// loses the accessibility focus. The accessibility focus is
1001 /// the green (on Android with TalkBack) or black (on iOS with VoiceOver)
1002 /// rectangle shown on screen to indicate what element an accessibility
1003 /// user is currently interacting with.
1004 ///
1005 /// The accessibility focus is different from the input focus. The input focus
1006 /// is usually held by the element that currently responds to keyboard inputs.
1007 /// Accessibility focus and input focus can be held by two different nodes!
1008 pub on_did_lose_accessibility_focus: Option<VoidCallback>,
1009
1010 /// The handler for `SemanticsAction.focus`.
1011 ///
1012 /// This handler is invoked when the assistive technology requests that the
1013 /// focusable widget corresponding to this semantics node gain input focus.
1014 /// The `FocusNode` that manages the focus of the widget must gain focus. The
1015 /// widget must begin responding to relevant key events. For example:
1016 ///
1017 /// * Buttons must respond to tap/click events produced via keyboard shortcuts.
1018 /// * Text fields must become focused and editable, showing an on-screen
1019 /// keyboard, if necessary.
1020 /// * Checkboxes, switches, and radio buttons must become toggleable using
1021 /// keyboard shortcuts.
1022 ///
1023 /// Focus behavior is specific to the platform and to the assistive technology
1024 /// used. See the documentation of `SemanticsAction.focus` for more detail.
1025 pub on_focus: Option<VoidCallback>,
1026
1027 /// The handler for `SemanticsAction.dismiss`.
1028 ///
1029 /// This is a request to dismiss the currently focused node.
1030 ///
1031 /// TalkBack users on Android can trigger this action in the local context
1032 /// menu, and VoiceOver users on iOS can trigger this action with a standard
1033 /// gesture or menu option.
1034 pub on_dismiss: Option<VoidCallback>,
1035
1036 /// The handler for `SemanticsAction.expand`.
1037 ///
1038 /// This is a request to expand the currently focused node. For example, this
1039 /// action might be recognized by a dropdown.
1040 ///
1041 /// This handler should only be set when the node is in a collapsed state
1042 /// (i.e., `expanded` is false).
1043 pub on_expand: Option<VoidCallback>,
1044
1045 /// The handler for `SemanticsAction.collapse`.
1046 ///
1047 /// This is a request to collapse the currently focused node. For example,
1048 /// this action might be recognized by a dropdown.
1049 ///
1050 /// This handler should only be set when the node is in an expanded state
1051 /// (i.e., `expanded` is true).
1052 pub on_collapse: Option<VoidCallback>,
1053
1054 /// A map from each supported `CustomSemanticsAction` to a provided handler.
1055 ///
1056 /// The handler associated with each custom action is called whenever a
1057 /// semantics action of type `SemanticsAction.customAction` is received. The
1058 /// provided argument will be an identifier used to retrieve an instance of
1059 /// a custom action which can then retrieve the correct handler from this map.
1060 pub custom_semantics_actions: Option<IndexMap<CustomSemanticsAction, VoidCallback>>,
1061
1062 /// A enum to describe what role the subtree represents.
1063 ///
1064 /// Setting the role for a widget subtree helps assistive technologies, such
1065 /// as screen readers, to understand and interact with the UI correctly.
1066 ///
1067 /// Defaults to `SemanticsRole.none` if not set, which means the subtree does
1068 /// not represent any complex ui or controls.
1069 ///
1070 /// For a list of available roles, see `SemanticsRole`.
1071 pub role: Option<SemanticsRole>,
1072
1073 /// The `SemanticsNode.identifier`s of widgets controlled by this subtree.
1074 ///
1075 /// If a widget is controlling the visibility or content of another widget,
1076 /// for example, `Tab`s control child visibilities of `TabBarView` or
1077 /// `ExpansionTile` controls visibility of its expanded content, one must
1078 /// assign a `SemanticsNode.identifier` to the content and also provide a set
1079 /// of identifiers including the content's identifier to this property.
1080 pub controls_nodes: Option<IndexSet<String>>,
1081
1082 /// Describes the validation result for a form field represented by this
1083 /// widget.
1084 ///
1085 /// Providing a validation result helps assistive technologies, such as screen
1086 /// readers, to communicate to the user whether they provided correct
1087 /// information in a form.
1088 ///
1089 /// Defaults to `SemanticsValidationResult.none` if not set, which means no
1090 /// validation information is available for the respective semantics node.
1091 ///
1092 /// For a list of available validation results, see `SemanticsValidationResult`.
1093 pub validation_result: SemanticsValidationResult,
1094
1095 /// Describes how the semantic node should behave during hit testing.
1096 ///
1097 /// See `ui.SemanticsHitTestBehavior` for more details.
1098 pub hit_test_behavior: Option<SemanticsHitTestBehavior>,
1099
1100 /// The input type for of a editable widget.
1101 ///
1102 /// This property is only used when the subtree represents a text field.
1103 ///
1104 /// Assistive technologies use this property to provide better information to
1105 /// users. For example, screen reader reads out the input type of text field
1106 /// when focused.
1107 pub input_type: Option<SemanticsInputType>,
1108
1109 /// The maximum value of the node.
1110 ///
1111 /// Used in conjunction with `value` to define the current value and range
1112 /// of a node. A typical usage is for progress indicators, where `value`
1113 /// represents the current progress and `maxValue` defines the maximum
1114 /// possible value.
1115 pub max_value: Option<String>,
1116
1117 /// The minimum value of the node.
1118 ///
1119 /// Used in conjunction with `value` to define the current value and range
1120 /// of a node. A typical usage is for progress indicators, where `value`
1121 /// represents the current progress and `minValue` defines the minimum
1122 /// possible value.
1123 pub min_value: Option<String>,
1124}
1125
1126impl SemanticsProperties {
1127 /// Creates a semantic annotation.
1128 pub fn new() -> SemanticsProperties {
1129 SemanticsProperties::default()
1130 }
1131
1132 /// Dart `SemanticsProperties(enabled:)`.
1133 pub fn enabled(mut self, enabled: bool) -> SemanticsProperties {
1134 self.enabled = Some(enabled);
1135 self
1136 }
1137
1138 /// Dart `SemanticsProperties(checked:)`.
1139 pub fn checked(mut self, checked: bool) -> SemanticsProperties {
1140 self.checked = Some(checked);
1141 self
1142 }
1143
1144 /// Dart `SemanticsProperties(mixed:)`.
1145 pub fn mixed(mut self, mixed: bool) -> SemanticsProperties {
1146 self.mixed = Some(mixed);
1147 self
1148 }
1149
1150 /// Dart `SemanticsProperties(expanded:)`.
1151 pub fn expanded(mut self, expanded: bool) -> SemanticsProperties {
1152 self.expanded = Some(expanded);
1153 self
1154 }
1155
1156 /// Dart `SemanticsProperties(toggled:)`.
1157 pub fn toggled(mut self, toggled: bool) -> SemanticsProperties {
1158 self.toggled = Some(toggled);
1159 self
1160 }
1161
1162 /// Dart `SemanticsProperties(selected:)`.
1163 pub fn selected(mut self, selected: bool) -> SemanticsProperties {
1164 self.selected = Some(selected);
1165 self
1166 }
1167
1168 /// Dart `SemanticsProperties(button:)`.
1169 pub fn button(mut self, button: bool) -> SemanticsProperties {
1170 self.button = Some(button);
1171 self
1172 }
1173
1174 /// Dart `SemanticsProperties(link:)`.
1175 pub fn link(mut self, link: bool) -> SemanticsProperties {
1176 self.link = Some(link);
1177 self
1178 }
1179
1180 /// Dart `SemanticsProperties(header:)`.
1181 pub fn header(mut self, header: bool) -> SemanticsProperties {
1182 self.header = Some(header);
1183 self
1184 }
1185
1186 /// Dart `SemanticsProperties(textField:)`.
1187 pub fn text_field(mut self, text_field: bool) -> SemanticsProperties {
1188 self.text_field = Some(text_field);
1189 self
1190 }
1191
1192 /// Dart `SemanticsProperties(slider:)`.
1193 pub fn slider(mut self, slider: bool) -> SemanticsProperties {
1194 self.slider = Some(slider);
1195 self
1196 }
1197
1198 /// Dart `SemanticsProperties(keyboardKey:)`.
1199 pub fn keyboard_key(mut self, keyboard_key: bool) -> SemanticsProperties {
1200 self.keyboard_key = Some(keyboard_key);
1201 self
1202 }
1203
1204 /// Dart `SemanticsProperties(readOnly:)`.
1205 pub fn read_only(mut self, read_only: bool) -> SemanticsProperties {
1206 self.read_only = Some(read_only);
1207 self
1208 }
1209
1210 /// Dart `SemanticsProperties(focusable:)`.
1211 pub fn focusable(mut self, focusable: bool) -> SemanticsProperties {
1212 self.focusable = Some(focusable);
1213 self
1214 }
1215
1216 /// Dart `SemanticsProperties(focused:)`.
1217 pub fn focused(mut self, focused: bool) -> SemanticsProperties {
1218 self.focused = Some(focused);
1219 self
1220 }
1221
1222 /// Dart `SemanticsProperties(accessibilityFocusBlockType:)`.
1223 pub fn accessibility_focus_block_type(
1224 mut self,
1225 accessibility_focus_block_type: AccessibilityFocusBlockType,
1226 ) -> SemanticsProperties {
1227 self.accessibility_focus_block_type = Some(accessibility_focus_block_type);
1228 self
1229 }
1230
1231 /// Dart `SemanticsProperties(inMutuallyExclusiveGroup:)`.
1232 pub fn in_mutually_exclusive_group(
1233 mut self,
1234 in_mutually_exclusive_group: bool,
1235 ) -> SemanticsProperties {
1236 self.in_mutually_exclusive_group = Some(in_mutually_exclusive_group);
1237 self
1238 }
1239
1240 /// Dart `SemanticsProperties(hidden:)`.
1241 pub fn hidden(mut self, hidden: bool) -> SemanticsProperties {
1242 self.hidden = Some(hidden);
1243 self
1244 }
1245
1246 /// Dart `SemanticsProperties(obscured:)`.
1247 pub fn obscured(mut self, obscured: bool) -> SemanticsProperties {
1248 self.obscured = Some(obscured);
1249 self
1250 }
1251
1252 /// Dart `SemanticsProperties(multiline:)`.
1253 pub fn multiline(mut self, multiline: bool) -> SemanticsProperties {
1254 self.multiline = Some(multiline);
1255 self
1256 }
1257
1258 /// Dart `SemanticsProperties(scopesRoute:)`.
1259 pub fn scopes_route(mut self, scopes_route: bool) -> SemanticsProperties {
1260 self.scopes_route = Some(scopes_route);
1261 self
1262 }
1263
1264 /// Dart `SemanticsProperties(namesRoute:)`.
1265 pub fn names_route(mut self, names_route: bool) -> SemanticsProperties {
1266 self.names_route = Some(names_route);
1267 self
1268 }
1269
1270 /// Dart `SemanticsProperties(image:)`.
1271 pub fn image(mut self, image: bool) -> SemanticsProperties {
1272 self.image = Some(image);
1273 self
1274 }
1275
1276 /// Dart `SemanticsProperties(liveRegion:)`.
1277 pub fn live_region(mut self, live_region: bool) -> SemanticsProperties {
1278 self.live_region = Some(live_region);
1279 self
1280 }
1281
1282 /// Dart `SemanticsProperties(isRequired:)`.
1283 pub fn is_required(mut self, is_required: bool) -> SemanticsProperties {
1284 self.is_required = Some(is_required);
1285 self
1286 }
1287
1288 /// Dart `SemanticsProperties(maxValueLength:)`.
1289 pub fn max_value_length(mut self, max_value_length: i32) -> SemanticsProperties {
1290 self.max_value_length = Some(max_value_length);
1291 self
1292 }
1293
1294 /// Dart `SemanticsProperties(currentValueLength:)`.
1295 pub fn current_value_length(mut self, current_value_length: i32) -> SemanticsProperties {
1296 self.current_value_length = Some(current_value_length);
1297 self
1298 }
1299
1300 /// Dart `SemanticsProperties(identifier:)`.
1301 pub fn identifier(mut self, identifier: impl Into<String>) -> SemanticsProperties {
1302 self.identifier = Some(identifier.into());
1303 self
1304 }
1305
1306 /// Dart `SemanticsProperties(traversalParentIdentifier:)`.
1307 pub fn traversal_parent_identifier(
1308 mut self,
1309 traversal_parent_identifier: Rc<dyn Any>,
1310 ) -> SemanticsProperties {
1311 self.traversal_parent_identifier = Some(traversal_parent_identifier);
1312 self
1313 }
1314
1315 /// Dart `SemanticsProperties(traversalChildIdentifier:)`.
1316 pub fn traversal_child_identifier(
1317 mut self,
1318 traversal_child_identifier: Rc<dyn Any>,
1319 ) -> SemanticsProperties {
1320 self.traversal_child_identifier = Some(traversal_child_identifier);
1321 self
1322 }
1323
1324 /// Dart `SemanticsProperties(label:)`.
1325 pub fn label(mut self, label: impl Into<String>) -> SemanticsProperties {
1326 self.label = Some(label.into());
1327 self
1328 }
1329
1330 /// Dart `SemanticsProperties(attributedLabel:)`.
1331 pub fn attributed_label(mut self, attributed_label: AttributedString) -> SemanticsProperties {
1332 self.attributed_label = Some(attributed_label);
1333 self
1334 }
1335
1336 /// Dart `SemanticsProperties(value:)`.
1337 pub fn value(mut self, value: impl Into<String>) -> SemanticsProperties {
1338 self.value = Some(value.into());
1339 self
1340 }
1341
1342 /// Dart `SemanticsProperties(attributedValue:)`.
1343 pub fn attributed_value(mut self, attributed_value: AttributedString) -> SemanticsProperties {
1344 self.attributed_value = Some(attributed_value);
1345 self
1346 }
1347
1348 /// Dart `SemanticsProperties(increasedValue:)`.
1349 pub fn increased_value(mut self, increased_value: impl Into<String>) -> SemanticsProperties {
1350 self.increased_value = Some(increased_value.into());
1351 self
1352 }
1353
1354 /// Dart `SemanticsProperties(attributedIncreasedValue:)`.
1355 pub fn attributed_increased_value(
1356 mut self,
1357 attributed_increased_value: AttributedString,
1358 ) -> SemanticsProperties {
1359 self.attributed_increased_value = Some(attributed_increased_value);
1360 self
1361 }
1362
1363 /// Dart `SemanticsProperties(decreasedValue:)`.
1364 pub fn decreased_value(mut self, decreased_value: impl Into<String>) -> SemanticsProperties {
1365 self.decreased_value = Some(decreased_value.into());
1366 self
1367 }
1368
1369 /// Dart `SemanticsProperties(attributedDecreasedValue:)`.
1370 pub fn attributed_decreased_value(
1371 mut self,
1372 attributed_decreased_value: AttributedString,
1373 ) -> SemanticsProperties {
1374 self.attributed_decreased_value = Some(attributed_decreased_value);
1375 self
1376 }
1377
1378 /// Dart `SemanticsProperties(hint:)`.
1379 pub fn hint(mut self, hint: impl Into<String>) -> SemanticsProperties {
1380 self.hint = Some(hint.into());
1381 self
1382 }
1383
1384 /// Dart `SemanticsProperties(attributedHint:)`.
1385 pub fn attributed_hint(mut self, attributed_hint: AttributedString) -> SemanticsProperties {
1386 self.attributed_hint = Some(attributed_hint);
1387 self
1388 }
1389
1390 /// Dart `SemanticsProperties(tooltip:)`.
1391 pub fn tooltip(mut self, tooltip: impl Into<String>) -> SemanticsProperties {
1392 self.tooltip = Some(tooltip.into());
1393 self
1394 }
1395
1396 /// Dart `SemanticsProperties(headingLevel:)`.
1397 pub fn heading_level(mut self, heading_level: i32) -> SemanticsProperties {
1398 debug_assert!(
1399 heading_level > 0 && heading_level <= 6,
1400 "Heading level must be between 1 and 6"
1401 );
1402 self.heading_level = Some(heading_level);
1403 self
1404 }
1405
1406 /// Dart `SemanticsProperties(hintOverrides:)`.
1407 pub fn hint_overrides(mut self, hint_overrides: SemanticsHintOverrides) -> SemanticsProperties {
1408 self.hint_overrides = Some(hint_overrides);
1409 self
1410 }
1411
1412 /// Dart `SemanticsProperties(textDirection:)`.
1413 pub fn text_direction(mut self, text_direction: TextDirection) -> SemanticsProperties {
1414 self.text_direction = Some(text_direction);
1415 self
1416 }
1417
1418 /// Dart `SemanticsProperties(sortKey:)`.
1419 pub fn sort_key(mut self, sort_key: SemanticsSortKeyRef) -> SemanticsProperties {
1420 self.sort_key = Some(sort_key);
1421 self
1422 }
1423
1424 /// Dart `SemanticsProperties(tagForChildren:)`.
1425 pub fn tag_for_children(mut self, tag_for_children: Rc<SemanticsTag>) -> SemanticsProperties {
1426 self.tag_for_children = Some(tag_for_children);
1427 self
1428 }
1429
1430 /// Dart `SemanticsProperties(linkUrl:)`.
1431 pub fn link_url(mut self, link_url: impl Into<String>) -> SemanticsProperties {
1432 self.link_url = Some(link_url.into());
1433 self
1434 }
1435
1436 /// Dart `SemanticsProperties(onTap:)`.
1437 pub fn on_tap(mut self, on_tap: VoidCallback) -> SemanticsProperties {
1438 self.on_tap = Some(on_tap);
1439 self
1440 }
1441
1442 /// Dart `SemanticsProperties(onLongPress:)`.
1443 pub fn on_long_press(mut self, on_long_press: VoidCallback) -> SemanticsProperties {
1444 self.on_long_press = Some(on_long_press);
1445 self
1446 }
1447
1448 /// Dart `SemanticsProperties(onScrollLeft:)`.
1449 pub fn on_scroll_left(mut self, on_scroll_left: VoidCallback) -> SemanticsProperties {
1450 self.on_scroll_left = Some(on_scroll_left);
1451 self
1452 }
1453
1454 /// Dart `SemanticsProperties(onScrollRight:)`.
1455 pub fn on_scroll_right(mut self, on_scroll_right: VoidCallback) -> SemanticsProperties {
1456 self.on_scroll_right = Some(on_scroll_right);
1457 self
1458 }
1459
1460 /// Dart `SemanticsProperties(onScrollUp:)`.
1461 pub fn on_scroll_up(mut self, on_scroll_up: VoidCallback) -> SemanticsProperties {
1462 self.on_scroll_up = Some(on_scroll_up);
1463 self
1464 }
1465
1466 /// Dart `SemanticsProperties(onScrollDown:)`.
1467 pub fn on_scroll_down(mut self, on_scroll_down: VoidCallback) -> SemanticsProperties {
1468 self.on_scroll_down = Some(on_scroll_down);
1469 self
1470 }
1471
1472 /// Dart `SemanticsProperties(onIncrease:)`.
1473 pub fn on_increase(mut self, on_increase: VoidCallback) -> SemanticsProperties {
1474 self.on_increase = Some(on_increase);
1475 self
1476 }
1477
1478 /// Dart `SemanticsProperties(onDecrease:)`.
1479 pub fn on_decrease(mut self, on_decrease: VoidCallback) -> SemanticsProperties {
1480 self.on_decrease = Some(on_decrease);
1481 self
1482 }
1483
1484 /// Dart `SemanticsProperties(onCopy:)`.
1485 pub fn on_copy(mut self, on_copy: VoidCallback) -> SemanticsProperties {
1486 self.on_copy = Some(on_copy);
1487 self
1488 }
1489
1490 /// Dart `SemanticsProperties(onCut:)`.
1491 pub fn on_cut(mut self, on_cut: VoidCallback) -> SemanticsProperties {
1492 self.on_cut = Some(on_cut);
1493 self
1494 }
1495
1496 /// Dart `SemanticsProperties(onPaste:)`.
1497 pub fn on_paste(mut self, on_paste: VoidCallback) -> SemanticsProperties {
1498 self.on_paste = Some(on_paste);
1499 self
1500 }
1501
1502 /// Dart `SemanticsProperties(onMoveCursorForwardByCharacter:)`.
1503 pub fn on_move_cursor_forward_by_character(
1504 mut self,
1505 on_move_cursor_forward_by_character: MoveCursorHandler,
1506 ) -> SemanticsProperties {
1507 self.on_move_cursor_forward_by_character = Some(on_move_cursor_forward_by_character);
1508 self
1509 }
1510
1511 /// Dart `SemanticsProperties(onMoveCursorBackwardByCharacter:)`.
1512 pub fn on_move_cursor_backward_by_character(
1513 mut self,
1514 on_move_cursor_backward_by_character: MoveCursorHandler,
1515 ) -> SemanticsProperties {
1516 self.on_move_cursor_backward_by_character = Some(on_move_cursor_backward_by_character);
1517 self
1518 }
1519
1520 /// Dart `SemanticsProperties(onMoveCursorForwardByWord:)`.
1521 pub fn on_move_cursor_forward_by_word(
1522 mut self,
1523 on_move_cursor_forward_by_word: MoveCursorHandler,
1524 ) -> SemanticsProperties {
1525 self.on_move_cursor_forward_by_word = Some(on_move_cursor_forward_by_word);
1526 self
1527 }
1528
1529 /// Dart `SemanticsProperties(onMoveCursorBackwardByWord:)`.
1530 pub fn on_move_cursor_backward_by_word(
1531 mut self,
1532 on_move_cursor_backward_by_word: MoveCursorHandler,
1533 ) -> SemanticsProperties {
1534 self.on_move_cursor_backward_by_word = Some(on_move_cursor_backward_by_word);
1535 self
1536 }
1537
1538 /// Dart `SemanticsProperties(onSetSelection:)`.
1539 pub fn on_set_selection(
1540 mut self,
1541 on_set_selection: SetSelectionHandler,
1542 ) -> SemanticsProperties {
1543 self.on_set_selection = Some(on_set_selection);
1544 self
1545 }
1546
1547 /// Dart `SemanticsProperties(onSetText:)`.
1548 pub fn on_set_text(mut self, on_set_text: SetTextHandler) -> SemanticsProperties {
1549 self.on_set_text = Some(on_set_text);
1550 self
1551 }
1552
1553 /// Dart `SemanticsProperties(onDidGainAccessibilityFocus:)`.
1554 pub fn on_did_gain_accessibility_focus(
1555 mut self,
1556 on_did_gain_accessibility_focus: VoidCallback,
1557 ) -> SemanticsProperties {
1558 self.on_did_gain_accessibility_focus = Some(on_did_gain_accessibility_focus);
1559 self
1560 }
1561
1562 /// Dart `SemanticsProperties(onDidLoseAccessibilityFocus:)`.
1563 pub fn on_did_lose_accessibility_focus(
1564 mut self,
1565 on_did_lose_accessibility_focus: VoidCallback,
1566 ) -> SemanticsProperties {
1567 self.on_did_lose_accessibility_focus = Some(on_did_lose_accessibility_focus);
1568 self
1569 }
1570
1571 /// Dart `SemanticsProperties(onFocus:)`.
1572 pub fn on_focus(mut self, on_focus: VoidCallback) -> SemanticsProperties {
1573 self.on_focus = Some(on_focus);
1574 self
1575 }
1576
1577 /// Dart `SemanticsProperties(onDismiss:)`.
1578 pub fn on_dismiss(mut self, on_dismiss: VoidCallback) -> SemanticsProperties {
1579 self.on_dismiss = Some(on_dismiss);
1580 self
1581 }
1582
1583 /// Dart `SemanticsProperties(onExpand:)`.
1584 pub fn on_expand(mut self, on_expand: VoidCallback) -> SemanticsProperties {
1585 self.on_expand = Some(on_expand);
1586 self
1587 }
1588
1589 /// Dart `SemanticsProperties(onCollapse:)`.
1590 pub fn on_collapse(mut self, on_collapse: VoidCallback) -> SemanticsProperties {
1591 self.on_collapse = Some(on_collapse);
1592 self
1593 }
1594
1595 /// Dart `SemanticsProperties(customSemanticsActions:)`.
1596 pub fn custom_semantics_actions(
1597 mut self,
1598 custom_semantics_actions: IndexMap<CustomSemanticsAction, VoidCallback>,
1599 ) -> SemanticsProperties {
1600 self.custom_semantics_actions = Some(custom_semantics_actions);
1601 self
1602 }
1603
1604 /// Dart `SemanticsProperties(role:)`.
1605 pub fn role(mut self, role: SemanticsRole) -> SemanticsProperties {
1606 self.role = Some(role);
1607 self
1608 }
1609
1610 /// Dart `SemanticsProperties(controlsNodes:)`.
1611 pub fn controls_nodes(mut self, controls_nodes: IndexSet<String>) -> SemanticsProperties {
1612 self.controls_nodes = Some(controls_nodes);
1613 self
1614 }
1615
1616 /// Dart `SemanticsProperties(validationResult:)`.
1617 pub fn validation_result(
1618 mut self,
1619 validation_result: SemanticsValidationResult,
1620 ) -> SemanticsProperties {
1621 self.validation_result = validation_result;
1622 self
1623 }
1624
1625 /// Dart `SemanticsProperties(hitTestBehavior:)`.
1626 pub fn hit_test_behavior(
1627 mut self,
1628 hit_test_behavior: SemanticsHitTestBehavior,
1629 ) -> SemanticsProperties {
1630 self.hit_test_behavior = Some(hit_test_behavior);
1631 self
1632 }
1633
1634 /// Dart `SemanticsProperties(inputType:)`.
1635 pub fn input_type(mut self, input_type: SemanticsInputType) -> SemanticsProperties {
1636 self.input_type = Some(input_type);
1637 self
1638 }
1639
1640 /// Dart `SemanticsProperties(maxValue:)`.
1641 pub fn max_value(mut self, max_value: impl Into<String>) -> SemanticsProperties {
1642 self.max_value = Some(max_value.into());
1643 self
1644 }
1645
1646 /// Dart `SemanticsProperties(minValue:)`.
1647 pub fn min_value(mut self, min_value: impl Into<String>) -> SemanticsProperties {
1648 self.min_value = Some(min_value.into());
1649 self
1650 }
1651
1652 /// Dart's constructor asserts that relate two fields. The widgets built on these properties
1653 /// run it from their `debug_check_constructor`; an assert on one field stays in its setter.
1654 pub fn debug_check_constructor(&self) {
1655 debug_assert!(
1656 self.label.is_none() || self.attributed_label.is_none(),
1657 "Only one of label or attributedLabel should be provided"
1658 );
1659 debug_assert!(
1660 self.value.is_none() || self.attributed_value.is_none(),
1661 "Only one of value or attributedValue should be provided"
1662 );
1663 debug_assert!(
1664 self.increased_value.is_none() || self.attributed_increased_value.is_none(),
1665 "Only one of increasedValue or attributedIncreasedValue should be provided"
1666 );
1667 debug_assert!(
1668 self.decreased_value.is_none() || self.attributed_decreased_value.is_none(),
1669 "Only one of decreasedValue or attributedDecreasedValue should be provided"
1670 );
1671 debug_assert!(
1672 self.hint.is_none() || self.attributed_hint.is_none(),
1673 "Only one of hint or attributedHint should be provided"
1674 );
1675 debug_assert!(
1676 self.link_url.is_none() || self.link.unwrap_or(false),
1677 "If linkUrl is set then link must be true"
1678 );
1679 }
1680}
1681
1682/// Dart's `debugFillProperties`, as it lists them.
1683impl Debug for SemanticsProperties {
1684 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1685 f.debug_struct("SemanticsProperties")
1686 .field("checked", &self.checked)
1687 .field("mixed", &self.mixed)
1688 .field("expanded", &self.expanded)
1689 .field("selected", &self.selected)
1690 .field("isRequired", &self.is_required)
1691 .field("identifier", &self.identifier)
1692 .field("label", &self.label)
1693 .field("attributedLabel", &self.attributed_label)
1694 .field("value", &self.value)
1695 .field("attributedValue", &self.attributed_value)
1696 .field("increasedValue", &self.value)
1697 .field("attributedIncreasedValue", &self.attributed_increased_value)
1698 .field("decreasedValue", &self.value)
1699 .field("attributedDecreasedValue", &self.attributed_decreased_value)
1700 .field("hint", &self.hint)
1701 .field("attributedHint", &self.attributed_hint)
1702 .field("tooltip", &self.tooltip)
1703 .field("textDirection", &self.text_direction)
1704 .field("role", &self.role)
1705 .field("validationResult", &self.validation_result)
1706 .field("sortKey", &self.sort_key)
1707 .field("hintOverrides", &self.hint_overrides)
1708 .finish_non_exhaustive()
1709 }
1710}
1711
1712/// Base class for all sort keys for [`SemanticsProperties::sort_key`] accessibility
1713/// traversal order sorting.
1714///
1715/// Sort keys are sorted by [`name`](Self::name), then by the comparison that the subclass
1716/// implements. If [`SemanticsProperties::sort_key`] is specified, sort keys within
1717/// the same semantic group must all be of the same type.
1718///
1719/// Keys with no [`name`](Self::name) are compared to other keys with no
1720/// [`name`](Self::name), and will be traversed before those with a [`name`](Self::name).
1721///
1722/// If no sort key is applied to a semantics node, then it will be ordered using
1723/// a platform dependent default algorithm.
1724pub trait SemanticsSortKey: Debug + Any {
1725 /// An optional name that will group this sort key with other sort keys of the
1726 /// same [`name`](Self::name).
1727 ///
1728 /// Sort keys must have the same type when compared.
1729 fn name(&self) -> Option<&str>;
1730
1731 /// The implementation of [`compare_to`](dyn SemanticsSortKey::compare_to).
1732 ///
1733 /// The argument is guaranteed to be of the same type as this object and have
1734 /// the same [`name`](Self::name).
1735 ///
1736 /// The method should return [`Ordering::Less`] if this object comes earlier in
1737 /// the sort order than the argument; and [`Ordering::Greater`] if it comes later
1738 /// in the sort order. Returning [`Ordering::Equal`] causes the system to use default sort
1739 /// order.
1740 fn do_compare(&self, other: &dyn SemanticsSortKey) -> Ordering;
1741}
1742
1743impl dyn SemanticsSortKey {
1744 /// Dart's `compareTo`: by name first and then the subclass's ordering.
1745 pub fn compare_to(&self, other: &dyn SemanticsSortKey) -> Ordering {
1746 debug_assert!(
1747 (self as &dyn Any).type_id() == (other as &dyn Any).type_id(),
1748 "Semantics sort keys can only be compared to other sort keys of the same type."
1749 );
1750
1751 // Defer to the subclass implementation for ordering only if the names are
1752 // identical (or both null).
1753 if self.name() == other.name() {
1754 return self.do_compare(other);
1755 }
1756
1757 // Keys that don't have a name are sorted together and come before those with
1758 // a name.
1759 match (self.name(), other.name()) {
1760 (None, Some(_)) => Ordering::Less,
1761 (Some(_), None) => Ordering::Greater,
1762 (Some(name), Some(other_name)) => name.cmp(other_name),
1763 (None, None) => unreachable!("equal names compared above"),
1764 }
1765 }
1766}
1767
1768/// A shared [`SemanticsSortKey`].
1769pub type SemanticsSortKeyRef = Rc<dyn SemanticsSortKey>;
1770
1771/// A [`SemanticsSortKey`] that sorts based on the `f64` value it is
1772/// given.
1773///
1774/// The [`OrdinalSortKey`] compares itself with other [`OrdinalSortKey`]s
1775/// to sort based on the order it is given.
1776///
1777/// [`OrdinalSortKey`]s are sorted by the optional [`name`](SemanticsSortKey::name), then by
1778/// their [`order`](Self::order). If [`SemanticsProperties::sort_key`] is a [`OrdinalSortKey`],
1779/// then all the other specified sort keys in the same semantics group must also be
1780/// [`OrdinalSortKey`]s.
1781///
1782/// The ordinal value [`order`](Self::order) is typically a whole number, though it can be
1783/// fractional, e.g. in order to fit between two other consecutive whole
1784/// numbers. The value must be finite (it cannot be NaN or infinite).
1785#[derive(Clone, Debug)]
1786pub struct OrdinalSortKey {
1787 name: Option<String>,
1788
1789 /// Determines the placement of this key in a sequence of keys that defines
1790 /// the order in which this node is traversed by the platform's accessibility
1791 /// services.
1792 ///
1793 /// Lower values will be traversed first. Keys with the same name will be
1794 /// grouped together and sorted by name first, and then sorted by order.
1795 pub order: f64,
1796}
1797
1798impl OrdinalSortKey {
1799 /// Creates a semantics sort key that uses a `f64` as its key value.
1800 ///
1801 /// The `order` must be a finite number.
1802 pub fn new(order: f64) -> OrdinalSortKey {
1803 debug_assert!(order > f64::NEG_INFINITY);
1804 debug_assert!(order < f64::INFINITY);
1805 OrdinalSortKey { name: None, order }
1806 }
1807
1808 /// Dart `OrdinalSortKey(name:)`.
1809 pub fn name(mut self, name: impl Into<String>) -> OrdinalSortKey {
1810 self.name = Some(name.into());
1811 self
1812 }
1813}
1814
1815impl SemanticsSortKey for OrdinalSortKey {
1816 fn name(&self) -> Option<&str> {
1817 self.name.as_deref()
1818 }
1819
1820 fn do_compare(&self, other: &dyn SemanticsSortKey) -> Ordering {
1821 let other = (other as &dyn Any)
1822 .downcast_ref::<OrdinalSortKey>()
1823 .expect("compare_to checks the type");
1824 if other.order == self.order {
1825 return Ordering::Equal;
1826 }
1827 self.order.total_cmp(&other.order)
1828 }
1829}
1830
1831#[cfg(test)]
1832mod tests {
1833 use waft_embedder::{Locale, LocaleStringAttribute, SpellOutStringAttribute};
1834
1835 use super::*;
1836
1837 fn key(order: f64) -> SemanticsSortKeyRef {
1838 Rc::new(OrdinalSortKey::new(order))
1839 }
1840
1841 fn named_key(order: f64, name: &str) -> SemanticsSortKeyRef {
1842 Rc::new(OrdinalSortKey::new(order).name(name))
1843 }
1844
1845 // semantics_test.dart: 'OrdinalSortKey compares correctly when names are the same'
1846 #[test]
1847 fn ordinal_sort_keys_with_the_same_name_compare_by_order() {
1848 let tests = [
1849 (key(0.0), key(0.0), Ordering::Equal),
1850 (key(0.0), key(1.0), Ordering::Less),
1851 (key(1.0), key(0.0), Ordering::Greater),
1852 (key(1.0), key(1.0), Ordering::Equal),
1853 (named_key(0.0, "a"), named_key(0.0, "a"), Ordering::Equal),
1854 (named_key(0.0, "a"), named_key(1.0, "a"), Ordering::Less),
1855 (named_key(1.0, "a"), named_key(0.0, "a"), Ordering::Greater),
1856 (named_key(1.0, "a"), named_key(1.0, "a"), Ordering::Equal),
1857 ];
1858 for (a, b, expected) in tests {
1859 assert_eq!(a.compare_to(b.as_ref()), expected, "{a:?} vs {b:?}");
1860 }
1861 }
1862
1863 // semantics_test.dart: 'OrdinalSortKey compares correctly when the names are different'
1864 #[test]
1865 fn ordinal_sort_keys_with_different_names_compare_by_name() {
1866 let tests = [
1867 (key(0.0), named_key(0.0, "bar"), Ordering::Less),
1868 (key(0.0), named_key(1.0, "bar"), Ordering::Less),
1869 (key(1.0), named_key(0.0, "bar"), Ordering::Less),
1870 (key(1.0), named_key(1.0, "bar"), Ordering::Less),
1871 (named_key(0.0, "foo"), key(0.0), Ordering::Greater),
1872 (named_key(0.0, "foo"), key(1.0), Ordering::Greater),
1873 (named_key(1.0, "foo"), key(0.0), Ordering::Greater),
1874 (named_key(1.0, "foo"), key(1.0), Ordering::Greater),
1875 (
1876 named_key(0.0, "foo"),
1877 named_key(0.0, "bar"),
1878 Ordering::Greater,
1879 ),
1880 (
1881 named_key(0.0, "foo"),
1882 named_key(1.0, "bar"),
1883 Ordering::Greater,
1884 ),
1885 (
1886 named_key(1.0, "foo"),
1887 named_key(0.0, "bar"),
1888 Ordering::Greater,
1889 ),
1890 (
1891 named_key(1.0, "foo"),
1892 named_key(1.0, "bar"),
1893 Ordering::Greater,
1894 ),
1895 (named_key(0.0, "bar"), named_key(0.0, "foo"), Ordering::Less),
1896 (named_key(0.0, "bar"), named_key(1.0, "foo"), Ordering::Less),
1897 (named_key(1.0, "bar"), named_key(0.0, "foo"), Ordering::Less),
1898 (named_key(1.0, "bar"), named_key(1.0, "foo"), Ordering::Less),
1899 ];
1900 for (a, b, expected) in tests {
1901 assert_eq!(a.compare_to(b.as_ref()), expected, "{a:?} vs {b:?}");
1902 }
1903 }
1904
1905 #[derive(Debug)]
1906 struct CustomSortKey(f64);
1907
1908 impl SemanticsSortKey for CustomSortKey {
1909 fn name(&self) -> Option<&str> {
1910 None
1911 }
1912
1913 fn do_compare(&self, other: &dyn SemanticsSortKey) -> Ordering {
1914 let other = (other as &dyn Any).downcast_ref::<CustomSortKey>().unwrap();
1915 self.0.total_cmp(&other.0)
1916 }
1917 }
1918
1919 // semantics_test.dart: 'Incompatible OrdinalSortKey throw AssertionError when compared'
1920 #[test]
1921 #[should_panic(expected = "Semantics sort keys can only be compared")]
1922 fn comparing_sort_keys_of_different_types_asserts() {
1923 let _ = key(0.0).compare_to(&CustomSortKey(0.0));
1924 }
1925
1926 // semantics_test.dart: 'Attributed String can concat'
1927 #[test]
1928 fn concatenating_attributed_strings_shifts_the_attributes_of_the_second() {
1929 let string1 = AttributedString::new("string1")
1930 .attributes(vec![SpellOutStringAttribute::new(TextRange::new(0, 4))]);
1931 let string2 =
1932 AttributedString::new("string2").attributes(vec![LocaleStringAttribute::new(
1933 TextRange::new(0, 4),
1934 Locale::new("es").country_code("MX"),
1935 )]);
1936 let result = string1 + string2;
1937 assert_eq!(result.string, "string1string2");
1938 assert_eq!(result.attributes.len(), 2);
1939 assert_eq!(result.attributes[0].range(), TextRange::new(0, 4));
1940 assert!(
1941 (result.attributes[0].as_ref() as &dyn Any)
1942 .downcast_ref::<SpellOutStringAttribute>()
1943 .is_some()
1944 );
1945 assert_eq!(
1946 format!("{:?}", result.attributes[1]),
1947 "LocaleStringAttribute(TextRange { start: 7, end: 11 }, es-MX)"
1948 );
1949 }
1950
1951 #[test]
1952 fn attributed_strings_are_equal_only_with_the_same_attributes() {
1953 let attribute = SpellOutStringAttribute::new(TextRange::new(0, 1));
1954 let a = AttributedString::new("a").attributes(vec![attribute.clone()]);
1955 let b = AttributedString::new("a").attributes(vec![attribute]);
1956 let c = AttributedString::new("a")
1957 .attributes(vec![SpellOutStringAttribute::new(TextRange::new(0, 1))]);
1958 assert_eq!(a, b);
1959 assert_ne!(a, c);
1960 assert_eq!(AttributedString::new("a"), AttributedString::new("a"));
1961 }
1962
1963 #[test]
1964 #[should_panic(expected = "Only one of label or attributedLabel should be provided")]
1965 fn a_label_and_an_attributed_label_together_assert() {
1966 SemanticsProperties::new()
1967 .label("a")
1968 .attributed_label(AttributedString::new("a"))
1969 .debug_check_constructor();
1970 }
1971
1972 #[test]
1973 #[should_panic(expected = "If linkUrl is set then link must be true")]
1974 fn a_link_url_without_link_asserts() {
1975 SemanticsProperties::new()
1976 .link_url("https://flutter.dev")
1977 .debug_check_constructor();
1978 }
1979
1980 #[test]
1981 #[should_panic(expected = "Heading level must be between 1 and 6")]
1982 fn a_heading_level_out_of_range_asserts() {
1983 let _ = SemanticsProperties::new().heading_level(7);
1984 }
1985}