use crate::{
document::Documents,
store::{ModelStore, JAVASCRIPT_DRAFT_KEY},
};
use crate::automation::hit_keys::HitKeyDoc;
use eframe::egui;
use std::collections::HashMap;
pub const WINDOW_ID: &str = "brep-javascript-editor";
pub static HIT_KEYS: &[HitKeyDoc] = &[
HitKeyDoc { panel: "javascript", prefix: "panel:clip", meaning: "the JavaScript editor window's OUTER rect — its whole visible region, frame included, so the title and grip handles below count as in view", command: None },
HitKeyDoc { panel: "javascript", prefix: "title", meaning: "a point on the window's title bar — a drag from it MOVES the window", command: None },
HitKeyDoc { panel: "javascript", prefix: "grip", meaning: "a point on the window's bottom-right resize corner — a drag from it RESIZES the window in both axes, up to the app surface", command: None },
HitKeyDoc { panel: "javascript", prefix: "run", meaning: "run the script in the active document", command: None },
HitKeyDoc { panel: "javascript", prefix: "cancel", meaning: "cancel the running script", command: None },
HitKeyDoc { panel: "javascript", prefix: "save", meaning: "save the source as the local draft", command: None },
HitKeyDoc { panel: "javascript", prefix: "open", meaning: "open a .js file into the editor (native; file-interchange stores only)", command: None },
HitKeyDoc { panel: "javascript", prefix: "export", meaning: "export the source as script.js through the file dialog's export door: the Save-file chooser on desktop, a download in the browser", command: None },
HitKeyDoc { panel: "javascript", prefix: "help", meaning: "the CAD API and examples collapsing header", command: None },
HitKeyDoc { panel: "javascript", prefix: "example", meaning: "load the box example into the editor (inside `help`)", command: None },
HitKeyDoc { panel: "javascript", prefix: "source", meaning: "the source editor's scroll region (the free space of the window: it grows with the window)", command: None },
HitKeyDoc { panel: "javascript", prefix: "output", meaning: "the output's scroll region, at the bottom of the window", command: None },
];
const EXAMPLE: &str = r#"// Run adds a box to the current document. Undo removes the whole run.
cad.document.addFeature("P.CU", { sizeX: 30, sizeY: 20, sizeZ: 10 });
console.log("Created a box");
ui.notify("Edit its dimensions in the feature history");
return { featuresBefore: cad.document.features.length };
"#;
pub trait ScriptHost {
fn ready(&self) -> Result<bool, String>;
fn run(&self, source: &str) -> Result<String, String>;
fn result(&self, id: &str) -> Result<Option<serde_json::Value>, String>;
fn halt(&self, id: &str) -> Result<(), String>;
}
enum Script {
Starting { doc: u64, program: String },
Running { doc: u64, id: String, token: u64 },
Closing { doc: u64, token: u64, rollback: bool, output: String, since: web_time::Instant, idle: u32 },
}
const CLOSE_WAIT: std::time::Duration = std::time::Duration::from_secs(30);
const CLOSE_IDLE_POLLS: u32 = 5;
const CLOSE_SETTLE: std::time::Duration = std::time::Duration::from_millis(250);
pub fn program(source: &str) -> String {
if source.lines().any(|l| l.starts_with("import ") || l.starts_with("export ")) {
return source.to_string();
}
format!(
r#"import {{ brep }} from "@brep/cad";
export default async function main() {{
const commands = [];
const stage = c => {{ if (commands.length >= 256) throw Error("too many document commands"); commands.push(c); }};
const snapshot = (await brep.document.doc_json({{}})).document;
const selection = (await brep.scene.selection({{}})).selection;
const document = Object.freeze({{
...snapshot,
addFeature: (type, params = {{}}, persistentData = {{}}) => stage(() => brep.features.feature_add(Object.keys(persistentData).length ? {{ type, params, persistent_data: persistentData }} : {{ type, params }})),
updateFeature: (id, params) => stage(() => brep.features.feature_set_params({{ id, patch: params }})),
deleteFeature: id => stage(() => brep.history.feature_delete({{ id }})),
}});
const notify = message => console.log(String(message));
const cad = Object.freeze({{ document, selection, params: {{}}, notify, brep }});
const ui = Object.freeze({{ notify }});
const result = await (async function (cad, ui) {{
{source}
}})(cad, ui);
for (const command of commands) await command();
if (result !== undefined) console.log("Result:", JSON.stringify(result));
return null;
}}
"#
)
}
fn script_output(result: &serde_json::Value) -> String {
let mut lines = vec![match result["state"].as_str() {
Some("succeeded") => "Completed.".to_string(),
Some("cancelled") => "Cancelled.".to_string(),
_ => format!("Failed: {}", result["error"]["message"].as_str().unwrap_or("the script failed")),
}];
if let Some(log) = result["logText"].as_str().filter(|l| !l.is_empty()) {
lines.push(log.to_string());
}
if !result["output"].is_null() {
lines.push(format!("Result: {}", result["output"]));
}
lines.join("\n")
}
pub struct JavaScriptEditor {
pub open: bool,
source: String,
output: String,
pending: Option<u64>, pub host: Option<Box<dyn ScriptHost>>,
script: Option<Script>,
importing: bool,
hits: HashMap<String, egui::Rect>,
rect: Option<egui::Rect>,
surface: egui::Rect,
exports: Vec<crate::panels::file::SaveRequest>,
}
impl JavaScriptEditor {
pub fn running_in(&self, document: u64) -> bool {
self.pending == Some(document)
}
pub fn set_source(&mut self, source: String) {
self.source = source;
}
pub fn editing_source(ctx: &egui::Context) -> bool {
ctx.memory(|memory| memory.has_focus(egui::Id::new("cad-javascript-source")))
}
pub fn new(store: &dyn ModelStore) -> Self {
Self {
open: false,
source: store
.read(JAVASCRIPT_DRAFT_KEY)
.unwrap_or_else(|| EXAMPLE.into()),
output: String::new(),
pending: None,
host: None,
script: None,
importing: false,
hits: HashMap::new(),
exports: Vec::new(),
rect: None,
surface: egui::Rect::NOTHING,
}
}
pub fn state_json(&self) -> String {
let rect = |r: egui::Rect| serde_json::json!([r.min.x, r.min.y, r.width(), r.height()]);
serde_json::json!({
"open": self.open,
"rect": self.rect.map(rect),
"surface": [self.surface.width(), self.surface.height()],
"running": self.pending.is_some(),
"output": self.output,
})
.to_string()
}
pub fn hits_json(&self) -> String {
crate::automation::hit_rects::hits_json(&self.hits)
}
fn halt_script(&mut self, docs: &mut Documents, output: String) {
match self.script.take() {
Some(Script::Starting { .. }) => {
self.pending = None;
self.output = output;
}
Some(Script::Running { doc, id, token }) => {
if let Some(host) = &self.host {
let _ = host.halt(&id);
}
if let Some(d) = docs.iter_mut().find(|d| d.id() == doc) {
d.engine.cancel_run();
}
self.script = Some(Script::Closing { doc, token, rollback: true, output, since: web_time::Instant::now(), idle: 0 });
}
other => self.script = other,
}
}
fn poll_script(&mut self, ctx: &egui::Context, docs: &mut Documents) {
ctx.request_repaint_after(std::time::Duration::from_millis(30));
let doc_id = match &self.script {
Some(Script::Starting { doc, .. } | Script::Running { doc, .. } | Script::Closing { doc, .. }) => *doc,
None => return,
};
if !docs.iter().any(|d| d.id() == doc_id) {
if let (Some(Script::Running { id, .. }), Some(host)) = (&self.script, &self.host) {
let _ = host.halt(id);
}
self.script = None;
self.pending = None;
self.output = "The script's document was closed.".into();
return;
}
if docs.active_id() != doc_id && matches!(self.script, Some(Script::Starting { .. } | Script::Running { .. })) {
return self.halt_script(docs, "Halted: the active document changed while the script ran; its edits were rolled back.".into());
}
let Some(host) = &self.host else { return };
let doc = docs.iter_mut().find(|d| d.id() == doc_id).expect("checked above");
match self.script.take() {
Some(Script::Starting { doc: d, program }) => match host.ready() {
Ok(true) => {
let token = doc.engine.history_group_begin();
match host.run(&program) {
Ok(id) => self.script = Some(Script::Running { doc: d, id, token }),
Err(e) => {
let _ = doc.engine.history_group_end(token, false);
self.pending = None;
self.output = e;
}
}
}
Ok(false) => self.script = Some(Script::Starting { doc: d, program }),
Err(e) => {
self.pending = None;
self.output = e;
}
},
Some(Script::Running { doc: d, id, token }) => match host.result(&id) {
Ok(None) => self.script = Some(Script::Running { doc: d, id, token }),
Ok(Some(result)) => {
let rollback = result["state"] != "succeeded";
let output = script_output(&result);
self.script = Some(Script::Closing { doc: d, token, rollback, output, since: web_time::Instant::now(), idle: 0 });
}
Err(e) => self.script = Some(Script::Closing { doc: d, token, rollback: true, output: e, since: web_time::Instant::now(), idle: 0 }),
},
Some(Script::Closing { doc: d, token, rollback, output, since, idle }) => {
doc.engine.pump();
let quiet = !doc.engine.run_pending() && !doc.engine.stage_feature_pending();
let idle = if quiet { idle + 1 } else { 0 };
let settled = idle >= CLOSE_IDLE_POLLS && since.elapsed() >= CLOSE_SETTLE;
if !settled && since.elapsed() < CLOSE_WAIT {
self.script = Some(Script::Closing { doc: d, token, rollback, output, since, idle });
return;
}
self.pending = None;
self.output = match doc.engine.history_group_end(token, rollback) {
Ok(true) => format!("{output}\nIts edits were rolled back."),
Ok(false) => output,
Err(e) => format!("{output}\n{e}"),
};
}
None => {}
}
}
fn hit(&mut self, key: &str, resp: &egui::Response) {
self.hits.insert(key.to_string(), resp.interact_rect);
}
pub fn poll(&mut self, ctx: &egui::Context, docs: &mut Documents, store: &dyn ModelStore) {
if self.importing {
if let Some(file) = store.take_import() {
self.importing = false;
match String::from_utf8(file.bytes) {
Ok(source) => self.source = source,
Err(e) => self.output = format!("Cannot open script: {e}"),
}
}
}
if self.script.is_some() {
return self.poll_script(ctx, docs);
}
let Some(id) = self.pending else {
return;
};
let Some(doc) = docs.iter_mut().find(|doc| doc.id() == id) else {
self.pending = None;
self.output = "The script's document was closed.".into();
return;
};
doc.engine.pump();
let status = doc.engine.plugin_action_status();
match status["state"].as_str() {
Some("complete") => {
let lines: Vec<_> = status["result"]["notifications"]
.as_array()
.into_iter()
.flatten()
.filter_map(|v| v.as_str())
.collect();
self.output = format!("Completed.\n{}", lines.join("\n"));
self.pending = None;
}
Some("error") => {
self.output = status["error"].as_str().unwrap_or("Script failed").into();
self.pending = None;
}
_ => {
ctx.request_repaint_after(std::time::Duration::from_millis(30));
}
}
}
pub fn take_save_requests(&mut self) -> Vec<crate::panels::file::SaveRequest> {
std::mem::take(&mut self.exports)
}
pub fn show(&mut self, ctx: &egui::Context, docs: &mut Documents, store: &dyn ModelStore) {
self.hits.clear();
self.rect = None;
self.surface = ctx.content_rect();
let mut open = self.open;
let shown = egui::Window::new("JavaScript editor").id(egui::Id::new(WINDOW_ID)).open(&mut open)
.default_pos(crate::panels::below_chrome(ctx, 16.0, 0.0))
.default_size(egui::vec2(720.0, 620.0)).min_size(egui::vec2(420.0, 320.0)).resizable(true).show(ctx, |ui| {
ui.label(format!("Run in: {}", docs.active().title()));
if let Some(id) = self.pending {
if let Some(doc) = docs.iter().find(|doc| doc.id() == id) {
ui.horizontal(|ui| {
ui.spinner();
ui.label(format!("Running in: {}", doc.title()));
});
}
}
ui.horizontal(|ui| {
let busy = self.pending.is_some() || docs.engine().run_pending()
|| docs.engine().plugin_action_status()["state"] == "pending";
let run = ui.add_enabled(!busy, egui::Button::new("Run script"));
self.hit("run", &run);
if run.clicked() && self.host.is_some() && !self.source.contains("cad.geometry") {
self.pending = Some(docs.active_id());
self.script = Some(Script::Starting { doc: docs.active_id(), program: program(&self.source) });
self.output = "Running…".into();
} else if run.clicked() {
match docs.engine_mut().run_javascript(&self.source) {
Ok(_) => { self.pending = Some(docs.active_id()); self.output = "Running…".into(); }
Err(e) => self.output = e,
}
}
let cancel = ui.add_enabled(self.pending.is_some(), egui::Button::new("Cancel"));
self.hit("cancel", &cancel);
if cancel.clicked() && self.script.is_some() {
self.halt_script(docs, "Cancelled.".into());
} else if cancel.clicked() {
if let Some(id) = self.pending {
if let Some(doc) = docs.iter_mut().find(|doc| doc.id() == id) {
doc.engine.cancel_plugin_action();
}
}
}
let save = ui.button("Save draft");
self.hit("save", &save);
if save.clicked() {
self.output = match store.write(JAVASCRIPT_DRAFT_KEY, &self.source) {
Ok(()) => "Draft saved.".into(), Err(e) => format!("Cannot save draft: {e}"),
};
}
if store.supports_file_interchange() {
let open = ui.add_enabled(!self.importing, egui::Button::new("Open .js…"));
self.hit("open", &open);
if open.clicked() {
match store.begin_import_filtered(("JavaScript", &["js"])) {
Ok(()) => self.importing = true, Err(e) => self.output = e,
}
}
}
let export = ui.button("Export .js…");
self.hit("export", &export);
if export.clicked() {
self.exports.push(crate::panels::file::SaveRequest::text("Export the script", "script.js", self.source.clone()));
}
});
let help = ui.collapsing("CAD API and examples", |ui| {
ui.label("Write JavaScript statements. cad.document is a snapshot of the current history; cad.selection contains the current selection.");
ui.monospace("cad.document.addFeature(type, params)\ncad.document.updateFeature(id, params)\ncad.document.deleteFeature(id)\nconsole.log / info / warn / error(...)\nui.notify(text)\nreturn { any: 'JSON result' };");
ui.label("Built-in types include P.CU (sizeX, sizeY, sizeZ), P.S (radius), and P.CY (radius, height). Successful changes form one undo step. Each Run executes the script again.");
if self.host.is_some() {
ui.label("Every app tool is a function too: await cad.brep.<group>.<tool>(args), the same functions an agent's run_script gets (typed in the server's brep://cad/sdk.d.ts resource). A program that starts with import { brep } from \"@brep/cad\" and export default async function main() runs as written. A failed or cancelled run is rolled back.");
}
let example = ui.button("Load box example");
if example.clicked() { self.source = EXAMPLE.into(); }
example
});
self.hits.insert("help".into(), help.header_response.interact_rect);
if let Some(example) = help.body_returned {
self.hits.insert("example".into(), example.interact_rect);
}
egui::containers::panel::Panel::bottom(egui::Id::new("brep-javascript-output"))
.resizable(true)
.default_size(160.0)
.min_size(48.0)
.frame(egui::Frame::NONE.inner_margin(egui::Margin::symmetric(0, 4)))
.show_inside(ui, |ui| {
ui.label("Output");
let output = egui::ScrollArea::both().id_salt("javascript-output").auto_shrink(false).show(ui, |ui| {
ui.add(egui::Label::new(egui::RichText::new(&self.output).monospace()).selectable(true));
});
self.hits.insert("output".into(), output.inner_rect);
});
egui::CentralPanel::default().frame(egui::Frame::NONE).show_inside(ui, |ui| {
let free = ui.available_height();
let row = ui.fonts_mut(|f| f.row_height(&egui::TextStyle::Monospace.resolve(ui.style())));
let rows = ((free - 4.0) / row).floor().max(4.0) as usize;
let source = egui::ScrollArea::both().id_salt("javascript-source").auto_shrink(false).show(ui, |ui| {
ui.add(egui::TextEdit::multiline(&mut self.source).code_editor()
.id(egui::Id::new("cad-javascript-source"))
.desired_rows(rows).desired_width(f32::INFINITY));
});
self.hits.insert("source".into(), source.inner_rect);
});
});
if let (Some(shown), true) = (shown, open) {
let rect = shown.response.rect;
self.rect = Some(rect);
self.hits.insert("panel:clip".into(), rect);
self.hits.insert("title".into(), egui::Rect::from_center_size(egui::pos2(rect.center().x, rect.min.y + 12.0), egui::Vec2::ZERO));
self.hits.insert("grip".into(), egui::Rect::from_center_size(rect.max - egui::vec2(3.0, 3.0), egui::Vec2::ZERO));
} else {
self.hits.clear();
}
self.open = open;
}
}