From a6e30e38a0ec344359893744b66b371ee6cfbb4e Mon Sep 17 00:00:00 2001 From: luoxiao Date: Tue, 16 May 2023 00:01:58 +0800 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20add=20if=20component?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/components/if_comp.rs | 34 ++++++++++++++++++++++++++++++++++ src/components/mod.rs | 10 +++++++++- src/components/option_comp.rs | 10 +++++++++- 3 files changed, 52 insertions(+), 2 deletions(-) create mode 100644 src/components/if_comp.rs diff --git a/src/components/if_comp.rs b/src/components/if_comp.rs new file mode 100644 index 0000000..94d8c78 --- /dev/null +++ b/src/components/if_comp.rs @@ -0,0 +1,34 @@ +use leptos::*; +use super::Fallback; + +#[slot] +pub struct Then { + children: ChildrenFn, +} + +#[slot] +pub struct ElseIf { + cond: MaybeSignal, + children: ChildrenFn, +} + +#[component] +pub fn If( + cx: Scope, + cond: MaybeSignal, + then: Then, + #[prop(default=vec![])] else_if: Vec, + #[prop(optional)] fallback: Option, +) -> impl IntoView { + move || { + if cond.get() { + (then.children)(cx).into_view(cx) + } else if let Some(else_if) = else_if.iter().find(|i| i.cond.get()) { + (else_if.children)(cx).into_view(cx) + } else if let Some(fallback) = &fallback { + (fallback.children)(cx).into_view(cx) + } else { + ().into_view(cx) + } + } +} diff --git a/src/components/mod.rs b/src/components/mod.rs index fd5606f..4f92fcf 100644 --- a/src/components/mod.rs +++ b/src/components/mod.rs @@ -1,3 +1,11 @@ +mod if_comp; mod option_comp; -pub use option_comp::*; \ No newline at end of file +pub use if_comp::*; +use leptos::*; +pub use option_comp::*; + +#[slot] +pub struct Fallback { + children: ChildrenFn, +} diff --git a/src/components/option_comp.rs b/src/components/option_comp.rs index 4c277bc..1cb261a 100644 --- a/src/components/option_comp.rs +++ b/src/components/option_comp.rs @@ -1,13 +1,21 @@ +use super::Fallback; use leptos::*; #[component] -pub fn OptionComp(cx: Scope, value: Option, view: VF) -> impl IntoView +pub fn OptionComp( + cx: Scope, + value: Option, + view: VF, + #[prop(optional)] fallback: Option, +) -> impl IntoView where VF: Fn(Scope, T) -> IV + 'static, IV: IntoView, { if let Some(value) = value { view(cx, value).into_view(cx) + } else if let Some(fallback) = &fallback { + (fallback.children)(cx).into_view(cx) } else { ().into_view(cx) }