update_state.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. use anymap::AnyMap;
  2. use dioxus::core as dioxus_core;
  3. use dioxus::core::ElementId;
  4. use dioxus::core::{AttributeValue, DomEdit, Mutations};
  5. use dioxus::prelude::*;
  6. use dioxus_native_core::node_ref::*;
  7. use dioxus_native_core::real_dom::*;
  8. use dioxus_native_core::state::{ChildDepState, NodeDepState, ParentDepState, State};
  9. use dioxus_native_core_macro::State;
  10. #[derive(Debug, Clone, Default, State)]
  11. struct CallCounterStatePart1 {
  12. #[child_dep_state(child_counter)]
  13. child_counter: ChildDepCallCounter,
  14. }
  15. #[derive(Debug, Clone, Default, State)]
  16. struct CallCounterStatePart2 {
  17. #[parent_dep_state(parent_counter)]
  18. parent_counter: ParentDepCallCounter,
  19. }
  20. #[derive(Debug, Clone, Default, State)]
  21. struct CallCounterStatePart3 {
  22. #[node_dep_state()]
  23. node_counter: NodeDepCallCounter,
  24. }
  25. #[derive(Debug, Clone, Default, State)]
  26. struct CallCounterState {
  27. #[child_dep_state(child_counter)]
  28. child_counter: ChildDepCallCounter,
  29. #[state]
  30. part2: CallCounterStatePart2,
  31. #[parent_dep_state(parent_counter)]
  32. parent_counter: ParentDepCallCounter,
  33. #[state]
  34. part1: CallCounterStatePart1,
  35. #[state]
  36. part3: CallCounterStatePart3,
  37. #[node_dep_state()]
  38. node_counter: NodeDepCallCounter,
  39. }
  40. #[derive(Debug, Clone, Default)]
  41. struct ChildDepCallCounter(u32);
  42. impl ChildDepState for ChildDepCallCounter {
  43. type Ctx = ();
  44. type DepState = Self;
  45. const NODE_MASK: NodeMask = NodeMask::ALL;
  46. fn reduce<'a>(
  47. &mut self,
  48. node: NodeView,
  49. _: impl Iterator<Item = &'a Self::DepState>,
  50. _: &Self::Ctx,
  51. ) -> bool
  52. where
  53. Self::DepState: 'a,
  54. {
  55. println!("{self:?} {:?}: {} {:?}", node.tag(), node.id(), node.text());
  56. self.0 += 1;
  57. true
  58. }
  59. }
  60. #[derive(Debug, Clone, Default)]
  61. struct ParentDepCallCounter(u32);
  62. impl ParentDepState for ParentDepCallCounter {
  63. type Ctx = ();
  64. type DepState = Self;
  65. const NODE_MASK: NodeMask = NodeMask::ALL;
  66. fn reduce(
  67. &mut self,
  68. _node: NodeView,
  69. _parent: Option<&Self::DepState>,
  70. _ctx: &Self::Ctx,
  71. ) -> bool {
  72. self.0 += 1;
  73. true
  74. }
  75. }
  76. #[derive(Debug, Clone, Default)]
  77. struct NodeDepCallCounter(u32);
  78. impl NodeDepState<()> for NodeDepCallCounter {
  79. type Ctx = ();
  80. const NODE_MASK: NodeMask = NodeMask::ALL;
  81. fn reduce(&mut self, _node: NodeView, _sibling: (), _ctx: &Self::Ctx) -> bool {
  82. self.0 += 1;
  83. true
  84. }
  85. }
  86. #[allow(clippy::vec_box)]
  87. #[derive(Debug, Clone, PartialEq, Default)]
  88. struct BubbledUpStateTester(Option<String>, Vec<Box<BubbledUpStateTester>>);
  89. impl ChildDepState for BubbledUpStateTester {
  90. type Ctx = u32;
  91. type DepState = Self;
  92. const NODE_MASK: NodeMask = NodeMask::new().with_tag();
  93. fn reduce<'a>(
  94. &mut self,
  95. node: NodeView,
  96. children: impl Iterator<Item = &'a Self::DepState>,
  97. ctx: &Self::Ctx,
  98. ) -> bool
  99. where
  100. Self::DepState: 'a,
  101. {
  102. assert_eq!(*ctx, 42);
  103. *self = BubbledUpStateTester(
  104. node.tag().map(|s| s.to_string()),
  105. children.into_iter().map(|c| Box::new(c.clone())).collect(),
  106. );
  107. true
  108. }
  109. }
  110. #[derive(Debug, Clone, PartialEq, Default)]
  111. struct PushedDownStateTester(Option<String>, Option<Box<PushedDownStateTester>>);
  112. impl ParentDepState for PushedDownStateTester {
  113. type Ctx = u32;
  114. type DepState = Self;
  115. const NODE_MASK: NodeMask = NodeMask::new().with_tag();
  116. fn reduce(&mut self, node: NodeView, parent: Option<&Self::DepState>, ctx: &Self::Ctx) -> bool {
  117. assert_eq!(*ctx, 42);
  118. *self = PushedDownStateTester(
  119. node.tag().map(|s| s.to_string()),
  120. parent.map(|c| Box::new(c.clone())),
  121. );
  122. true
  123. }
  124. }
  125. #[derive(Debug, Clone, PartialEq, Default)]
  126. struct NodeStateTester(Option<String>, Vec<(String, String)>);
  127. impl NodeDepState<()> for NodeStateTester {
  128. type Ctx = u32;
  129. const NODE_MASK: NodeMask = NodeMask::new_with_attrs(AttributeMask::All).with_tag();
  130. fn reduce(&mut self, node: NodeView, _sibling: (), ctx: &Self::Ctx) -> bool {
  131. assert_eq!(*ctx, 42);
  132. *self = NodeStateTester(
  133. node.tag().map(|s| s.to_string()),
  134. node.attributes()
  135. .map(|a| (a.name.to_string(), a.value.to_string()))
  136. .collect(),
  137. );
  138. true
  139. }
  140. }
  141. #[derive(State, Clone, Default, Debug)]
  142. struct StateTester {
  143. #[child_dep_state(bubbled, u32)]
  144. bubbled: BubbledUpStateTester,
  145. #[parent_dep_state(pushed, u32)]
  146. pushed: PushedDownStateTester,
  147. #[node_dep_state(NONE, u32)]
  148. node: NodeStateTester,
  149. }
  150. #[test]
  151. fn state_initial() {
  152. #[allow(non_snake_case)]
  153. fn Base(cx: Scope) -> Element {
  154. render!(div {
  155. p{}
  156. h1{}
  157. })
  158. }
  159. let vdom = VirtualDom::new(Base);
  160. let mutations = vdom.create_vnodes(rsx! {
  161. div {
  162. p{
  163. color: "red"
  164. }
  165. h1{}
  166. }
  167. });
  168. let mut dom: RealDom<StateTester> = RealDom::new();
  169. let nodes_updated = dom.apply_mutations(vec![mutations]);
  170. let mut ctx = AnyMap::new();
  171. ctx.insert(42u32);
  172. let _to_rerender = dom.update_state(&vdom, nodes_updated, ctx);
  173. let root_div = &dom[ElementId(1)];
  174. assert_eq!(root_div.state.bubbled.0, Some("div".to_string()));
  175. assert_eq!(
  176. root_div.state.bubbled.1,
  177. vec![
  178. Box::new(BubbledUpStateTester(Some("p".to_string()), Vec::new())),
  179. Box::new(BubbledUpStateTester(Some("h1".to_string()), Vec::new()))
  180. ]
  181. );
  182. assert_eq!(root_div.state.pushed.0, Some("div".to_string()));
  183. assert_eq!(
  184. root_div.state.pushed.1,
  185. Some(Box::new(PushedDownStateTester(None, None)))
  186. );
  187. assert_eq!(root_div.state.node.0, Some("div".to_string()));
  188. assert_eq!(root_div.state.node.1, vec![]);
  189. let child_p = &dom[ElementId(2)];
  190. assert_eq!(child_p.state.bubbled.0, Some("p".to_string()));
  191. assert_eq!(child_p.state.bubbled.1, Vec::new());
  192. assert_eq!(child_p.state.pushed.0, Some("p".to_string()));
  193. assert_eq!(
  194. child_p.state.pushed.1,
  195. Some(Box::new(PushedDownStateTester(
  196. Some("div".to_string()),
  197. Some(Box::new(PushedDownStateTester(None, None)))
  198. )))
  199. );
  200. assert_eq!(child_p.state.node.0, Some("p".to_string()));
  201. assert_eq!(
  202. child_p.state.node.1,
  203. vec![("color".to_string(), "red".to_string())]
  204. );
  205. let child_h1 = &dom[ElementId(3)];
  206. assert_eq!(child_h1.state.bubbled.0, Some("h1".to_string()));
  207. assert_eq!(child_h1.state.bubbled.1, Vec::new());
  208. assert_eq!(child_h1.state.pushed.0, Some("h1".to_string()));
  209. assert_eq!(
  210. child_h1.state.pushed.1,
  211. Some(Box::new(PushedDownStateTester(
  212. Some("div".to_string()),
  213. Some(Box::new(PushedDownStateTester(None, None)))
  214. )))
  215. );
  216. assert_eq!(child_h1.state.node.0, Some("h1".to_string()));
  217. assert_eq!(child_h1.state.node.1, vec![]);
  218. }
  219. #[test]
  220. fn state_reduce_parent_called_minimally_on_update() {
  221. #[allow(non_snake_case)]
  222. fn Base(cx: Scope) -> Element {
  223. render!(div {
  224. width: "100%",
  225. div{
  226. div{
  227. p{}
  228. }
  229. p{
  230. "hello"
  231. }
  232. div{
  233. h1{}
  234. }
  235. p{
  236. "world"
  237. }
  238. }
  239. })
  240. }
  241. let vdom = VirtualDom::new(Base);
  242. let mutations = vdom.create_vnodes(rsx! {
  243. div {
  244. width: "100%",
  245. div{
  246. div{
  247. p{}
  248. }
  249. p{
  250. "hello"
  251. }
  252. div{
  253. h1{}
  254. }
  255. p{
  256. "world"
  257. }
  258. }
  259. }
  260. });
  261. let mut dom: RealDom<CallCounterState> = RealDom::new();
  262. let nodes_updated = dom.apply_mutations(vec![mutations]);
  263. let _to_rerender = dom.update_state(&vdom, nodes_updated, AnyMap::new());
  264. let nodes_updated = dom.apply_mutations(vec![Mutations {
  265. edits: vec![DomEdit::SetAttribute {
  266. root: 1,
  267. field: "width",
  268. value: AttributeValue::Text("99%"),
  269. ns: Some("style"),
  270. }],
  271. dirty_scopes: fxhash::FxHashSet::default(),
  272. refs: Vec::new(),
  273. }]);
  274. let _to_rerender = dom.update_state(&vdom, nodes_updated, AnyMap::new());
  275. dom.traverse_depth_first(|n| {
  276. assert_eq!(n.state.part2.parent_counter.0, 2);
  277. assert_eq!(n.state.parent_counter.0, 2);
  278. });
  279. }
  280. #[test]
  281. fn state_reduce_child_called_minimally_on_update() {
  282. #[allow(non_snake_case)]
  283. fn Base(cx: Scope) -> Element {
  284. render!(div {
  285. div{
  286. div{
  287. p{
  288. width: "100%",
  289. }
  290. }
  291. p{
  292. "hello"
  293. }
  294. div{
  295. h1{}
  296. }
  297. p{
  298. "world"
  299. }
  300. }
  301. })
  302. }
  303. let vdom = VirtualDom::new(Base);
  304. let mutations = vdom.create_vnodes(rsx! {
  305. div {
  306. div{
  307. div{
  308. p{
  309. width: "100%",
  310. }
  311. }
  312. p{
  313. "hello"
  314. }
  315. div{
  316. h1{}
  317. }
  318. p{
  319. "world"
  320. }
  321. }
  322. }
  323. });
  324. let mut dom: RealDom<CallCounterState> = RealDom::new();
  325. let nodes_updated = dom.apply_mutations(vec![mutations]);
  326. let _to_rerender = dom.update_state(&vdom, nodes_updated, AnyMap::new());
  327. let nodes_updated = dom.apply_mutations(vec![Mutations {
  328. edits: vec![DomEdit::SetAttribute {
  329. root: 4,
  330. field: "width",
  331. value: AttributeValue::Text("99%"),
  332. ns: Some("style"),
  333. }],
  334. dirty_scopes: fxhash::FxHashSet::default(),
  335. refs: Vec::new(),
  336. }]);
  337. let _to_rerender = dom.update_state(&vdom, nodes_updated, AnyMap::new());
  338. dom.traverse_depth_first(|n| {
  339. println!("{:?}", n);
  340. assert_eq!(
  341. n.state.part1.child_counter.0,
  342. if n.id.0 > 4 { 1 } else { 2 }
  343. );
  344. assert_eq!(n.state.child_counter.0, if n.id.0 > 4 { 1 } else { 2 });
  345. });
  346. }
  347. #[derive(Debug, Clone, Default, State)]
  348. struct UnorderedDependanciesState {
  349. #[node_dep_state(c)]
  350. b: BDepCallCounter,
  351. #[node_dep_state()]
  352. c: CDepCallCounter,
  353. #[node_dep_state(b)]
  354. a: ADepCallCounter,
  355. }
  356. #[derive(Debug, Clone, Default, PartialEq)]
  357. struct ADepCallCounter(usize, BDepCallCounter);
  358. impl<'a> NodeDepState<(&'a BDepCallCounter,)> for ADepCallCounter {
  359. type Ctx = ();
  360. const NODE_MASK: NodeMask = NodeMask::NONE;
  361. fn reduce(
  362. &mut self,
  363. _node: NodeView,
  364. (sibling,): (&'a BDepCallCounter,),
  365. _ctx: &Self::Ctx,
  366. ) -> bool {
  367. self.0 += 1;
  368. self.1 = sibling.clone();
  369. true
  370. }
  371. }
  372. #[derive(Debug, Clone, Default, PartialEq)]
  373. struct BDepCallCounter(usize, CDepCallCounter);
  374. impl<'a> NodeDepState<(&'a CDepCallCounter,)> for BDepCallCounter {
  375. type Ctx = ();
  376. const NODE_MASK: NodeMask = NodeMask::NONE;
  377. fn reduce(
  378. &mut self,
  379. _node: NodeView,
  380. (sibling,): (&'a CDepCallCounter,),
  381. _ctx: &Self::Ctx,
  382. ) -> bool {
  383. self.0 += 1;
  384. self.1 = sibling.clone();
  385. true
  386. }
  387. }
  388. #[derive(Debug, Clone, Default, PartialEq)]
  389. struct CDepCallCounter(usize);
  390. impl NodeDepState<()> for CDepCallCounter {
  391. type Ctx = ();
  392. const NODE_MASK: NodeMask = NodeMask::ALL;
  393. fn reduce(&mut self, _node: NodeView, _sibling: (), _ctx: &Self::Ctx) -> bool {
  394. self.0 += 1;
  395. true
  396. }
  397. }
  398. #[test]
  399. fn dependancies_order_independant() {
  400. #[allow(non_snake_case)]
  401. fn Base(cx: Scope) -> Element {
  402. render!(div {
  403. width: "100%",
  404. p{
  405. "hello"
  406. }
  407. })
  408. }
  409. let vdom = VirtualDom::new(Base);
  410. let mutations = vdom.create_vnodes(rsx! {
  411. div {
  412. width: "100%",
  413. p{
  414. "hello"
  415. }
  416. }
  417. });
  418. let mut dom: RealDom<UnorderedDependanciesState> = RealDom::new();
  419. let nodes_updated = dom.apply_mutations(vec![mutations]);
  420. let _to_rerender = dom.update_state(&vdom, nodes_updated, AnyMap::new());
  421. let c = CDepCallCounter(1);
  422. let b = BDepCallCounter(1, c.clone());
  423. let a = ADepCallCounter(1, b.clone());
  424. dom.traverse_depth_first(|n| {
  425. assert_eq!(&n.state.a, &a);
  426. assert_eq!(&n.state.b, &b);
  427. assert_eq!(&n.state.c, &c);
  428. });
  429. }
  430. #[derive(Clone, Default, State)]
  431. struct DependanciesStateTest {
  432. #[node_dep_state(c)]
  433. b: BDepCallCounter,
  434. #[node_dep_state()]
  435. c: CDepCallCounter,
  436. #[node_dep_state(b)]
  437. a: ADepCallCounter,
  438. #[state]
  439. child: UnorderedDependanciesState,
  440. }