Code/StyleBuilder.cs
using System;
using System.Text;
using TypeLibrary = Sandbox.Internal.TypeLibrary;
namespace BetterUI;
/// <summary>
/// A builder for styles.
/// </summary>
public sealed class StyleBuilder
{
private readonly StringBuilder _builder = new();
/// <summary>
/// Adds a style to the builder.
/// </summary>
/// <param name="name">The name of the style.</param>
/// <param name="value">The value of the style.</param>
/// <returns>The builder.</returns>
public StyleBuilder AddStyle( string name, object value )
{
Append( name, value );
return this;
}
/// <summary>
/// Adds a style to the builder if the condition is true.
/// </summary>
/// <param name="name">The name of the style.</param>
/// <param name="value">The value of the style.</param>
/// <param name="condition">The condition to check.</param>
/// <returns>The builder.</returns>
public StyleBuilder AddStyle( string name, object value, bool condition )
{
if ( condition )
Append( name, value );
return this;
}
/// <summary>
/// Adds a style to the builder if the condition is true.
/// </summary>
/// <param name="name">The name of the style.</param>
/// <param name="value">The value of the style.</param>
/// <param name="condition">The condition to check.</param>
/// <returns>The builder.</returns>
public StyleBuilder AddStyle( string name, object value, Func<bool> condition )
{
if ( condition.Invoke() )
Append( name, value );
return this;
}
/// <summary>
/// Appends a style to the builder.
/// </summary>
/// <param name="name">The name of the style.</param>
/// <param name="value">The value of the style.</param>
/// <remarks>
/// If the builder is not empty, a space is prepended to the new style.
/// </remarks>
private void Append( string name, object value )
{
if ( _builder.Length is not 0 )
_builder.Append( ' ' );
_builder.Append( new CssPropertyBuilder().WithName( name ).WithValue( value ).Build() );
}
/// <summary>
/// Builds the styles.
/// </summary>
/// <returns>The built styles.</returns>
public string Build() => _builder.ToString();
/// <inheritdoc />
public override string ToString() => _builder.ToString();
}