rsx-web 0.1.0

Web (WASM) renderer for RSX.
Documentation
use rsx_core::{PropValue, Renderer, VNode};
use std::collections::HashMap;
use std::sync::Once;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use web_sys::{window, Document, Element as DomEl, Node};

static INIT_ONCE: Once = Once::new();

/// Initialize RSX web renderer (call this manually if needed)
pub fn init() {
    INIT_ONCE.call_once(|| {
        console_error_panic_hook::set_once();
        // Drive effects roughly once per animation frame.
        let frame = RcFrame::new(move || rsx_core::Scheduler::flush_if_dirty());
        frame.schedule();
    });
}

struct RcFrame(std::rc::Rc<std::cell::RefCell<Option<Closure<dyn FnMut()>>>>);

impl RcFrame {
    fn new(mut tick: impl FnMut() + 'static) -> Self {
        let rc: std::rc::Rc<std::cell::RefCell<Option<Closure<dyn FnMut()>>>> =
            std::rc::Rc::new(std::cell::RefCell::new(None));
        let rc_clone = rc.clone();
        let closure = Closure::wrap(Box::new(move || {
            tick();
            // re-schedule
            web_sys::window()
                .unwrap()
                .request_animation_frame(
                    rc_clone.borrow().as_ref().unwrap().as_ref().unchecked_ref(),
                )
                .unwrap();
        }) as Box<dyn FnMut()>);
        *rc.borrow_mut() = Some(closure);
        Self(rc)
    }

    fn schedule(&self) {
        web_sys::window()
            .unwrap()
            .request_animation_frame(self.0.borrow().as_ref().unwrap().as_ref().unchecked_ref())
            .ok();
    }
}

pub struct WebRenderer {
    doc: Document,
    callbacks: HashMap<String, js_sys::Function>, // id -> JS fn
}

pub struct MountHandle {
    root: DomEl,
    dom: Node,
    pub current: VNode,
}

impl WebRenderer {
    pub fn new() -> Self {
        let w = window().expect("no window");
        let doc = w.document().expect("no document");
        WebRenderer {
            doc,
            callbacks: Default::default(),
        }
    }

    pub fn on(&mut self, id: &str, f: &js_sys::Function) {
        self.callbacks.insert(id.to_string(), f.clone());
    }
}

impl Default for WebRenderer {
    fn default() -> Self {
        Self::new()
    }
}

impl Renderer for WebRenderer {
    type Handle = MountHandle;

    fn mount(&mut self, root_selector: &str, vnode: &VNode) -> Self::Handle {
        let root = self
            .doc
            .query_selector(root_selector)
            .unwrap()
            .expect("root not found")
            .dyn_into::<DomEl>()
            .unwrap();
        while let Some(c) = root.first_child() {
            root.remove_child(&c).ok();
        }
        let dom = create_dom(&self.doc, vnode, &self.callbacks);
        root.append_child(&dom).unwrap();
        MountHandle {
            root,
            dom,
            current: vnode.clone(),
        }
    }

    fn patch(&mut self, handle: &mut Self::Handle, prev: &VNode, next: &VNode) {
        if !patch(
            &self.doc,
            &handle.root,
            &mut handle.dom,
            prev,
            next,
            &self.callbacks,
        ) {
            // fallback: replace
            let nd = create_dom(&self.doc, next, &self.callbacks);
            handle.root.replace_child(&nd, &handle.dom).ok();
            handle.dom = nd;
        }
        handle.current = next.clone();
    }
}

/// ---- DOM creation and (simple) diff ----

fn create_dom(doc: &Document, v: &VNode, cbs: &HashMap<String, js_sys::Function>) -> Node {
    match v {
        VNode::Text(t) => doc.create_text_node(t).dyn_into::<Node>().unwrap(),
        VNode::Fragment(children) => {
            let frag = doc.create_document_fragment();
            for ch in children {
                frag.append_child(&create_dom(doc, ch, cbs)).ok();
            }
            frag.unchecked_into()
        }
        VNode::Element(el) => {
            let elmt = doc.create_element(&el.tag).unwrap();
            set_props(&elmt, &el.props, cbs);
            for ch in &el.children {
                elmt.append_child(&create_dom(doc, ch, cbs)).ok();
            }
            elmt.unchecked_into()
        }
    }
}

