agentmux_srv/server/streamed_browser/
nav.rs1use serde_json::{json, Value};
8
9use super::cdp::Cdp;
10use super::protocol::{check_url, Go};
11
12pub fn nav_message(history: &Value, loading: bool) -> Value {
14 let entries = history.get("entries").and_then(Value::as_array).cloned().unwrap_or_default();
15 let at = history.get("currentIndex").and_then(Value::as_u64).unwrap_or(0) as usize;
16 let here = entries.get(at);
17 let text = |key: &str| here.and_then(|e| e.get(key)).and_then(Value::as_str).unwrap_or("").to_string();
18 json!({
19 "t": "nav",
20 "url": text("url"),
21 "title": text("title"),
22 "canGoBack": at > 0,
23 "canGoForward": at + 1 < entries.len(),
24 "loading": loading,
25 })
26}
27
28pub fn history_step(history: &Value, step: i64) -> Option<i64> {
30 let entries = history.get("entries")?.as_array()?;
31 let at = history.get("currentIndex")?.as_i64()?;
32 let target = usize::try_from(at + step).ok()?;
33 entries.get(target)?.get("id")?.as_i64()
34}
35
36pub async fn history(cdp: &Cdp, session: &str) -> Value {
37 cdp.call("Page.getNavigationHistory", json!({}), Some(session)).await.unwrap_or(Value::Null)
38}
39
40pub async fn go(cdp: &Cdp, session: &str, go: Go, url: &str) -> Result<(), String> {
42 match go {
43 Go::Url => {
44 let url = check_url(url)?;
45 let answer = cdp.call("Page.navigate", json!({ "url": url }), Some(session)).await?;
46 match answer.get("errorText").and_then(Value::as_str) {
47 Some(e) if !e.is_empty() => Err(format!("the page could not be reached ({e})")),
48 _ => Ok(()),
49 }
50 }
51 Go::Back | Go::Forward => {
52 let h = history(cdp, session).await;
53 let step = if go == Go::Back { -1 } else { 1 };
54 match history_step(&h, step) {
55 Some(id) => cdp.call("Page.navigateToHistoryEntry", json!({ "entryId": id }), Some(session)).await.map(|_| ()),
56 None => Ok(()),
57 }
58 }
59 Go::Reload => cdp.call("Page.reload", json!({}), Some(session)).await.map(|_| ()),
60 Go::Stop => cdp.call("Page.stopLoading", json!({}), Some(session)).await.map(|_| ()),
61 }
62}
63
64#[cfg(test)]
65mod tests {
66 use super::*;
67
68 fn history() -> Value {
69 json!({ "currentIndex": 1, "entries": [
70 { "id": 7, "url": "https://a.test/", "title": "A" },
71 { "id": 9, "url": "https://b.test/", "title": "B" },
72 { "id": 12, "url": "https://c.test/", "title": "C" },
73 ]})
74 }
75
76 #[test]
77 fn the_bar_shows_where_the_page_is_and_what_the_buttons_may_do() {
78 let m = nav_message(&history(), true);
79 assert_eq!(m["url"], "https://b.test/");
80 assert_eq!(m["title"], "B");
81 assert_eq!((m["canGoBack"].as_bool(), m["canGoForward"].as_bool(), m["loading"].as_bool()), (Some(true), Some(true), Some(true)));
82 let first = json!({ "currentIndex": 0, "entries": [{ "id": 1, "url": "about:blank", "title": "" }] });
83 let m = nav_message(&first, false);
84 assert_eq!((m["canGoBack"].as_bool(), m["canGoForward"].as_bool()), (Some(false), Some(false)));
85 assert_eq!(nav_message(&Value::Null, false)["url"], "");
86 }
87
88 #[test]
89 fn back_and_forward_find_the_neighbouring_entry_or_none_at_the_end() {
90 assert_eq!(history_step(&history(), -1), Some(7));
91 assert_eq!(history_step(&history(), 1), Some(12));
92 let at_end = json!({ "currentIndex": 2, "entries": history()["entries"] });
93 assert_eq!(history_step(&at_end, 1), None);
94 let at_start = json!({ "currentIndex": 0, "entries": history()["entries"] });
95 assert_eq!(history_step(&at_start, -1), None);
96 assert_eq!(history_step(&Value::Null, -1), None);
97 }
98}