Skip to main content

rsx_web/
lib.rs

1use rsx_core::{PropValue, Renderer, VNode};
2use std::collections::HashMap;
3use std::sync::Once;
4use wasm_bindgen::prelude::*;
5use wasm_bindgen::JsCast;
6use web_sys::{window, Document, Element as DomEl, Node};
7
8static INIT_ONCE: Once = Once::new();
9
10/// Initialize RSX web renderer (call this manually if needed)
11pub fn init() {
12    INIT_ONCE.call_once(|| {
13        console_error_panic_hook::set_once();
14        // Drive effects roughly once per animation frame.
15        let frame = RcFrame::new(move || rsx_core::Scheduler::flush_if_dirty());
16        frame.schedule();
17    });
18}
19
20struct RcFrame(std::rc::Rc<std::cell::RefCell<Option<Closure<dyn FnMut()>>>>);
21
22impl RcFrame {
23    fn new(mut tick: impl FnMut() + 'static) -> Self {
24        let rc: std::rc::Rc<std::cell::RefCell<Option<Closure<dyn FnMut()>>>> =
25            std::rc::Rc::new(std::cell::RefCell::new(None));
26        let rc_clone = rc.clone();
27        let closure = Closure::wrap(Box::new(move || {
28            tick();
29            // re-schedule
30            web_sys::window()
31                .unwrap()
32                .request_animation_frame(
33                    rc_clone.borrow().as_ref().unwrap().as_ref().unchecked_ref(),
34                )
35                .unwrap();
36        }) as Box<dyn FnMut()>);
37        *rc.borrow_mut() = Some(closure);
38        Self(rc)
39    }
40
41    fn schedule(&self) {
42        web_sys::window()
43            .unwrap()
44            .request_animation_frame(self.0.borrow().as_ref().unwrap().as_ref().unchecked_ref())
45            .ok();
46    }
47}
48
49pub struct WebRenderer {
50    doc: Document,
51    callbacks: HashMap<String, js_sys::Function>, // id -> JS fn
52}
53
54pub struct MountHandle {
55    root: DomEl,
56    dom: Node,
57    pub current: VNode,
58}
59
60impl WebRenderer {
61    pub fn new() -> Self {
62        let w = window().expect("no window");
63        let doc = w.document().expect("no document");
64        WebRenderer {
65            doc,
66            callbacks: Default::default(),
67        }
68    }
69
70    pub fn on(&mut self, id: &str, f: &js_sys::Function) {
71        self.callbacks.insert(id.to_string(), f.clone());
72    }
73}
74
75impl Default for WebRenderer {
76    fn default() -> Self {
77        Self::new()
78    }
79}
80
81impl Renderer for WebRenderer {
82    type Handle = MountHandle;
83
84    fn mount(&mut self, root_selector: &str, vnode: &VNode) -> Self::Handle {
85        let root = self
86            .doc
87            .query_selector(root_selector)
88            .unwrap()
89            .expect("root not found")
90            .dyn_into::<DomEl>()
91            .unwrap();
92        while let Some(c) = root.first_child() {
93            root.remove_child(&c).ok();
94        }
95        let dom = create_dom(&self.doc, vnode, &self.callbacks);
96        root.append_child(&dom).unwrap();
97        MountHandle {
98            root,
99            dom,
100            current: vnode.clone(),
101        }
102    }
103
104    fn patch(&mut self, handle: &mut Self::Handle, prev: &VNode, next: &VNode) {
105        if !patch(
106            &self.doc,
107            &handle.root,
108            &mut handle.dom,
109            prev,
110            next,
111            &self.callbacks,
112        ) {
113            // fallback: replace
114            let nd = create_dom(&self.doc, next, &self.callbacks);
115            handle.root.replace_child(&nd, &handle.dom).ok();
116            handle.dom = nd;
117        }
118        handle.current = next.clone();
119    }
120}
121
122/// ---- DOM creation and (simple) diff ----
123
124fn create_dom(doc: &Document, v: &VNode, cbs: &HashMap<String, js_sys::Function>) -> Node {
125    match v {
126        VNode::Text(t) => doc.create_text_node(t).dyn_into::<Node>().unwrap(),
127        VNode::Fragment(children) => {
128            let frag = doc.create_document_fragment();
129            for ch in children {
130                frag.append_child(&create_dom(doc, ch, cbs)).ok();
131            }
132            frag.unchecked_into()
133        }
134        VNode::Element(el) => {
135            let elmt = doc.create_element(&el.tag).unwrap();
136            set_props(&elmt, &el.props, cbs);
137            for ch in &el.children {
138                elmt.append_child(&create_dom(doc, ch, cbs)).ok();
139            }
140            elmt.unchecked_into()
141        }
142    }
143}
144
145fn set_props(
146    el: &DomEl,
147    props: &indexmap::IndexMap<String, PropValue>,
148    cbs: &HashMap<String, js_sys::Function>,
149) {
150    for (k, v) in props {
151        if k.starts_with("on:") {
152            match v {
153                PropValue::Callback(id) => {
154                    if let Some(f) = cbs.get(id) {
155                        let event_name = &k["on:".len()..];
156                        let _ = el.add_event_listener_with_callback(event_name, f);
157                    }
158                }
159                PropValue::EventHandler(handler) => {
160                    let event_name = &k["on:".len()..];
161                    let handler_clone = handler.clone();
162                    let closure = Closure::wrap(Box::new(move |_event: web_sys::Event| {
163                        handler_clone.borrow_mut()();
164                    }) as Box<dyn FnMut(_)>);
165                    let _ = el.add_event_listener_with_callback(
166                        event_name,
167                        closure.as_ref().unchecked_ref(),
168                    );
169                    closure.forget(); // Keep alive for the element's lifetime
170                }
171                _ => {}
172            }
173            continue;
174        }
175        match v {
176            PropValue::Str(s) => {
177                el.set_attribute(k, s).ok();
178            }
179            PropValue::Bool(b) => {
180                if *b {
181                    el.set_attribute(k, "true").ok();
182                } else {
183                    el.remove_attribute(k).ok();
184                }
185            }
186            PropValue::Num(n) => {
187                el.set_attribute(k, &n.to_string()).ok();
188            }
189            PropValue::Dataset(ds) => {
190                for (dk, dv) in ds {
191                    el.set_attribute(&format!("data-{}", dk), dv).ok();
192                }
193            }
194            PropValue::Callback(_) | PropValue::EventHandler(_) => {}
195        }
196    }
197}
198
199fn patch(
200    doc: &Document,
201    _root: &DomEl,
202    dom: &mut Node,
203    prev: &VNode,
204    next: &VNode,
205    cbs: &HashMap<String, js_sys::Function>,
206) -> bool {
207    use web_sys::Element as DomElem;
208    match (prev, next) {
209        (VNode::Text(a), VNode::Text(b)) => {
210            if a != b {
211                if let Some(text_node) = dom.dyn_ref::<web_sys::Text>() {
212                    text_node.set_node_value(Some(b));
213                }
214            }
215            true
216        }
217        (VNode::Element(ae), VNode::Element(be)) if ae.tag == be.tag => {
218            let el = dom.dyn_ref::<DomElem>().unwrap();
219
220            // naive prop patch: clear & set (good enough for MVP)
221            // Clear existing attributes
222            let attrs = el.attributes();
223            let mut attr_names = Vec::new();
224            for i in 0..attrs.length() {
225                if let Some(attr) = attrs.item(i) {
226                    attr_names.push(attr.name());
227                }
228            }
229            for name in attr_names {
230                el.remove_attribute(&name).ok();
231            }
232
233            // Set new props
234            set_props(el, &be.props, cbs);
235
236            // children - naive approach: replace all
237            while let Some(child) = dom.first_child() {
238                dom.remove_child(&child).ok();
239            }
240            for ch in &be.children {
241                el.append_child(&create_dom(doc, ch, cbs)).ok();
242            }
243            true
244        }
245        _ => false,
246    }
247}
248
249/// ---- Simple App Mounting & Auto-Reactivity ----
250
251thread_local! {
252    pub static APP_STATE: RefCell<Option<AppState>> = RefCell::new(None);
253}
254
255pub struct AppState {
256    pub renderer: WebRenderer,
257    pub handle: MountHandle,
258    pub component_id: rsx_core::ComponentId,
259}
260
261/// High-level entry point that mirrors React's createRoot/render flow.
262pub fn launch<F>(selector: &str, component: F)
263where
264    F: Fn() -> VNode + 'static,
265{
266    init();
267    mount(selector, component);
268}
269
270/// Low-level mount function used by `launch`; call `init` yourself before using.
271pub fn mount<F>(selector: &str, component: F)
272where
273    F: Fn() -> VNode + 'static,
274{
275    let component_id = rsx_core::register_component(component);
276    let mut renderer = WebRenderer::new();
277    let initial_vnode = rsx_core::render_component(component_id);
278    let handle = renderer.mount(selector, &initial_vnode);
279
280    // Store app state globally
281    APP_STATE.with(|state| {
282        *state.borrow_mut() = Some(AppState {
283            renderer,
284            handle,
285            component_id,
286        });
287    });
288
289    // Register re-render effect for reactivity
290    rsx_core::effect(move || {
291        APP_STATE.with(|state| {
292            if let Some(ref mut app_state) = *state.borrow_mut() {
293                let current = app_state.handle.current.clone();
294                let next = rsx_core::render_component(component_id);
295                app_state
296                    .renderer
297                    .patch(&mut app_state.handle, &current, &next);
298            }
299        });
300    });
301}
302
303use std::cell::RefCell;
304/// ---- Minimal client-side router (hash-based) ----
305use std::rc::Rc;
306
307pub struct Router {
308    #[allow(dead_code)]
309    _callback: Rc<RefCell<Box<dyn FnMut(String)>>>,
310}
311
312impl Router {
313    pub fn new(on_change: impl FnMut(String) + 'static) -> Self {
314        let callback = Rc::new(RefCell::new(Box::new(on_change) as Box<dyn FnMut(String)>));
315
316        let callback_clone = callback.clone();
317        let cb = Closure::<dyn FnMut(_)>::wrap(Box::new(move |_e: web_sys::HashChangeEvent| {
318            let h = window().unwrap().location().hash().unwrap_or_default();
319            let p = h.trim_start_matches('#').to_string();
320            callback_clone.borrow_mut()(p);
321        }) as Box<dyn FnMut(_)>);
322
323        window()
324            .unwrap()
325            .add_event_listener_with_callback("hashchange", cb.as_ref().unchecked_ref())
326            .unwrap();
327        cb.forget(); // leak (page lifetime)
328
329        // fire once
330        let init = window()
331            .unwrap()
332            .location()
333            .hash()
334            .unwrap_or_default()
335            .trim_start_matches('#')
336            .to_string();
337        callback.borrow_mut()(init);
338
339        Router {
340            _callback: callback,
341        }
342    }
343}