1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
//! Element Abstraction
//!
//! DOM element wrapper and its bounding box type.
use crate::action::ActionCall;
use crate::error::{Error, Result};
use crate::page::Page;
use crate::{Action, LocatorQuery, LocatorSpec};
use serde_json::{json, Value};
/// Bounding box of an element
#[derive(Debug, Clone, Copy)]
pub struct BoundingBox {
/// X coordinate of the top-left corner, in CSS pixels.
pub x: f64,
/// Y coordinate of the top-left corner, in CSS pixels.
pub y: f64,
/// Width in CSS pixels.
pub width: f64,
/// Height in CSS pixels.
pub height: f64,
}
impl BoundingBox {
/// Center point of the box as `(x, y)`.
pub fn center(&self) -> (f64, f64) {
(self.x + self.width / 2.0, self.y + self.height / 2.0)
}
}
/// A handle to a DOM element. Owns a cheap clone of its `Page`, so it is
/// `'static` — you can store it, return it, and pass it around freely.
///
/// Pinned to Chrome's backend node id. Its JavaScript reads (`text`,
/// `value`, `get_attribute`, ...) run in eoka's isolated world, so page
/// scripts that patch DOM prototypes cannot change their results; a custom
/// element's JavaScript-defined accessors are not visible there. Removing the
/// node or navigating makes the handle stale for actions (a removed node can
/// still be read); it is never retargeted to a replacement.
pub struct Element {
pub(crate) page: Page,
pub(crate) backend_node_id: i64,
}
impl Element {
fn action_target(&self) -> LocatorSpec {
LocatorSpec {
query: LocatorQuery::BackendNode {
id: self.backend_node_id,
},
frame_id: None,
index: None,
}
}
async fn box_model(&self) -> Result<crate::cdp::types::BoxModel> {
let result: crate::cdp::types::DOMGetBoxModelResult = self
.page
.session
.send(
"DOM.getBoxModel",
&json!({ "backendNodeId": self.backend_node_id }),
)
.await?;
Ok(result.model)
}
/// Get the element's center coordinates
pub async fn center(&self) -> Result<(f64, f64)> {
let model = self.box_model().await?;
model.try_center().ok_or_else(|| {
Error::element_not_visible(format!("backend node {}", self.backend_node_id))
})
}
/// Click this element. Awaiting proves dispatch only; see [`ActionCall`].
pub fn click(&self) -> ActionCall {
ActionCall::new(&self.page, Action::click(self.action_target(), false))
}
/// Click this element with human-like mouse movement. Awaiting proves
/// dispatch only; see [`ActionCall`].
pub fn human_click(&self) -> ActionCall {
ActionCall::new(&self.page, Action::click(self.action_target(), true))
}
/// Drag horizontally from this element's center using human-like motion.
/// See [`crate::stealth::Human::drag_by`] for ownership and cleanup semantics.
pub fn human_drag_by(&self, dx: f64) -> ActionCall {
ActionCall::new(
&self.page,
Action::Drag {
target: self.action_target(),
dx,
dy: 0.0,
},
)
}
/// Get outer HTML
pub async fn outer_html(&self) -> Result<String> {
let result: Value = self
.page
.session
.send(
"DOM.getOuterHTML",
&json!({ "backendNodeId": self.backend_node_id }),
)
.await?;
Ok(result["outerHTML"].as_str().unwrap_or_default().to_owned())
}
/// Get the element's `textContent` (empty when it has none).
pub async fn text(&self) -> Result<String> {
self.eval_str("function(){return this.textContent || ''}", &[])
.await
}
/// Calls `function` with this element as `this` in eoka's isolated
/// world, returning the result by value. The remote object is released
/// afterwards so repeated calls don't pin nodes.
async fn call_on_element(&self, function: &str, args: &[Value]) -> Result<Value> {
crate::action::call_on(&self.page, &self.action_target(), function, args.to_vec()).await
}
/// Call a function on the element, returning a String (empty on null/non-string)
async fn eval_str(&self, function: &str, args: &[Value]) -> Result<String> {
let value = self.call_on_element(function, args).await?;
Ok(value.as_str().unwrap_or("").to_string())
}
/// Call a function on the element, returning a bool with a default
async fn eval_bool(&self, function: &str, default: bool) -> Result<bool> {
let value = self.call_on_element(function, &[]).await?;
Ok(value.as_bool().unwrap_or(default))
}
/// Type text into this element. Awaiting proves dispatch only; see [`ActionCall`].
pub fn type_text(&self, text: &str) -> ActionCall {
ActionCall::new(&self.page, Action::type_text(self.action_target(), text))
}
/// Focus this element
pub async fn focus(&self) -> Result<()> {
self.page
.act_default(Action::Focus {
target: self.action_target(),
})
.await
}
/// Check for a rendered, nonzero box with visible CSS visibility.
/// Offscreen, transparent and disabled elements can still be visible.
pub async fn is_visible(&self) -> Result<bool> {
crate::action::is_visible(&self.page, &self.action_target()).await
}
/// Get the element's bounding box
///
/// Returns None if the element is not visible/rendered.
pub async fn bounding_box(&self) -> Option<BoundingBox> {
let model = self.box_model().await.ok()?;
let (min_x, min_y, max_x, max_y) =
crate::cdp::types::Quad::from_slice(&model.content)?.bounds();
Some(BoundingBox {
x: min_x,
y: min_y,
width: max_x - min_x,
height: max_y - min_y,
})
}
/// Get an attribute value
pub async fn get_attribute(&self, name: &str) -> Result<Option<String>> {
let value = self
.call_on_element(
"function(name){return this.getAttribute(name)}",
&[json!(name)],
)
.await?;
Ok(value.as_str().map(str::to_owned))
}
/// Get the tag name of the element (e.g., "div", "input", "a")
pub async fn tag_name(&self) -> Result<String> {
self.eval_str("function(){return this.tagName.toLowerCase()}", &[])
.await
}
/// Check if the element is enabled (not disabled)
pub async fn is_enabled(&self) -> Result<bool> {
self.eval_bool("function(){return !this.disabled}", true)
.await
}
/// Check if a checkbox/radio is checked
pub async fn is_checked(&self) -> Result<bool> {
self.eval_bool("function(){return this.checked === true}", false)
.await
}
/// Get the value of an input element
pub async fn value(&self) -> Result<String> {
self.eval_str("function(){return this.value || ''}", &[])
.await
}
/// Get computed CSS property value
pub async fn css(&self, property: &str) -> Result<String> {
self.eval_str(
"function(property){return getComputedStyle(this).getPropertyValue(property)}",
&[json!(property)],
)
.await
}
/// Scroll this element into view
pub async fn scroll_into_view(&self) -> Result<()> {
self.page
.act_default(Action::ScrollIntoView {
target: self.action_target(),
})
.await
}
}
#[cfg(test)]
mod tests {
use super::Element;
// Element owns its Page, so it must be Send + 'static — storable, returnable,
// and movable across await points and tasks. This is the reusability contract.
#[test]
fn element_is_send_and_static() {
fn assert_send_static<T: Send + 'static>() {}
assert_send_static::<Element>();
}
}