use crate::{
dom_types::{self, El, ElContainer, MessageMapper, Namespace},
events, next_tick, routing, util, websys_bridge,
};
use enclose::enclose;
use futures::Future;
use next_tick::NextTick;
use std::{
cell::RefCell,
collections::{vec_deque::VecDeque, HashMap},
rc::Rc,
};
use wasm_bindgen::closure::Closure;
use wasm_bindgen_futures::spawn_local;
use web_sys::{Document, Element, Event, EventTarget, Window};
pub fn call_update<Ms, Mdl>(update: UpdateFn<Ms, Mdl>, msg: Ms, model: &mut Mdl) -> Orders<Ms> {
let mut orders = Orders::<Ms>::default();
(update)(msg, model, &mut orders);
orders
}
pub enum Effect<Ms> {
Msg(Ms),
Cmd(Box<dyn Future<Item = Ms, Error = Ms> + 'static>),
}
impl<Ms> From<Ms> for Effect<Ms> {
fn from(message: Ms) -> Self {
Effect::Msg(message)
}
}
impl<Ms: 'static, OtherMs: 'static> MessageMapper<Ms, OtherMs> for Effect<Ms> {
type SelfWithOtherMs = Effect<OtherMs>;
fn map_message(self, f: fn(Ms) -> OtherMs) -> Effect<OtherMs> {
match self {
Effect::Msg(msg) => Effect::Msg(f(msg)),
Effect::Cmd(cmd) => Effect::Cmd(Box::new(cmd.map(f).map_err(f))),
}
}
}
pub enum ShouldRender {
Render,
ForceRenderNow,
Skip,
}
pub struct Orders<Ms> {
should_render: ShouldRender,
effects: VecDeque<Effect<Ms>>,
}
impl<Ms> Default for Orders<Ms> {
fn default() -> Self {
Self {
should_render: ShouldRender::Render,
effects: VecDeque::new(),
}
}
}
impl<Ms: 'static, OtherMs: 'static> MessageMapper<Ms, OtherMs> for Orders<Ms> {
type SelfWithOtherMs = Orders<OtherMs>;
fn map_message(self, f: fn(Ms) -> OtherMs) -> Orders<OtherMs> {
Orders {
should_render: self.should_render,
effects: self
.effects
.into_iter()
.map(|effect| effect.map_message(f))
.collect(),
}
}
}
impl<Ms: 'static> Orders<Ms> {
pub fn render(&mut self) -> &mut Self {
self.should_render = ShouldRender::Render;
self
}
pub fn force_render_now(&mut self) -> &mut Self {
self.should_render = ShouldRender::ForceRenderNow;
self
}
pub fn skip(&mut self) -> &mut Self {
self.should_render = ShouldRender::Skip;
self
}
pub fn send_msg(&mut self, msg: Ms) -> &mut Self {
self.effects.push_back(msg.into());
self
}
pub fn perform_cmd<C>(&mut self, cmd: C) -> &mut Self
where
C: Future<Item = Ms, Error = Ms> + 'static,
{
self.effects.push_back(Effect::Cmd(Box::new(cmd)));
self
}
}
type UpdateFn<Ms, Mdl> = fn(Ms, &mut Mdl, &mut Orders<Ms>);
type ViewFn<Mdl, ElC> = fn(&Mdl) -> ElC;
type RoutesFn<Ms> = fn(routing::Url) -> Ms;
type WindowEvents<Ms, Mdl> = fn(&Mdl) -> Vec<events::Listener<Ms>>;
type MsgListeners<Ms> = Vec<Box<Fn(&Ms)>>;
pub struct Mailbox<Message: 'static> {
func: Rc<Fn(Message)>,
}
impl<Ms> Mailbox<Ms> {
pub fn new(func: impl Fn(Ms) + 'static) -> Self {
Mailbox {
func: Rc::new(func),
}
}
pub fn send(&self, message: Ms) {
(self.func)(message)
}
}
impl<Ms> Clone for Mailbox<Ms> {
fn clone(&self) -> Self {
Mailbox {
func: self.func.clone(),
}
}
}
type StoredPopstate = RefCell<Option<Closure<FnMut(Event)>>>;
pub struct AppData<Ms: 'static, Mdl> {
pub model: RefCell<Mdl>,
main_el_vdom: RefCell<Option<El<Ms>>>,
pub popstate_closure: StoredPopstate,
pub routes: RefCell<Option<RoutesFn<Ms>>>,
window_listeners: RefCell<Vec<events::Listener<Ms>>>,
msg_listeners: RefCell<MsgListeners<Ms>>,
scheduled_render_handle: RefCell<Option<util::RequestAnimationFrameHandle>>,
}
pub struct AppCfg<Ms, Mdl, ElC>
where
Ms: 'static,
Mdl: 'static,
ElC: ElContainer<Ms>,
{
document: web_sys::Document,
mount_point: web_sys::Element,
pub update: UpdateFn<Ms, Mdl>,
view: ViewFn<Mdl, ElC>,
window_events: Option<WindowEvents<Ms, Mdl>>,
}
pub struct App<Ms, Mdl, ElC>
where
Ms: 'static,
Mdl: 'static,
ElC: ElContainer<Ms>,
{
pub cfg: Rc<AppCfg<Ms, Mdl, ElC>>,
pub data: Rc<AppData<Ms, Mdl>>,
}
impl<Ms: 'static, Mdl: 'static, ElC: ElContainer<Ms>> ::std::fmt::Debug for App<Ms, Mdl, ElC> {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "App")
}
}
pub trait MountPoint {
fn element(self) -> Element;
}
impl MountPoint for &str {
fn element(self) -> Element {
util::document().get_element_by_id(self).unwrap_or_else(|| {
panic!(
"Can't find element with id={:?} - app cannot be mounted!\n\
(Id defaults to \"app\", or can be set with the .mount() method)",
self
)
})
}
}
impl MountPoint for Element {
fn element(self) -> Element {
self
}
}
impl MountPoint for web_sys::HtmlElement {
fn element(self) -> Element {
self.into()
}
}
#[derive(Clone)]
pub struct AppBuilder<Ms: 'static, Mdl: 'static, ElC: ElContainer<Ms>> {
model: Mdl,
update: UpdateFn<Ms, Mdl>,
view: ViewFn<Mdl, ElC>,
mount_point: Option<Element>,
routes: Option<RoutesFn<Ms>>,
window_events: Option<WindowEvents<Ms, Mdl>>,
}
impl<Ms, Mdl, ElC: ElContainer<Ms> + 'static> AppBuilder<Ms, Mdl, ElC> {
pub fn mount(mut self, mount_point: impl MountPoint) -> Self {
self.mount_point = Some(mount_point.element());
self
}
#[deprecated(since = "0.3.3", note = "please use `mount` instead")]
pub fn mount_el(mut self, el: Element) -> Self {
self.mount_point = Some(el);
self
}
pub fn routes(mut self, routes: RoutesFn<Ms>) -> Self {
self.routes = Some(routes);
self
}
pub fn window_events(mut self, evts: WindowEvents<Ms, Mdl>) -> Self {
self.window_events = Some(evts);
self
}
pub fn finish(mut self) -> App<Ms, Mdl, ElC> {
if self.mount_point.is_none() {
self = self.mount("app")
}
App::new(
self.model,
self.update,
self.view,
self.mount_point.unwrap(),
self.routes,
self.window_events,
)
}
}
impl<Ms, Mdl, ElC: ElContainer<Ms> + 'static> App<Ms, Mdl, ElC> {
pub fn build(
model: Mdl,
update: UpdateFn<Ms, Mdl>,
view: ViewFn<Mdl, ElC>,
) -> AppBuilder<Ms, Mdl, ElC> {
console_error_panic_hook::set_once();
AppBuilder {
model,
update,
view,
mount_point: None,
routes: None,
window_events: None,
}
}
fn new(
model: Mdl,
update: UpdateFn<Ms, Mdl>,
view: ViewFn<Mdl, ElC>,
mount_point: Element,
routes: Option<RoutesFn<Ms>>,
window_events: Option<WindowEvents<Ms, Mdl>>,
) -> Self {
let window = util::window();
let document = window.document().expect("Can't find the window's document");
Self {
cfg: Rc::new(AppCfg {
document,
mount_point,
update,
view,
window_events,
}),
data: Rc::new(AppData {
model: RefCell::new(model),
main_el_vdom: RefCell::new(None),
popstate_closure: RefCell::new(None),
routes: RefCell::new(routes),
window_listeners: RefCell::new(Vec::new()),
msg_listeners: RefCell::new(Vec::new()),
scheduled_render_handle: RefCell::new(None),
}),
}
}
pub fn setup_window_listeners(&self) {
if let Some(window_events) = self.cfg.window_events {
let mut new_listeners = (window_events)(&self.data.model.borrow());
setup_window_listeners(
&util::window(),
&mut self.data.window_listeners.borrow_mut(),
&mut new_listeners,
&self.mailbox(),
);
self.data.window_listeners.replace(new_listeners);
}
}
pub fn run(self) -> Self {
let mut new = El::empty(dom_types::Tag::Section);
new.children = (self.cfg.view)(&self.data.model.borrow()).els();
self.setup_window_listeners();
setup_input_listeners(&mut new);
setup_websys_el_and_children(&util::document(), &mut new);
attach_listeners(&mut new, &self.mailbox());
for top_child in &mut new.children {
websys_bridge::attach_el_and_children(top_child, &self.cfg.mount_point, &self)
}
self.data.main_el_vdom.replace(Some(new));
if let Some(routes) = *self.data.routes.borrow() {
routing::initial(|msg| self.update(msg), routes);
routing::setup_popstate_listener(
enclose!((self => s) move |msg| s.update(msg)),
enclose!((self => s) move |closure| {
s.data.popstate_closure.replace(Some(closure));
}),
routes,
);
routing::setup_link_listener(enclose!((self => s) move |msg| s.update(msg)), routes);
}
self
}
pub fn update(&self, message: Ms) {
let mut msg_and_cmd_queue: VecDeque<Effect<Ms>> = VecDeque::new();
msg_and_cmd_queue.push_front(message.into());
while let Some(effect) = msg_and_cmd_queue.pop_front() {
match effect {
Effect::Msg(msg) => {
let mut new_effects = self.process_queue_message(msg);
msg_and_cmd_queue.append(&mut new_effects);
}
Effect::Cmd(cmd) => self.process_queue_cmd(cmd),
}
}
}
fn process_queue_message(&self, message: Ms) -> VecDeque<Effect<Ms>> {
for l in self.data.msg_listeners.borrow().iter() {
(l)(&message)
}
let mut orders = Orders::default();
(self.cfg.update)(message, &mut self.data.model.borrow_mut(), &mut orders);
self.setup_window_listeners();
match orders.should_render {
ShouldRender::Render => self.schedule_render(),
ShouldRender::ForceRenderNow => {
self.cancel_scheduled_render();
self.rerender_vdom();
}
ShouldRender::Skip => (),
};
orders.effects
}
fn process_queue_cmd(&self, cmd: Box<dyn Future<Item = Ms, Error = Ms>>) {
let lazy_schedule_cmd = enclose!((self => s) move |_| {
spawn_local(cmd.then(move |res| {
let msg_returned_from_effect = res.unwrap_or_else(|err_msg| err_msg);
s.update(msg_returned_from_effect);
Ok(())
}))
});
spawn_local(NextTick::new().map(lazy_schedule_cmd));
}
fn schedule_render(&self) {
let mut scheduled_render_handle = self.data.scheduled_render_handle.borrow_mut();
if scheduled_render_handle.is_none() {
let cb = Closure::wrap(Box::new(enclose!((self => s) move |_| {
s.rerender_vdom();
s.data.scheduled_render_handle.borrow_mut().take();
}))
as Box<FnMut(util::RequestAnimationFrameTime)>);
*scheduled_render_handle = Some(util::request_animation_frame(cb));
}
}
fn cancel_scheduled_render(&self) {
self.data.scheduled_render_handle.borrow_mut().take();
}
fn rerender_vdom(&self) {
let mut new = El::empty(dom_types::Tag::Section);
new.children = (self.cfg.view)(&self.data.model.borrow()).els();
let mut old = self
.data
.main_el_vdom
.borrow_mut()
.take()
.expect("missing main_el_vdom");
detach_listeners(&mut old);
let num_children_in_both = old.children.len().min(new.children.len());
let mut old_children_iter = old.children.into_iter();
let mut new_children_iter = new.children.iter_mut();
let mut last_visited_node: Option<web_sys::Node> = None;
for _i in 0..num_children_in_both {
let child_old = old_children_iter.next().unwrap();
let child_new = new_children_iter.next().unwrap();
if let Some(new_el_ws) = patch(
&self.cfg.document,
child_old,
child_new,
&self.cfg.mount_point,
match last_visited_node.as_ref() {
Some(node) => node.next_sibling(),
None => self.cfg.mount_point.first_child(),
},
&self.mailbox(),
&self.clone(),
) {
last_visited_node = Some(new_el_ws.clone());
}
}
for child_new in new_children_iter {
setup_websys_el_and_children(&self.cfg.document, child_new);
websys_bridge::attach_el_and_children(child_new, &self.cfg.mount_point, &self.clone());
attach_listeners(child_new, &self.mailbox());
}
for mut child in old_children_iter {
let child_el_ws = child.el_ws.take().expect("Missing child el_ws");
if let Some(unmount_actions) = &mut child.hooks.will_unmount {
(unmount_actions.actions)(&child_el_ws);
}
}
self.data.main_el_vdom.borrow_mut().replace(new);
}
pub fn add_message_listener<F>(&self, listener: F)
where
F: Fn(&Ms) + 'static,
{
self.data
.msg_listeners
.borrow_mut()
.push(Box::new(listener));
}
fn _find(&self, ref_: &str) -> Option<El<Ms>> {
let top_el = &self
.data
.main_el_vdom
.borrow()
.clone()
.expect("Can't find main vdom el in find");
find_el(ref_, top_el)
}
fn mailbox(&self) -> Mailbox<Ms> {
Mailbox::new(enclose!((self => s) move |message| {
s.update(message);
}))
}
}
fn setup_input_listener<Ms>(el: &mut El<Ms>)
where
Ms: 'static,
{
if el.tag == dom_types::Tag::Input
|| el.tag == dom_types::Tag::Select
|| el.tag == dom_types::Tag::TextArea
{
let listener = if let Some(checked) = el.attrs.vals.get(&dom_types::At::Checked) {
let checked_bool = match checked.as_ref() {
"true" => true,
"false" => false,
_ => panic!("checked must be true or false."),
};
events::Listener::new_control_check(checked_bool)
} else if let Some(control_val) = el.attrs.vals.get(&dom_types::At::Value) {
events::Listener::new_control(control_val.to_string())
} else {
events::Listener::new_control("".to_string())
};
el.listeners.push(listener);
}
}
fn setup_websys_el<Ms>(document: &Document, el: &mut El<Ms>)
where
Ms: 'static,
{
if el.el_ws.is_none() {
el.el_ws = Some(websys_bridge::make_websys_el(el, document));
}
}
fn setup_input_listeners<Ms>(el_vdom: &mut El<Ms>)
where
Ms: 'static,
{
el_vdom.walk_tree_mut(setup_input_listener);
}
fn setup_websys_el_and_children<Ms>(document: &Document, el: &mut El<Ms>)
where
Ms: 'static,
{
el.walk_tree_mut(|el| setup_websys_el(document, el));
}
impl<Ms, Mdl, ElC: ElContainer<Ms>> Clone for App<Ms, Mdl, ElC> {
fn clone(&self) -> Self {
Self {
cfg: Rc::clone(&self.cfg),
data: Rc::clone(&self.data),
}
}
}
fn attach_listeners<Ms>(el: &mut dom_types::El<Ms>, mailbox: &Mailbox<Ms>) {
el.walk_tree_mut(|el| {
if let Some(el_ws) = el.el_ws.as_ref() {
for listener in &mut el.listeners {
if listener.control_val.is_some() || listener.control_checked.is_some() {
listener.attach_control(el_ws);
} else {
listener.attach(el_ws, mailbox.clone());
}
}
}
});
}
fn detach_listeners<Ms>(el: &mut dom_types::El<Ms>) {
el.walk_tree_mut(|el| {
if let Some(el_ws) = el.el_ws.as_ref() {
for listener in &mut el.listeners {
listener.detach(el_ws);
}
}
});
}
fn setup_window_listeners<Ms>(
window: &Window,
old: &mut Vec<events::Listener<Ms>>,
new: &mut Vec<events::Listener<Ms>>,
mailbox: &Mailbox<Ms>,
) {
for listener in old {
listener.detach(window);
}
for listener in new {
listener.attach(window, mailbox.clone());
}
}
pub(crate) fn patch<'a, Ms, Mdl, ElC: ElContainer<Ms>>(
document: &Document,
mut old: El<Ms>,
new: &'a mut El<Ms>,
parent: &web_sys::Node,
next_node: Option<web_sys::Node>,
mailbox: &Mailbox<Ms>,
app: &App<Ms, Mdl, ElC>,
) -> Option<&'a web_sys::Node> {
if old != *new {
if new.empty && !old.empty {
let old_el_ws = old
.el_ws
.take()
.expect("old el_ws missing in call to unmount_actions");
parent
.remove_child(&old_el_ws)
.expect("Problem removing old el_ws when updating to empty");
if let Some(unmount_actions) = &mut old.hooks.will_unmount {
(unmount_actions.actions)(&old_el_ws);
}
return None;
} else if new.empty && old.empty {
return None;
}
else if old.tag != new.tag
|| old.namespace != new.namespace
|| old.empty != new.empty
|| old.text.is_some() != new.text.is_some()
{
let old_el_ws = old.el_ws.take();
if let Some(unmount_actions) = &mut old.hooks.will_unmount {
(unmount_actions.actions)(
old_el_ws
.as_ref()
.expect("old el_ws missing in call to unmount_actions"),
);
}
setup_websys_el_and_children(document, new);
websys_bridge::attach_children(new, app);
let new_el_ws = new.el_ws.as_ref().expect("Missing websys el");
if old.empty {
match next_node {
Some(n) => {
parent
.insert_before(new_el_ws, Some(&n))
.expect("Problem adding element to replace previously empty one");
}
None => {
parent
.append_child(new_el_ws)
.expect("Problem adding element to replace previously empty one");
}
}
} else {
parent
.replace_child(
new_el_ws,
&old_el_ws.expect("old el_ws missing in call to replace_child"),
)
.expect("Problem replacing element");
}
if let Some(mount_actions) = &mut new.hooks.did_mount {
(mount_actions.actions)(new_el_ws);
}
attach_listeners(new, mailbox);
return new.el_ws.as_ref();
} else {
let old_el_ws = old
.el_ws
.as_ref()
.expect("missing old el_ws when patching non-empty el")
.clone();
websys_bridge::patch_el_details(&mut old, new, &old_el_ws);
}
}
if old.empty && new.empty {
return None;
}
let old_el_ws = old.el_ws.take().unwrap();
for listener in &mut new.listeners {
if listener.control_val.is_some() || listener.control_checked.is_some() {
listener.attach_control(&old_el_ws);
} else {
listener.attach(&old_el_ws, mailbox.clone());
}
}
let num_children_in_both = old.children.len().min(new.children.len());
let mut old_children_iter = old.children.into_iter();
let mut new_children_iter = new.children.iter_mut();
let mut last_visited_node: Option<web_sys::Node> = None;
for _i in 0..num_children_in_both {
let child_old = old_children_iter.next().unwrap();
let child_new = new_children_iter.next().unwrap();
if let Some(new_el_ws) = patch(
document,
child_old,
child_new,
&old_el_ws,
match last_visited_node.as_ref() {
Some(node) => node.next_sibling(),
None => old_el_ws.first_child(),
},
mailbox,
app,
) {
last_visited_node = Some(new_el_ws.clone());
}
}
for child_new in new_children_iter {
setup_websys_el_and_children(document, child_new);
websys_bridge::attach_el_and_children(child_new, &old_el_ws, app);
attach_listeners(child_new, mailbox);
}
for mut child in old_children_iter {
let child_el_ws = child.el_ws.take().expect("Missing child el_ws");
if let Some(unmount_actions) = &mut child.hooks.will_unmount {
(unmount_actions.actions)(&child_el_ws);
}
match old_el_ws.remove_child(&child_el_ws) {
Ok(_) => {}
Err(_) => {
crate::error("Minor error patching html element. (remove)");
}
}
}
new.el_ws = Some(old_el_ws);
new.el_ws.as_ref()
}
pub trait _Attrs: PartialEq + ToString {
fn vals(self) -> HashMap<String, String>;
}
pub trait _Style: PartialEq + ToString {
fn vals(self) -> HashMap<String, String>;
}
pub trait _Listener<Ms>: Sized {
fn attach<T: AsRef<EventTarget>>(&mut self, el_ws: &T, mailbox: Mailbox<Ms>);
fn detach<T: AsRef<EventTarget>>(&self, el_ws: &T);
}
pub trait _DomEl<Ms>: Sized + PartialEq + DomElLifecycle {
type Tg: PartialEq + ToString;
type At: _Attrs;
type St: _Style;
type Ls: _Listener<Ms>;
type Tx: PartialEq + ToString + Clone + Default;
fn tag(self) -> Self::Tg;
fn attrs(self) -> Self::At;
fn style(self) -> Self::St;
fn listeners(self) -> Vec<Self::Ls>;
fn text(self) -> Option<Self::Tx>;
fn children(self) -> Vec<Self>;
fn websys_el(self) -> Option<web_sys::Element>;
fn id(self) -> Option<u32>;
fn namespace(self) -> Option<Namespace>;
fn empty(self) -> Self;
fn set_id(&mut self, id: Option<u32>);
fn set_websys_el(&mut self, el: Option<Element>);
}
pub trait DomElLifecycle {
fn did_mount(self) -> Option<Box<FnMut(&Element)>>;
fn did_update(self) -> Option<Box<FnMut(&Element)>>;
fn will_unmount(self) -> Option<Box<FnMut(&Element)>>;
}
pub fn find_el<Msg>(ref_: &str, top_el: &El<Msg>) -> Option<El<Msg>> {
if top_el.ref_ == Some(ref_.to_string()) {
return Some(top_el.clone());
}
for child in &top_el.children {
let result = find_el(ref_, child);
if result.is_some() {
return result;
}
}
None
}
#[cfg(test)]
pub mod tests {
use wasm_bindgen_test::*;
wasm_bindgen_test_configure!(run_in_browser);
use super::*;
use crate as seed;
use crate::{class, prelude::*};
use futures::future;
use wasm_bindgen::JsCast;
use web_sys::{Node, Text};
#[derive(Clone, Debug)]
enum Msg {}
struct Model {}
fn create_app() -> App<Msg, Model, El<Msg>> {
App::build(Model {}, |_, _, _| (), |_| seed::empty())
.mount(util::body())
.finish()
}
fn call_patch(
doc: &Document,
parent: &Element,
mailbox: &Mailbox<Msg>,
old_vdom: El<Msg>,
mut new_vdom: El<Msg>,
app: &App<Msg, Model, El<Msg>>,
) -> El<Msg> {
patch(&doc, old_vdom, &mut new_vdom, parent, None, mailbox, &app);
new_vdom
}
fn iter_nodelist(list: web_sys::NodeList) -> impl Iterator<Item = Node> {
(0..list.length()).map(move |i| list.item(i).unwrap())
}
fn iter_child_nodes(node: &Node) -> impl Iterator<Item = Node> {
iter_nodelist(node.child_nodes())
}
#[wasm_bindgen_test]
fn el_added() {
let app = create_app();
let mailbox = Mailbox::new(|_msg: Msg| {});
let doc = util::document();
let parent = doc.create_element("div").unwrap();
let mut vdom = El::empty(seed::dom_types::Tag::Div);
setup_websys_el(&doc, &mut vdom);
let old_ws = vdom.el_ws.as_ref().unwrap().clone();
parent.append_child(&old_ws).unwrap();
assert_eq!(parent.children().length(), 1);
assert_eq!(old_ws.child_nodes().length(), 0);
vdom = call_patch(&doc, &parent, &mailbox, vdom, div!["text"], &app);
assert_eq!(parent.children().length(), 1);
assert!(old_ws.is_same_node(parent.first_child().as_ref()));
assert_eq!(old_ws.child_nodes().length(), 1);
assert_eq!(
old_ws.first_child().unwrap().text_content().unwrap(),
"text"
);
call_patch(
&doc,
&parent,
&mailbox,
vdom,
div!["text", "more text", vec![li!["even more text"]]],
&app,
);
assert_eq!(parent.children().length(), 1);
assert!(old_ws.is_same_node(parent.first_child().as_ref()));
assert_eq!(old_ws.child_nodes().length(), 3);
assert_eq!(
old_ws
.child_nodes()
.item(0)
.unwrap()
.text_content()
.unwrap(),
"text"
);
assert_eq!(
old_ws
.child_nodes()
.item(1)
.unwrap()
.text_content()
.unwrap(),
"more text"
);
let child3 = old_ws.child_nodes().item(2).unwrap();
assert_eq!(child3.node_name(), "LI");
assert_eq!(child3.text_content().unwrap(), "even more text");
}
#[wasm_bindgen_test]
fn el_removed() {
let app = create_app();
let mailbox = Mailbox::new(|_msg: Msg| {});
let doc = util::document();
let parent = doc.create_element("div").unwrap();
let mut vdom = El::empty(seed::dom_types::Tag::Div);
setup_websys_el(&doc, &mut vdom);
let old_ws = vdom.el_ws.as_ref().unwrap().clone();
parent.append_child(&old_ws).unwrap();
vdom = call_patch(
&doc,
&parent,
&mailbox,
vdom,
div!["text", "more text", vec![li!["even more text"]]],
&app,
);
assert_eq!(parent.children().length(), 1);
assert_eq!(old_ws.child_nodes().length(), 3);
let old_child1 = old_ws.child_nodes().item(0).unwrap();
call_patch(&doc, &parent, &mailbox, vdom, div!["text"], &app);
assert_eq!(parent.children().length(), 1);
assert!(old_ws.is_same_node(parent.first_child().as_ref()));
assert_eq!(old_ws.child_nodes().length(), 1);
assert!(old_child1.is_same_node(old_ws.child_nodes().item(0).as_ref()));
}
#[wasm_bindgen_test]
fn el_changed() {
let app = create_app();
let mailbox = Mailbox::new(|_msg: Msg| {});
let doc = util::document();
let parent = doc.create_element("div").unwrap();
let mut vdom = El::empty(seed::dom_types::Tag::Div);
setup_websys_el(&doc, &mut vdom);
let old_ws = vdom.el_ws.as_ref().unwrap().clone();
parent.append_child(&old_ws).unwrap();
vdom = call_patch(
&doc,
&parent,
&mailbox,
vdom,
div![span!["hello"], ", ", span!["world"]],
&app,
);
assert_eq!(parent.child_nodes().length(), 1);
assert_eq!(old_ws.child_nodes().length(), 3);
call_patch(
&doc,
&parent,
&mailbox,
vdom,
div![
span![class!["first"], "hello"],
", ",
span![class!["second"], "world"],
],
&app,
);
let child1 = old_ws
.child_nodes()
.item(0)
.unwrap()
.dyn_into::<Element>()
.unwrap();
assert_eq!(child1.get_attribute("class"), Some("first".to_string()));
let child3 = old_ws
.child_nodes()
.item(2)
.unwrap()
.dyn_into::<Element>()
.unwrap();
assert_eq!(child3.get_attribute("class"), Some("second".to_string()));
}
#[wasm_bindgen_test]
fn empty_changed_in_front() {
let app = create_app();
let mailbox = Mailbox::new(|_msg: Msg| {});
let doc = util::document();
let parent = doc.create_element("div").unwrap();
let mut vdom = El::empty(seed::dom_types::Tag::Div);
setup_websys_el(&doc, &mut vdom);
let old_ws = vdom.el_ws.as_ref().unwrap().clone();
parent.append_child(&old_ws).unwrap();
assert_eq!(parent.children().length(), 1);
assert_eq!(old_ws.child_nodes().length(), 0);
vdom = call_patch(
&doc,
&parent,
&mailbox,
vdom,
div![seed::empty(), "b", "c"],
&app,
);
assert_eq!(parent.children().length(), 1);
assert!(old_ws.is_same_node(parent.first_child().as_ref()));
assert_eq!(
iter_child_nodes(&old_ws)
.map(|node| node.text_content().unwrap())
.collect::<Vec<_>>(),
&["b", "c"],
);
call_patch(&doc, &parent, &mailbox, vdom, div!["a", "b", "c"], &app);
assert_eq!(parent.children().length(), 1);
assert!(old_ws.is_same_node(parent.first_child().as_ref()));
assert_eq!(
iter_child_nodes(&old_ws)
.map(|node| node.text_content().unwrap())
.collect::<Vec<_>>(),
&["a", "b", "c"],
);
}
#[wasm_bindgen_test]
fn empty_changed_in_the_middle() {
let app = create_app();
let mailbox = Mailbox::new(|_msg: Msg| {});
let doc = util::document();
let parent = doc.create_element("div").unwrap();
let mut vdom = El::empty(seed::dom_types::Tag::Div);
setup_websys_el(&doc, &mut vdom);
let old_ws = vdom.el_ws.as_ref().unwrap().clone();
parent.append_child(&old_ws).unwrap();
assert_eq!(parent.children().length(), 1);
assert_eq!(old_ws.child_nodes().length(), 0);
vdom = call_patch(
&doc,
&parent,
&mailbox,
vdom,
div!["a", seed::empty(), "c"],
&app,
);
assert_eq!(parent.children().length(), 1);
assert!(old_ws.is_same_node(parent.first_child().as_ref()));
assert_eq!(
iter_child_nodes(&old_ws)
.map(|node| node.text_content().unwrap())
.collect::<Vec<_>>(),
&["a", "c"],
);
call_patch(&doc, &parent, &mailbox, vdom, div!["a", "b", "c"], &app);
assert_eq!(parent.children().length(), 1);
assert!(old_ws.is_same_node(parent.first_child().as_ref()));
assert_eq!(
iter_child_nodes(&old_ws)
.map(|node| node.text_content().unwrap())
.collect::<Vec<_>>(),
&["a", "b", "c"],
);
}
#[wasm_bindgen_test]
fn root_empty_changed() {
let app = create_app();
let mailbox = Mailbox::new(|_msg: Msg| {});
let doc = util::document();
let parent = doc.create_element("div").unwrap();
let mut vdom = seed::empty();
vdom = call_patch(
&doc,
&parent,
&mailbox,
vdom,
div!["a", seed::empty(), "c"],
&app,
);
assert_eq!(parent.children().length(), 1);
let el_ws = vdom.el_ws.as_ref().expect("el_ws missing");
assert!(el_ws.is_same_node(parent.first_child().as_ref()));
assert_eq!(
iter_child_nodes(&el_ws)
.map(|node| node.text_content().unwrap())
.collect::<Vec<_>>(),
&["a", "c"],
);
}
#[wasm_bindgen_test]
fn root_empty_to_empty() {
let app = create_app();
let mailbox = Mailbox::new(|_msg: Msg| {});
let doc = util::document();
let parent = doc.create_element("div").unwrap();
let old = seed::empty();
call_patch(&doc, &parent, &mailbox, old, seed::empty(), &app);
assert_eq!(parent.children().length(), 0);
}
#[wasm_bindgen_test]
fn text_to_element_to_text() {
let app = create_app();
let mailbox = Mailbox::new(|_msg: Msg| {});
let doc = util::document();
let parent = doc.create_element("div").unwrap();
let mut vdom = seed::empty();
vdom = call_patch(&doc, &parent, &mailbox, vdom, El::new_text("abc"), &app);
assert_eq!(parent.child_nodes().length(), 1);
let text = parent
.first_child()
.unwrap()
.dyn_ref::<Text>()
.expect("not a Text node")
.clone();
assert_eq!(text.text_content().unwrap(), "abc");
vdom = call_patch(
&doc,
&parent,
&mailbox,
vdom,
span![style!["color" => "red"], "def"],
&app,
);
assert_eq!(parent.child_nodes().length(), 1);
let element = parent
.first_child()
.unwrap()
.dyn_ref::<Element>()
.expect("not an Element node")
.clone();
assert_eq!(&element.tag_name().to_lowercase(), "span");
call_patch(&doc, &parent, &mailbox, vdom, El::new_text("abc"), &app);
assert_eq!(parent.child_nodes().length(), 1);
let text = parent
.first_child()
.unwrap()
.dyn_ref::<Text>()
.expect("not a Text node")
.clone();
assert_eq!(text.text_content().unwrap(), "abc");
}
#[wasm_bindgen_test]
fn lifecycle_hooks() {
let app = create_app();
use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
let mailbox = Mailbox::new(|_msg: Msg| {});
let doc = util::document();
let parent = doc.create_element("div").unwrap();
let mut vdom = seed::empty();
let node_ref: Rc<RefCell<Option<Node>>> = Default::default();
let mount_op_counter: Rc<AtomicUsize> = Default::default();
let update_counter: Rc<AtomicUsize> = Default::default();
let did_mount_func = {
let node_ref = node_ref.clone();
let mount_op_counter = mount_op_counter.clone();
move |node: &Node| {
node_ref.borrow_mut().replace(node.clone());
assert_eq!(
mount_op_counter.fetch_add(1, SeqCst),
0,
"did_mount was called more than once"
);
}
};
let did_update_func = {
let update_counter = update_counter.clone();
move |_node: &Node| {
update_counter.fetch_add(1, SeqCst);
}
};
let will_unmount_func = {
let node_ref = node_ref.clone();
move |_node: &Node| {
node_ref.borrow_mut().take();
assert_eq!(
mount_op_counter.fetch_add(1, SeqCst),
1,
"will_unmount was called more than once"
);
}
};
vdom = call_patch(
&doc,
&parent,
&mailbox,
vdom,
div![
"a",
did_mount(did_mount_func.clone()),
did_update(did_update_func.clone()),
will_unmount(will_unmount_func.clone()),
],
&app,
);
assert!(
node_ref.borrow().is_some(),
"did_mount wasn't called and should have been"
);
assert_eq!(
update_counter.load(SeqCst),
0,
"did_update was called and shouldn't have been"
);
let first_child = parent.first_child().unwrap();
assert!(node_ref
.borrow()
.as_ref()
.unwrap()
.is_same_node(Some(&first_child)));
vdom = call_patch(
&doc,
&parent,
&mailbox,
vdom,
div![
"a",
attrs! {At::Href => "#"},
did_mount(did_mount_func.clone()),
did_update(did_update_func.clone()),
will_unmount(will_unmount_func.clone()),
],
&app,
);
assert!(
node_ref
.borrow()
.as_ref()
.expect("will_unmount was called early")
.is_same_node(Some(&first_child)),
"node reference changed"
);
assert_eq!(
update_counter.load(SeqCst),
1,
"did_update wasn't called and should have been"
);
call_patch(&doc, &parent, &mailbox, vdom, seed::empty(), &app);
assert!(node_ref.borrow().is_none(), "will_unmount wasn't called");
}
#[wasm_bindgen_test(async)]
fn update_promises() -> impl Future<Item = (), Error = JsValue> {
let (test_value_sender, test_value_receiver) = futures::oneshot::<Counters>();
const MESSAGES_TO_SEND: i32 = 5_000;
const COMMANDS_TO_PERFORM: i32 = 4_000;
#[derive(Default, Copy, Clone, Debug)]
struct Counters {
messages_sent: i32,
commands_scheduled: i32,
messages_received: i32,
commands_performed: i32,
}
#[derive(Default)]
struct Model {
counters: Counters,
test_value_sender: Option<futures::sync::oneshot::Sender<Counters>>,
}
enum Msg {
MessageReceived,
CommandPerformed,
Start,
}
fn update(msg: Msg, model: &mut Model, orders: &mut Orders<Msg>) {
orders.skip();
match msg {
Msg::MessageReceived => model.counters.messages_received += 1,
Msg::CommandPerformed => model.counters.commands_performed += 1,
Msg::Start => (),
}
if model.counters.messages_sent < MESSAGES_TO_SEND {
orders.send_msg(Msg::MessageReceived);
model.counters.messages_sent += 1;
}
if model.counters.commands_scheduled < MESSAGES_TO_SEND {
orders.perform_cmd(future::ok(Msg::CommandPerformed));
model.counters.commands_scheduled += 1;
}
if model.counters.messages_received == MESSAGES_TO_SEND
&& model.counters.commands_performed == COMMANDS_TO_PERFORM
{
model
.test_value_sender
.take()
.unwrap()
.send(model.counters)
.unwrap()
}
}
let app = App::build(
Model {
test_value_sender: Some(test_value_sender),
..Default::default()
},
update,
|_| seed::empty(),
)
.mount(seed::body())
.finish()
.run();
app.update(Msg::Start);
test_value_receiver
.map(|counters| {
assert_eq!(counters.messages_received, MESSAGES_TO_SEND);
assert_eq!(counters.commands_performed, COMMANDS_TO_PERFORM);
})
.map_err(|_| panic!("test_value_sender.send probably wasn't called!"))
}
}