use std::cell::RefCell;
use std::rc::Rc;
use brep_script_core::boa_engine::object::ObjectInitializer;
use brep_script_core::boa_engine::property::Attribute;
use brep_script_core::boa_engine::{Context, JsResult, JsString, JsValue, NativeFunction};
pub use brep_script_core::{Failure, Success};
use serde_json::Value;
pub const PLM_BINDINGS: &[&str] = &[];
pub fn store_kind() -> &'static str {
if cfg!(target_arch = "wasm32") {
"browser"
} else {
"file"
}
}
#[derive(Debug, Clone)]
pub struct Outcome<T> {
pub result: T,
pub notices: Vec<String>,
}
pub fn call(source: &str, file: &str, function: &str, input: &Value) -> Result<Outcome<Success>, Outcome<Failure>> {
let notices: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
let installed = notices.clone();
let result = brep_script_core::call(source, file, function, input, &move |context, _| {
install(context, &installed)
});
let notices = notices.borrow().clone();
match result {
Ok(result) => Ok(Outcome { result, notices }),
Err(result) => Err(Outcome { result, notices }),
}
}
fn install(context: &mut Context, notices: &Rc<RefCell<Vec<String>>>) -> JsResult<()> {
let cad = ObjectInitializer::new(context)
.property(JsString::from("version"), JsString::from(env!("CARGO_PKG_VERSION")), Attribute::READONLY)
.property(JsString::from("store"), JsString::from(store_kind()), Attribute::READONLY)
.property(JsString::from("plm"), false, Attribute::READONLY)
.build();
context.register_global_property(JsString::from("cad"), cad, Attribute::all())?;
let notices = notices.clone();
let notify = unsafe {
NativeFunction::from_closure(move |_, args, context| {
let line = args
.iter()
.map(|value| brep_script_core::text_of(value, context))
.collect::<Vec<_>>()
.join(" ");
notices.borrow_mut().push(line);
Ok(JsValue::undefined())
})
};
let ui = ObjectInitializer::new(context).function(notify, JsString::from("notify"), 1).build();
context.register_global_property(JsString::from("ui"), ui, Attribute::all())
}