57 lines
2.5 KiB
C#
57 lines
2.5 KiB
C#
namespace Htmx.ApiDemo.Templates.Components;
|
|
|
|
/// <summary>
|
|
/// shadcn-style Select (native HTML select) component.
|
|
/// </summary>
|
|
public sealed class Select : SelectBase
|
|
{
|
|
private readonly byte[] _idData;
|
|
private readonly byte[] _nameData;
|
|
private readonly byte[] _labelData;
|
|
private readonly byte[] _descriptionData;
|
|
private readonly byte[] _optionsData;
|
|
private readonly byte[] _extraClassesData;
|
|
private readonly byte[] _hxAttrsData;
|
|
|
|
/// <param name="options">Collection of (value, display) tuples. Mark selected with selectedValue.</param>
|
|
public Select(
|
|
string id,
|
|
IEnumerable<(string Value, string Display)> options,
|
|
string selectedValue = "",
|
|
string name = "",
|
|
string label = "",
|
|
string description = "",
|
|
string extraClasses = "",
|
|
string hxAttrs = "")
|
|
{
|
|
_idData = id.ToUtf8Bytes();
|
|
_nameData = (string.IsNullOrEmpty(name) ? id : name).ToUtf8Bytes();
|
|
_extraClassesData = extraClasses.ToUtf8Bytes();
|
|
_hxAttrsData = hxAttrs.ToUtf8Bytes();
|
|
|
|
_labelData = string.IsNullOrEmpty(label)
|
|
? []
|
|
: $"""<label for="{id}" class="text-sm font-medium leading-none">{label}</label>""".ToUtf8Bytes();
|
|
|
|
_descriptionData = string.IsNullOrEmpty(description)
|
|
? []
|
|
: $"""<p class="text-xs text-muted-foreground">{description}</p>""".ToUtf8Bytes();
|
|
|
|
var sb = new System.Text.StringBuilder();
|
|
foreach (var (value, display) in options)
|
|
{
|
|
var selected = value == selectedValue ? " selected" : "";
|
|
sb.Append($"""<option value="{value}"{selected}>{display}</option>""");
|
|
}
|
|
_optionsData = sb.ToString().ToUtf8Bytes();
|
|
}
|
|
|
|
protected override void RenderId(HtmxRenderContext ctx) => ctx.Writer.WriteUtf8(_idData);
|
|
protected override void RenderName(HtmxRenderContext ctx) => ctx.Writer.WriteUtf8(_nameData);
|
|
protected override void RenderLabel(HtmxRenderContext ctx) => ctx.Writer.WriteUtf8(_labelData);
|
|
protected override void RenderDescription(HtmxRenderContext ctx) => ctx.Writer.WriteUtf8(_descriptionData);
|
|
protected override void RenderOptions(HtmxRenderContext ctx) => ctx.Writer.WriteUtf8(_optionsData);
|
|
protected override void RenderExtraClasses(HtmxRenderContext ctx) => ctx.Writer.WriteUtf8(_extraClassesData);
|
|
protected override void RenderHxAttrs(HtmxRenderContext ctx) => ctx.Writer.WriteUtf8(_hxAttrsData);
|
|
}
|