Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Css Builder Extensions
<li aria-selected=@IsActive role="tab" class="@ClassToRender">
...
</li>
@functions {
...
protected bool IsActive => ContainerTabSet.ActiveTab == this;
[Parameter] protected bool Disabled { get; set; }
[Parameter] protected string Class { get; set; }
protected string ClassToRender { get; set; }
protected override void OnParametersSet()
{
ClassToRender = new CssBuilder(Class) // User supplied CSS
.AddClass("tab-item") // base CSS
.AddClass("tab-state-active tab-tab-on-top", IsActive)
.AddClass("tab-state-default", !IsActive)
.AddClass("tab-state-disabled", Disabled)
.Build();
}
}
public class CssBuilder
{
private readonly StringBuilder sb;
public CssBuilder() => sb = new StringBuilder();
public CssBuilder(string value) => sb = new StringBuilder(value);
public CssBuilder AddValue(string value)
{
sb.Append(value);
return this;
}
public CssBuilder AddClass(string value) => AddValue(" ").AddValue(value);
public CssBuilder AddClass(string value, bool when = true) => condition ? this.AddClass(value) : this;
public CssBuilder AddClass(string value, Func<bool> when = null) => this.AddClass(value, when());
public string Build() => ToString();
public override string ToString() => sb.ToString();
}
static class CssExtensions
{
public static StringBuilder AppendCss(this StringBuilder sb, string value) => sb.Append(" ").Append(value);
public static StringBuilder AppendCssWhen(this StringBuilder sb, string value, bool condition) => condition ? sb.AppendCss(value) : sb;
public static StringBuilder AppendCssWhen(this StringBuilder sb, string value, Func<bool> condition) => condition() ? sb.AppendCss(value) : sb;
public static string ToCssString(this StringBuilder sb) => sb.ToString().Trim();
}
<li aria-selected=@IsActive role="tab" class="@ClassToRender">
...
</li>
@functions {
...
protected bool IsActive => ContainerTabSet.ActiveTab == this;
[Parameter] protected bool Disabled { get; set; }
[Parameter] protected string Class { get; set; }
protected string ClassToRender { get; set; }
protected override void OnParametersSet()
{
ClassToRender = new StringBuilder(Class) // User supplied CSS
.AppendCss("tab-item") // Base CSS
.AppendCssWhen("tab-state--active tab-on-top", IsActive)
.AppendCssWhen("tab-state--default", !IsActive)
.AppendCssWhen("tab-state--disabled", Disabled)
.ToCssString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.