51 lines
2.1 KiB
C#
51 lines
2.1 KiB
C#
namespace Htmx.ApiDemo.Templates.Components;
|
|
|
|
/// <summary>
|
|
/// shadcn-style Table component.
|
|
/// Headers: column header strings.
|
|
/// Rows: each row is an IEnumerable of cell strings.
|
|
/// Caption and Footer are optional.
|
|
/// </summary>
|
|
public sealed class Table : TableBase
|
|
{
|
|
private readonly byte[] _captionData;
|
|
private readonly byte[] _headersData;
|
|
private readonly byte[] _rowsData;
|
|
private readonly byte[] _footerData;
|
|
|
|
public Table(
|
|
IEnumerable<string> headers,
|
|
IEnumerable<IEnumerable<string>> rows,
|
|
string caption = "",
|
|
string footer = "")
|
|
{
|
|
_captionData = string.IsNullOrEmpty(caption)
|
|
? []
|
|
: $"""<caption class="mt-4 text-sm text-muted-foreground">{caption}</caption>""".ToUtf8Bytes();
|
|
|
|
var hSb = new System.Text.StringBuilder();
|
|
foreach (var h in headers)
|
|
hSb.Append($"""<th class="h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0">{h}</th>""");
|
|
_headersData = hSb.ToString().ToUtf8Bytes();
|
|
|
|
var rSb = new System.Text.StringBuilder();
|
|
foreach (var row in rows)
|
|
{
|
|
rSb.Append("""<tr class="border-b border-border transition-colors hover:bg-muted/50">""");
|
|
foreach (var cell in row)
|
|
rSb.Append($"""<td class="p-4 align-middle [&:has([role=checkbox])]:pr-0">{cell}</td>""");
|
|
rSb.Append("</tr>");
|
|
}
|
|
_rowsData = rSb.ToString().ToUtf8Bytes();
|
|
|
|
_footerData = string.IsNullOrEmpty(footer)
|
|
? []
|
|
: $"""<tfoot><tr class="border-t border-border font-medium"><td colspan="99" class="p-4">{footer}</td></tr></tfoot>""".ToUtf8Bytes();
|
|
}
|
|
|
|
protected override void RenderCaption(HtmxRenderContext ctx) => ctx.Writer.WriteUtf8(_captionData);
|
|
protected override void RenderHeaders(HtmxRenderContext ctx) => ctx.Writer.WriteUtf8(_headersData);
|
|
protected override void RenderRows(HtmxRenderContext ctx) => ctx.Writer.WriteUtf8(_rowsData);
|
|
protected override void RenderFooter(HtmxRenderContext ctx) => ctx.Writer.WriteUtf8(_footerData);
|
|
}
|