update_state.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. use anymap::AnyMap;
  2. use dioxus::core::ElementId;
  3. use dioxus::core::{self as dioxus_core, GlobalNodeId};
  4. use dioxus::core::{AttributeValue, DomEdit, Mutations};
  5. use dioxus::core_macro::rsx_without_templates;
  6. use dioxus::prelude::*;
  7. use dioxus_native_core::node_ref::*;
  8. use dioxus_native_core::real_dom::*;
  9. use dioxus_native_core::state::{ChildDepState, NodeDepState, ParentDepState, State};
  10. use dioxus_native_core_macro::State;
  11. #[derive(Debug, Clone, Default, State)]
  12. struct CallCounterStatePart1 {
  13. #[child_dep_state(child_counter)]
  14. child_counter: ChildDepCallCounter,
  15. }
  16. #[derive(Debug, Clone, Default, State)]
  17. struct CallCounterStatePart2 {
  18. #[parent_dep_state(parent_counter)]
  19. parent_counter: ParentDepCallCounter,
  20. }
  21. #[derive(Debug, Clone, Default, State)]
  22. struct CallCounterStatePart3 {
  23. #[node_dep_state()]
  24. node_counter: NodeDepCallCounter,
  25. }
  26. #[derive(Debug, Clone, Default, State)]
  27. struct CallCounterState {
  28. #[child_dep_state(child_counter)]
  29. child_counter: ChildDepCallCounter,
  30. #[state]
  31. part2: CallCounterStatePart2,
  32. #[parent_dep_state(parent_counter)]
  33. parent_counter: ParentDepCallCounter,
  34. #[state]
  35. part1: CallCounterStatePart1,
  36. #[state]
  37. part3: CallCounterStatePart3,
  38. #[node_dep_state()]
  39. node_counter: NodeDepCallCounter,
  40. }
  41. #[derive(Debug, Clone, Default)]
  42. struct ChildDepCallCounter(u32);
  43. impl ChildDepState for ChildDepCallCounter {
  44. type Ctx = ();
  45. type DepState = Self;
  46. const NODE_MASK: NodeMask = NodeMask::ALL;
  47. fn reduce<'a>(
  48. &mut self,
  49. _: NodeView,
  50. _: impl Iterator<Item = &'a Self::DepState>,
  51. _: &Self::Ctx,
  52. ) -> bool
  53. where
  54. Self::DepState: 'a,
  55. {
  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(|iter| {
  136. iter.map(|a| {
  137. (
  138. a.attribute.name.to_string(),
  139. format!("{}", a.value.as_text().unwrap()),
  140. )
  141. })
  142. .collect()
  143. })
  144. .unwrap_or_default(),
  145. );
  146. true
  147. }
  148. }
  149. #[derive(State, Clone, Default, Debug)]
  150. struct StateTester {
  151. #[child_dep_state(bubbled, u32)]
  152. bubbled: BubbledUpStateTester,
  153. #[parent_dep_state(pushed, u32)]
  154. pushed: PushedDownStateTester,
  155. #[node_dep_state(NONE, u32)]
  156. node: NodeStateTester,
  157. }
  158. #[test]
  159. fn state_initial() {
  160. #[allow(non_snake_case)]
  161. fn Base(cx: Scope) -> Element {
  162. render!(div {
  163. p{}
  164. h1{}
  165. })
  166. }
  167. let vdom = VirtualDom::new(Base);
  168. let mutations = vdom.create_vnodes(rsx! {
  169. div {
  170. p{
  171. color: "red"
  172. }
  173. h1{}
  174. }
  175. });
  176. let mut dom: RealDom<StateTester> = RealDom::new();
  177. let nodes_updated = dom.apply_mutations(vec![mutations]);
  178. let mut ctx = AnyMap::new();
  179. ctx.insert(42u32);
  180. let _to_rerender = dom.update_state(nodes_updated, ctx);
  181. let root_div = &dom[GlobalNodeId::TemplateId {
  182. template_ref_id: dioxus_core::ElementId(1),
  183. template_node_id: dioxus::prelude::TemplateNodeId(0),
  184. }];
  185. assert_eq!(root_div.state.bubbled.0, Some("div".to_string()));
  186. assert_eq!(
  187. root_div.state.bubbled.1,
  188. vec![
  189. Box::new(BubbledUpStateTester(Some("p".to_string()), Vec::new())),
  190. Box::new(BubbledUpStateTester(Some("h1".to_string()), Vec::new()))
  191. ]
  192. );
  193. assert_eq!(root_div.state.pushed.0, Some("div".to_string()));
  194. assert_eq!(
  195. root_div.state.pushed.1,
  196. Some(Box::new(PushedDownStateTester(
  197. Some("Root".to_string()),
  198. None
  199. )))
  200. );
  201. assert_eq!(root_div.state.node.0, Some("div".to_string()));
  202. assert_eq!(root_div.state.node.1, vec![]);
  203. let child_p = &dom[GlobalNodeId::TemplateId {
  204. template_ref_id: dioxus_core::ElementId(1),
  205. template_node_id: dioxus::prelude::TemplateNodeId(1),
  206. }];
  207. assert_eq!(child_p.state.bubbled.0, Some("p".to_string()));
  208. assert_eq!(child_p.state.bubbled.1, Vec::new());
  209. assert_eq!(child_p.state.pushed.0, Some("p".to_string()));
  210. assert_eq!(
  211. child_p.state.pushed.1,
  212. Some(Box::new(PushedDownStateTester(
  213. Some("div".to_string()),
  214. Some(Box::new(PushedDownStateTester(
  215. Some("Root".to_string()),
  216. None
  217. )))
  218. )))
  219. );
  220. assert_eq!(child_p.state.node.0, Some("p".to_string()));
  221. assert_eq!(
  222. child_p.state.node.1,
  223. vec![("color".to_string(), "red".to_string())]
  224. );
  225. let child_h1 = &dom[GlobalNodeId::TemplateId {
  226. template_ref_id: dioxus_core::ElementId(1),
  227. template_node_id: dioxus::prelude::TemplateNodeId(2),
  228. }];
  229. assert_eq!(child_h1.state.bubbled.0, Some("h1".to_string()));
  230. assert_eq!(child_h1.state.bubbled.1, Vec::new());
  231. assert_eq!(child_h1.state.pushed.0, Some("h1".to_string()));
  232. assert_eq!(
  233. child_h1.state.pushed.1,
  234. Some(Box::new(PushedDownStateTester(
  235. Some("div".to_string()),
  236. Some(Box::new(PushedDownStateTester(
  237. Some("Root".to_string()),
  238. None
  239. )))
  240. )))
  241. );
  242. assert_eq!(child_h1.state.node.0, Some("h1".to_string()));
  243. assert_eq!(child_h1.state.node.1, vec![]);
  244. }
  245. #[test]
  246. fn state_reduce_parent_called_minimally_on_update() {
  247. #[allow(non_snake_case)]
  248. fn Base(cx: Scope) -> Element {
  249. render!(div {
  250. width: "100%",
  251. div{
  252. div{
  253. p{}
  254. }
  255. p{
  256. "hello"
  257. }
  258. div{
  259. h1{}
  260. }
  261. p{
  262. "world"
  263. }
  264. }
  265. })
  266. }
  267. let vdom = VirtualDom::new(Base);
  268. let mutations = vdom.create_vnodes(rsx_without_templates! {
  269. div {
  270. width: "100%",
  271. div{
  272. div{
  273. p{}
  274. }
  275. p{
  276. "hello"
  277. }
  278. div{
  279. h1{}
  280. }
  281. p{
  282. "world"
  283. }
  284. }
  285. }
  286. });
  287. let mut dom: RealDom<CallCounterState> = RealDom::new();
  288. let nodes_updated = dom.apply_mutations(vec![mutations]);
  289. let _to_rerender = dom.update_state(nodes_updated, AnyMap::new());
  290. let nodes_updated = dom.apply_mutations(vec![Mutations {
  291. edits: vec![DomEdit::SetAttribute {
  292. root: 1,
  293. field: "width",
  294. value: AttributeValue::Text("99%"),
  295. ns: Some("style"),
  296. }],
  297. dirty_scopes: fxhash::FxHashSet::default(),
  298. refs: Vec::new(),
  299. }]);
  300. let _to_rerender = dom.update_state(nodes_updated, AnyMap::new());
  301. dom.traverse_depth_first(|n| {
  302. assert_eq!(n.state.part2.parent_counter.0, 2);
  303. assert_eq!(n.state.parent_counter.0, 2);
  304. });
  305. }
  306. #[test]
  307. fn state_reduce_child_called_minimally_on_update() {
  308. #[allow(non_snake_case)]
  309. fn Base(cx: Scope) -> Element {
  310. cx.render(rsx_without_templates!(div {
  311. div{
  312. div{
  313. p{
  314. width: "100%",
  315. }
  316. }
  317. p{
  318. "hello"
  319. }
  320. div{
  321. h1{}
  322. }
  323. p{
  324. "world"
  325. }
  326. }
  327. }))
  328. }
  329. let vdom = VirtualDom::new(Base);
  330. let mutations = vdom.create_vnodes(rsx_without_templates! {
  331. div {
  332. div{
  333. div{
  334. p{
  335. width: "100%",
  336. }
  337. }
  338. p{
  339. "hello"
  340. }
  341. div{
  342. h1{}
  343. }
  344. p{
  345. "world"
  346. }
  347. }
  348. }
  349. });
  350. let mut dom: RealDom<CallCounterState> = RealDom::new();
  351. let nodes_updated = dom.apply_mutations(vec![mutations]);
  352. let _to_rerender = dom.update_state(nodes_updated, AnyMap::new());
  353. let nodes_updated = dom.apply_mutations(vec![Mutations {
  354. edits: vec![DomEdit::SetAttribute {
  355. root: 4,
  356. field: "width",
  357. value: AttributeValue::Text("99%"),
  358. ns: Some("style"),
  359. }],
  360. dirty_scopes: fxhash::FxHashSet::default(),
  361. refs: Vec::new(),
  362. }]);
  363. let _to_rerender = dom.update_state(nodes_updated, AnyMap::new());
  364. dom.traverse_depth_first(|n| {
  365. assert_eq!(
  366. n.state.part1.child_counter.0,
  367. if let GlobalNodeId::VNodeId(ElementId(id)) = n.node_data.id {
  368. if id > 4 {
  369. 1
  370. } else {
  371. 2
  372. }
  373. } else {
  374. panic!()
  375. }
  376. );
  377. assert_eq!(
  378. n.state.child_counter.0,
  379. if let GlobalNodeId::VNodeId(ElementId(id)) = n.node_data.id {
  380. if id > 4 {
  381. 1
  382. } else {
  383. 2
  384. }
  385. } else {
  386. panic!()
  387. }
  388. );
  389. });
  390. }
  391. #[derive(Debug, Clone, Default, State)]
  392. struct UnorderedDependanciesState {
  393. #[node_dep_state(c)]
  394. b: BDepCallCounter,
  395. #[node_dep_state()]
  396. c: CDepCallCounter,
  397. #[node_dep_state(b)]
  398. a: ADepCallCounter,
  399. }
  400. #[derive(Debug, Clone, Default, PartialEq)]
  401. struct ADepCallCounter(usize, BDepCallCounter);
  402. impl<'a> NodeDepState<(&'a BDepCallCounter,)> for ADepCallCounter {
  403. type Ctx = ();
  404. const NODE_MASK: NodeMask = NodeMask::NONE;
  405. fn reduce(
  406. &mut self,
  407. _node: NodeView,
  408. (sibling,): (&'a BDepCallCounter,),
  409. _ctx: &Self::Ctx,
  410. ) -> bool {
  411. self.0 += 1;
  412. self.1 = sibling.clone();
  413. true
  414. }
  415. }
  416. #[derive(Debug, Clone, Default, PartialEq)]
  417. struct BDepCallCounter(usize, CDepCallCounter);
  418. impl<'a> NodeDepState<(&'a CDepCallCounter,)> for BDepCallCounter {
  419. type Ctx = ();
  420. const NODE_MASK: NodeMask = NodeMask::NONE;
  421. fn reduce(
  422. &mut self,
  423. _node: NodeView,
  424. (sibling,): (&'a CDepCallCounter,),
  425. _ctx: &Self::Ctx,
  426. ) -> bool {
  427. self.0 += 1;
  428. self.1 = sibling.clone();
  429. true
  430. }
  431. }
  432. #[derive(Debug, Clone, Default, PartialEq)]
  433. struct CDepCallCounter(usize);
  434. impl NodeDepState<()> for CDepCallCounter {
  435. type Ctx = ();
  436. const NODE_MASK: NodeMask = NodeMask::ALL;
  437. fn reduce(&mut self, _node: NodeView, _sibling: (), _ctx: &Self::Ctx) -> bool {
  438. self.0 += 1;
  439. true
  440. }
  441. }
  442. #[test]
  443. fn dependancies_order_independant() {
  444. #[allow(non_snake_case)]
  445. fn Base(cx: Scope) -> Element {
  446. render!(div {
  447. width: "100%",
  448. p{
  449. "hello"
  450. }
  451. })
  452. }
  453. let vdom = VirtualDom::new(Base);
  454. let mutations = vdom.create_vnodes(rsx! {
  455. div {
  456. width: "100%",
  457. p{
  458. "hello"
  459. }
  460. }
  461. });
  462. let mut dom: RealDom<UnorderedDependanciesState> = RealDom::new();
  463. let nodes_updated = dom.apply_mutations(vec![mutations]);
  464. let _to_rerender = dom.update_state(nodes_updated, AnyMap::new());
  465. let c = CDepCallCounter(1);
  466. let b = BDepCallCounter(1, c.clone());
  467. let a = ADepCallCounter(1, b.clone());
  468. dom.traverse_depth_first(|n| {
  469. assert_eq!(&n.state.a, &a);
  470. assert_eq!(&n.state.b, &b);
  471. assert_eq!(&n.state.c, &c);
  472. });
  473. }
  474. #[derive(Clone, Default, State)]
  475. struct DependanciesStateTest {
  476. #[node_dep_state(c)]
  477. b: BDepCallCounter,
  478. #[node_dep_state()]
  479. c: CDepCallCounter,
  480. #[node_dep_state(b)]
  481. a: ADepCallCounter,
  482. #[state]
  483. child: UnorderedDependanciesState,
  484. }