1use crate::{
3 document::Documents,
4 store::{ModelStore, JAVASCRIPT_DRAFT_KEY},
5};
6use crate::automation::hit_keys::HitKeyDoc;
7use eframe::egui;
8use std::collections::HashMap;
9
10pub const WINDOW_ID: &str = "brep-javascript-editor";
12
13pub static HIT_KEYS: &[HitKeyDoc] = &[
17 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 },
18 HitKeyDoc { panel: "javascript", prefix: "title", meaning: "a point on the window's title bar — a drag from it MOVES the window", command: None },
19 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 },
20 HitKeyDoc { panel: "javascript", prefix: "run", meaning: "run the script in the active document", command: None },
21 HitKeyDoc { panel: "javascript", prefix: "cancel", meaning: "cancel the running script", command: None },
22 HitKeyDoc { panel: "javascript", prefix: "save", meaning: "save the source as the local draft", command: None },
23 HitKeyDoc { panel: "javascript", prefix: "open", meaning: "open a .js file into the editor (native; file-interchange stores only)", command: None },
24 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 },
25 HitKeyDoc { panel: "javascript", prefix: "help", meaning: "the CAD API and examples collapsing header", command: None },
26 HitKeyDoc { panel: "javascript", prefix: "example", meaning: "load the box example into the editor (inside `help`)", command: None },
27 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 },
28 HitKeyDoc { panel: "javascript", prefix: "output", meaning: "the output's scroll region, at the bottom of the window", command: None },
29];
30
31const EXAMPLE: &str = r#"// Run adds a box to the current document. Undo removes the whole run.
32cad.document.addFeature("P.CU", { sizeX: 30, sizeY: 20, sizeZ: 10 });
33console.log("Created a box");
34ui.notify("Edit its dimensions in the feature history");
35return { featuresBefore: cad.document.features.length };
36"#;
37
38pub trait ScriptHost {
44 fn ready(&self) -> Result<bool, String>;
46 fn run(&self, source: &str) -> Result<String, String>;
48 fn result(&self, id: &str) -> Result<Option<serde_json::Value>, String>;
50 fn halt(&self, id: &str) -> Result<(), String>;
52}
53
54enum Script {
58 Starting { doc: u64, program: String },
59 Running { doc: u64, id: String, token: u64 },
60 Closing { doc: u64, token: u64, rollback: bool, output: String, since: web_time::Instant, idle: u32 },
63}
64
65const CLOSE_WAIT: std::time::Duration = std::time::Duration::from_secs(30);
68
69const CLOSE_IDLE_POLLS: u32 = 5;
75const CLOSE_SETTLE: std::time::Duration = std::time::Duration::from_millis(250);
76
77pub fn program(source: &str) -> String {
88 let source = without_sdk_import(source);
89 format!(
90 r#"const __commands = [];
91const __stage = c => {{ if (__commands.length >= 256) throw Error("too many document commands"); __commands.push(c); }};
92const __snapshot = (await sdk.document.doc_json({{}})).document;
93const __selection = (await sdk.scene.selection({{}})).selection;
94const __document = Object.freeze({{
95 ...__snapshot,
96 addFeature: (type, params = {{}}, persistentData = {{}}) => __stage(() => sdk.features.feature_add(Object.keys(persistentData).length ? {{ type, params, persistent_data: persistentData }} : {{ type, params }})),
97 updateFeature: (id, params) => __stage(() => sdk.features.feature_set_params({{ id, patch: params }})),
98 deleteFeature: id => __stage(() => sdk.history.feature_delete({{ id }})),
99}});
100const __notify = message => console.log(String(message));
101const __result = await (async function (cad, ui) {{
102{source}
103}})(Object.freeze({{ document: __document, selection: __selection, params: {{}}, notify: __notify, sdk }}), Object.freeze({{ notify: __notify }}));
104for (const command of __commands) await command();
105if (__result !== undefined) console.log("Result:", JSON.stringify(__result));
106return null;
107"#
108 )
109}
110
111fn without_sdk_import(source: &str) -> String {
116 let Some(first) = source.lines().find(|l| !l.trim().is_empty() && !l.trim_start().starts_with("//")) else { return source.to_string() };
117 let line = first.trim();
118 let import = line.starts_with("import") && (line.ends_with("\"@brep/cad\";") || line.ends_with("\"@brep/cad\"") || line.ends_with("'@brep/cad';") || line.ends_with("'@brep/cad'"));
119 if !import {
120 return source.to_string();
121 }
122 source.replacen(first, "", 1)
123}
124
125fn script_output(result: &serde_json::Value) -> String {
128 let mut lines = vec![match result["state"].as_str() {
129 Some("succeeded") => "Completed.".to_string(),
130 Some("cancelled") => "Cancelled.".to_string(),
131 _ => format!("Failed: {}", result["error"]["message"].as_str().unwrap_or("the script failed")),
132 }];
133 if let Some(log) = result["logText"].as_str().filter(|l| !l.is_empty()) {
134 lines.push(log.to_string());
135 }
136 if !result["output"].is_null() {
137 lines.push(format!("Result: {}", result["output"]));
138 }
139 lines.join("\n")
140}
141
142pub struct JavaScriptEditor {
143 pub open: bool,
144 source: String,
145 output: String,
146 pending: Option<u64>, pub host: Option<Box<dyn ScriptHost>>,
149 script: Option<Script>,
150 importing: bool,
151 hits: HashMap<String, egui::Rect>,
154 rect: Option<egui::Rect>,
156 surface: egui::Rect,
158 exports: Vec<crate::panels::file::SaveRequest>,
161}
162
163
164impl JavaScriptEditor {
165 pub fn running_in(&self, document: u64) -> bool {
166 self.pending == Some(document)
167 }
168
169 pub fn set_source(&mut self, source: String) {
170 self.source = source;
171 }
172
173 pub fn editing_source(ctx: &egui::Context) -> bool {
174 ctx.memory(|memory| memory.has_focus(egui::Id::new("cad-javascript-source")))
175 }
176
177 pub fn new(store: &dyn ModelStore) -> Self {
178 Self {
179 open: false,
180 source: store
181 .read(JAVASCRIPT_DRAFT_KEY)
182 .unwrap_or_else(|| EXAMPLE.into()),
183 output: String::new(),
184 pending: None,
185 host: None,
186 script: None,
187 importing: false,
188 hits: HashMap::new(),
189 exports: Vec::new(),
190 rect: None,
191 surface: egui::Rect::NOTHING,
192 }
193 }
194
195 pub fn state_json(&self) -> String {
199 let rect = |r: egui::Rect| serde_json::json!([r.min.x, r.min.y, r.width(), r.height()]);
200 serde_json::json!({
201 "open": self.open,
202 "rect": self.rect.map(rect),
203 "surface": [self.surface.width(), self.surface.height()],
204 "running": self.pending.is_some(),
205 "output": self.output,
206 })
207 .to_string()
208 }
209
210 pub fn hits_json(&self) -> String {
212 crate::automation::hit_rects::hits_json(&self.hits)
213 }
214
215 fn halt_script(&mut self, docs: &mut Documents, output: String) {
218 match self.script.take() {
219 Some(Script::Starting { .. }) => {
220 self.pending = None;
221 self.output = output;
222 }
223 Some(Script::Running { doc, id, token }) => {
224 if let Some(host) = &self.host {
225 let _ = host.halt(&id);
226 }
227 if let Some(d) = docs.iter_mut().find(|d| d.id() == doc) {
230 d.engine.cancel_run();
231 }
232 self.script = Some(Script::Closing { doc, token, rollback: true, output, since: web_time::Instant::now(), idle: 0 });
233 }
234 other => self.script = other,
235 }
236 }
237
238 fn poll_script(&mut self, ctx: &egui::Context, docs: &mut Documents) {
240 ctx.request_repaint_after(std::time::Duration::from_millis(30));
241 let doc_id = match &self.script {
242 Some(Script::Starting { doc, .. } | Script::Running { doc, .. } | Script::Closing { doc, .. }) => *doc,
243 None => return,
244 };
245 if !docs.iter().any(|d| d.id() == doc_id) {
246 if let (Some(Script::Running { id, .. }), Some(host)) = (&self.script, &self.host) {
247 let _ = host.halt(id);
248 }
249 self.script = None;
250 self.pending = None;
251 self.output = "The script's document was closed.".into();
252 return;
253 }
254 if docs.active_id() != doc_id && matches!(self.script, Some(Script::Starting { .. } | Script::Running { .. })) {
257 return self.halt_script(docs, "Halted: the active document changed while the script ran; its edits were rolled back.".into());
258 }
259 let Some(host) = &self.host else { return };
260 let doc = docs.iter_mut().find(|d| d.id() == doc_id).expect("checked above");
261 match self.script.take() {
262 Some(Script::Starting { doc: d, program }) => match host.ready() {
263 Ok(true) => {
264 let token = doc.engine.history_group_begin();
265 match host.run(&program) {
266 Ok(id) => self.script = Some(Script::Running { doc: d, id, token }),
267 Err(e) => {
268 let _ = doc.engine.history_group_end(token, false);
269 self.pending = None;
270 self.output = e;
271 }
272 }
273 }
274 Ok(false) => self.script = Some(Script::Starting { doc: d, program }),
275 Err(e) => {
276 self.pending = None;
277 self.output = e;
278 }
279 },
280 Some(Script::Running { doc: d, id, token }) => match host.result(&id) {
281 Ok(None) => self.script = Some(Script::Running { doc: d, id, token }),
282 Ok(Some(result)) => {
283 let rollback = result["state"] != "succeeded";
284 let output = script_output(&result);
285 self.script = Some(Script::Closing { doc: d, token, rollback, output, since: web_time::Instant::now(), idle: 0 });
286 }
287 Err(e) => self.script = Some(Script::Closing { doc: d, token, rollback: true, output: e, since: web_time::Instant::now(), idle: 0 }),
288 },
289 Some(Script::Closing { doc: d, token, rollback, output, since, idle }) => {
290 doc.engine.pump();
291 let quiet = !doc.engine.run_pending() && !doc.engine.stage_feature_pending();
292 let idle = if quiet { idle + 1 } else { 0 };
293 let settled = idle >= CLOSE_IDLE_POLLS && since.elapsed() >= CLOSE_SETTLE;
294 if !settled && since.elapsed() < CLOSE_WAIT {
295 self.script = Some(Script::Closing { doc: d, token, rollback, output, since, idle });
296 return;
297 }
298 self.pending = None;
299 self.output = match doc.engine.history_group_end(token, rollback) {
300 Ok(true) => format!("{output}\nIts edits were rolled back."),
301 Ok(false) => output,
302 Err(e) => format!("{output}\n{e}"),
303 };
304 }
305 None => {}
306 }
307 }
308
309 fn hit(&mut self, key: &str, resp: &egui::Response) {
311 self.hits.insert(key.to_string(), resp.interact_rect);
312 }
313
314 pub fn poll(&mut self, ctx: &egui::Context, docs: &mut Documents, store: &dyn ModelStore) {
315 if self.importing {
316 if let Some(file) = store.take_import() {
317 self.importing = false;
318 match String::from_utf8(file.bytes) {
319 Ok(source) => self.source = source,
320 Err(e) => self.output = format!("Cannot open script: {e}"),
321 }
322 }
323 }
324 if self.script.is_some() {
325 return self.poll_script(ctx, docs);
326 }
327 let Some(id) = self.pending else {
328 return;
329 };
330 let Some(doc) = docs.iter_mut().find(|doc| doc.id() == id) else {
331 self.pending = None;
332 self.output = "The script's document was closed.".into();
333 return;
334 };
335 doc.engine.pump();
336 let status = doc.engine.plugin_action_status();
337 match status["state"].as_str() {
338 Some("complete") => {
339 let lines: Vec<_> = status["result"]["notifications"]
340 .as_array()
341 .into_iter()
342 .flatten()
343 .filter_map(|v| v.as_str())
344 .collect();
345 self.output = format!("Completed.\n{}", lines.join("\n"));
346 self.pending = None;
347 }
348 Some("error") => {
349 self.output = status["error"].as_str().unwrap_or("Script failed").into();
350 self.pending = None;
351 }
352 _ => {
353 ctx.request_repaint_after(std::time::Duration::from_millis(30));
354 }
355 }
356 }
357
358 pub fn take_save_requests(&mut self) -> Vec<crate::panels::file::SaveRequest> {
361 std::mem::take(&mut self.exports)
362 }
363
364 pub fn show(&mut self, ctx: &egui::Context, docs: &mut Documents, store: &dyn ModelStore) {
365 self.hits.clear();
366 self.rect = None;
367 self.surface = ctx.content_rect();
368 let mut open = self.open;
369 let shown = egui::Window::new("JavaScript editor").id(egui::Id::new(WINDOW_ID)).open(&mut open)
370 .default_pos(crate::panels::below_chrome(ctx, 16.0, 0.0))
373 .default_size(egui::vec2(720.0, 620.0)).min_size(egui::vec2(420.0, 320.0)).resizable(true).show(ctx, |ui| {
374 ui.label(format!("Run in: {}", docs.active().title()));
375 if let Some(id) = self.pending {
376 if let Some(doc) = docs.iter().find(|doc| doc.id() == id) {
377 ui.horizontal(|ui| {
378 ui.spinner();
379 ui.label(format!("Running in: {}", doc.title()));
380 });
381 }
382 }
383 ui.horizontal(|ui| {
384 let busy = self.pending.is_some() || docs.engine().run_pending()
385 || docs.engine().plugin_action_status()["state"] == "pending";
386 let run = ui.add_enabled(!busy, egui::Button::new("Run script"));
387 self.hit("run", &run);
388 if run.clicked() && self.host.is_some() && !self.source.contains("cad.geometry") {
391 self.pending = Some(docs.active_id());
392 self.script = Some(Script::Starting { doc: docs.active_id(), program: program(&self.source) });
393 self.output = "Running…".into();
394 } else if run.clicked() {
395 match docs.engine_mut().run_javascript(&self.source) {
396 Ok(_) => { self.pending = Some(docs.active_id()); self.output = "Running…".into(); }
397 Err(e) => self.output = e,
398 }
399 }
400 let cancel = ui.add_enabled(self.pending.is_some(), egui::Button::new("Cancel"));
401 self.hit("cancel", &cancel);
402 if cancel.clicked() && self.script.is_some() {
403 self.halt_script(docs, "Cancelled.".into());
404 } else if cancel.clicked() {
405 if let Some(id) = self.pending {
406 if let Some(doc) = docs.iter_mut().find(|doc| doc.id() == id) {
407 doc.engine.cancel_plugin_action();
408 }
409 }
410 }
411 let save = ui.button("Save draft");
412 self.hit("save", &save);
413 if save.clicked() {
414 self.output = match store.write(JAVASCRIPT_DRAFT_KEY, &self.source) {
415 Ok(()) => "Draft saved.".into(), Err(e) => format!("Cannot save draft: {e}"),
416 };
417 }
418 if store.supports_file_interchange() {
424 let open = ui.add_enabled(!self.importing, egui::Button::new("Open .js…"));
425 self.hit("open", &open);
426 if open.clicked() {
427 match store.begin_import_filtered(("JavaScript", &["js"])) {
428 Ok(()) => self.importing = true, Err(e) => self.output = e,
429 }
430 }
431 }
432 let export = ui.button("Export .js…");
433 self.hit("export", &export);
434 if export.clicked() {
435 self.exports.push(crate::panels::file::SaveRequest::text("Export the script", "script.js", self.source.clone()));
436 }
437 });
438 let help = ui.collapsing("CAD API and examples", |ui| {
439 ui.label("Write JavaScript statements. cad.document is a snapshot of the current history; cad.selection contains the current selection.");
440 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' };");
441 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.");
442 if self.host.is_some() {
443 ui.label("Every app command is a function too: await sdk.<namespace>.<action>(args), the same functions an agent's run program gets (the MCP sdk tool lists and types them). The script is a plain body: await at the top level, and return a value to see it as Result. A failed or cancelled run is rolled back.");
444 }
445 let example = ui.button("Load box example");
446 if example.clicked() { self.source = EXAMPLE.into(); }
447 example
448 });
449 self.hits.insert("help".into(), help.header_response.interact_rect);
450 if let Some(example) = help.body_returned {
451 self.hits.insert("example".into(), example.interact_rect);
452 }
453 egui::containers::panel::Panel::bottom(egui::Id::new("brep-javascript-output"))
463 .resizable(true)
464 .default_size(160.0)
465 .min_size(48.0)
466 .frame(egui::Frame::NONE.inner_margin(egui::Margin::symmetric(0, 4)))
467 .show_inside(ui, |ui| {
468 ui.label("Output");
469 let output = egui::ScrollArea::both().id_salt("javascript-output").auto_shrink(false).show(ui, |ui| {
470 ui.add(egui::Label::new(egui::RichText::new(&self.output).monospace()).selectable(true));
471 });
472 self.hits.insert("output".into(), output.inner_rect);
473 });
474 egui::CentralPanel::default().frame(egui::Frame::NONE).show_inside(ui, |ui| {
475 let free = ui.available_height();
482 let row = ui.fonts_mut(|f| f.row_height(&egui::TextStyle::Monospace.resolve(ui.style())));
483 let rows = ((free - 4.0) / row).floor().max(4.0) as usize;
484 let source = egui::ScrollArea::both().id_salt("javascript-source").auto_shrink(false).show(ui, |ui| {
485 ui.add(egui::TextEdit::multiline(&mut self.source).code_editor()
486 .id(egui::Id::new("cad-javascript-source"))
487 .desired_rows(rows).desired_width(f32::INFINITY));
488 });
489 self.hits.insert("source".into(), source.inner_rect);
490 });
491 });
492 if let (Some(shown), true) = (shown, open) {
496 let rect = shown.response.rect;
497 self.rect = Some(rect);
498 self.hits.insert("panel:clip".into(), rect);
503 self.hits.insert("title".into(), egui::Rect::from_center_size(egui::pos2(rect.center().x, rect.min.y + 12.0), egui::Vec2::ZERO));
504 self.hits.insert("grip".into(), egui::Rect::from_center_size(rect.max - egui::vec2(3.0, 3.0), egui::Vec2::ZERO));
505 } else {
506 self.hits.clear();
507 }
508 self.open = open;
509 }
510}