Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion crates/preview-mcp/src/page/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,8 @@ pub fn evaluate(expression: &str) -> String {
}

/// Decode the JSON an engine's evaluation callback yields; anything that is
/// not JSON, such as wry's empty string for `undefined`, is returned as text.
/// not JSON, such as WebKit's empty string for `undefined`, is returned as
/// text.
pub fn parse_result(raw: &str) -> Value {
serde_json::from_str(raw).unwrap_or_else(|_| Value::String(raw.to_string()))
}
Expand Down
13 changes: 10 additions & 3 deletions crates/ui/src/preview_panel/lifecycle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1096,7 +1096,13 @@ fn evaluate_in_page(
) {
#[cfg(target_os = "android")]
view.read(cx).raw().evaluate_json(script, reply, cx);
#[cfg(not(target_os = "android"))]
#[cfg(any(target_os = "macos", target_os = "ios"))]
page_agent::evaluate(view.read(cx).raw(), script, move |result| {
let _ = reply.try_send(
result.map(|raw| PreviewResponse::Json(preview_mcp::page::parse_result(&raw))),
);
});
#[cfg(any(target_os = "linux", target_os = "windows"))]
{
let result = view.read(cx).raw().evaluate_script_with_callback(script, {
let reply = reply.clone();
Expand Down Expand Up @@ -1224,8 +1230,9 @@ mod platform {
lifecycle.record_unavailable(format!("WebKitGTK 4.1 could not be loaded: {error}"), cx);
return Availability::Unavailable;
}
// No first document: lb-wry holds evaluations back until a
// navigation commits, and the page's evaluations wait for its first
// No first document: an evaluation before one runs in the empty page
// on macOS and iOS, and on Linux is held back by lb-wry until a
// navigation commits; the page agent's calls wait for its first
// document (`PageEvents`).
let nonce = page_agent::nonce();
let (page, events, receiver) = lifecycle.open_page(nonce.clone(), false);
Expand Down
53 changes: 53 additions & 0 deletions crates/ui/src/preview_panel/page_agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ pub(super) fn nonce() -> String {
uuid::Uuid::new_v4().simple().to_string()
}

#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(super) use imp::evaluate;
#[cfg(not(target_os = "android"))]
pub(super) use imp::install;
#[cfg(any(target_os = "macos", target_os = "ios", target_os = "linux"))]
Expand Down Expand Up @@ -216,6 +218,57 @@ mod imp {
}
}

/// Evaluate `expression` in the page's own world. `done` gets its value
/// as the JSON text the page made of it, empty for `undefined`, or what
/// WebKit said went wrong.
///
/// Gap: lb-wry's evaluation callback gives WebKit's result object to
/// `NSJSONSerialization`, which raises on a value JSON has no form for (a
/// NaN, an infinity, a `Date`), and that exception ends the process; it
/// also drops the error WebKit reports. So the page makes the JSON, which
/// is what the other engines hand back, and only text crosses.
pub(crate) fn evaluate(
raw: &wry::WebView,
expression: &str,
done: impl Fn(Result<String, String>) + 'static,
) {
let webview = raw.webview();
let done = block2::RcBlock::new(move |value: *mut AnyObject, error: *mut NSError| {
// SAFETY: WebKit passes a live error or nil, and a live value or nil.
let (value, error) = unsafe { (value.as_ref(), error.as_ref()) };
done(match (value, error) {
(_, Some(error)) => Err(script_error(error)),
(None, None) => Ok(String::new()),
// A page may have replaced `JSON.stringify`.
(Some(value), None) => value
.downcast_ref::<NSString>()
.map(NSString::to_string)
.ok_or_else(|| "the page's JSON.stringify did not return text".to_owned()),
});
});
// objc2-web-kit declares WKWebView for macOS only.
unsafe {
let () = msg_send![
&*webview,
evaluateJavaScript: &*NSString::from_str(&format!("JSON.stringify({expression})")),
completionHandler: &*done
];
}
}

/// The exception a script threw, where that is what failed.
fn script_error(error: &NSError) -> String {
let thrown = NSString::from_str("WKJavaScriptExceptionMessage");
error
.userInfo()
.objectForKey(&thrown)
.and_then(|message| message.downcast::<NSString>().ok())
.map_or_else(
|| error.localizedDescription().to_string(),
|message| message.to_string(),
)
}

pub(crate) fn forget(raw: &wry::WebView) {
PAGES.with_borrow_mut(|pages| pages.remove(&key(raw)));
}
Expand Down
Loading