1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
use leptos::{
component, create_effect, Children, IntoView, SignalGet, SignalUpdate, SignalUpdateUntracked,
};
use rcss::extend::in_chain_ops::ScopeChainOps;
pub mod private;
pub type Scope = &'static str;
pub type Style = &'static str;
///
/// Entry point to register your inline styles.
/// Collects all styles and register them as seperate css @layer.
/// Each layer name is a scope id.
///
/// Notifies `RenderView` component to update styles in the DOM.
/// It will do nothing if style is empty or already registered.
///
/// Check out rcss-bundler for usage with style bundling.
///
///
/// # Example:
/// ```no_build
/// use leptos::*;
///
/// #[component]
/// fn my_component() -> impl IntoView {
/// let style = rcss::css!{
/// .my-class {
/// color: red;
/// & .nested-class {
/// color: blue;
/// }
/// };
/// rcss_leptos::register_styles(style.clone());
/// view! {
/// <div class=style.my_class>
/// "Hello "<span class=style.nested_class>"world"</span>
/// </div>
/// }
/// }
/// ```
///
///
pub fn register_styles<T>(chain: T)
where
T: ScopeChainOps + 'static,
{
let run_once = crate::private::run_once(move || {
let meta = private::LayeredCssMeta::get();
let mut was_changed = false;
meta.layered_style
.update_untracked(|l| was_changed |= l.add_style_chain(&chain));
if was_changed {
meta.layered_style.update(|_| {});
}
});
create_effect(move |_| run_once());
}
///
/// Provide a context to use rcss styles.
/// In reality it is a pseudo component that doesn't render anything.
/// But it uses meta context to register new <style> elements.
///
/// # Example:
/// ```no_build
/// use leptos::*;
/// use rcss_leptos::WithStyles;
///
///
/// #[component]
/// fn app() -> impl IntoView {
/// view!{
/// <WithStyles>
/// <RealEntrypoint/>
/// </WithStyles>
/// }
/// }
/// ```
///
#[component]
pub fn with_styles(children: Children) -> impl IntoView {
use leptos::For;
use private::CustomStyle;
let styles = crate::private::LayeredCssMeta::get()
.layered_style
.split()
.0;
leptos::view! {
<For each= move|| styles.get().styles.into_iter()
key = |v| (v.0.clone(), v.1.uniq_layers.len())
let:css
>
<CustomStyle id=css.0 style =css.1 />
</For>
{children()}
}
}