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();
pub fn init() {
INIT_ONCE.call_once(|| {
console_error_panic_hook::set_once();
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();
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>, }
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,
) {
let nd = create_dom(&self.doc, next, &self.callbacks);
handle.root.replace_child(&nd, &handle.dom).ok();
handle.dom = nd;
}
handle.current = next.clone();
}
}
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(); }
_ => {}
}
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();
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_props(el, &be.props, cbs);
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,
}
}
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,
}
pub fn launch<F>(selector: &str, component: F)
where
F: Fn() -> VNode + 'static,
{
init();
mount(selector, component);
}
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);
APP_STATE.with(|state| {
*state.borrow_mut() = Some(AppState {
renderer,
handle,
component_id,
});
});
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, ¤t, &next);
}
});
});
}
use std::cell::RefCell;
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();
let init = window()
.unwrap()
.location()
.hash()
.unwrap_or_default()
.trim_start_matches('#')
.to_string();
callback.borrow_mut()(init);
Router {
_callback: callback,
}
}
}