use std::any::Any;
use std::cmp::Ordering;
use std::fmt::{self, Debug};
use std::ops::Add;
use std::rc::Rc;
use indexmap::{IndexMap, IndexSet};
use waft_embedder::{
SemanticsAction, SemanticsHitTestBehavior, SemanticsInputType, SemanticsRole,
SemanticsValidationResult, StringAttributeRef, TextDirection, TextRange, TextSelection,
};
use waft_foundation::{App, VoidCallback};
pub type MoveCursorHandler = Rc<dyn Fn(&mut App, bool)>;
pub type SetSelectionHandler = Rc<dyn Fn(&mut App, TextSelection)>;
pub type SetTextHandler = Rc<dyn Fn(&mut App, String)>;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AccessibilityFocusBlockType {
None,
BlockSubtree,
BlockNode,
}
pub struct SemanticsTag {
pub name: String,
}
impl SemanticsTag {
pub fn new(name: impl Into<String>) -> Rc<SemanticsTag> {
Rc::new(SemanticsTag { name: name.into() })
}
}
impl Debug for SemanticsTag {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "SemanticsTag({})", self.name)
}
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct CustomSemanticsAction {
pub label: Option<String>,
pub hint: Option<String>,
pub action: Option<SemanticsAction>,
}
impl CustomSemanticsAction {
pub fn new(label: impl Into<String>) -> CustomSemanticsAction {
let label = label.into();
debug_assert!(!label.is_empty());
CustomSemanticsAction {
label: Some(label),
hint: None,
action: None,
}
}
pub fn overriding_action(
hint: impl Into<String>,
action: SemanticsAction,
) -> CustomSemanticsAction {
let hint = hint.into();
debug_assert!(!hint.is_empty());
CustomSemanticsAction {
label: None,
hint: Some(hint),
action: Some(action),
}
}
}
impl Debug for CustomSemanticsAction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"CustomSemanticsAction(label:{:?}, hint:{:?}, action:{:?})",
self.label, self.hint, self.action
)
}
}
#[derive(Clone)]
pub struct AttributedString {
pub string: String,
pub attributes: Vec<StringAttributeRef>,
}
impl AttributedString {
pub fn new(string: impl Into<String>) -> AttributedString {
AttributedString {
string: string.into(),
attributes: Vec::new(),
}
}
pub fn attributes(mut self, attributes: Vec<StringAttributeRef>) -> AttributedString {
debug_assert!(!self.string.is_empty() || attributes.is_empty());
if cfg!(debug_assertions) {
let length = utf16_length(&self.string);
for attribute in &attributes {
debug_assert!(
length >= attribute.range().start && length >= attribute.range().end,
"The range in {attribute:?} is outside of the string {}",
self.string
);
}
}
self.attributes = attributes;
self
}
}
fn utf16_length(string: &str) -> i32 {
string.encode_utf16().count() as i32
}
impl Add for AttributedString {
type Output = AttributedString;
fn add(self, other: AttributedString) -> AttributedString {
if self.string.is_empty() {
return other;
}
if other.string.is_empty() {
return self;
}
let new_string = self.string.clone() + &other.string;
let mut new_attributes = self.attributes.clone();
if !other.attributes.is_empty() {
let offset = utf16_length(&self.string);
for attribute in &other.attributes {
let new_range = TextRange::new(
attribute.range().start + offset,
attribute.range().end + offset,
);
let adjusted_attribute = attribute.copy(new_range);
new_attributes.push(adjusted_attribute);
}
}
AttributedString::new(new_string).attributes(new_attributes)
}
}
impl PartialEq for AttributedString {
fn eq(&self, other: &AttributedString) -> bool {
other.string == self.string
&& other.attributes.len() == self.attributes.len()
&& other
.attributes
.iter()
.zip(&self.attributes)
.all(|(a, b)| Rc::ptr_eq(a, b))
}
}
impl Debug for AttributedString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"AttributedString('{}', attributes: {:?})",
self.string, self.attributes
)
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct SemanticsHintOverrides {
pub on_tap_hint: Option<String>,
pub on_long_press_hint: Option<String>,
}
impl SemanticsHintOverrides {
pub fn new() -> SemanticsHintOverrides {
SemanticsHintOverrides::default()
}
pub fn on_tap_hint(mut self, on_tap_hint: impl Into<String>) -> SemanticsHintOverrides {
let on_tap_hint = on_tap_hint.into();
debug_assert!(!on_tap_hint.is_empty());
self.on_tap_hint = Some(on_tap_hint);
self
}
pub fn on_long_press_hint(
mut self,
on_long_press_hint: impl Into<String>,
) -> SemanticsHintOverrides {
let on_long_press_hint = on_long_press_hint.into();
debug_assert!(!on_long_press_hint.is_empty());
self.on_long_press_hint = Some(on_long_press_hint);
self
}
pub fn is_not_empty(&self) -> bool {
self.on_tap_hint.is_some() || self.on_long_press_hint.is_some()
}
}
#[derive(Clone, Default)]
pub struct SemanticsProperties {
pub enabled: Option<bool>,
pub checked: Option<bool>,
pub mixed: Option<bool>,
pub expanded: Option<bool>,
pub toggled: Option<bool>,
pub selected: Option<bool>,
pub button: Option<bool>,
pub link: Option<bool>,
pub header: Option<bool>,
pub text_field: Option<bool>,
pub slider: Option<bool>,
pub keyboard_key: Option<bool>,
pub read_only: Option<bool>,
pub focusable: Option<bool>,
pub focused: Option<bool>,
pub accessibility_focus_block_type: Option<AccessibilityFocusBlockType>,
pub in_mutually_exclusive_group: Option<bool>,
pub hidden: Option<bool>,
pub obscured: Option<bool>,
pub multiline: Option<bool>,
pub scopes_route: Option<bool>,
pub names_route: Option<bool>,
pub image: Option<bool>,
pub live_region: Option<bool>,
pub is_required: Option<bool>,
pub max_value_length: Option<i32>,
pub current_value_length: Option<i32>,
pub identifier: Option<String>,
pub traversal_parent_identifier: Option<Rc<dyn Any>>,
pub traversal_child_identifier: Option<Rc<dyn Any>>,
pub label: Option<String>,
pub attributed_label: Option<AttributedString>,
pub value: Option<String>,
pub attributed_value: Option<AttributedString>,
pub increased_value: Option<String>,
pub attributed_increased_value: Option<AttributedString>,
pub decreased_value: Option<String>,
pub attributed_decreased_value: Option<AttributedString>,
pub hint: Option<String>,
pub attributed_hint: Option<AttributedString>,
pub tooltip: Option<String>,
pub heading_level: Option<i32>,
pub hint_overrides: Option<SemanticsHintOverrides>,
pub text_direction: Option<TextDirection>,
pub sort_key: Option<SemanticsSortKeyRef>,
pub tag_for_children: Option<Rc<SemanticsTag>>,
pub link_url: Option<String>,
pub on_tap: Option<VoidCallback>,
pub on_long_press: Option<VoidCallback>,
pub on_scroll_left: Option<VoidCallback>,
pub on_scroll_right: Option<VoidCallback>,
pub on_scroll_up: Option<VoidCallback>,
pub on_scroll_down: Option<VoidCallback>,
pub on_increase: Option<VoidCallback>,
pub on_decrease: Option<VoidCallback>,
pub on_copy: Option<VoidCallback>,
pub on_cut: Option<VoidCallback>,
pub on_paste: Option<VoidCallback>,
pub on_move_cursor_forward_by_character: Option<MoveCursorHandler>,
pub on_move_cursor_backward_by_character: Option<MoveCursorHandler>,
pub on_move_cursor_forward_by_word: Option<MoveCursorHandler>,
pub on_move_cursor_backward_by_word: Option<MoveCursorHandler>,
pub on_set_selection: Option<SetSelectionHandler>,
pub on_set_text: Option<SetTextHandler>,
pub on_did_gain_accessibility_focus: Option<VoidCallback>,
pub on_did_lose_accessibility_focus: Option<VoidCallback>,
pub on_focus: Option<VoidCallback>,
pub on_dismiss: Option<VoidCallback>,
pub on_expand: Option<VoidCallback>,
pub on_collapse: Option<VoidCallback>,
pub custom_semantics_actions: Option<IndexMap<CustomSemanticsAction, VoidCallback>>,
pub role: Option<SemanticsRole>,
pub controls_nodes: Option<IndexSet<String>>,
pub validation_result: SemanticsValidationResult,
pub hit_test_behavior: Option<SemanticsHitTestBehavior>,
pub input_type: Option<SemanticsInputType>,
pub max_value: Option<String>,
pub min_value: Option<String>,
}
impl SemanticsProperties {
pub fn new() -> SemanticsProperties {
SemanticsProperties::default()
}
pub fn enabled(mut self, enabled: bool) -> SemanticsProperties {
self.enabled = Some(enabled);
self
}
pub fn checked(mut self, checked: bool) -> SemanticsProperties {
self.checked = Some(checked);
self
}
pub fn mixed(mut self, mixed: bool) -> SemanticsProperties {
self.mixed = Some(mixed);
self
}
pub fn expanded(mut self, expanded: bool) -> SemanticsProperties {
self.expanded = Some(expanded);
self
}
pub fn toggled(mut self, toggled: bool) -> SemanticsProperties {
self.toggled = Some(toggled);
self
}
pub fn selected(mut self, selected: bool) -> SemanticsProperties {
self.selected = Some(selected);
self
}
pub fn button(mut self, button: bool) -> SemanticsProperties {
self.button = Some(button);
self
}
pub fn link(mut self, link: bool) -> SemanticsProperties {
self.link = Some(link);
self
}
pub fn header(mut self, header: bool) -> SemanticsProperties {
self.header = Some(header);
self
}
pub fn text_field(mut self, text_field: bool) -> SemanticsProperties {
self.text_field = Some(text_field);
self
}
pub fn slider(mut self, slider: bool) -> SemanticsProperties {
self.slider = Some(slider);
self
}
pub fn keyboard_key(mut self, keyboard_key: bool) -> SemanticsProperties {
self.keyboard_key = Some(keyboard_key);
self
}
pub fn read_only(mut self, read_only: bool) -> SemanticsProperties {
self.read_only = Some(read_only);
self
}
pub fn focusable(mut self, focusable: bool) -> SemanticsProperties {
self.focusable = Some(focusable);
self
}
pub fn focused(mut self, focused: bool) -> SemanticsProperties {
self.focused = Some(focused);
self
}
pub fn accessibility_focus_block_type(
mut self,
accessibility_focus_block_type: AccessibilityFocusBlockType,
) -> SemanticsProperties {
self.accessibility_focus_block_type = Some(accessibility_focus_block_type);
self
}
pub fn in_mutually_exclusive_group(
mut self,
in_mutually_exclusive_group: bool,
) -> SemanticsProperties {
self.in_mutually_exclusive_group = Some(in_mutually_exclusive_group);
self
}
pub fn hidden(mut self, hidden: bool) -> SemanticsProperties {
self.hidden = Some(hidden);
self
}
pub fn obscured(mut self, obscured: bool) -> SemanticsProperties {
self.obscured = Some(obscured);
self
}
pub fn multiline(mut self, multiline: bool) -> SemanticsProperties {
self.multiline = Some(multiline);
self
}
pub fn scopes_route(mut self, scopes_route: bool) -> SemanticsProperties {
self.scopes_route = Some(scopes_route);
self
}
pub fn names_route(mut self, names_route: bool) -> SemanticsProperties {
self.names_route = Some(names_route);
self
}
pub fn image(mut self, image: bool) -> SemanticsProperties {
self.image = Some(image);
self
}
pub fn live_region(mut self, live_region: bool) -> SemanticsProperties {
self.live_region = Some(live_region);
self
}
pub fn is_required(mut self, is_required: bool) -> SemanticsProperties {
self.is_required = Some(is_required);
self
}
pub fn max_value_length(mut self, max_value_length: i32) -> SemanticsProperties {
self.max_value_length = Some(max_value_length);
self
}
pub fn current_value_length(mut self, current_value_length: i32) -> SemanticsProperties {
self.current_value_length = Some(current_value_length);
self
}
pub fn identifier(mut self, identifier: impl Into<String>) -> SemanticsProperties {
self.identifier = Some(identifier.into());
self
}
pub fn traversal_parent_identifier(
mut self,
traversal_parent_identifier: Rc<dyn Any>,
) -> SemanticsProperties {
self.traversal_parent_identifier = Some(traversal_parent_identifier);
self
}
pub fn traversal_child_identifier(
mut self,
traversal_child_identifier: Rc<dyn Any>,
) -> SemanticsProperties {
self.traversal_child_identifier = Some(traversal_child_identifier);
self
}
pub fn label(mut self, label: impl Into<String>) -> SemanticsProperties {
self.label = Some(label.into());
self
}
pub fn attributed_label(mut self, attributed_label: AttributedString) -> SemanticsProperties {
self.attributed_label = Some(attributed_label);
self
}
pub fn value(mut self, value: impl Into<String>) -> SemanticsProperties {
self.value = Some(value.into());
self
}
pub fn attributed_value(mut self, attributed_value: AttributedString) -> SemanticsProperties {
self.attributed_value = Some(attributed_value);
self
}
pub fn increased_value(mut self, increased_value: impl Into<String>) -> SemanticsProperties {
self.increased_value = Some(increased_value.into());
self
}
pub fn attributed_increased_value(
mut self,
attributed_increased_value: AttributedString,
) -> SemanticsProperties {
self.attributed_increased_value = Some(attributed_increased_value);
self
}
pub fn decreased_value(mut self, decreased_value: impl Into<String>) -> SemanticsProperties {
self.decreased_value = Some(decreased_value.into());
self
}
pub fn attributed_decreased_value(
mut self,
attributed_decreased_value: AttributedString,
) -> SemanticsProperties {
self.attributed_decreased_value = Some(attributed_decreased_value);
self
}
pub fn hint(mut self, hint: impl Into<String>) -> SemanticsProperties {
self.hint = Some(hint.into());
self
}
pub fn attributed_hint(mut self, attributed_hint: AttributedString) -> SemanticsProperties {
self.attributed_hint = Some(attributed_hint);
self
}
pub fn tooltip(mut self, tooltip: impl Into<String>) -> SemanticsProperties {
self.tooltip = Some(tooltip.into());
self
}
pub fn heading_level(mut self, heading_level: i32) -> SemanticsProperties {
debug_assert!(
heading_level > 0 && heading_level <= 6,
"Heading level must be between 1 and 6"
);
self.heading_level = Some(heading_level);
self
}
pub fn hint_overrides(mut self, hint_overrides: SemanticsHintOverrides) -> SemanticsProperties {
self.hint_overrides = Some(hint_overrides);
self
}
pub fn text_direction(mut self, text_direction: TextDirection) -> SemanticsProperties {
self.text_direction = Some(text_direction);
self
}
pub fn sort_key(mut self, sort_key: SemanticsSortKeyRef) -> SemanticsProperties {
self.sort_key = Some(sort_key);
self
}
pub fn tag_for_children(mut self, tag_for_children: Rc<SemanticsTag>) -> SemanticsProperties {
self.tag_for_children = Some(tag_for_children);
self
}
pub fn link_url(mut self, link_url: impl Into<String>) -> SemanticsProperties {
self.link_url = Some(link_url.into());
self
}
pub fn on_tap(mut self, on_tap: VoidCallback) -> SemanticsProperties {
self.on_tap = Some(on_tap);
self
}
pub fn on_long_press(mut self, on_long_press: VoidCallback) -> SemanticsProperties {
self.on_long_press = Some(on_long_press);
self
}
pub fn on_scroll_left(mut self, on_scroll_left: VoidCallback) -> SemanticsProperties {
self.on_scroll_left = Some(on_scroll_left);
self
}
pub fn on_scroll_right(mut self, on_scroll_right: VoidCallback) -> SemanticsProperties {
self.on_scroll_right = Some(on_scroll_right);
self
}
pub fn on_scroll_up(mut self, on_scroll_up: VoidCallback) -> SemanticsProperties {
self.on_scroll_up = Some(on_scroll_up);
self
}
pub fn on_scroll_down(mut self, on_scroll_down: VoidCallback) -> SemanticsProperties {
self.on_scroll_down = Some(on_scroll_down);
self
}
pub fn on_increase(mut self, on_increase: VoidCallback) -> SemanticsProperties {
self.on_increase = Some(on_increase);
self
}
pub fn on_decrease(mut self, on_decrease: VoidCallback) -> SemanticsProperties {
self.on_decrease = Some(on_decrease);
self
}
pub fn on_copy(mut self, on_copy: VoidCallback) -> SemanticsProperties {
self.on_copy = Some(on_copy);
self
}
pub fn on_cut(mut self, on_cut: VoidCallback) -> SemanticsProperties {
self.on_cut = Some(on_cut);
self
}
pub fn on_paste(mut self, on_paste: VoidCallback) -> SemanticsProperties {
self.on_paste = Some(on_paste);
self
}
pub fn on_move_cursor_forward_by_character(
mut self,
on_move_cursor_forward_by_character: MoveCursorHandler,
) -> SemanticsProperties {
self.on_move_cursor_forward_by_character = Some(on_move_cursor_forward_by_character);
self
}
pub fn on_move_cursor_backward_by_character(
mut self,
on_move_cursor_backward_by_character: MoveCursorHandler,
) -> SemanticsProperties {
self.on_move_cursor_backward_by_character = Some(on_move_cursor_backward_by_character);
self
}
pub fn on_move_cursor_forward_by_word(
mut self,
on_move_cursor_forward_by_word: MoveCursorHandler,
) -> SemanticsProperties {
self.on_move_cursor_forward_by_word = Some(on_move_cursor_forward_by_word);
self
}
pub fn on_move_cursor_backward_by_word(
mut self,
on_move_cursor_backward_by_word: MoveCursorHandler,
) -> SemanticsProperties {
self.on_move_cursor_backward_by_word = Some(on_move_cursor_backward_by_word);
self
}
pub fn on_set_selection(
mut self,
on_set_selection: SetSelectionHandler,
) -> SemanticsProperties {
self.on_set_selection = Some(on_set_selection);
self
}
pub fn on_set_text(mut self, on_set_text: SetTextHandler) -> SemanticsProperties {
self.on_set_text = Some(on_set_text);
self
}
pub fn on_did_gain_accessibility_focus(
mut self,
on_did_gain_accessibility_focus: VoidCallback,
) -> SemanticsProperties {
self.on_did_gain_accessibility_focus = Some(on_did_gain_accessibility_focus);
self
}
pub fn on_did_lose_accessibility_focus(
mut self,
on_did_lose_accessibility_focus: VoidCallback,
) -> SemanticsProperties {
self.on_did_lose_accessibility_focus = Some(on_did_lose_accessibility_focus);
self
}
pub fn on_focus(mut self, on_focus: VoidCallback) -> SemanticsProperties {
self.on_focus = Some(on_focus);
self
}
pub fn on_dismiss(mut self, on_dismiss: VoidCallback) -> SemanticsProperties {
self.on_dismiss = Some(on_dismiss);
self
}
pub fn on_expand(mut self, on_expand: VoidCallback) -> SemanticsProperties {
self.on_expand = Some(on_expand);
self
}
pub fn on_collapse(mut self, on_collapse: VoidCallback) -> SemanticsProperties {
self.on_collapse = Some(on_collapse);
self
}
pub fn custom_semantics_actions(
mut self,
custom_semantics_actions: IndexMap<CustomSemanticsAction, VoidCallback>,
) -> SemanticsProperties {
self.custom_semantics_actions = Some(custom_semantics_actions);
self
}
pub fn role(mut self, role: SemanticsRole) -> SemanticsProperties {
self.role = Some(role);
self
}
pub fn controls_nodes(mut self, controls_nodes: IndexSet<String>) -> SemanticsProperties {
self.controls_nodes = Some(controls_nodes);
self
}
pub fn validation_result(
mut self,
validation_result: SemanticsValidationResult,
) -> SemanticsProperties {
self.validation_result = validation_result;
self
}
pub fn hit_test_behavior(
mut self,
hit_test_behavior: SemanticsHitTestBehavior,
) -> SemanticsProperties {
self.hit_test_behavior = Some(hit_test_behavior);
self
}
pub fn input_type(mut self, input_type: SemanticsInputType) -> SemanticsProperties {
self.input_type = Some(input_type);
self
}
pub fn max_value(mut self, max_value: impl Into<String>) -> SemanticsProperties {
self.max_value = Some(max_value.into());
self
}
pub fn min_value(mut self, min_value: impl Into<String>) -> SemanticsProperties {
self.min_value = Some(min_value.into());
self
}
pub fn debug_check_constructor(&self) {
debug_assert!(
self.label.is_none() || self.attributed_label.is_none(),
"Only one of label or attributedLabel should be provided"
);
debug_assert!(
self.value.is_none() || self.attributed_value.is_none(),
"Only one of value or attributedValue should be provided"
);
debug_assert!(
self.increased_value.is_none() || self.attributed_increased_value.is_none(),
"Only one of increasedValue or attributedIncreasedValue should be provided"
);
debug_assert!(
self.decreased_value.is_none() || self.attributed_decreased_value.is_none(),
"Only one of decreasedValue or attributedDecreasedValue should be provided"
);
debug_assert!(
self.hint.is_none() || self.attributed_hint.is_none(),
"Only one of hint or attributedHint should be provided"
);
debug_assert!(
self.link_url.is_none() || self.link.unwrap_or(false),
"If linkUrl is set then link must be true"
);
}
}
impl Debug for SemanticsProperties {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SemanticsProperties")
.field("checked", &self.checked)
.field("mixed", &self.mixed)
.field("expanded", &self.expanded)
.field("selected", &self.selected)
.field("isRequired", &self.is_required)
.field("identifier", &self.identifier)
.field("label", &self.label)
.field("attributedLabel", &self.attributed_label)
.field("value", &self.value)
.field("attributedValue", &self.attributed_value)
.field("increasedValue", &self.value)
.field("attributedIncreasedValue", &self.attributed_increased_value)
.field("decreasedValue", &self.value)
.field("attributedDecreasedValue", &self.attributed_decreased_value)
.field("hint", &self.hint)
.field("attributedHint", &self.attributed_hint)
.field("tooltip", &self.tooltip)
.field("textDirection", &self.text_direction)
.field("role", &self.role)
.field("validationResult", &self.validation_result)
.field("sortKey", &self.sort_key)
.field("hintOverrides", &self.hint_overrides)
.finish_non_exhaustive()
}
}
pub trait SemanticsSortKey: Debug + Any {
fn name(&self) -> Option<&str>;
fn do_compare(&self, other: &dyn SemanticsSortKey) -> Ordering;
}
impl dyn SemanticsSortKey {
pub fn compare_to(&self, other: &dyn SemanticsSortKey) -> Ordering {
debug_assert!(
(self as &dyn Any).type_id() == (other as &dyn Any).type_id(),
"Semantics sort keys can only be compared to other sort keys of the same type."
);
if self.name() == other.name() {
return self.do_compare(other);
}
match (self.name(), other.name()) {
(None, Some(_)) => Ordering::Less,
(Some(_), None) => Ordering::Greater,
(Some(name), Some(other_name)) => name.cmp(other_name),
(None, None) => unreachable!("equal names compared above"),
}
}
}
pub type SemanticsSortKeyRef = Rc<dyn SemanticsSortKey>;
#[derive(Clone, Debug)]
pub struct OrdinalSortKey {
name: Option<String>,
pub order: f64,
}
impl OrdinalSortKey {
pub fn new(order: f64) -> OrdinalSortKey {
debug_assert!(order > f64::NEG_INFINITY);
debug_assert!(order < f64::INFINITY);
OrdinalSortKey { name: None, order }
}
pub fn name(mut self, name: impl Into<String>) -> OrdinalSortKey {
self.name = Some(name.into());
self
}
}
impl SemanticsSortKey for OrdinalSortKey {
fn name(&self) -> Option<&str> {
self.name.as_deref()
}
fn do_compare(&self, other: &dyn SemanticsSortKey) -> Ordering {
let other = (other as &dyn Any)
.downcast_ref::<OrdinalSortKey>()
.expect("compare_to checks the type");
if other.order == self.order {
return Ordering::Equal;
}
self.order.total_cmp(&other.order)
}
}
#[cfg(test)]
mod tests {
use waft_embedder::{Locale, LocaleStringAttribute, SpellOutStringAttribute};
use super::*;
fn key(order: f64) -> SemanticsSortKeyRef {
Rc::new(OrdinalSortKey::new(order))
}
fn named_key(order: f64, name: &str) -> SemanticsSortKeyRef {
Rc::new(OrdinalSortKey::new(order).name(name))
}
#[test]
fn ordinal_sort_keys_with_the_same_name_compare_by_order() {
let tests = [
(key(0.0), key(0.0), Ordering::Equal),
(key(0.0), key(1.0), Ordering::Less),
(key(1.0), key(0.0), Ordering::Greater),
(key(1.0), key(1.0), Ordering::Equal),
(named_key(0.0, "a"), named_key(0.0, "a"), Ordering::Equal),
(named_key(0.0, "a"), named_key(1.0, "a"), Ordering::Less),
(named_key(1.0, "a"), named_key(0.0, "a"), Ordering::Greater),
(named_key(1.0, "a"), named_key(1.0, "a"), Ordering::Equal),
];
for (a, b, expected) in tests {
assert_eq!(a.compare_to(b.as_ref()), expected, "{a:?} vs {b:?}");
}
}
#[test]
fn ordinal_sort_keys_with_different_names_compare_by_name() {
let tests = [
(key(0.0), named_key(0.0, "bar"), Ordering::Less),
(key(0.0), named_key(1.0, "bar"), Ordering::Less),
(key(1.0), named_key(0.0, "bar"), Ordering::Less),
(key(1.0), named_key(1.0, "bar"), Ordering::Less),
(named_key(0.0, "foo"), key(0.0), Ordering::Greater),
(named_key(0.0, "foo"), key(1.0), Ordering::Greater),
(named_key(1.0, "foo"), key(0.0), Ordering::Greater),
(named_key(1.0, "foo"), key(1.0), Ordering::Greater),
(
named_key(0.0, "foo"),
named_key(0.0, "bar"),
Ordering::Greater,
),
(
named_key(0.0, "foo"),
named_key(1.0, "bar"),
Ordering::Greater,
),
(
named_key(1.0, "foo"),
named_key(0.0, "bar"),
Ordering::Greater,
),
(
named_key(1.0, "foo"),
named_key(1.0, "bar"),
Ordering::Greater,
),
(named_key(0.0, "bar"), named_key(0.0, "foo"), Ordering::Less),
(named_key(0.0, "bar"), named_key(1.0, "foo"), Ordering::Less),
(named_key(1.0, "bar"), named_key(0.0, "foo"), Ordering::Less),
(named_key(1.0, "bar"), named_key(1.0, "foo"), Ordering::Less),
];
for (a, b, expected) in tests {
assert_eq!(a.compare_to(b.as_ref()), expected, "{a:?} vs {b:?}");
}
}
#[derive(Debug)]
struct CustomSortKey(f64);
impl SemanticsSortKey for CustomSortKey {
fn name(&self) -> Option<&str> {
None
}
fn do_compare(&self, other: &dyn SemanticsSortKey) -> Ordering {
let other = (other as &dyn Any).downcast_ref::<CustomSortKey>().unwrap();
self.0.total_cmp(&other.0)
}
}
#[test]
#[should_panic(expected = "Semantics sort keys can only be compared")]
fn comparing_sort_keys_of_different_types_asserts() {
let _ = key(0.0).compare_to(&CustomSortKey(0.0));
}
#[test]
fn concatenating_attributed_strings_shifts_the_attributes_of_the_second() {
let string1 = AttributedString::new("string1")
.attributes(vec![SpellOutStringAttribute::new(TextRange::new(0, 4))]);
let string2 =
AttributedString::new("string2").attributes(vec![LocaleStringAttribute::new(
TextRange::new(0, 4),
Locale::new("es").country_code("MX"),
)]);
let result = string1 + string2;
assert_eq!(result.string, "string1string2");
assert_eq!(result.attributes.len(), 2);
assert_eq!(result.attributes[0].range(), TextRange::new(0, 4));
assert!(
(result.attributes[0].as_ref() as &dyn Any)
.downcast_ref::<SpellOutStringAttribute>()
.is_some()
);
assert_eq!(
format!("{:?}", result.attributes[1]),
"LocaleStringAttribute(TextRange { start: 7, end: 11 }, es-MX)"
);
}
#[test]
fn attributed_strings_are_equal_only_with_the_same_attributes() {
let attribute = SpellOutStringAttribute::new(TextRange::new(0, 1));
let a = AttributedString::new("a").attributes(vec![attribute.clone()]);
let b = AttributedString::new("a").attributes(vec![attribute]);
let c = AttributedString::new("a")
.attributes(vec![SpellOutStringAttribute::new(TextRange::new(0, 1))]);
assert_eq!(a, b);
assert_ne!(a, c);
assert_eq!(AttributedString::new("a"), AttributedString::new("a"));
}
#[test]
#[should_panic(expected = "Only one of label or attributedLabel should be provided")]
fn a_label_and_an_attributed_label_together_assert() {
SemanticsProperties::new()
.label("a")
.attributed_label(AttributedString::new("a"))
.debug_check_constructor();
}
#[test]
#[should_panic(expected = "If linkUrl is set then link must be true")]
fn a_link_url_without_link_asserts() {
SemanticsProperties::new()
.link_url("https://flutter.dev")
.debug_check_constructor();
}
#[test]
#[should_panic(expected = "Heading level must be between 1 and 6")]
fn a_heading_level_out_of_range_asserts() {
let _ = SemanticsProperties::new().heading_level(7);
}
}