use super::evaluate::check_js_result;
use super::{Element, Page, TextMatch};
use crate::action::{ActionCall, TryActionCall};
use crate::error::{Error, Result};
use crate::{Action, InputMode, LocatorSpec};
fn text_candidates_expression(text: &str, match_type: TextMatch, all: bool) -> Result<String> {
let mode = match match_type {
TextMatch::Exact => "exact",
TextMatch::Contains => "contains",
TextMatch::StartsWith => "starts_with",
TextMatch::EndsWith => "ends_with",
};
Ok(format!(
"({})({}, '{mode}', {all})",
include_str!("text_candidates.js"),
serde_json::to_string(text)?
))
}
impl Page {
pub(crate) async fn act_default(&self, action: Action) -> Result<()> {
self.act(action, self.action_defaults.options())
.await
.map(|_| ())
}
pub fn human_drag(&self, selector: &str, dx: f64) -> ActionCall {
ActionCall::new(
self,
Action::Drag {
target: LocatorSpec::css(selector),
dx,
dy: 0.0,
},
)
}
pub async fn find(&self, selector: &str) -> Result<Element> {
let node_id = self
.with_document(|doc| self.session.query_selector(doc, selector))
.await?;
if node_id == 0 {
return Err(Error::ElementNotFound(selector.to_string()));
}
Element::from_node_id(self, node_id).await
}
pub async fn find_all(&self, selector: &str) -> Result<Vec<Element>> {
let node_ids = self
.with_document(|doc| self.session.query_selector_all(doc, selector))
.await?;
futures_util::future::try_join_all(
node_ids
.into_iter()
.filter(|&id| id != 0)
.map(|node_id| Element::from_node_id(self, node_id)),
)
.await
}
#[must_use = "returns true if element exists"]
pub async fn exists(&self, selector: &str) -> bool {
self.find(selector).await.is_ok()
}
pub async fn find_by_text(&self, text: &str) -> Result<Element> {
self.find_by_text_match(text, TextMatch::Contains).await
}
pub async fn find_by_text_match(&self, text: &str, match_type: TextMatch) -> Result<Element> {
let js = format!(
"({})[0] ?? null",
text_candidates_expression(text, match_type, false)?
);
let (result, _objects) = self.session.evaluate_for_remote_object(&js).await?;
let remote = check_js_result(result)?;
if remote.subtype.as_deref() == Some("null") {
return Err(Error::ElementNotFound(format!("text: {text}")));
}
let object_id = remote
.object_id
.ok_or_else(|| Error::ElementNotFound(format!("text: {text}")))?;
let node_id = self.request_nodes(std::slice::from_ref(&object_id)).await?[0];
if node_id == 0 {
return Err(Error::ElementNotFound(format!("text: {text}")));
}
Element::from_node_id(self, node_id).await
}
pub async fn find_all_by_text(&self, text: &str) -> Result<Vec<Element>> {
let js = text_candidates_expression(text, TextMatch::Contains, true)?;
let (result, _objects) = self.session.evaluate_for_remote_object(&js).await?;
let remote = check_js_result(result)?;
let array_object_id = match &remote.object_id {
Some(id) => id.clone(),
None => return Ok(Vec::new()),
};
let properties = self.session.get_properties(&array_object_id).await?;
let object_ids: Vec<String> = properties
.into_iter()
.filter(|prop| prop.name.parse::<usize>().is_ok())
.filter_map(|prop| prop.value?.object_id)
.collect();
let node_ids = self.request_nodes(&object_ids).await?;
futures_util::future::try_join_all(
node_ids
.into_iter()
.filter(|&node_id| node_id != 0)
.map(|node_id| Element::from_node_id(self, node_id)),
)
.await
}
async fn request_nodes(&self, object_ids: &[String]) -> Result<Vec<i32>> {
let mut refreshed = false;
loop {
self.document_node().await?;
let mut node_ids = Vec::with_capacity(object_ids.len());
for object_id in object_ids {
node_ids.push(self.session.request_node(object_id).await?);
}
if refreshed || !node_ids.contains(&0) {
return Ok(node_ids);
}
self.invalidate_document();
refreshed = true;
}
}
#[must_use = "returns true if text exists on page"]
pub async fn text_exists(&self, text: &str) -> bool {
self.find_by_text(text).await.is_ok()
}
pub fn click(&self, selector: &str) -> ActionCall {
ActionCall::new(self, Action::click(LocatorSpec::css(selector), false))
}
pub fn type_into(&self, selector: &str, text: &str) -> ActionCall {
ActionCall::new(
self,
Action::type_text(LocatorSpec::css(selector), text, InputMode::default()),
)
}
pub fn click_by_text(&self, text: &str) -> ActionCall {
ActionCall::new(self, Action::click(LocatorSpec::text(text), false))
}
pub fn try_click(&self, selector: &str) -> TryActionCall {
TryActionCall::new(self, Action::click(LocatorSpec::css(selector), false))
}
pub fn try_click_by_text(&self, text: &str) -> TryActionCall {
TryActionCall::new(self, Action::click(LocatorSpec::text(text), false))
}
pub async fn fill(&self, selector: &str, value: &str) -> Result<()> {
self.act_default(Action::fill(
LocatorSpec::css(selector),
value,
InputMode::default(),
))
.await
}
pub fn human_click(&self, selector: &str) -> ActionCall {
ActionCall::new(self, Action::click(LocatorSpec::css(selector), true))
}
pub fn human_type(&self, selector: &str, text: &str) -> ActionCall {
ActionCall::new(
self,
Action::type_text(LocatorSpec::css(selector), text, InputMode::Human),
)
}
pub fn human_click_by_text(&self, text: &str) -> ActionCall {
ActionCall::new(self, Action::click(LocatorSpec::text(text), true))
}
pub fn try_human_click(&self, selector: &str) -> TryActionCall {
TryActionCall::new(self, Action::click(LocatorSpec::css(selector), true))
}
pub fn try_human_click_by_text(&self, text: &str) -> TryActionCall {
TryActionCall::new(self, Action::click(LocatorSpec::text(text), true))
}
pub async fn human_fill(&self, selector: &str, value: &str) -> Result<()> {
self.act_default(Action::fill(
LocatorSpec::css(selector),
value,
InputMode::Human,
))
.await
}
pub async fn find_any(&self, selectors: &[&str]) -> Result<Element> {
for selector in selectors {
match self.find(selector).await {
Ok(element) => return Ok(element),
Err(Error::ElementNotFound(_)) => {}
Err(error) => return Err(error),
}
}
Err(Error::ElementNotFound(format!(
"None of the selectors found: {selectors:?}"
)))
}
pub async fn upload_file(&self, selector: &str, path: &str) -> Result<()> {
self.upload_files(selector, &[path]).await
}
pub async fn upload_files(&self, selector: &str, paths: &[&str]) -> Result<()> {
self.act_default(Action::Upload {
target: LocatorSpec::css(selector),
files: paths.iter().map(|v| (*v).into()).collect(),
})
.await
}
pub async fn select(&self, selector: &str, value: &str) -> Result<()> {
self.act_default(Action::Select {
target: LocatorSpec::css(selector),
values: vec![value.into()],
})
.await
}
pub async fn select_by_text(&self, selector: &str, text: &str) -> Result<()> {
self.act_default(Action::SelectText {
target: LocatorSpec::css(selector),
text: text.into(),
})
.await
}
pub async fn select_multiple(&self, selector: &str, values: &[&str]) -> Result<()> {
self.act_default(Action::Select {
target: LocatorSpec::css(selector),
values: values.iter().map(|v| (*v).into()).collect(),
})
.await
}
pub async fn hover(&self, selector: &str) -> Result<()> {
self.act_default(Action::hover(LocatorSpec::css(selector), false))
.await
}
pub async fn human_hover(&self, selector: &str) -> Result<()> {
self.act_default(Action::hover(LocatorSpec::css(selector), true))
.await
}
}