leptos/
component.rs

1//! Utility traits and functions that allow building components,
2//! as either functions of their props or functions with no arguments,
3//! without knowing the name of the props struct.
4
5pub trait Component<P> {}
6
7pub trait Props {
8    type Builder;
9
10    fn builder() -> Self::Builder;
11}
12
13#[doc(hidden)]
14pub trait PropsOrNoPropsBuilder {
15    type Builder;
16
17    fn builder_or_not() -> Self::Builder;
18}
19
20#[doc(hidden)]
21#[derive(Copy, Clone, Debug, Default)]
22pub struct EmptyPropsBuilder {}
23
24impl EmptyPropsBuilder {
25    pub fn build(self) {}
26}
27
28impl<P: Props> PropsOrNoPropsBuilder for P {
29    type Builder = <P as Props>::Builder;
30
31    fn builder_or_not() -> Self::Builder {
32        Self::builder()
33    }
34}
35
36impl PropsOrNoPropsBuilder for EmptyPropsBuilder {
37    type Builder = EmptyPropsBuilder;
38
39    fn builder_or_not() -> Self::Builder {
40        EmptyPropsBuilder {}
41    }
42}
43
44impl<F, R> Component<EmptyPropsBuilder> for F where F: FnOnce() -> R {}
45
46impl<P, F, R> Component<P> for F
47where
48    F: FnOnce(P) -> R,
49    P: Props,
50{
51}
52
53pub fn component_props_builder<P: PropsOrNoPropsBuilder>(
54    _f: &impl Component<P>,
55) -> <P as PropsOrNoPropsBuilder>::Builder {
56    <P as PropsOrNoPropsBuilder>::builder_or_not()
57}
58
59pub fn component_view<P, T>(f: impl ComponentConstructor<P, T>, props: P) -> T {
60    f.construct(props)
61}
62pub trait ComponentConstructor<P, T> {
63    fn construct(self, props: P) -> T;
64}
65
66impl<Func, T> ComponentConstructor<(), T> for Func
67where
68    Func: FnOnce() -> T,
69{
70    fn construct(self, (): ()) -> T {
71        (self)()
72    }
73}
74
75impl<Func, T, P> ComponentConstructor<P, T> for Func
76where
77    Func: FnOnce(P) -> T,
78    P: PropsOrNoPropsBuilder,
79{
80    fn construct(self, props: P) -> T {
81        (self)(props)
82    }
83}