eoka 0.17.1

Stealth browser automation for Rust. Puppeteer/Playwright alternative with anti-bot bypass.
Documentation
//! 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 makes the handle stale for actions (a removed node can still be read);
/// it is never retargeted to a replacement. Once the page commits another
/// document, every use fails with `target_stale`: a new renderer (after a
/// crash or a cross-site navigation) numbers its nodes from scratch, so the old
/// id may name a different node. While the page is crashed, uses fail with
/// `target_crashed`.
pub struct Element {
    pub(crate) page: Page,
    pub(crate) backend_node_id: i64,
    /// The page's document count when the node was found.
    pub(crate) document: u64,
}

impl Element {
    /// Fails with `target_stale` once the page has moved to another document.
    fn live(&self) -> Result<()> {
        if self.page.document() == self.document {
            Ok(())
        } else {
            Err(crate::action::stale())
        }
    }

    /// `result`, unless the page changed documents while it was produced:
    /// Chrome sends the navigation event before any later reply.
    fn still_live<T>(&self, result: Result<T>) -> Result<T> {
        let value = result?;
        self.live()?;
        Ok(value)
    }

    fn action(&self, action: Action) -> ActionCall {
        ActionCall::new(&self.page, action).pinned(self.document)
    }

    /// A strict action on this element with the page's defaults.
    async fn act(&self, action: Action) -> Result<()> {
        self.page
            .run_pinned(action, self.page.action_options(), false, self.document)
            .await
            .map(drop)
    }

    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> {
        self.live()?;
        let result: crate::cdp::types::DOMGetBoxModelResult = self.still_live(
            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 {
        self.action(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 {
        self.action(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 {
        self.action(Action::Drag {
            target: self.action_target(),
            dx,
            dy: 0.0,
        })
    }

    /// Get outer HTML
    pub async fn outer_html(&self) -> Result<String> {
        self.live()?;
        let result: Value = self.still_live(
            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> {
        self.live()?;
        self.still_live(
            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 {
        self.action(Action::type_text(self.action_target(), text))
    }

    /// Focus this element
    pub async fn focus(&self) -> Result<()> {
        self.act(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> {
        self.live()?;
        self.still_live(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.act(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>();
    }
}