component.rs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. //! This file handles the supporting infrastructure for the `Component` trait and `Properties` which makes it possible
  2. //! for components to be used within Nodes.
  3. //!
  4. //! Note - using the builder pattern does not required the Properties trait to be implemented - the only thing that matters is
  5. //! if the type supports PartialEq. The Properties trait is used by the rsx! and html! macros to generate the type-safe builder
  6. //! that ensures compile-time required and optional fields on cx.
  7. use crate::innerlude::{Context, Element, LazyNodes, ScopeChildren};
  8. /// A component is a wrapper around a Context and some Props that share a lifetime
  9. ///
  10. ///
  11. /// # Example
  12. ///
  13. /// With memoized state:
  14. /// ```rust
  15. /// struct State {}
  16. ///
  17. /// fn Example((cx, props): Scope<State>) -> DomTree {
  18. /// // ...
  19. /// }
  20. /// ```
  21. ///
  22. /// With borrowed state:
  23. /// ```rust
  24. /// struct State<'a> {
  25. /// name: &'a str
  26. /// }
  27. ///
  28. /// fn Example<'a>((cx, props): Scope<'a, State>) -> DomTree<'a> {
  29. /// // ...
  30. /// }
  31. /// ```
  32. ///
  33. /// With owned state as a closure:
  34. /// ```rust
  35. /// static Example: FC<()> = |(cx, props)| {
  36. /// // ...
  37. /// };
  38. /// ```
  39. ///
  40. pub type Scope<'a, T> = (Context<'a>, &'a T);
  41. pub struct FragmentProps<'a> {
  42. children: ScopeChildren<'a>,
  43. }
  44. pub struct FragmentBuilder<'a, const BUILT: bool> {
  45. children: Option<ScopeChildren<'a>>,
  46. }
  47. impl<'a> FragmentBuilder<'a, false> {
  48. pub fn children(self, children: ScopeChildren<'a>) -> FragmentBuilder<'a, true> {
  49. FragmentBuilder {
  50. children: Some(children),
  51. }
  52. }
  53. }
  54. impl<'a, const A: bool> FragmentBuilder<'a, A> {
  55. pub fn build(self) -> FragmentProps<'a> {
  56. FragmentProps {
  57. children: self.children.unwrap_or_default(),
  58. }
  59. }
  60. }
  61. impl<'a> Properties for FragmentProps<'a> {
  62. type Builder = FragmentBuilder<'a, false>;
  63. const IS_STATIC: bool = false;
  64. fn builder() -> Self::Builder {
  65. FragmentBuilder { children: None }
  66. }
  67. unsafe fn memoize(&self, _other: &Self) -> bool {
  68. false
  69. }
  70. }
  71. /// Create inline fragments using Component syntax.
  72. ///
  73. /// Fragments capture a series of children without rendering extra nodes.
  74. ///
  75. /// # Example
  76. ///
  77. /// ```rust
  78. /// rsx!{
  79. /// Fragment { key: "abc" }
  80. /// }
  81. /// ```
  82. ///
  83. /// # Details
  84. ///
  85. /// Fragments are incredibly useful when necessary, but *do* add cost in the diffing phase.
  86. /// Try to avoid nesting fragments if you can. There is no protection against infinitely nested fragments.
  87. ///
  88. /// This function defines a dedicated `Fragment` component that can be used to create inline fragments in the RSX macro.
  89. ///
  90. /// You want to use this free-function when your fragment needs a key and simply returning multiple nodes from rsx! won't cut it.
  91. ///
  92. #[allow(non_upper_case_globals, non_snake_case)]
  93. pub fn Fragment<'a>((cx, props): Scope<'a, FragmentProps<'a>>) -> Element<'a> {
  94. cx.render(Some(LazyNodes::new(|f| {
  95. f.fragment_from_iter(&props.children)
  96. })))
  97. }
  98. /// Every "Props" used for a component must implement the `Properties` trait. This trait gives some hints to Dioxus
  99. /// on how to memoize the props and some additional optimizations that can be made. We strongly encourage using the
  100. /// derive macro to implement the `Properties` trait automatically as guarantee that your memoization strategy is safe.
  101. ///
  102. /// If your props are 'static, then Dioxus will require that they also be PartialEq for the derived memoize strategy. However,
  103. /// if your props borrow data, then the memoization strategy will simply default to "false" and the PartialEq will be ignored.
  104. /// This tends to be useful when props borrow something that simply cannot be compared (IE a reference to a closure);
  105. ///
  106. /// By default, the memoization strategy is very conservative, but can be tuned to be more aggressive manually. However,
  107. /// this is only safe if the props are 'static - otherwise you might borrow references after-free.
  108. ///
  109. /// We strongly suggest that any changes to memoization be done at the "PartialEq" level for 'static props. Additionally,
  110. /// we advise the use of smart pointers in cases where memoization is important.
  111. ///
  112. /// ## Example
  113. ///
  114. /// For props that are 'static:
  115. /// ```rust ignore
  116. /// #[derive(Props, PartialEq)]
  117. /// struct MyProps {
  118. /// data: String
  119. /// }
  120. /// ```
  121. ///
  122. /// For props that borrow:
  123. ///
  124. /// ```rust ignore
  125. /// #[derive(Props)]
  126. /// struct MyProps<'a >{
  127. /// data: &'a str
  128. /// }
  129. /// ```
  130. pub trait Properties: Sized {
  131. type Builder;
  132. const IS_STATIC: bool;
  133. fn builder() -> Self::Builder;
  134. /// Memoization can only happen if the props are valid for the 'static lifetime
  135. ///
  136. /// # Safety
  137. /// The user must know if their props are static, but if they make a mistake, UB happens
  138. /// Therefore it's unsafe to memoize.
  139. unsafe fn memoize(&self, other: &Self) -> bool;
  140. }
  141. impl Properties for () {
  142. type Builder = EmptyBuilder;
  143. const IS_STATIC: bool = true;
  144. fn builder() -> Self::Builder {
  145. EmptyBuilder {}
  146. }
  147. unsafe fn memoize(&self, _other: &Self) -> bool {
  148. true
  149. }
  150. }
  151. // We allow components to use the () generic parameter if they have no props. This impl enables the "build" method
  152. // that the macros use to anonymously complete prop construction.
  153. pub struct EmptyBuilder;
  154. impl EmptyBuilder {
  155. #[inline]
  156. pub fn build(self) {}
  157. }
  158. /// This utility function launches the builder method so rsx! and html! macros can use the typed-builder pattern
  159. /// to initialize a component's props.
  160. pub fn fc_to_builder<'a, T: Properties + 'a>(_: fn(Scope<'a, T>) -> Element<'a>) -> T::Builder {
  161. T::builder()
  162. }