fable-compiler / Fable.Lit

Write Fable Elmish apps with Lit
https://fable.io/Fable.Lit/
MIT License
91 stars 13 forks source link

Add styles in the Lit functions #34

Closed AngelMunoz closed 2 years ago

AngelMunoz commented 2 years ago

While writing an example for one of the discussions I noticed that we don't expose styleMap in any way in the Lit type as we do with classes it can be useful in cases we want to override css variables (or other styles) inline

The example in question would be

[<LitElement("horiz-stack")>]
let HorizStack() = 
    let _, props =
        LitElement.init(fun init ->
            init.useShadowDom <- true
            init.props <- 
                {| 
                    columns = Prop.Of(defaultValue = 2, attribute = "columns")
                    gap = Prop.Of(defaultValue = "0px", attribute = "gap")
                |}
            // This is the place where you can put any shared styles
            // These styles are applied via Shadow DOM and are "Scoped" to this element
            // the benefit is that you styles get declared once per component definition
            // and not per component instance (like in the example you could figure out)
            init.styles <- [
                css
                    $"""
                    .grid {{
                        display: grid;
                        grid-template-columns: repeat(var(--column-count, 1), 1fr);
                        grid-gap: var(--column-gap, 8px);
                    }}

                    ::slotted(div) {{
                        box-sizing: border-box;
                    }}
                    """
            ]
        )
    // here we leverage CSS Custom Properties
    // to update them via our properties for this element
    // but they could also be modified by the user's stylesheet 
    // to have a different set of defaults (4 columns rather than 1, 1em gap rather than in px)
    let styles =
        {| ``--column-count`` = props.columns.Value
           ``--column-gap`` = props.gap.Value |}

    html $"""
        <!-- we apply our css variable overides -->
        <div class="grid" style="{Lit.styles styles}">
            <slot></slot>
        </div>
    """

Let me know if those overloads are okay or if we should approach it differently