Skip to main content

yew_e2e/test_driver/
pointer.rs

1//! Pressing, holding and letting go with the pointer.
2
3use anyhow::Result;
4use thirtyfour::By;
5
6use crate::finding::{OutOfTime, poll};
7use crate::{IntoBy, TestDriver, TestElement};
8
9impl TestDriver {
10    /// Carry one element onto another and let go.
11    pub async fn pointer_drag_onto(&self, from: &TestElement, to: &TestElement) -> Result<()> {
12        from.inner.scroll_into_view().await?;
13        self.inner
14            .action_chain()
15            .move_to_element_center(&from.inner)
16            .click_and_hold()
17            .move_by_offset(8, 0)
18            .release_on_element(&to.inner)
19            .perform()
20            .await?;
21        Ok(())
22    }
23
24    /// Let go of every key and button the actions above hold, the WebDriver
25    /// way, which also puts down a drag an engine would otherwise keep
26    /// carrying into the next test.
27    ///
28    /// A drag begun here is let go where the pointer is, as the specification
29    /// asks; chromedriver's own release would let it go where it was pressed.
30    pub async fn release_all_input(&self) -> Result<()> {
31        if self.holding.take() {
32            self.inner.action_chain().release().perform().await?;
33        }
34
35        self.inner.action_chain().reset_actions().await?;
36        Ok(())
37    }
38
39    /// Press the middle button over an element.
40    pub async fn middle_click(&self, element: &TestElement) -> Result<()> {
41        tracing::trace!("Middle-clicking an element");
42
43        let script = "for (const type of ['mousedown', 'mouseup', 'auxclick']) {\
44             arguments[0].dispatchEvent(new MouseEvent(type, \
45             { button: 1, buttons: 4, bubbles: true, cancelable: true })); \
46         }";
47
48        self.inner
49            .execute(script, vec![element.inner.to_json()?])
50            .await?;
51
52        Ok(())
53    }
54
55    /// Pan with a native middle-button drag, releasing the button at the end.
56    pub async fn middle_drag_by(&self, element: &TestElement, dx: i64) -> Result<()> {
57        use thirtyfour::common::command::Command;
58
59        let actions = serde_json::json!([{
60            "type": "pointer", "id": "pointer", "parameters": {"pointerType": "mouse"},
61            "actions": [
62                {"type": "pointerMove", "duration": 0, "origin": element.inner.to_json()?, "x": 0, "y": 0},
63                {"type": "pointerDown", "button": 1},
64                {"type": "pointerMove", "duration": 150, "origin": "pointer", "x": dx, "y": 0},
65                {"type": "pointerUp", "button": 1}
66            ]
67        }]);
68        self.inner
69            .cmd(Command::PerformActions(actions.into()))
70            .await?;
71        Ok(())
72    }
73
74    /// Carry a held drag somewhere else without letting go of it.
75    pub async fn move_held(&self, dx: i64, dy: i64) -> Result<()> {
76        tracing::trace!(dx, dy, "Carrying a held drag");
77
78        self.inner
79            .action_chain()
80            .move_by_offset(dx, dy)
81            .perform()
82            .await?;
83
84        Ok(())
85    }
86
87    /// Let go of whatever [`TestElement::drag_by`] is holding.
88    pub async fn drop_held(&self) -> Result<()> {
89        tracing::trace!("Releasing a held drag");
90        self.inner.action_chain().release().perform().await?;
91        self.holding.set(false);
92        Ok(())
93    }
94
95    /// Cancel a captured pointer without releasing the test's held button, so
96    /// a later mouse-up can prove that cancelled work is not committed.
97    pub async fn cancel_pointer(&self, element: &TestElement) -> Result<()> {
98        self.inner
99            .execute(
100                "arguments[0].dispatchEvent(new PointerEvent('pointercancel', { bubbles: true }));",
101                vec![element.inner.to_json()?],
102            )
103            .await?;
104        Ok(())
105    }
106
107    /// The same for a drag that was begun with `alt` held, which has to give
108    /// the key back as well as the button.
109    pub async fn drop_held_alt(&self) -> Result<()> {
110        tracing::trace!("Releasing a held drag and the alt key with it");
111
112        self.inner
113            .action_chain()
114            .release()
115            .key_up(thirtyfour::Key::Alt)
116            .perform()
117            .await?;
118        self.holding.set(false);
119
120        Ok(())
121    }
122
123    /// Press the `index`th element matching `by`, re-finding it if the page
124    /// moves underneath.
125    ///
126    /// Giving up says why the last press did not land, such as another
127    /// element covering this one, under the timeout.
128    pub async fn press_nth(&self, by: impl IntoBy, index: usize) -> Result<()> {
129        let by = by.into_by();
130
131        tracing::trace!(?by, index, "Pressing element");
132
133        self.press_nth_with(by, index, "pressing", async |item| item.click().await)
134            .await
135    }
136
137    /// The same as [`TestDriver::press_nth`], right-handed. A context menu that
138    /// belongs to a thing is opened on the thing itself, so there is no button
139    /// to press and this is how a test reaches one.
140    pub async fn context_press_nth(&self, by: impl IntoBy, index: usize) -> Result<()> {
141        let by = by.into_by();
142
143        tracing::trace!(?by, index, "Right-clicking element");
144
145        self.press_nth_with(by, index, "right-clicking", async |item| {
146            item.context_click().await
147        })
148        .await
149    }
150
151    /// Press the `index`th element matching `by` with `press` until it lands,
152    /// giving up with what the last attempt said under a timeout saying what
153    /// `doing` was.
154    async fn press_nth_with(
155        &self,
156        by: By,
157        index: usize,
158        doing: &str,
159        press: impl AsyncFn(&TestElement) -> Result<()>,
160    ) -> Result<()> {
161        let mut refused = None;
162
163        let pressed = poll(self.wait_timeout, async || {
164            if let Some(item) = self.find_all(by.clone()).await?.get(index) {
165                match press(item).await {
166                    Ok(()) => return Ok(Some(())),
167                    Err(error) => refused = Some(error),
168                }
169            }
170
171            Ok(None)
172        })
173        .await?;
174
175        if pressed.is_some() {
176            return Ok(());
177        }
178
179        let timeout = OutOfTime(format!(
180            "Timed out after {:?} {doing} {by} at {index}",
181            self.wait_timeout
182        ));
183
184        Err(match refused {
185            Some(error) => error.context(timeout),
186            None => timeout.into(),
187        })
188    }
189}