dioxus_core/
properties.rs

1use std::fmt::Arguments;
2
3use crate::innerlude::*;
4
5/// Every "Props" used for a component must implement the `Properties` trait. This trait gives some hints to Dioxus
6/// on how to memoize the props and some additional optimizations that can be made. We strongly encourage using the
7/// derive macro to implement the `Properties` trait automatically.
8///
9/// Dioxus requires your props to be 'static, `Clone`, and `PartialEq`. We use the `PartialEq` trait to determine if
10/// the props have changed when we diff the component.
11///
12/// ## Example
13///
14/// ```rust
15/// # use dioxus::prelude::*;
16/// #[derive(Props, PartialEq, Clone)]
17/// struct MyComponentProps {
18///     data: String
19/// }
20///
21/// fn MyComponent(props: MyComponentProps) -> Element {
22///     rsx! {
23///         div { "Hello {props.data}" }
24///     }
25/// }
26/// ```
27///
28/// Or even better, derive your entire props struct with the [`#[crate::component]`] macro:
29///
30/// ```rust
31/// # use dioxus::prelude::*;
32/// #[component]
33/// fn MyComponent(data: String) -> Element {
34///     rsx! {
35///         div { "Hello {data}" }
36///     }
37/// }
38/// ```
39#[rustversion::attr(
40    since(1.78.0),
41    diagnostic::on_unimplemented(
42        message = "`Props` is not implemented for `{Self}`",
43        label = "Props",
44        note = "Props is a trait that is automatically implemented for all structs that can be used as props for a component",
45        note = "If you manually created a new properties struct, you may have forgotten to add `#[derive(Props, PartialEq, Clone)]` to your struct",
46    )
47)]
48pub trait Properties: Clone + Sized + 'static {
49    /// The type of the builder for this component.
50    /// Used to create "in-progress" versions of the props.
51    type Builder;
52
53    /// Create a builder for this component.
54    fn builder() -> Self::Builder;
55
56    /// Make the old props equal to the new props. Return if the props were equal and should be memoized.
57    fn memoize(&mut self, other: &Self) -> bool;
58
59    /// Create a component from the props.
60    fn into_vcomponent<M: 'static>(self, render_fn: impl ComponentFunction<Self, M>) -> VComponent {
61        let type_name = std::any::type_name_of_val(&render_fn);
62        VComponent::new(render_fn, self, type_name)
63    }
64}
65
66impl Properties for () {
67    type Builder = EmptyBuilder;
68    fn builder() -> Self::Builder {
69        EmptyBuilder {}
70    }
71    fn memoize(&mut self, _other: &Self) -> bool {
72        true
73    }
74}
75
76/// Root properties never need to be memoized, so we can use a dummy implementation.
77pub(crate) struct RootProps<P>(pub P);
78
79impl<P> Clone for RootProps<P>
80where
81    P: Clone,
82{
83    fn clone(&self) -> Self {
84        Self(self.0.clone())
85    }
86}
87
88impl<P> Properties for RootProps<P>
89where
90    P: Clone + 'static,
91{
92    type Builder = P;
93    fn builder() -> Self::Builder {
94        unreachable!("Root props technically are never built")
95    }
96    fn memoize(&mut self, _other: &Self) -> bool {
97        true
98    }
99}
100
101// We allow components to use the () generic parameter if they have no props. This impl enables the "build" method
102// that the macros use to anonymously complete prop construction.
103pub struct EmptyBuilder;
104impl EmptyBuilder {
105    pub fn build(self) {}
106}
107
108/// This utility function launches the builder method so that the rsx! macro can use the typed-builder pattern
109/// to initialize a component's props.
110pub fn fc_to_builder<P, M>(_: impl ComponentFunction<P, M>) -> <P as Properties>::Builder
111where
112    P: Properties,
113{
114    P::builder()
115}
116
117/// Any component that implements the `ComponentFn` trait can be used as a component.
118///
119/// This trait is automatically implemented for functions that are in one of the following forms:
120/// - `fn() -> Element`
121/// - `fn(props: Properties) -> Element`
122///
123/// You can derive it automatically for any function with arguments that implement PartialEq with the `#[component]` attribute:
124/// ```rust
125/// # use dioxus::prelude::*;
126/// #[component]
127/// fn MyComponent(a: u32, b: u32) -> Element {
128///     rsx! { "a: {a}, b: {b}" }
129/// }
130/// ```
131#[rustversion::attr(
132    since(1.78.0),
133    diagnostic::on_unimplemented(
134        message = "`Component<{Props}>` is not implemented for `{Self}`",
135        label = "Component",
136        note = "Components are functions in the form `fn() -> Element`, `fn(props: Properties) -> Element`, or `#[component] fn(partial_eq1: u32, partial_eq2: u32) -> Element`.",
137        note = "You may have forgotten to add `#[component]` to your function to automatically implement the `ComponentFunction` trait."
138    )
139)]
140pub trait ComponentFunction<Props, Marker = ()>: Clone + 'static {
141    /// Get the raw address of the component render function.
142    fn fn_ptr(&self) -> usize;
143
144    /// Convert the component to a function that takes props and returns an element.
145    fn rebuild(&self, props: Props) -> Element;
146}
147
148/// Accept any callbacks that take props
149impl<F, P> ComponentFunction<P> for F
150where
151    F: Fn(P) -> Element + Clone + 'static,
152{
153    fn rebuild(&self, props: P) -> Element {
154        subsecond::HotFn::current(self.clone()).call((props,))
155    }
156
157    fn fn_ptr(&self) -> usize {
158        subsecond::HotFn::current(self.clone()).ptr_address().0 as usize
159    }
160}
161
162/// Accept any callbacks that take no props
163pub struct EmptyMarker;
164impl<F> ComponentFunction<(), EmptyMarker> for F
165where
166    F: Fn() -> Element + Clone + 'static,
167{
168    fn rebuild(&self, props: ()) -> Element {
169        subsecond::HotFn::current(self.clone()).call(props)
170    }
171
172    fn fn_ptr(&self) -> usize {
173        subsecond::HotFn::current(self.clone()).ptr_address().0 as usize
174    }
175}
176
177/// A enhanced version of the `Into` trait that allows with more flexibility.
178pub trait SuperInto<O, M = ()> {
179    /// Convert from a type to another type.
180    fn super_into(self) -> O;
181}
182
183impl<T, O, M> SuperInto<O, M> for T
184where
185    O: SuperFrom<T, M>,
186{
187    fn super_into(self) -> O {
188        O::super_from(self)
189    }
190}
191
192/// A enhanced version of the `From` trait that allows with more flexibility.
193pub trait SuperFrom<T, M = ()> {
194    /// Convert from a type to another type.
195    fn super_from(_: T) -> Self;
196}
197
198// first implement for all types that are that implement the From trait
199impl<T, O> SuperFrom<T, ()> for O
200where
201    O: From<T>,
202{
203    fn super_from(input: T) -> Self {
204        Self::from(input)
205    }
206}
207
208#[doc(hidden)]
209pub struct OptionStringFromMarker;
210
211impl<'a> SuperFrom<&'a str, OptionStringFromMarker> for Option<String> {
212    fn super_from(input: &'a str) -> Self {
213        Some(String::from(input))
214    }
215}
216
217#[doc(hidden)]
218pub struct OptionArgumentsFromMarker;
219
220impl<'a> SuperFrom<Arguments<'a>, OptionArgumentsFromMarker> for Option<String> {
221    fn super_from(input: Arguments<'a>) -> Self {
222        Some(input.to_string())
223    }
224}
225
226#[doc(hidden)]
227pub struct OptionCallbackMarker<T>(std::marker::PhantomData<T>);
228
229// Closure can be created from FnMut -> async { anything } or FnMut -> Ret
230impl<
231        Function: FnMut(Args) -> Spawn + 'static,
232        Args: 'static,
233        Spawn: SpawnIfAsync<Marker, Ret> + 'static,
234        Ret: 'static,
235        Marker,
236    > SuperFrom<Function, OptionCallbackMarker<Marker>> for Option<Callback<Args, Ret>>
237{
238    fn super_from(input: Function) -> Self {
239        Some(Callback::new(input))
240    }
241}
242
243#[test]
244#[allow(unused)]
245fn optional_callback_compiles() {
246    fn compiles() {
247        // Converting from closures (without type hints in the closure works)
248        let callback: Callback<i32, i32> = (|num| num * num).super_into();
249        let callback: Callback<i32, ()> = (|num| async move { println!("{num}") }).super_into();
250
251        // Converting from closures to optional callbacks works
252        let optional: Option<Callback<i32, i32>> = (|num| num * num).super_into();
253        let optional: Option<Callback<i32, ()>> =
254            (|num| async move { println!("{num}") }).super_into();
255    }
256}
257
258#[test]
259#[allow(unused)]
260fn from_props_compiles() {
261    // T -> T works
262    let option: i32 = 0i32.super_into();
263    let option: i32 = 0.super_into(); // Note we don't need type hints on all inputs
264    let option: i128 = 0.super_into();
265    let option: &'static str = "hello world".super_into();
266
267    // // T -> From<T> works
268    let option: i64 = 0i32.super_into();
269    let option: String = "hello world".super_into();
270
271    // T -> Option works
272    let option: Option<i32> = 0i32.super_into();
273    let option: Option<i32> = 0.super_into();
274    let option: Option<i128> = 0.super_into();
275    fn takes_option_string<M>(_: impl SuperInto<Option<String>, M>) {}
276    takes_option_string("hello world");
277    takes_option_string("hello world".to_string());
278}