use std::{future::Future, future::IntoFuture, pin::Pin, time::Duration};
use super::{Action, ActionOptions, ActionReceipt, Destination, Expectation};
use crate::{DispatchState, Error, ErrorCode, Page, Result};
type ActionFuture<T> = Pin<Box<dyn Future<Output = Result<T>> + Send>>;
#[must_use = "actions do nothing until awaited"]
pub struct ActionCall {
page: Page,
action: Action,
options: ActionOptions,
}
impl ActionCall {
pub(crate) fn new(page: &Page, action: Action) -> Self {
Self {
page: page.clone(),
action,
options: page.action_defaults.options(),
}
}
pub fn expecting(mut self, expect: Expectation) -> Self {
self.options.expect = Some(expect);
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.options.timeout_ms = super::types::duration_to_ms(timeout);
self
}
pub fn destination(mut self, destination: Destination) -> Self {
self.options.destination = destination;
self
}
}
impl IntoFuture for ActionCall {
type Output = Result<ActionReceipt>;
type IntoFuture = ActionFuture<ActionReceipt>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(async move { self.page.explore(self.action, self.options).await })
}
}
#[must_use = "actions do nothing until awaited"]
pub struct TryActionCall(ActionCall);
impl TryActionCall {
pub(crate) fn new(page: &Page, action: Action) -> Self {
Self(ActionCall::new(page, action))
}
pub fn expecting(self, expect: Expectation) -> Self {
Self(self.0.expecting(expect))
}
pub fn timeout(self, timeout: Duration) -> Self {
Self(self.0.timeout(timeout))
}
pub fn destination(self, destination: Destination) -> Self {
Self(self.0.destination(destination))
}
}
impl IntoFuture for TryActionCall {
type Output = Result<bool>;
type IntoFuture = ActionFuture<bool>;
fn into_future(self) -> Self::IntoFuture {
let ActionCall {
page,
action,
mut options,
} = self.0;
options.wait_for_target = false;
Box::pin(async move {
match page.explore(action, options).await {
Ok(_) => Ok(true),
Err(Error::Action {
receipt, source, ..
}) if receipt.dispatch == DispatchState::NotSent
&& matches!(
*source,
Error::ElementNotFound(_)
| Error::ElementNotVisible { .. }
| Error::Coded {
code: ErrorCode::ActionabilityChanged | ErrorCode::TargetStale,
..
}
) =>
{
Ok(false)
}
Err(error) => Err(error),
}
})
}
}