test_dom.rs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. //! A DOM for testing - both internal and external code.
  2. use bumpalo::Bump;
  3. use crate::innerlude::*;
  4. use crate::nodes::IntoVNode;
  5. pub struct TestDom {
  6. bump: Bump,
  7. scheduler: Scheduler,
  8. }
  9. impl TestDom {
  10. pub fn new() -> TestDom {
  11. let bump = Bump::new();
  12. let scheduler = Scheduler::new();
  13. TestDom { bump, scheduler }
  14. }
  15. pub fn new_factory(&self) -> NodeFactory {
  16. NodeFactory::new(&self.bump)
  17. }
  18. pub fn render_direct<'a, F>(&'a self, lazy_nodes: LazyNodes<'a, F>) -> VNode<'a>
  19. where
  20. F: FnOnce(NodeFactory<'a>) -> VNode<'a>,
  21. {
  22. lazy_nodes.into_vnode(NodeFactory::new(&self.bump))
  23. }
  24. pub fn render<'a, F>(&'a self, lazy_nodes: LazyNodes<'a, F>) -> &'a VNode<'a>
  25. where
  26. F: FnOnce(NodeFactory<'a>) -> VNode<'a>,
  27. {
  28. self.bump
  29. .alloc(lazy_nodes.into_vnode(NodeFactory::new(&self.bump)))
  30. }
  31. pub fn diff<'a>(&'a self, old: &'a VNode<'a>, new: &'a VNode<'a>) -> Mutations<'a> {
  32. let mutations = Mutations::new();
  33. let mut machine = DiffMachine::new(mutations, &self.scheduler.pool);
  34. machine.stack.push(DiffInstruction::Diff { new, old });
  35. machine.mutations
  36. }
  37. pub fn create<'a, F1>(&'a self, left: LazyNodes<'a, F1>) -> Mutations<'a>
  38. where
  39. F1: FnOnce(NodeFactory<'a>) -> VNode<'a>,
  40. {
  41. let old = self.bump.alloc(self.render_direct(left));
  42. let mut machine = DiffMachine::new(Mutations::new(), &self.scheduler.pool);
  43. machine.stack.create_node(old, MountType::Append);
  44. machine.work(&mut || false);
  45. machine.mutations
  46. }
  47. pub fn lazy_diff<'a, F1, F2>(
  48. &'a self,
  49. left: LazyNodes<'a, F1>,
  50. right: LazyNodes<'a, F2>,
  51. ) -> (Mutations<'a>, Mutations<'a>)
  52. where
  53. F1: FnOnce(NodeFactory<'a>) -> VNode<'a>,
  54. F2: FnOnce(NodeFactory<'a>) -> VNode<'a>,
  55. {
  56. let (old, new) = (self.render(left), self.render(right));
  57. let mut machine = DiffMachine::new(Mutations::new(), &self.scheduler.pool);
  58. machine.stack.create_node(old, MountType::Append);
  59. machine.work(|| false);
  60. let create_edits = machine.mutations;
  61. let mut machine = DiffMachine::new(Mutations::new(), &self.scheduler.pool);
  62. machine.stack.push(DiffInstruction::Diff { old, new });
  63. machine.work(&mut || false);
  64. let edits = machine.mutations;
  65. (create_edits, edits)
  66. }
  67. }
  68. impl Default for TestDom {
  69. fn default() -> Self {
  70. Self::new()
  71. }
  72. }
  73. impl VirtualDom {
  74. pub fn simulate(&mut self) {
  75. //
  76. }
  77. }