Introduced a flexible code block that enables to show code examples in a tab menu, single blocks or inline code blocks

This commit is contained in:
nilsk 2025-05-19 10:12:42 +02:00
parent 08c1a54e51
commit d9fb0dedaf
4 changed files with 96 additions and 0 deletions

View File

@ -0,0 +1,15 @@

@if (!this.IsInline)
{
@if (this.ParentTabs is null)
{
<MudPaper Class="code-block no-elevation" Style="@this.BlockPadding()">
<pre><code>@this.ChildContent</code></pre>
</MudPaper>
}
}
else
{
<span class="inline-code-block"><kbd>@this.ChildContent</kbd></span>
}

View File

@ -0,0 +1,42 @@
using Microsoft.AspNetCore.Components;
using MudBlazor.Utilities;
namespace AIStudio.Components;
public partial class CodeBlock : ComponentBase
{
[Parameter]
public RenderFragment? ChildContent { get; set; }
[Parameter]
public string? Title { get; set; } = string.Empty;
[Parameter]
public bool IsInline { get; set; } = false;
[CascadingParameter]
public CodeTabs? ParentTabs { get; set; }
private static readonly string DARK_BACKGROUND_COLOR = "#2d2d2d";
private static readonly string DARK_FOREGROUND_COLOR = "#f8f8f2";
protected override void OnInitialized()
{
if (this.ParentTabs is not null && this.Title is not null)
{
RenderFragment blockSelf = builder =>
{
builder.OpenComponent<CodeBlock>(0);
builder.AddAttribute(1, "Title", this.Title);
builder.AddAttribute(2, "ChildContent", this.ChildContent);
builder.CloseComponent();
};
this.ParentTabs.RegisterBlock(this.Title, blockSelf);
}
}
private string BlockPadding()
{
return this.ParentTabs is null ? "padding: 16px !important;" : "padding: 8px !important";
}
}

View File

@ -0,0 +1,11 @@
<MudTabs @bind-ActivePanelIndex="selectedIndex" PanelClass="code-block">
@foreach (var block in blocks)
{
<MudTabPanel Text="@block.Title">
@block.Fragment
</MudTabPanel>
}
</MudTabs>
<CascadingValue Value="this">
@this.ChildContent
</CascadingValue>

View File

@ -0,0 +1,28 @@
using Microsoft.AspNetCore.Components;
namespace AIStudio.Components;
public partial class CodeTabs : ComponentBase
{
[Parameter]
public RenderFragment? ChildContent { get; set; }
private List<CodeTabItem> blocks = new();
private int selectedIndex = 0;
internal void RegisterBlock(string title, RenderFragment fragment)
{
this.blocks.Add(new CodeTabItem
{
Title = title,
Fragment = fragment,
});
this.StateHasChanged();
}
private class CodeTabItem
{
public string Title { get; init; } = string.Empty;
public RenderFragment Fragment { get; init; }
}
}