Skip to main content

yew_e2e/test_driver/
keyboard.rs

1//! Keys, pressed through WebDriver or dispatched on an element, and focus.
2
3use anyhow::Result;
4use thirtyfour::prelude::*;
5
6use crate::TestDriver;
7
8impl TestDriver {
9    /// Press a key with nothing in particular focused, the way a hand does when
10    /// it has just opened something with the pointer.
11    pub async fn press_key(&self, key: Key) -> Result<()> {
12        tracing::trace!(?key, "Pressing a key");
13        self.inner.action_chain().send_keys(key).perform().await?;
14        Ok(())
15    }
16
17    /// Hold a real WebDriver key across observations, rather than sending a
18    /// down/up pair too quickly for an animation frame to show it.
19    pub async fn hold_key(&self, key: char) -> Result<()> {
20        self.inner.action_chain().key_down(key).perform().await?;
21        Ok(())
22    }
23
24    /// Let go of a key held with [`Self::hold_key`].
25    pub async fn release_key(&self, key: char) -> Result<()> {
26        self.inner.action_chain().key_up(key).perform().await?;
27        Ok(())
28    }
29
30    /// Dispatch a named key on a focused element, including keys WebDriver cannot encode.
31    pub async fn press_key_on(&self, selector: &str, key: &str) -> Result<()> {
32        let script = "const at = document.querySelector(arguments[0]); \
33             if (!at) throw new Error('No element for keyboard press'); \
34             at.focus(); at.dispatchEvent(new KeyboardEvent('keydown', \
35             { key: arguments[1], bubbles: true, cancelable: true }));";
36        self.inner
37            .execute(
38                script,
39                vec![serde_json::json!(selector), serde_json::json!(key)],
40            )
41            .await?;
42        Ok(())
43    }
44
45    /// **Press a key on one element with `control` held**, which is how undo,
46    /// redo and select-all are reached.
47    ///
48    /// Dispatched on the element so the press lands where the test says. The
49    /// event carries the `code` a real letter key does, since a listener on
50    /// the document may read the code and a press without one would never
51    /// reach it.
52    pub async fn press_key_with_ctrl(&self, selector: &str, key: &str) -> Result<()> {
53        tracing::trace!(selector, key, "Pressing a key with control held");
54
55        let code = match key.chars().collect::<Vec<_>>().as_slice() {
56            [c] if c.is_ascii_alphabetic() => format!("Key{}", c.to_ascii_uppercase()),
57            _ => key.to_owned(),
58        };
59
60        let script = "const at = document.querySelector(arguments[0]); \
61             if (at) { at.focus(); at.dispatchEvent(new KeyboardEvent('keydown', \
62             { key: arguments[1], code: arguments[2], ctrlKey: true, bubbles: true, cancelable: true })); }";
63
64        self.inner
65            .execute(
66                script,
67                vec![
68                    serde_json::json!(selector),
69                    serde_json::json!(key),
70                    serde_json::json!(code),
71                ],
72            )
73            .await?;
74        Ok(())
75    }
76
77    /// **Press a key on one element with shift held**, dispatched for the
78    /// same reason [`Self::press_key_with_ctrl`] is.
79    pub async fn press_key_with_shift(&self, selector: &str, key: &str) -> Result<()> {
80        tracing::trace!(selector, key, "Pressing a key with shift held");
81
82        let script = "const at = document.querySelector(arguments[0]); \
83             if (at) { at.focus(); at.dispatchEvent(new KeyboardEvent('keydown', \
84             { key: arguments[1], shiftKey: true, bubbles: true, cancelable: true })); }";
85
86        self.inner
87            .execute(
88                script,
89                vec![serde_json::json!(selector), serde_json::json!(key)],
90            )
91            .await?;
92        Ok(())
93    }
94
95    /// Take keyboard focus off whatever has it, so the next key lands on the
96    /// page rather than on a control.
97    pub async fn blur(&self) -> Result<()> {
98        tracing::trace!("Blurring the focused element");
99
100        self.inner
101            .execute(
102                "document.activeElement && document.activeElement.blur();",
103                Vec::new(),
104            )
105            .await?;
106
107        Ok(())
108    }
109
110    /// One attribute of whatever element has keyboard focus, or `None` when
111    /// it has no such attribute. Where nothing is focused, that is the
112    /// document's `<body>`.
113    ///
114    /// Answers once, at the time of asking; it does not wait.
115    pub async fn focused_attr(&self, name: &str) -> Result<Option<String>> {
116        let found = self
117            .inner
118            .execute(
119                "return document.activeElement \
120                 && document.activeElement.getAttribute(arguments[0])",
121                vec![serde_json::json!(name)],
122            )
123            .await?;
124
125        Ok(found.json().as_str().map(str::to_owned))
126    }
127}