fn set_props(
    el: &DomEl,
    props: &indexmap::IndexMap<String, PropValue>,
    cbs: &HashMap<String, js_sys::Function>,
) {
    for (k, v) in props {
        if k.starts_with("on:") {
            match v {
                PropValue::Callback(id) => {
                    if let Some(f) = cbs.get(id) {
                        let event_name = &k["on:".len()..];
                        let _ = el.add_event_listener_with_callback(event_name, f);
                    }
                }
                PropValue::EventHandler(handler) => {
                    let event_name = &k["on:".len()..];
                    let handler_clone = handler.clone();
                    let closure = Closure::wrap(Box::new(move |_event: web_sys::Event| {
                        handler_clone.borrow_mut()();
                    }) as Box<dyn FnMut(_)>);
                    let _ = el.add_event_listener_with_callback(
                        event_name,
                        closure.as_ref().unchecked_ref(),
                    );
                    closure.forget(); // Keep alive for the element's lifetime
                }
                _ => {}
            }
            continue;
        }
        match v {
            PropValue::Str(s) => {
                el.set_attribute(k, s).ok();
            }
            PropValue::Bool(b) => {
                if *b {
                    el.set_attribute(k, "true").ok();
                } else {
                    el.remove_attribute(k).ok();
                }
            }
            PropValue::Num(n) => {
                el.set_attribute(k, &n.to_string()).ok();
            }
            PropValue::Dataset(ds) => {
                for (dk, dv) in ds {
                    el.set_attribute(&format!("data-{}", dk), dv).ok();
                }
            }
            PropValue::Callback(_) | PropValue::EventHandler(_) => {}
        }
    }
}

fn patch(
    doc: &Document,
    _root: &DomEl,
    dom: &mut Node,
    prev: &VNode,
    next: &VNode,
    cbs: &HashMap<String, js_sys::Function>,
) -> bool {
    use web_sys::Element as DomElem;
    match (prev, next) {
        (VNode::Text(a), VNode::Text(b)) => {
            if a != b {
                if let Some(text_node) = dom.dyn_ref::<web_sys::Text>() {
                    text_node.set_node_value(Some(b));
                }
            }
            true
        }
        (VNode::Element(ae), VNode::Element(be)) if ae.tag == be.tag => {
            let el = dom.dyn_ref::<DomElem>().unwrap();

            // naive prop patch: clear & set (good enough for MVP)
            // Clear existing attributes
            let attrs = el.attributes();
            let mut attr_names = Vec::new();
            for i in 0..attrs.length() {
                if let Some(attr) = attrs.item(i) {
                    attr_names.push(attr.name());
                }
            }
            for name in attr_names {
                el.remove_attribute(&name).ok();
            }

            // Set new props
            set_props(el, &be.props, cbs);

            // children - naive approach: replace all
            while let Some(child) = dom.first_child() {
                dom.remove_child(&child).ok();
            }
            for ch in &be.children {
                el.append_child(&create_dom(doc, ch, cbs)).ok();
            }
            true
        }
        _ => false,
    }
}

/// ---- Simple App Mounting & Auto-Reactivity ----

thread_local! {
    pub static APP_STATE: RefCell<Option<AppState>> = RefCell::new(None);
}

pub struct AppState {
    pub renderer: WebRenderer,
    pub handle: MountHandle,
    pub component_id: rsx_core::ComponentId,
}

/// High-level entry point that mirrors React's createRoot/render flow.
pub fn launch<F>(selector: &str, component: F)
where
    F: Fn() -> VNode + 'static,
{
    init();
    mount(selector, component);
}

/// Low-level mount function used by `launch`; call `init` yourself before using.
pub fn mount<F>(selector: &str, component: F)
where
    F: Fn() -> VNode + 'static,
{
    let component_id = rsx_core::register_component(component);
    let mut renderer = WebRenderer::new();
    let initial_vnode = rsx_core::render_component(component_id);
    let handle = renderer.mount(selector, &initial_vnode);

    // Store app state globally
    APP_STATE.with(|state| {
        *state.borrow_mut() = Some(AppState {
            renderer,
            handle,
            component_id,
        });
    });

    // Register re-render effect for reactivity
    rsx_core::effect(move || {
        APP_STATE.with(|state| {
            if let Some(ref mut app_state) = *state.borrow_mut() {
                let current = app_state.handle.current.clone();
                let next = rsx_core::render_component(component_id);
                app_state
                    .renderer
                    .patch(&mut app_state.handle, &current, &next);
            }
        });
    });
}

use std::cell::RefCell;
/// ---- Minimal client-side router (hash-based) ----
use std::rc::Rc;

pub struct Router {
    #[allow(dead_code)]
    _callback: Rc<RefCell<Box<dyn FnMut(String)>>>,
}

impl Router {
    pub fn new(on_change: impl FnMut(String) + 'static) -> Self {
        let callback = Rc::new(RefCell::new(Box::new(on_change) as Box<dyn FnMut(String)>));

        let callback_clone = callback.clone();
        let cb = Closure::<dyn FnMut(_)>::wrap(Box::new(move |_e: web_sys::HashChangeEvent| {
            let h = window().unwrap().location().hash().unwrap_or_default();
            let p = h.trim_start_matches('#').to_string();
            callback_clone.borrow_mut()(p);
        }) as Box<dyn FnMut(_)>);

        window()
            .unwrap()
            .add_event_listener_with_callback("hashchange", cb.as_ref().unchecked_ref())
            .unwrap();
        cb.forget(); // leak (page lifetime)

        // fire once
        let init = window()
            .unwrap()
            .location()
            .hash()
            .unwrap_or_default()
            .trim_start_matches('#')
            .to_string();
        callback.borrow_mut()(init);

        Router {
            _callback: callback,
        }
    }
}