use tracing::{debug, instrument};
use viewpoint_cdp::protocol::input::DispatchKeyEventParams;
use super::super::Locator;
use crate::error::LocatorError;
use crate::wait::NavigationWaiter;
#[derive(Debug)]
pub struct FillBuilder<'l, 'a> {
locator: &'l Locator<'a>,
text: String,
no_wait_after: bool,
}
impl<'l, 'a> FillBuilder<'l, 'a> {
pub(crate) fn new(locator: &'l Locator<'a>, text: &str) -> Self {
Self {
locator,
text: text.to_string(),
no_wait_after: false,
}
}
#[must_use]
pub fn no_wait_after(mut self, no_wait_after: bool) -> Self {
self.no_wait_after = no_wait_after;
self
}
#[instrument(level = "debug", skip(self), fields(selector = ?self.locator.selector))]
pub async fn send(self) -> Result<(), LocatorError> {
let navigation_waiter = if self.no_wait_after {
None
} else {
Some(NavigationWaiter::new(
self.locator.page.connection().subscribe_events(),
self.locator.page.session_id().to_string(),
self.locator.page.frame_id().to_string(),
))
};
self.perform_fill().await?;
if let Some(waiter) = navigation_waiter {
if let Err(e) = waiter.wait_for_navigation_if_triggered().await {
debug!(error = ?e, "Navigation wait failed after fill");
return Err(LocatorError::WaitError(e));
}
}
Ok(())
}
async fn perform_fill(&self) -> Result<(), LocatorError> {
self.locator.wait_for_actionable().await?;
debug!(text = %self.text, "Filling element");
self.locator.focus_element().await?;
self.locator
.dispatch_key_event(DispatchKeyEventParams::key_down("a"))
.await?;
let mut select_all = DispatchKeyEventParams::key_down("a");
select_all.modifiers = Some(viewpoint_cdp::protocol::input::modifiers::CTRL);
self.locator.dispatch_key_event(select_all).await?;
self.locator
.dispatch_key_event(DispatchKeyEventParams::key_down("Backspace"))
.await?;
self.locator.insert_text(&self.text).await?;
Ok(())
}
}
impl<'l> std::future::IntoFuture for FillBuilder<'l, '_> {
type Output = Result<(), LocatorError>;
type IntoFuture =
std::pin::Pin<Box<dyn std::future::Future<Output = Self::Output> + Send + 'l>>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(self.send())
}
}