1use std::time::Duration;
10
11use axum::response::{IntoResponse, Response};
12use axum::Json;
13use serde_json::{json, Value};
14
15use super::zoom::{refuse, text};
16use super::AppState;
17
18const MIN: f64 = 0.25;
20const MAX: f64 = 2.0;
21const STEP: f64 = 0.05;
22const HOST_TIMEOUT: Duration = Duration::from_secs(20);
23
24pub(super) fn is_browser_pane(state: &AppState, block: &str) -> bool {
26 state
27 .mstore
28 .get::<crate::backend::obj::Block>(block)
29 .ok()
30 .flatten()
31 .is_some_and(|b| b.meta.get("view").and_then(Value::as_str) == Some("browser"))
32}
33
34fn entry(block: &str, factor: f64) -> Value {
35 json!({
36 "block": block, "view": "browser", "supported": true,
37 "zoom": { "value": factor, "min": MIN, "max": MAX, "step": STEP, "default": 1.0, "mechanism": "emulation" },
38 })
39}
40
41fn factor_of(data: &Value) -> f64 {
43 data.get("factor").and_then(Value::as_f64).unwrap_or(1.0)
44}
45
46fn value_of(body: &Value) -> Result<f64, Response> {
48 match body.get("value").and_then(Value::as_f64) {
49 Some(v) if v.is_finite() && (MIN - 1e-9..=MAX + 1e-9).contains(&v) => Ok((v * 100.0).round() / 100.0),
50 _ => Err(refuse("out_of_range", format!("a browser pane takes a zoom from {MIN} to {MAX}"), json!({ "min": MIN, "max": MAX }))),
51 }
52}
53
54async fn host(state: &AppState, block: &str, ask: Value) -> Result<Value, Response> {
55 let mut body = json!({ "block_id": block });
56 if let (Some(b), Some(a)) = (body.as_object_mut(), ask.as_object()) {
57 b.extend(a.clone());
58 }
59 super::ui_handlers::proxy_value(state, "zoom", body, HOST_TIMEOUT)
60 .await
61 .map_err(|(_, e)| refuse("window_unreachable", format!("the browser pane did not answer: {e}"), json!({})))
62}
63
64async fn held_for_person(state: &AppState, own: &str, block: &str) -> Option<Response> {
68 let ask = json!({ "block_id": own, "op": "prompt", "args": { "block": block } });
69 let answer = super::ui_handlers::proxy_value(state, "zoom_op", ask, HOST_TIMEOUT).await.ok()?;
70 is_refusal(&answer).then(|| Json(answer).into_response())
71}
72
73fn is_refusal(answer: &Value) -> bool {
75 answer.get("ok").and_then(Value::as_bool) == Some(false)
76}
77
78pub(super) async fn run(state: &AppState, own: &str, slug: &str, action: &str, body: &Value) -> Response {
80 let block = text(body, "block");
81 if let Err((_, why)) = super::ui_handlers::target_for(state, own, slug, Some(&block)) {
83 return refuse("not_in_your_tab", format!("{block} is a browser pane you do not drive: {why}"), json!({}));
84 }
85 let before = match host(state, &block, json!({ "status": true })).await {
86 Ok(d) => factor_of(&d),
87 Err(r) => return r,
88 };
89 match action {
90 "get" => Json(json!({ "ok": true, "panes": [entry(&block, before)] })).into_response(),
91 "set" | "reset" => {
92 if let Some(held) = held_for_person(state, own, &block).await {
93 return held;
94 }
95 let ask = if action == "reset" {
96 json!({ "reset": true })
97 } else {
98 match value_of(body) {
99 Ok(v) => json!({ "factor": v }),
100 Err(r) => return r,
101 }
102 };
103 let data = match host(state, &block, ask).await {
104 Ok(d) => d,
105 Err(r) => return r,
106 };
107 super::browser_zoom::remember(&block, slug, &data);
108 Json(json!({
109 "ok": true, "target": "pane", "block": block, "before": before, "after": factor_of(&data),
110 "mechanism": "emulation", "note": "Browser with action zoom and reset puts it back; there is no undo token for a browser pane",
111 }))
112 .into_response()
113 }
114 _ => refuse("unsupported_view", "a browser pane takes get, set and reset here; fit and check do not apply to it", json!({})),
115 }
116}
117
118#[cfg(test)]
119mod tests {
120 use super::*;
121
122 #[test]
123 fn the_emulation_range_is_wider_than_pane_zoom() {
124 assert!(value_of(&json!({ "value": 0.25 })).is_ok());
125 assert!(value_of(&json!({ "value": 2.0 })).is_ok());
126 assert_eq!(value_of(&json!({ "value": 0.835 })).ok(), Some(0.84));
127 for bad in [json!({ "value": 0.24 }), json!({ "value": 2.01 }), json!({ "value": "x" }), json!({})] {
128 assert!(value_of(&bad).is_err(), "{bad}");
129 }
130 }
131
132 #[test]
133 fn only_a_refusal_from_the_window_holds_a_write_back() {
134 assert!(is_refusal(&json!({ "ok": false, "error": "person_prompt_showing", "message": "m" })));
135 assert!(!is_refusal(&json!({ "ok": true })));
136 assert!(!is_refusal(&json!({})));
137 }
138
139 #[test]
140 fn a_browser_pane_answers_in_the_shape_of_any_pane_with_its_own_mechanism_and_range() {
141 let e = entry("b1", 0.5);
142 assert_eq!((e["zoom"]["mechanism"].as_str(), e["zoom"]["min"].as_f64(), e["zoom"]["max"].as_f64()), (Some("emulation"), Some(0.25), Some(2.0)));
143 assert_eq!(e["supported"], true);
144 assert_eq!(factor_of(&json!({ "zoomed": false })), 1.0);
145 assert_eq!(factor_of(&json!({ "factor": 0.8 })), 0.8);
146 }
147}