Code/CssBuilder.cs
using System;
using System.Text;
namespace BetterUI;
/// <summary>
/// A builder for CSS classes.
/// </summary>
public sealed class CssBuilder
{
private readonly StringBuilder _builder = new();
/// <summary>
/// Adds a CSS class to the builder.
/// </summary>
/// <param name="name">The name of the class to add.</param>
/// <returns>The builder.</returns>
public CssBuilder AddClass( string name )
{
Append( name );
return this;
}
/// <summary>
/// Adds a CSS class to the builder if the condition is true.
/// </summary>
/// <param name="name">The name of the class to add.</param>
/// <param name="condition">The condition to check.</param>
/// <returns>The builder.</returns>
public CssBuilder AddClass( string name, bool condition )
{
if ( condition )
Append( name );
return this;
}
/// <summary>
/// Adds a CSS class to the builder if the condition is true.
/// </summary>
/// <param name="name">The name of the class to add.</param>
/// <param name="condition">The condition to check.</param>
/// <returns>The builder.</returns>
public CssBuilder AddClass( string name, Func<bool> condition )
{
if ( condition.Invoke() )
Append( name );
return this;
}
/// <summary>
/// Appends a CSS class to the builder.
/// </summary>
/// <param name="name">The name of the class to append.</param>
private void Append( string name )
{
if ( _builder.Length is 0 ) _builder.Append( name );
else _builder.Append( ' ' ).Append( name );
}
/// <summary>
/// Builds the CSS classes.
/// </summary>
/// <returns>The CSS classes as a string.</returns>
public string Build() => _builder.ToString();
public override string ToString() => _builder.ToString();
}