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