Skip to main content

iced_cube/
testing.rs

1//! Locators that know how iced-cube components are built, for icedwright
2//! tests. Behind the `icedwright` feature.
3//!
4//! Each one wraps a locator for a component's root node and builds locators
5//! for its parts, so a test says `tree.item(["Projects", "Roadmap"])` rather
6//! than chaining roles and names. They are pure queries: bind one to a
7//! harness to act on it.
8//!
9//! ```no_run
10//! use iced_cube::testing::{ComponentLocator, Tree};
11//! use icedwright_locator::{Scope, get_by_role, role};
12//!
13//! let tree = Tree::from_locator(get_by_role(role::Tree).name("Projects").any_role());
14//! let roadmap = tree.item(["Projects", "Roadmap"]);
15//! # let _ = roadmap;
16//! ```
17
18use icedwright_locator::{
19    Locator, Role, RoleKind, Scope, TextMatch, get_by_role_dyn, of_type, role,
20};
21use icedwright_semantics::{Node, SemanticTree};
22
23/// A component's locator, built over the locator for its root node.
24pub trait ComponentLocator: Sized {
25    /// The kind the component's annotations report, such as `"iced_cube::tree"`.
26    const KIND: &'static str;
27
28    /// The role of the component's root node.
29    const ROOT: Role;
30
31    /// Wraps a locator that finds the component's root.
32    fn from_locator(root: Locator) -> Self;
33
34    /// The locator for the component's root.
35    fn locator(&self) -> &Locator;
36
37    /// Every component of this kind on the page. Its parts report the same
38    /// kind, so this matches the root role as well.
39    fn of_kind() -> Self {
40        Self::from_locator(get_by_role_dyn(Self::ROOT).and(of_type(Self::KIND)))
41    }
42}
43
44macro_rules! component {
45    ($(#[$doc:meta])* $name:ident, $kind:literal, $root:ident) => {
46        $(#[$doc])*
47        #[derive(Debug, Clone, PartialEq, Eq)]
48        pub struct $name {
49            root: Locator,
50        }
51
52        impl ComponentLocator for $name {
53            const KIND: &'static str = $kind;
54            const ROOT: Role = Role::$root;
55
56            fn from_locator(root: Locator) -> Self {
57                Self { root }
58            }
59
60            fn locator(&self) -> &Locator {
61                &self.root
62            }
63        }
64    };
65}
66
67component!(
68    /// A [`tree`](mod@crate::tree): items found by their path of labels.
69    Tree,
70    "iced_cube::tree",
71    Tree
72);
73
74impl Tree {
75    /// The item at `path`, each label an exact name, following each item
76    /// into the items it owns.
77    pub fn item(&self, path: impl IntoIterator<Item = impl AsRef<str>>) -> Locator<role::TreeItem> {
78        let mut path = path.into_iter();
79        let Some(first) = path.next() else {
80            return self.root.clone().get_by_role(role::TreeItem).first();
81        };
82        path.fold(
83            item_named(self.root.clone(), first.as_ref()),
84            |item, label| item_named(item.any_role(), label.as_ref()),
85        )
86    }
87
88    /// The button that expands or collapses the item at `path`.
89    pub fn expander(
90        &self,
91        path: impl IntoIterator<Item = impl AsRef<str>>,
92    ) -> Locator<role::Button> {
93        self.item(path).get_by_role(role::Button).first()
94    }
95
96    /// The selected items.
97    pub fn selected(&self) -> Locator<role::TreeItem> {
98        self.root.clone().get_by_role(role::TreeItem).selected(true)
99    }
100}
101
102fn item_named(scope: Locator, label: &str) -> Locator<role::TreeItem> {
103    scope
104        .get_by_role(role::TreeItem)
105        .name(TextMatch::exact(label))
106        .first()
107}
108
109component!(
110    /// [`tabs`](mod@crate::tabs): a tab strip.
111    Tabs,
112    "iced_cube::tabs",
113    TabList
114);
115
116impl Tabs {
117    /// The tab labelled `name`.
118    pub fn tab(&self, name: &str) -> Locator<role::Tab> {
119        self.root
120            .clone()
121            .get_by_role(role::Tab)
122            .name(TextMatch::exact(name))
123    }
124
125    /// The selected tab.
126    pub fn selected(&self) -> Locator<role::Tab> {
127        self.root.clone().get_by_role(role::Tab).selected(true)
128    }
129}
130
131component!(
132    /// [`document_tabs`](mod@crate::document_tabs): open documents, each with a
133    /// close button.
134    DocumentTabs,
135    "iced_cube::document_tabs",
136    TabList
137);
138
139impl DocumentTabs {
140    /// The tab labelled `name`.
141    pub fn tab(&self, name: &str) -> Locator<role::Tab> {
142        self.root
143            .clone()
144            .get_by_role(role::Tab)
145            .name(TextMatch::exact(name))
146    }
147
148    /// The button that closes the tab labelled `name`.
149    pub fn close_button(&self, name: &str) -> Locator<role::Button> {
150        self.tab(name)
151            .get_by_role(role::Button)
152            .name(TextMatch::exact(format!("Close {name}")))
153    }
154
155    /// The selected, active tab.
156    pub fn selected(&self) -> Locator<role::Tab> {
157        self.root.clone().get_by_role(role::Tab).selected(true)
158    }
159
160    /// The tabs with unsaved changes in `tree`, one locator each. Locators
161    /// cannot match props, so this reads them from a tree.
162    pub fn unsaved(&self, tree: &SemanticTree) -> Vec<Locator<role::Tab>> {
163        let tabs = self.root.clone().get_by_role(role::Tab);
164        tabs.all(tree)
165            .filter(|tab| {
166                resolved(tree, tab).is_some_and(|node| {
167                    node.props.get("unsaved").map(String::as_str) == Some("true")
168                })
169            })
170            .collect()
171    }
172}
173
174component!(
175    /// An open menu. [`of_kind`](ComponentLocator::of_kind) finds
176    /// [`dropdown_menu`](mod@crate::dropdown_menu) panels; wrap a locator for
177    /// the `Menu` node to use it on a [`context_menu`](mod@crate::context_menu)
178    /// or menu bar panel.
179    Menu,
180    "iced_cube::dropdown_menu",
181    Menu
182);
183
184impl Menu {
185    /// The item labelled `name`, including check and radio items.
186    pub fn item(&self, name: &str) -> Locator {
187        let named =
188            |role: Role| icedwright_locator::get_by_role_dyn(role).name(TextMatch::exact(name));
189        self.root.clone().locator(
190            named(Role::MenuItem)
191                .or(named(Role::MenuItemCheckBox))
192                .or(named(Role::MenuItemRadio)),
193        )
194    }
195}
196
197component!(
198    /// A [`virtual_list`](mod@crate::virtual_list): only the rows on screen are
199    /// in the tree, each with its position in the whole list.
200    VirtualList,
201    "iced_cube::virtual_list",
202    List
203);
204
205/// How far to scroll a list to bring a row into view.
206#[derive(Debug, Clone, Copy, PartialEq)]
207pub struct ScrollTarget {
208    /// The position of the scrollable around the list among the
209    /// interface's scrollables, or `None` when the list scrolls itself, as
210    /// the virtual list does, and is driven by its own events.
211    pub ordinal: Option<u32>,
212    /// The vertical offset, in logical pixels, that puts the row at the top.
213    pub offset: f32,
214}
215
216impl VirtualList {
217    fn rows(&self) -> Locator<role::ListItem> {
218        self.root.clone().get_by_role(role::ListItem)
219    }
220
221    /// The rendered row at `index`, counted from 0 over the whole list, or
222    /// `None` when that row is not rendered in `tree`.
223    pub fn row(&self, tree: &SemanticTree, index: u32) -> Option<Locator<role::ListItem>> {
224        self.rows()
225            .all(tree)
226            .find(|row| resolved(tree, row).and_then(|n| n.set.position) == Some(index + 1))
227    }
228
229    /// The scroll that brings row `index` to the top of the list, from a
230    /// rendered row's height, since every row has the same height. `None`
231    /// when no row is rendered.
232    pub fn scroll_target(&self, tree: &SemanticTree, index: u32) -> Option<ScrollTarget> {
233        let row = self.rows().all(tree).find_map(|row| resolved(tree, &row))?;
234        Some(ScrollTarget {
235            ordinal: row.scroll_ancestors.last().map(|scroll| scroll.ordinal),
236            offset: index as f32 * row.bounds.height,
237        })
238    }
239}
240
241component!(
242    /// A [`timeline`](mod@crate::data::timeline): one slider over its steps,
243    /// whose value is the current step.
244    Timeline,
245    "iced_cube::timeline",
246    Slider
247);
248
249impl Timeline {
250    /// The slider itself, for setting or reading the current step.
251    pub fn slider(&self) -> Locator<role::Slider> {
252        self.root.clone().into_role::<role::Slider>()
253    }
254}
255
256component!(
257    /// An [`image_compare`](mod@crate::data::image_compare): a group of the
258    /// before and after images and, in slider mode, the divider.
259    ImageCompare,
260    "iced_cube::image_compare",
261    Group
262);
263
264impl ImageCompare {
265    /// The before image, when one is shown.
266    pub fn before(&self) -> Locator<role::Image> {
267        self.image("Before")
268    }
269
270    /// The after image, or the only one.
271    pub fn after(&self) -> Locator<role::Image> {
272        self.image("After")
273    }
274
275    /// The divider, a splitter whose value runs from 0 to 100.
276    pub fn divider(&self) -> Locator<role::Splitter> {
277        self.root
278            .clone()
279            .get_by_role(role::Splitter)
280            .name(TextMatch::exact("Divider"))
281    }
282
283    fn image(&self, name: &str) -> Locator<role::Image> {
284        self.root
285            .clone()
286            .get_by_role(role::Image)
287            .name(TextMatch::exact(name))
288    }
289}
290
291fn resolved<'t, R: RoleKind>(tree: &'t SemanticTree, locator: &Locator<R>) -> Option<&'t Node> {
292    let id = icedwright_locator::resolve(tree, locator).ok()?;
293    tree.get(id)
294}