55 lines
2.2 KiB
C#
55 lines
2.2 KiB
C#
namespace Htmx.ApiDemo.Templates.Components;
|
|
|
|
/// <summary>
|
|
/// shadcn-style Tabs component. Tabs are activated client-side via components.js.
|
|
/// Pass a list of (Id, Label, Content) tuples.
|
|
/// </summary>
|
|
public sealed class Tabs : TabsBase
|
|
{
|
|
private readonly byte[] _idData;
|
|
private readonly byte[] _tabsListData;
|
|
private readonly byte[] _tabsPanelsData;
|
|
|
|
private const string TriggerBase =
|
|
"tabs-trigger inline-flex items-center justify-center whitespace-nowrap rounded-sm " +
|
|
"px-3 py-1.5 text-sm font-medium ring-offset-background transition-all " +
|
|
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring " +
|
|
"focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50";
|
|
|
|
private const string PanelBase =
|
|
"tabs-panel mt-2 ring-offset-background " +
|
|
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2";
|
|
|
|
public Tabs(string id, IEnumerable<(string Id, string Label, string Content)> tabs)
|
|
{
|
|
_idData = id.ToUtf8Bytes();
|
|
|
|
var tabList = tabs.ToList();
|
|
var triggerSb = new System.Text.StringBuilder();
|
|
var panelSb = new System.Text.StringBuilder();
|
|
|
|
foreach (var (tabId, label, content) in tabList)
|
|
{
|
|
triggerSb.Append($"""
|
|
<button type="button" role="tab" aria-selected="false" aria-controls="tabpanel-{tabId}"
|
|
class="{TriggerBase}">
|
|
{label}
|
|
</button>
|
|
""");
|
|
|
|
panelSb.Append($"""
|
|
<div id="tabpanel-{tabId}" role="tabpanel" class="{PanelBase}">
|
|
{content}
|
|
</div>
|
|
""");
|
|
}
|
|
|
|
_tabsListData = triggerSb.ToString().ToUtf8Bytes();
|
|
_tabsPanelsData = panelSb.ToString().ToUtf8Bytes();
|
|
}
|
|
|
|
protected override void RenderId(HtmxRenderContext ctx) => ctx.Writer.WriteUtf8(_idData);
|
|
protected override void RenderTabsList(HtmxRenderContext ctx) => ctx.Writer.WriteUtf8(_tabsListData);
|
|
protected override void RenderTabsPanels(HtmxRenderContext ctx) => ctx.Writer.WriteUtf8(_tabsPanelsData);
|
|
}
|