using Htmx.ApiDemo; using Htmx.ApiDemo.Templates.Components; using Microsoft.AspNetCore.Http; namespace Htmx.ApiDemo; public sealed class MainLayout : Templates.MainLayoutBase { private byte[] _titleData = []; private byte[] _appNameData = []; private byte[] _pageTitleData = []; private byte[] _userSectionData = []; public IHtmxComponent Body { get; } public MainLayout(IHtmxComponent body, string title = "App", string appName = "MyApp", string pageTitle = "Dashboard", string? userName = null, string? afToken = null) { Body = body; _titleData = title.ToUtf8Bytes(); _appNameData = appName.ToUtf8Bytes(); _pageTitleData = pageTitle.ToUtf8Bytes(); var afInput = string.IsNullOrEmpty(afToken) ? "" : $""""""; _userSectionData = userName is not null ? $"""
{System.Web.HttpUtility.HtmlEncode(GetInitials(userName))}
{afInput}
""".ToUtf8Bytes() : """ Sign in """.ToUtf8Bytes(); } private static string GetInitials(string name) { var parts = name.Trim().Split(' ', System.StringSplitOptions.RemoveEmptyEntries); return parts.Length >= 2 ? $"{parts[0][0]}{parts[^1][0]}".ToUpperInvariant() : name.Length > 0 ? name[0].ToString().ToUpperInvariant() : "?"; } protected override void RenderBody(HtmxRenderContext context) => Body.Render(context); protected override void RenderTitle(HtmxRenderContext context) => context.Writer.WriteUtf8(_titleData); protected override void RenderAppName(HtmxRenderContext context) => context.Writer.WriteUtf8(_appNameData); protected override void RenderPageTitle(HtmxRenderContext context) => context.Writer.WriteUtf8(_pageTitleData); protected override void RenderUserSection(HtmxRenderContext context) => context.Writer.WriteUtf8(_userSectionData); }