Skip to main content

yew_e2e/test_driver/
keyboard.rs

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