Files
Htmx/Htmx.ApiDemo/Templates/Components/Breadcrumb.htmx.cs
T
2026-05-04 18:58:48 +05:00

43 lines
1.6 KiB
C#

namespace Htmx.ApiDemo.Templates.Components;
/// <summary>
/// shadcn-style Breadcrumb navigation.
/// Pass items as (Label, Href) tuples — empty Href renders a non-linked span.
/// The last item is always rendered as the current page (non-linked, foreground colour).
/// </summary>
public sealed class Breadcrumb : BreadcrumbBase
{
private const string ChevronSvg =
"""<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="h-3.5 w-3.5"><path d="m9 18 6-6-6-6"/></svg>""";
private readonly byte[] _itemsData;
public Breadcrumb(IEnumerable<(string Label, string Href)> items)
{
var list = items.ToList();
var sb = new System.Text.StringBuilder();
for (int i = 0; i < list.Count; i++)
{
var (label, href) = list[i];
bool isLast = i == list.Count - 1;
sb.Append("""<li class="inline-flex items-center gap-1.5">""");
if (isLast || string.IsNullOrEmpty(href))
sb.Append($"""<span class="{(isLast ? "font-normal text-foreground" : "")}">{label}</span>""");
else
sb.Append($"""<a href="{href}" class="hover:text-foreground transition-colors">{label}</a>""");
if (!isLast)
sb.Append($"""<span role="presentation" aria-hidden="true">{ChevronSvg}</span>""");
sb.Append("</li>");
}
_itemsData = sb.ToString().ToUtf8Bytes();
}
protected override void RenderItems(HtmxRenderContext ctx) => ctx.Writer.WriteUtf8(_itemsData);
}