Skip to main content

playwright_rs/protocol/
keyboard.rs

1// Keyboard - Low-level keyboard control
2//
3// See: https://playwright.dev/docs/api/class-keyboard
4
5use crate::error::Result;
6use crate::protocol::page::Page;
7
8/// Keyboard provides low-level keyboard control.
9///
10/// See: <https://playwright.dev/docs/api/class-keyboard>
11#[derive(Clone)]
12pub struct Keyboard {
13    page: Page,
14}
15
16impl Keyboard {
17    /// Creates a new Keyboard instance for the given page
18    pub(crate) fn new(page: Page) -> Self {
19        Self { page }
20    }
21
22    /// Dispatches a `keydown` event.
23    ///
24    /// See: <https://playwright.dev/docs/api/class-keyboard#keyboard-down>
25    pub async fn down(&self, key: &str) -> Result<()> {
26        self.page.keyboard_down(key).await
27    }
28
29    /// Dispatches a `keyup` event.
30    ///
31    /// See: <https://playwright.dev/docs/api/class-keyboard#keyboard-up>
32    pub async fn up(&self, key: &str) -> Result<()> {
33        self.page.keyboard_up(key).await
34    }
35
36    /// Executes a complete key press (down + up sequence).
37    ///
38    /// See: <https://playwright.dev/docs/api/class-keyboard#keyboard-press>
39    pub async fn press(
40        &self,
41        key: &str,
42        options: impl Into<Option<crate::protocol::KeyboardOptions>>,
43    ) -> Result<()> {
44        let options = options.into();
45        self.page.keyboard_press(key, options).await
46    }
47
48    /// Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character.
49    ///
50    /// See: <https://playwright.dev/docs/api/class-keyboard#keyboard-type>
51    pub async fn type_text(
52        &self,
53        text: &str,
54        options: impl Into<Option<crate::protocol::KeyboardOptions>>,
55    ) -> Result<()> {
56        let options = options.into();
57        self.page.keyboard_type(text, options).await
58    }
59
60    /// Dispatches only `input` event, does not emit `keydown`, `keyup` or `keypress` events.
61    ///
62    /// See: <https://playwright.dev/docs/api/class-keyboard#keyboard-insert-text>
63    pub async fn insert_text(&self, text: &str) -> Result<()> {
64        self.page.keyboard_insert_text(text).await
65    }
66}