use crate::action::ActionCall;
use crate::error::{Error, Result};
use crate::page::Page;
use crate::{Action, LocatorQuery, LocatorSpec};
use serde_json::{json, Value};
#[derive(Debug, Clone, Copy)]
pub struct BoundingBox {
pub x: f64,
pub y: f64,
pub width: f64,
pub height: f64,
}
impl BoundingBox {
pub fn center(&self) -> (f64, f64) {
(self.x + self.width / 2.0, self.y + self.height / 2.0)
}
}
pub struct Element {
pub(crate) page: Page,
pub(crate) backend_node_id: i64,
}
impl Element {
pub(crate) async fn from_node_id(page: &Page, node_id: i32) -> Result<Self> {
let described: Value = page
.session
.send("DOM.describeNode", &json!({ "nodeId": node_id }))
.await?;
let backend_node_id = described["node"]["backendNodeId"]
.as_i64()
.ok_or_else(|| Error::cdp("DOM.describeNode", -1, "No backendNodeId returned"))?;
Ok(Self {
page: page.clone(),
backend_node_id,
})
}
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)
}
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))
})
}
pub fn click(&self) -> ActionCall {
ActionCall::new(&self.page, Action::click(self.action_target(), false))
}
pub fn human_click(&self) -> ActionCall {
ActionCall::new(&self.page, Action::click(self.action_target(), true))
}
pub fn human_drag_by(&self, dx: f64) -> ActionCall {
ActionCall::new(
&self.page,
Action::Drag {
target: self.action_target(),
dx,
dy: 0.0,
},
)
}
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())
}
pub async fn text(&self) -> Result<String> {
self.eval_str("function(){return this.textContent || ''}", &[])
.await
}
async fn call_on_element(&self, function: &str, args: &[Value]) -> Result<Value> {
let resolved: Value = self
.page
.session
.send(
"DOM.resolveNode",
&json!({ "backendNodeId": self.backend_node_id }),
)
.await?;
let object_id = resolved["object"]["objectId"]
.as_str()
.ok_or_else(|| Error::cdp("DOM.resolveNode", -1, "No object_id returned"))?
.to_owned();
let arguments: Vec<Value> = args.iter().map(|value| json!({ "value": value })).collect();
let result: Result<Value> = self
.page
.session
.send(
"Runtime.callFunctionOn",
&json!({
"objectId": object_id,
"functionDeclaration": function,
"arguments": arguments,
"returnByValue": true,
}),
)
.await;
let _ = self
.page
.session
.send::<_, Value>("Runtime.releaseObject", &json!({ "objectId": object_id }))
.await;
let result = result?;
if let Some(details) = result.get("exceptionDetails") {
return Err(Error::javascript_exception(details));
}
Ok(result["result"]["value"].clone())
}
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())
}
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))
}
pub fn type_text(&self, text: &str) -> ActionCall {
ActionCall::new(&self.page, Action::type_text(self.action_target(), text))
}
pub async fn focus(&self) -> Result<()> {
self.page
.act_default(Action::Focus {
target: self.action_target(),
})
.await
}
pub async fn is_visible(&self) -> Result<bool> {
crate::action::is_visible(&self.page, &self.action_target()).await
}
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,
})
}
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))
}
pub async fn tag_name(&self) -> Result<String> {
self.eval_str("function(){return this.tagName.toLowerCase()}", &[])
.await
}
pub async fn is_enabled(&self) -> Result<bool> {
self.eval_bool("function(){return !this.disabled}", true)
.await
}
pub async fn is_checked(&self) -> Result<bool> {
self.eval_bool("function(){return this.checked === true}", false)
.await
}
pub async fn value(&self) -> Result<String> {
self.eval_str("function(){return this.value || ''}", &[])
.await
}
pub async fn css(&self, property: &str) -> Result<String> {
self.eval_str(
"function(property){return getComputedStyle(this).getPropertyValue(property)}",
&[json!(property)],
)
.await
}
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;
#[test]
fn element_is_send_and_static() {
fn assert_send_static<T: Send + 'static>() {}
assert_send_static::<Element>();
}
}