use std::path::Path;
use anyhow::{Context, Result};
use serde_json::{Value, json};
use super::command::Rex;
use crate::config::RexPlacement;
const POPUP_BOUNDS: [f64; 4] = [0.05, 0.075, 0.9, 0.85];
pub(crate) fn open(
rex: &Rex,
block: &str,
placement: RexPlacement,
cwd: Option<&Path>,
argv: &[String],
) -> Result<()> {
let review = review_block(cwd, argv);
match placement {
RexPlacement::Split => rex.api("session.new_split", &split(block, &review))?,
RexPlacement::Popup => {
let described = rex.api("session.describe_block", &json!({ "block_id": block }))?;
let window = described.pointer("/block/window_id").and_then(Value::as_str);
let window = window.with_context(|| format!("block {block} is not in a window"))?;
rex.api("session.new_layer", &layer(window, &review))?
}
};
Ok(())
}
fn review_block(cwd: Option<&Path>, argv: &[String]) -> Value {
let mut options = serde_json::Map::new();
options.insert("shell".to_owned(), json!("none"));
options.insert("command".to_owned(), json!(argv));
if let Some(cwd) = cwd {
options.insert("cwd".to_owned(), json!(cwd.display().to_string()));
}
json!({ "block": { "flavor": "com.superlogical.terminal.shell", "label": "Annotate", "options": options } })
}
fn split(block: &str, review: &Value) -> Value {
json!({ "anchor_id": block, "direction": "horizontal", "side": "after", "focus": true, "layout": review })
}
fn layer(window: &str, review: &Value) -> Value {
json!({ "window_id": window, "bounds": POPUP_BOUNDS, "focus": true, "layout": review })
}
#[cfg(test)]
#[allow(clippy::indexing_slicing, reason = "tests assert by panicking")]
mod tests {
use super::*;
#[test]
fn the_review_opens_to_the_right_of_the_agents_block_and_runs_directly() {
let split = split("block:b", &review_block(Some(Path::new("/tmp")), &["/bin/pt".to_owned()]));
assert_eq!(split["anchor_id"], "block:b");
assert_eq!((&split["direction"], &split["side"]), (&json!("horizontal"), &json!("after")));
assert_eq!(split["layout"]["block"]["options"]["shell"], "none");
assert_eq!(split["layout"]["block"]["options"]["command"], json!(["/bin/pt"]));
assert_eq!(split["layout"]["block"]["options"]["cwd"], "/tmp");
}
#[test]
fn a_popup_floats_inside_the_agents_window_and_takes_focus() {
let layer = layer("window:w", &review_block(None, &["/bin/pt".to_owned()]));
assert_eq!(layer["window_id"], "window:w");
assert_eq!(layer["focus"], true);
let bounds: Vec<f64> = serde_json::from_value(layer["bounds"].clone()).unwrap_or_default();
let fits = matches!(bounds[..], [x, y, w, h] if x >= 0.0 && y >= 0.0 && x + w <= 1.0 && y + h <= 1.0);
assert!(fits, "four bounds inside the window: {bounds:?}");
assert_eq!(layer["layout"]["block"]["label"], "Annotate");
}
}