use crate::entry::PageClock;
use crate::host_js;
use crate::signals::Runtime;
use crate::swap::{App, Files, Manifest};
use crate::transport::{CallId, Sink, Wire, WireItem};
use crate::tree::dom::Dom;
use serde_json::{json, Map, Value};
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
pub const STREAM: &str = "plexus:stream";
pub const ITEM: &str = "plexus:item";
pub const STOP: &str = "plexus:stop";
pub const FAILED: &str = "plexus:failed";
struct Inner {
channel: String,
next: Cell<u64>,
sinks: RefCell<HashMap<String, Sink>>,
hearing: RefCell<Option<(String, bool)>>,
}
#[derive(Clone)]
pub struct FrameWire(Rc<Inner>);
fn window() -> web_sys::Window {
web_sys::window().expect("a window")
}
fn parent() -> Option<web_sys::Window> {
window().parent().ok().flatten()
}
fn post(message: &Value) {
if let Some(p) = parent() {
let _ = p.post_message(&host_js::to_js(message), "*");
}
}
fn key(n: u64) -> String {
format!("e{n}")
}
impl FrameWire {
pub fn new(channel: &str) -> Self {
let wire = Self(Rc::new(Inner { channel: channel.into(), next: Cell::new(0), sinks: RefCell::new(HashMap::new()), hearing: RefCell::new(None) }));
let w = wire.clone();
let on = Closure::<dyn FnMut(web_sys::MessageEvent)>::new(move |e: web_sys::MessageEvent| w.heard(&e));
let _ = window().add_event_listener_with_callback("message", on.as_ref().unchecked_ref());
on.forget();
wire
}
fn heard(&self, e: &web_sys::MessageEvent) {
let from_parent = match (e.source(), parent()) {
(Some(s), Some(p)) => js_sys::Object::is(&s, &p),
_ => false,
};
if !from_parent {
return;
}
let d = host_js::from_js(&e.data());
if d["type"] != ITEM || d["channel"] != self.0.channel.as_str() {
return;
}
let Some(id) = d["id"].as_str() else { return };
let it = &d["item"];
let words = || it["message"].as_str().unwrap_or("refused").to_string();
let item = match it["type"].as_str() {
Some("data") => WireItem::Data(it["content"].clone()),
Some("done") => WireItem::Done,
Some("refused") => WireItem::Refused(words(), it["error"].clone()),
Some("dropped") => WireItem::Dropped,
Some(_) => WireItem::Failed(words()),
None => return,
};
let end = !matches!(item, WireItem::Data(_));
let Some(mut sink) = self.0.sinks.borrow_mut().remove(id) else { return };
*self.0.hearing.borrow_mut() = Some((id.to_string(), false));
sink(item);
let closed = self.0.hearing.borrow_mut().take().is_some_and(|(_, closed)| closed);
if !end && !closed {
self.0.sinks.borrow_mut().insert(id.to_string(), sink);
}
}
}
impl Wire for FrameWire {
fn open(&self, method: &str, params: Value, sink: Sink) -> CallId {
let n = self.0.next.get() + 1;
self.0.next.set(n);
self.0.sinks.borrow_mut().insert(key(n), sink);
post(&json!({ "type": STREAM, "channel": self.0.channel, "id": key(n), "method": method, "params": params }));
CallId(n)
}
fn close(&self, call: CallId) {
let id = key(call.0);
let open = self.0.sinks.borrow_mut().remove(&id).is_some();
let inside = match self.0.hearing.borrow_mut().as_mut() {
Some((h, closed)) if *h == id => {
*closed = true;
true
}
_ => false,
};
if open || inside {
post(&json!({ "type": STOP, "channel": self.0.channel, "id": id }));
}
}
}
type FrameApp = App<Dom, FrameWire, PageClock>;
thread_local! {
static FRAMED: RefCell<Option<Rc<FrameApp>>> = const { RefCell::new(None) };
}
#[wasm_bindgen]
pub fn boot_frame(version: String, name: String, props: String, manifest: String, components: Option<String>, channel: String) {
wasm_bindgen_futures::spawn_local(async move {
if let Err(e) = run(&version, &name, &props, &manifest, components.as_deref(), &channel).await {
web_sys::console::error_1(&format!("ui: the framed {name}: {e}").into());
post(&json!({ "type": FAILED, "channel": channel, "message": e }));
}
});
}
async fn run(version: &str, name: &str, props: &str, manifest: &str, components: Option<&str>, channel: &str) -> Result<(), String> {
let document = window().document().ok_or("no document")?;
let root: web_sys::Node = document.body().ok_or("no body")?.into();
let m = Manifest::parse(manifest)?;
if !m.components.contains_key(name) {
return Err(format!("version {version} has no component {name}"));
}
let app = App::new(&Runtime::new(), Dom::new(document), FrameWire::new(channel), PageClock);
app.load(version, m.clone());
let mut files = Files::default();
let doc: Map<String, Value> = components.and_then(|t| serde_json::from_str::<Value>(t).ok()).and_then(|v| v.as_object().cloned()).unwrap_or_default();
for (n, e) in m.components.iter().filter(|(_, e)| e.is_rhx()) {
let entry = doc.get(n);
if let (Some(t), Some(h)) = (entry.and_then(|e| e["tree"].as_str()), entry.and_then(|e| e["handlers"].as_str())) {
files.put_version(version, n, t, h);
if let Some(css) = entry.and_then(|e| e["css"].as_str()) {
files.put_sheet(version, n, css);
}
} else if e.is_rhx() && n == name {
return Err(format!("{name}'s tree is not in components.json"));
}
}
app.provide(&files);
for n in app.reachable(name) {
let Some(entry) = m.components.get(&n).filter(|e| !e.is_rhx()) else { continue };
let module = host_js::import(version, &n).await?;
app.provide_module(version, &n, entry.clone(), Rc::new(module));
}
let props = serde_json::from_str::<Value>(props).ok().and_then(|v| v.as_object().cloned()).unwrap_or_default();
app.mount(&root, name, props).map_err(|e| e.to_string())?;
FRAMED.with(|f| *f.borrow_mut() = Some(app));
Ok(())
}