1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
use crate::{ dom_types, dom_types::{El, Namespace}, routing, util, websys_bridge, }; use std::{cell::RefCell, collections::HashMap, panic, rc::Rc}; use wasm_bindgen::{closure::Closure, JsCast}; use web_sys::{Document, Element, Event, EventTarget, Window}; pub enum Update<Mdl: Clone> { Render(Mdl), Skip(Mdl), } type UpdateFn<Ms, Mdl> = fn(Ms, Mdl) -> Update<Mdl>; type ViewFn<Ms, Mdl> = fn(App<Ms, Mdl>, &Mdl) -> El<Ms>; type RoutesFn<Ms> = fn(crate::routing::Url) -> Ms; type WindowEvents<Ms, Mdl> = fn(Mdl) -> Vec<dom_types::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(), } } } // TODO: Examine what needs to be ref cells, rcs etc type StoredPopstate = RefCell<Option<Closure<FnMut(Event)>>>; /// Used as part of an interior-mutability pattern, ie Rc<RefCell<>> pub struct AppData<Ms: Clone + 'static, Mdl: Clone> { // Model is in a RefCell here so we can replace it in self.update(). pub model: RefCell<Mdl>, main_el_vdom: RefCell<El<Ms>>, pub popstate_closure: StoredPopstate, pub routes: RefCell<Option<RoutesFn<Ms>>>, window_listeners: RefCell<Vec<dom_types::Listener<Ms>>>, msg_listeners: RefCell<MsgListeners<Ms>>, } pub struct AppCfg<Ms: Clone + 'static, Mdl: Clone + 'static> { document: web_sys::Document, mount_point: web_sys::Element, pub update: UpdateFn<Ms, Mdl>, view: ViewFn<Ms, Mdl>, window_events: Option<WindowEvents<Ms, Mdl>>, } pub struct App<Ms: Clone + 'static, Mdl: 'static + Clone> { /// Stateless app configuration pub cfg: Rc<AppCfg<Ms, Mdl>>, /// Mutable app state pub data: Rc<AppData<Ms, Mdl>>, } #[derive(Clone)] pub struct AppBuilder<Ms: Clone + 'static, Mdl: 'static + Clone> { model: Mdl, update: UpdateFn<Ms, Mdl>, view: ViewFn<Ms, Mdl>, parent_div_id: Option<&'static str>, routes: Option<RoutesFn<Ms>>, window_events: Option<WindowEvents<Ms, Mdl>>, } impl<Ms: Clone, Mdl: Clone> AppBuilder<Ms, Mdl> { pub fn mount(mut self, id: &'static str) -> Self { self.parent_div_id = Some(id); 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(self) -> App<Ms, Mdl> { let parent_div_id = self.parent_div_id.unwrap_or("app"); App::new( self.model, self.update, self.view, parent_div_id, self.routes, self.window_events, ) } } /// We use a struct instead of series of functions, in order to avoid passing /// repetative sequences of parameters. impl<Ms: Clone, Mdl: Clone> App<Ms, Mdl> { pub fn build( model: Mdl, update: UpdateFn<Ms, Mdl>, view: ViewFn<Ms, Mdl>, ) -> AppBuilder<Ms, Mdl> { AppBuilder { model, update, view, parent_div_id: None, routes: None, window_events: None, } } fn new( model: Mdl, update: UpdateFn<Ms, Mdl>, view: ViewFn<Ms, Mdl>, parent_div_id: &str, // routes: Option<Routes<Ms>>, 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."); let mount_point = document .get_element_by_id(parent_div_id) .expect("Problem finding parent div"); 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(El::empty(dom_types::Tag::Div)), popstate_closure: RefCell::new(None), routes: RefCell::new(routes), window_listeners: RefCell::new(Vec::new()), msg_listeners: RefCell::new(Vec::new()), }), } } /// App initialization: Collect its fundamental components, setup, and perform /// an initial render. pub fn run(self) -> Self { // Our initial render. Can't initialize in new due to mailbox() requiring self. // TODO: maybe have view take an update instead of whole app? // TODO: There's a lot of DRY between here and update. // let mut topel_vdom = (app.data.view)(app.clone(), model.clone()); let window = util::window(); // Only clone model if we have window events. let mut topel_vdom; match self.cfg.window_events { //TODO: use window events Some(_window_events) => { topel_vdom = (self.cfg.view)(self.clone(), &self.data.model.borrow()); setup_window_listeners( &util::window(), &mut Vec::new(), // TODO: // Fix this. Bug where if we try to add initial listeners, // we get many runtime panics. Workaround is to wait until // app.update, which means an event must be triggered // prior to window listeners working. &mut Vec::new(), // &mut (window_events)(model), &self.mailbox(), ); } None => { topel_vdom = (self.cfg.view)(self.clone(), &self.data.model.borrow()); } } let document = window.document().expect("Problem getting document"); setup_els(&document, &mut topel_vdom, 0, 0); attach_listeners(&mut topel_vdom, &self.mailbox()); // Attach all children: This is where our initial render occurs. websys_bridge::attach_els(&mut topel_vdom, &self.cfg.mount_point); self.data.main_el_vdom.replace(topel_vdom); // Update the state on page load, based // on the starting URL. Must be set up on the server as well. if let Some(routes) = self.data.routes.borrow().clone() { // ignore clippy re clone() on copy routing::setup_popstate_listener( &routing::initial(self.clone(), routes), // &self.clone(), routes ); } // todo put back // Allows panic messages to output to the browser console.error. panic::set_hook(Box::new(console_error_panic_hook::hook)); self } /// This runs whenever the state is changed, ie the user-written update function is called. /// It updates the state, and any DOM elements affected by this change. /// todo this is where we need to compare against differences and only update nodes affected /// by the state change. /// /// We re-create the whole virtual dom each time (Is there a way around this? Probably not without /// knowing what vars the model holds ahead of time), but only edit the rendered, web_sys dom /// for things that have been changed. /// We re-render the virtual DOM on every change, but (attempt to) only change /// the actual DOM, via web_sys, when we need. /// The model storred in inner is the old model; updated_model is a newly-calculated one. pub fn update(&self, message: Ms) { for l in self.data.msg_listeners.borrow().iter() { (l)(&message) } // data.model is the old model; pass it to the update function created in the app, // which outputs an updated model. // We clone the model before running update, and again before passing it // to the view func, instead of using refs, to improve API syntax. // This approach may have performance impacts of unknown magnitude. let model_to_update = self.data.model.borrow().clone(); let updated_model = (self.cfg.update)(message, model_to_update); let mut should_render = true; let updated_model = match updated_model { Update::Render(m) => m, Update::Skip(m) => { should_render = false; m } }; // Unlike in run, we clone model here anyway, so no need to change top_new_vdom // logic based on if we have window listeners. if let Some(window_events) = self.cfg.window_events { let mut new_listeners = (window_events)(updated_model.clone()); setup_window_listeners( &util::window(), &mut self.data.window_listeners.borrow_mut(), // &mut Vec::new(), &mut new_listeners, &self.mailbox(), ); self.data.window_listeners.replace(new_listeners); } if should_render { // Create a new vdom: The top element, and all its children. Does not yet // have ids, nest levels, or associated web_sys elements. // We accept cloning here, for the benefit of making data easier to work // with in the app. let mut topel_new_vdom = (self.cfg.view)(self.clone(), &updated_model); // We setup the vdom (which populates web_sys els through it, but don't // render them with attach_children; we try to do it cleverly via patch(). setup_els(&self.cfg.document, &mut topel_new_vdom, 0, 0); // Detach all old listeners before patching. We'll re-add them as required during patching. // We'll get a runtime panic if any are left un-removed. detach_listeners(&mut self.data.main_el_vdom.borrow_mut()); // We haven't updated data.main_el_vdom, so we use it as our old (previous) state. patch( &self.cfg.document, &mut self.data.main_el_vdom.borrow_mut(), &mut topel_new_vdom, &self.cfg.mount_point, // None, &self.mailbox(), ); // Now that we've re-rendered, replace our stored El with the new one; // it will be used as the old El next (. self.data.main_el_vdom.replace(topel_new_vdom); } // We're now done with this updated model; store it for use as the old // model for the next update. // Note: It appears that this step is why we need data.model to be in a RefCell. self.data.model.replace(updated_model); } 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 mailbox(&self) -> Mailbox<Ms> { let cloned = self.clone(); Mailbox::new(move |message| { cloned.update(message); }) } } /// Used to identify input/textarea/select elements that don't have an input trigger /// so we can manually keep them in sync with the model. fn input_listener_exists<Ms>(el_vdom: &El<Ms>) -> bool where Ms: Clone + 'static, { let checkbox = match el_vdom.attrs.vals.get(&dom_types::At::Type) { Some(t) => t == "checkbox", None => false }; // todo handle checkboxes. for listener in &el_vdom.listeners { if !checkbox && listener.trigger == dom_types::Ev::Input { return true; } } false } /// Populate the attached web_sys elements, ids, and nest-levels. Run this after creating a vdom, but before /// using it to process the web_sys dom. Does not attach children in the DOM. Run this on the top-level element. pub fn setup_els<Ms>(document: &Document, el_vdom: &mut El<Ms>, active_level: u32, active_id: u32) // pub for tests. where Ms: Clone + 'static, { // id iterates once per item; active-level once per nesting level. let mut id = active_id; el_vdom.id = Some(id); id += 1; // Raise the id after each element we process. el_vdom.nest_level = Some(active_level); // Set up controlled components: Input elements must stay in sync with the state; // don't let them get out of syn with state from typing, which occurs if a change // doesn't trigger a re-render. match el_vdom.tag { dom_types::Tag::Input => { if !input_listener_exists(el_vdom) { el_vdom.controlled = true; } } dom_types::Tag::TextArea => { if !input_listener_exists(el_vdom) { el_vdom.controlled = true; } } dom_types::Tag::Select => { if !input_listener_exists(el_vdom) { el_vdom.controlled = true; } } _ => (), } // Create the web_sys element; add it to the working tree; store it in // its corresponding vdom El. let el_ws = websys_bridge::make_websys_el(el_vdom, document); if el_vdom.controlled { el_vdom.listeners.push(dom_types::Listener::new_control()); } el_vdom.el_ws = Some(el_ws); for child in &mut el_vdom.children { // Raise the active level once per recursion. setup_els(document, child, active_level + 1, id); id += 1; } } // trying this approach leads to lifetime problems. //fn mailbox<Ms, Mdl>(app: &'static App<Ms, Mdl>) -> Mailbox<Ms> // where Ms: Clone + 'static, Mdl: Clone + 'static { // Mailbox::new(move |message| { // app.clone().update(message); // }) // //} impl<Ms: Clone, Mdl: Clone> Clone for App<Ms, Mdl> { fn clone(&self) -> Self { App { cfg: Rc::clone(&self.cfg), data: Rc::clone(&self.data), } } } /// Normally, we only have the handler at this point, and build/store the closure /// with Listener.attach. For controlled-ones, there's no handler, but we have the closure. fn attach_controlled_listener<Ms: Clone>( listener: &mut dom_types::Listener<Ms>, el_ws: &web_sys::Node, value: String, ) { let e2 = el_ws.clone(); let closure = Closure::wrap( Box::new(move |_: web_sys::Event| util::set_value(&e2, &value)) as Box<FnMut(web_sys::Event) + 'static>, ); (el_ws.as_ref() as &web_sys::EventTarget) .add_event_listener_with_callback( listener.trigger.as_str(), closure.as_ref().unchecked_ref(), ) .expect("problem adding controlled listener to element"); listener.closure = Some(closure); } /// Recursively attach event-listeners. Run this at init. fn attach_listeners<Ms: Clone>(el: &mut dom_types::El<Ms>, mailbox: &Mailbox<Ms>) { let el_ws = el .el_ws .take() .expect("Missing el_ws on attach_all_listeners"); for listener in &mut el.listeners { if !listener.control { listener.attach(&el_ws, mailbox.clone()); } else { attach_controlled_listener(listener, &el_ws, util::input_value2(&el_ws)); } } for child in &mut el.children { attach_listeners(child, mailbox) } el.el_ws.replace(el_ws); } // TODO: should this be here, or in a diff module? /// Recursively detach event-listeners. Run this before patching. fn detach_listeners<Ms: Clone>(el: &mut dom_types::El<Ms>) { let el_ws = el .el_ws .take(); let el_ws2; match el_ws { Some(e) => el_ws2 = e, None => return } for listener in &mut el.listeners { listener.detach(&el_ws2); } for child in &mut el.children { detach_listeners(child) } el.el_ws.replace(el_ws2); } /// We reattach all listeners, as with normal Els, since we have no /// way of diffing them. fn setup_window_listeners<Ms: Clone>( window: &Window, old: &mut Vec<dom_types::Listener<Ms>>, new: &mut Vec<dom_types::Listener<Ms>>, mailbox: &Mailbox<Ms>, ) { for listener in old { listener.detach(window); } for listener in new { listener.attach(window, mailbox.clone()); } } fn patch<Ms: Clone>( document: &Document, old: &mut El<Ms>, new: &mut El<Ms>, parent: &web_sys::Node, // prev_child: Option<web_sys::Node>, // todo remove mailbox: &Mailbox<Ms>, ) { // Old_el_ws is what we're patching, with items from the new vDOM el; or replacing. // TODO: Current sceme is that if the parent changes, redraw all children... // TODO: fix this later. // We make an assumption that most of the page is not dramatically changed // by each event, to optimize. // TODO: There are a lot of ways you could make this more sophisticated. // Assume setup_vdom has been run on the new el, all listeners have been removed // from the old el_ws, and the only the old el vdom's elements are still attached. // take removes the interior value from the Option; otherwise we run into problems // about not being able to remove from borrowed content. // We remove it from the old el_vodom now, and at the end... add it to the new one. // We don't run attach_children() when patching, hence this approach. // if new.is_dummy() == true { return } let old_el_ws = match old.el_ws.take() { Some(o) => o, None => return }; // crate::log(format!("{:?}", old)); if old != new { // Something about this element itself is different: patch it. // At this step, we already assume we have the right element - either // by entering this func directly for the top-level, or recursively after // analyzing children // If the tag's different, we must redraw the element and its children; there's // no way to patch one element type into another. // TODO: forcing a rerender for differnet listeners is inefficient // TODO:, but I'm not sure how to patch them. if old.tag != new.tag { // TODO: DRY here between this and later in func. if let Some(unmount_actions) = &mut old.hooks.will_unmount { unmount_actions(&old_el_ws) } parent .remove_child(&old_el_ws) .expect("Problem removing an element"); websys_bridge::attach_els(new, parent); let mut new = new; attach_listeners(&mut new, &mailbox); // We've re-rendered this child and all children; we're done with this recursion. return } // Patch parts of the Element. websys_bridge::patch_el_details(old, new, &old_el_ws); } // Before running patch, assume we've removed all listeners from the old element. // Perform this attachment after we've verified we can patch this element, ie // it has the same tag - otherwise we'd have to detach after the parent.remove_child step. // Note that unlike the attach_listeners function, this only attaches for the currently // element. for listener in &mut new.listeners { if !listener.control { listener.attach(&old_el_ws, mailbox.clone()); } else { attach_controlled_listener(listener, &old_el_ws, util::input_value2(&old_el_ws)); } } // todo new, less-sophisticated approach that should avoid order problems, // todo compared to the commented-out code below. let mut old_children_patched: Vec<u32> = Vec::new(); for (i_new, child_new) in new.children.iter_mut().enumerate() { match old.children.get(i_new) { Some(mut child_old) => { patch(document, &mut child_old.clone(), child_new, &old_el_ws, &mailbox); old_children_patched.push(child_old.id.expect("Can't find child's id")); }, None => { // We ran out of old children to patch; create new ones. websys_bridge::attach_els(child_new, &old_el_ws); let mut child_new = child_new; attach_listeners(&mut child_new, &mailbox); } } } // // // // Now pair up children as best we can. // // If there are the same number of children, assume there's a 1-to-1 mapping, // // where we will not add or remove any; but patch as needed. // let avail_old_children = &mut old.children; // let mut prev_child: Option<web_sys::Node> = None; // let mut best_match; //// let mut t; // for (i_new, child_new) in new.children.iter_mut().enumerate() { // if avail_old_children.is_empty() { // // One or more new children has been added, or much content has // // changed, or we've made a mistake: Attach new children. // websys_bridge::attach_els(child_new, &old_el_ws); // let mut child_new = child_new; // attach_listeners(&mut child_new, &mailbox); // // } else { // // We still have old children to pick a match from. If we pick // // incorrectly, or there is no "good" match, we'll have some // // patching and/or attaching (rendering) to do in subsequent recursions. // let mut scores: Vec<(u32, f32)> = avail_old_children // .iter() // .enumerate() // .map(|(i_old, c_old)| (c_old.id.unwrap(), match_score(c_old, i_old, child_new, i_new))) // .collect(); // // // should put highest score at the end. // scores.sort_by(|b, a| b.1.partial_cmp(&a.1).unwrap()); // // // Sorting children vice picking the best one makes this easier to handle // // without irking the borrow checker, despite appearing less counter-intuitive, // // due to the convenient pop method. // avail_old_children.sort_by(|b, a| { // scores // .iter() // .find(|s| s.0 == b.id.unwrap()) // .unwrap() // .1 // .partial_cmp(&scores.iter().find(|s| s.0 == a.id.unwrap()).unwrap().1) // .unwrap() // }); // // best_match = avail_old_children.pop().expect("Problem popping"); // crate::log(best_match.el_ws.is_some()); // crate::log(prev_child.is_some()); // // let expected_posit = i_new; // let actual_posit = __; // // Now make sure the order is correct; the code above will place children // // in the wrong order, if the best_match guess is wrong. //// let best_ws = best_match.clone().el_ws; //// let best_ws = best2.clone().el_ws; // if let Some(prev) = prev_child { // best_match // .clone() // .el_ws // .expect("Problem finding el_ws in sorting") // .dyn_ref::<web_sys::Element>() // .expect("Problem casting node as element") // .after_with_node_1(&prev) // .expect("Problem reordering children"); // } // // // // // Set up the previous child before patching, since patching will strip out the web_sys el. // prev_child = best_match.el_ws.clone(); // patch(document, &mut best_match, child_new, &old_el_ws, prev_child, &mailbox); // patch(document, &mut best_match, child_new, &old_el_ws, None, &mailbox); // prev_best = Some(best_match); // todo remove the extra param you added // } // } // Now purge any existing no-longer-needed children; they're not part of the new vdom. // for child in avail_old_children { for child in old.children.iter_mut() .filter(|c| !old_children_patched .contains(&c.id.expect("Can't find child's id")) ) { let child_el_ws = child.el_ws.take().expect("Missing child el_ws"); // TODO: DRY here between this and earlier in func if let Some(unmount_actions) = &mut child.hooks.will_unmount { unmount_actions(&child_el_ws) } old_el_ws .remove_child(&child_el_ws) .expect("Problem removing child"); child.el_ws.replace(child_el_ws); } new.el_ws = Some(old_el_ws); } /// Compare two elements. Rank based on how similar they are, using subjective criteria. fn match_score<Ms: Clone>(old: &El<Ms>, old_posit: usize, new: &El<Ms>, new_posit: usize) -> f32 { // children_to_eval is the number of children to look at on each nest level. // let children_to_eval = 3; // Don't weight children as heavily as the parent. This effect acculates the further down we go. let child_score_significance: f32 = 0.6; let mut score = 0.; // Tags are not likely to change! Good indicator of it being the wrong element. if old.tag == new.tag { score += 0.3 } else { score -= 0.3 }; if old.text_node == new.text_node { score += 0.2 } else { score -= 0.2 }; // Position will not change in many cases. if old_posit == new_posit { score += 0.1 } // Attrs are not likely to change. // TODO:: Compare attrs more directly. if old.attrs == new.attrs { score += 0.15 } else { score -= 0.15 }; // Style is likely to change. if old.style == new.style { score += 0.05 } else { score -= 0.05 }; // Text is likely to change, but may still be a good indicator. if old.text == new.text { score += 0.05 } else { score -= 0.05 }; if old.get_text() == new.get_text() { score += 0.15 } else { score -= 0.15 }; // For children length, don't do it based on the difference, since children that actually change in // len may have very large changes. But having identical length is a sanity check. if old.children.len() == new.children.len() { score += 0.1 // } else if (old.children.len() as i16 - new.children.len() as i16).abs() == 1 { // // Perhaps we've added or removed a child. // score += 0.05 // TODO: non-even transaction } else { score -= 0.1 } // Same id implies it may have been added in the same order. if old.id.expect("Missing id") == new.id.expect("Missing id") { score += 0.15 } else { score -= 0.15 }; // Weight each child subsequently-less by taking powers of child_significant. for posit in 0..old.children.len() { if let Some(child_old) = &old.children.get(posit) { if let Some(child_new) = &new.children.get(posit) { score += child_score_significance.powi(posit as i32) * match_score(child_old, posit, child_new, posit); } } } score } 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); } /// WIP towards a modular VDOM /// Assumes dependency on web_sys. // TODO:: Do we need <Ms> ? pub trait DomEl<Ms>: Sized + PartialEq + DomElLifecycle { type Tg: PartialEq + ToString; // TODO: tostring type At: Attrs; type St: Style; type Ls: Listener<Ms>; type Tx: PartialEq + ToString + Clone + Default; // Fields 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 raw_html(self) -> bool; // TODO: tying to dom_types is temp - defeats the urpose of the trait fn namespace(self) -> Option<Namespace>; // Methods fn empty(self) -> Self; // setters fn set_id(&mut self, id: Option<u32>); fn set_websys_el(&mut self, el: Option<Element>); // fn make_websys_el(&self, document: &web_sys::Document) -> web_sys::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)>>; } #[cfg(test)] pub mod tests { use wasm_bindgen_test::wasm_bindgen_test_configure; wasm_bindgen_test_configure!(run_in_browser); use super::*; use wasm_bindgen_test::*; use crate as seed; // required for macros to work. use crate::{div, li, prelude::*}; #[derive(Clone)] enum Msg {} #[ignore] // #[wasm_bindgen_test] #[test] fn el_added() { let mut old_vdom: El<Msg> = div!["text", vec![li!["child1"],]]; let mut new_vdom: El<Msg> = div!["text", vec![li!["child1"], li!["child2"]]]; let doc = util::document(); let old_ws = doc.create_element("div").unwrap(); let new_ws = doc.create_element("div").unwrap(); let child1 = doc.create_element("li").unwrap(); let child2 = doc.create_element("li").unwrap(); // TODO: make this match how you're setting text_content, eg could // TODO: be adding a text node. old_ws.set_text_content(Some("text")); child1.set_text_content(Some("child1")); child2.set_text_content(Some("child2")); old_ws.append_child(&child1).unwrap(); new_ws.append_child(&child1).unwrap(); new_ws.append_child(&child2).unwrap(); let mailbox = Mailbox::new(|msg: Msg| {}); let parent = doc.create_element("div").unwrap(); patch(&doc, &mut old_vdom, &mut new_vdom, &parent, &mailbox); unimplemented!() } #[ignore] #[test] fn el_removed() { unimplemented!() } #[ignore] #[test] fn el_changed() { unimplemented!() } }