A UI RichText panel component that parses and renders [color:...]...[/color] tokens. It extracts the color and inner text, parses the color into a Color, and renders a label styled with the parsed RGBA value.
@namespace Sandbox
@inherits Panel
@using Sandbox.UI
@using System
@implements IRichTextPanel
@attribute [RichTextPanel( @"\[color:([^\]]+)\](.*?)\[/color\]", UseCaptureGroup = false )]
<root class="richtext-color-token">
<label style="color: @ParsedColor.Rgba;">@DisplayText</label>
</root>
@code
{
public float? ImageSize { get; set; }
string DisplayText = "";
Color ParsedColor = Color.White;
public void ParseRichText( string text )
{
const string prefix = "[color:";
const string suffix = "[/color]";
DisplayText = text;
ParsedColor = Color.White;
if ( string.IsNullOrWhiteSpace( text ) || !text.StartsWith( prefix ) || !text.EndsWith( suffix ) )
return;
var colorEndIndex = text.IndexOf( ']' );
if ( colorEndIndex <= prefix.Length )
return;
var colorText = text[prefix.Length..colorEndIndex];
DisplayText = text[(colorEndIndex + 1)..^suffix.Length];
try
{
ParsedColor = Color.Parse( colorText ) ?? Color.White;
}
catch
{
ParsedColor = Color.White;
}
}
protected override int BuildHash()
{
return HashCode.Combine( DisplayText, ParsedColor );
}
}