use super::tabs::OpenTab;
use rho_protocol::BrowserCursor;
use std::time::Duration;
const CURSOR: &str = r##"function (x, y) {
let at = document.elementFromPoint(x, y);
const shadowRoots = [];
while (at && at.shadowRoot) {
const inner = at.shadowRoot.elementFromPoint(x, y);
if (!inner || inner === at) break;
shadowRoots.push(at.shadowRoot);
at = inner;
}
if (!at) return "default";
const style = getComputedStyle(at);
const cursor = style.cursor.split(",").pop().trim();
if (cursor !== "auto") return cursor;
const typed = ["button", "submit", "reset", "checkbox", "radio", "range", "color", "file", "image"];
if (at.isContentEditable || at.tagName === "TEXTAREA"
|| (at.tagName === "INPUT" && !typed.includes(at.type))) {
return "text";
}
if (style.userSelect === "none" || at.closest("button, select")) return "default";
const caret = document.caretPositionFromPoint
? document.caretPositionFromPoint(x, y, { shadowRoots })
: document.caretRangeFromPoint(x, y);
const node = caret && (caret.offsetNode || caret.startContainer);
if (!node || node.nodeType !== Node.TEXT_NODE) return "default";
const text = document.createRange();
text.selectNodeContents(node);
for (const line of text.getClientRects()) {
if (x >= line.left && x <= line.right && y >= line.top && y <= line.bottom) return "text";
}
return "default";
}"##;
const READ_LIMIT: Duration = Duration::from_millis(250);
pub(super) async fn under(open: &mut OpenTab, x: f64, y: f64) -> Option<BrowserCursor> {
let expression = format!("({CURSOR})({x}, {y})");
let keyword = tokio::time::timeout(READ_LIMIT, open.evaluate(&expression))
.await
.ok()?
.ok()?;
match serde_json::from_value(keyword) {
Ok(BrowserCursor::Unknown) | Err(_) => Some(BrowserCursor::Default),
Ok(cursor) => Some(cursor),
}
}