Skip to main content

cdp_driver/
action_builder.rs

1//! Assembling a sequence of [`BrowserAction`]s to run in one go.
2
3use crate::action::BrowserAction;
4
5/// Fluent builder for a sequence of [`BrowserAction`]s, run with
6/// [`BrowserAgent::execute_many`](crate::agent::BrowserAgent::execute_many).
7pub struct ActionBuilder {
8    actions: Vec<BrowserAction>,
9}
10
11impl Default for ActionBuilder {
12    fn default() -> Self {
13        Self::new()
14    }
15}
16
17impl ActionBuilder {
18    /// Start an empty action sequence.
19    pub fn new() -> Self {
20        ActionBuilder {
21            actions: Vec::new(),
22        }
23    }
24
25    /// Append [`BrowserAction::Navigate`].
26    pub fn navigate(mut self, url: &str) -> Self {
27        self.actions
28            .push(BrowserAction::Navigate { url: url.into() });
29        self
30    }
31
32    /// Append [`BrowserAction::Wait`].
33    pub fn wait(mut self, ms: u64) -> Self {
34        self.actions.push(BrowserAction::Wait { ms });
35        self
36    }
37
38    /// Append [`BrowserAction::Click`] targeting a CSS selector.
39    pub fn click(mut self, selector: &str) -> Self {
40        self.actions.push(BrowserAction::Click {
41            selector: Some(selector.into()),
42            x: None,
43            y: None,
44        });
45        self
46    }
47
48    /// Append [`BrowserAction::Fill`].
49    pub fn fill(mut self, selector: &str, value: &str) -> Self {
50        self.actions.push(BrowserAction::Fill {
51            selector: selector.into(),
52            value: value.into(),
53        });
54        self
55    }
56
57    /// Append [`BrowserAction::PressKey`].
58    pub fn press_key(mut self, key: &str) -> Self {
59        self.actions
60            .push(BrowserAction::PressKey { key: key.into() });
61        self
62    }
63
64    /// Append [`BrowserAction::Screenshot`].
65    pub fn screenshot(mut self, path: Option<&str>) -> Self {
66        self.actions.push(BrowserAction::Screenshot {
67            path: path.map(Into::into),
68        });
69        self
70    }
71
72    /// Append [`BrowserAction::Evaluate`].
73    pub fn evaluate(mut self, expr: &str) -> Self {
74        self.actions.push(BrowserAction::Evaluate {
75            expression: expr.into(),
76        });
77        self
78    }
79
80    /// Append [`BrowserAction::Scroll`].
81    pub fn scroll(mut self, x: f64, y: f64) -> Self {
82        self.actions.push(BrowserAction::Scroll { x, y });
83        self
84    }
85
86    /// Append [`BrowserAction::GetTitle`].
87    pub fn get_title(mut self) -> Self {
88        self.actions.push(BrowserAction::GetTitle);
89        self
90    }
91
92    /// Finish building and return the action sequence.
93    pub fn build(self) -> Vec<BrowserAction> {
94        self.actions
95    }
96}