Skip to content

Guides

Task-oriented recipes for the hub. Each one states its goal, shows complete code and explains the part that is not obvious. For the first project, start with Getting started.

On this page

Register only the libraries you use

Goal: keep the dependency list and the registrations to what the app needs.

Install the packages of the libraries you use instead of Klyroo.Stack, then call their registration methods:

Shell
dotnet add package Klyroo.Table --prerelease
dotnet add package Klyroo.Form --prerelease
C#
using Klyroo.Form;
using Klyroo.Table;

builder.Services.AddKlyrooTable();   // also registers Klyroo.UI and Klyroo.Query
builder.Services.AddKlyrooForm();    // also registers Klyroo.UI

AddKlyrooTable() calls AddKlyrooUi() and AddKlyrooQuery() itself, and AddKlyrooForm(), AddKlyrooDashboard(), AddKlyrooDisplay() and AddKlyrooSpreadsheet() call AddKlyrooUi(). Calling AddKlyrooUi more than once is safe: a later call configures the same options object. AddKlyrooQuery() and AddKlyrooAgent() do not register Klyroo.UI, because those libraries do not depend on it.

AddKlyrooStack() is exactly this list for all eight libraries. The only reason to prefer it is that you do not have to keep the list in step with the packages you reference.

Share options between the server and the WebAssembly client

Goal: give the server and the WebAssembly client the same Klyroo options, so components look the same before and after the client takes over.

Put the registration in one method of a project that both reference, and call it from both Program.cs files:

C#
using Klyroo.Stack;
using Microsoft.Extensions.DependencyInjection;

public static class KlyrooSetup
{
    // Shared by the server and the client Program.cs, so both register the same options.
    public static IServiceCollection AddAppKlyroo(this IServiceCollection services) =>
        services.AddKlyrooStack(configureUi: ui => ui.Button.Slot("base", "font-semibold"));
}
C#
// Program.cs of the server project and of the .Client project
builder.Services.AddAppKlyroo();

AddKlyrooStack takes two callbacks: configureUi receives KlyrooOptions (the themes and settings of Klyroo.UI) and configureTable receives KlyrooTableOptions (the themes and messages of Klyroo.Table). Both objects freeze once components start resolving themes and texts (Klyroo.Table messages throw InvalidOperationException when changed after that), so configure them in the registration call, never later.

Configure the options of each library

Goal: change the options of Klyroo.Dashboard or Klyroo.Display although AddKlyrooStack() has no callback for them.

AddKlyrooStack takes configureUi (KlyrooOptions) and configureTable (KlyrooTableOptions). For any other library, call its own registration method after it, with a callback:

C#
using Klyroo.Dashboard;
using Klyroo.Display;
using Klyroo.Stack;

builder.Services.AddKlyrooStack(configureUi: ui => ui.Defaults.Size = KlySize.Sm);

builder.Services.AddKlyrooDashboard(o => o.PersistMaxBytes = 4096);
builder.Services.AddKlyrooDisplay(o => o.Texts("de", t => t with { ClosePreview = "Schließen" }));

This works because every one of these methods looks for the options object that an earlier call registered and changes it, instead of registering a second one. AddKlyrooDashboard keeps a single KlyrooDashboardOptions singleton, and AddKlyrooDisplay and AddKlyrooTable call AddKlyrooUi, which holds their options as extensions of the KlyrooOptions it keeps (options.Extension<KlyrooDisplayOptions>()). Whatever the order, one instance results, which this repository's tests check (a call before AddKlyrooStack, after it, and the Klyroo.UI and Klyroo.Table callbacks together with a later call of the same methods).

AddKlyrooForm(), AddKlyrooSpreadsheet(), AddKlyrooQuery() and AddKlyrooAgent() have no options to configure. Two rules from the libraries apply: options freeze once components start resolving them (a theme or a message table throws InvalidOperationException when changed later), so configure during registration, and in an app with a WebAssembly client make the same calls in the server and in the client project, through the shared method described in Share options between the server and the WebAssembly client.

Find which library owns a component

Goal: route a component or controller name to its library, packages and template, for a tool, a generator or a help command.

KlyrooStackCatalog lives in Klyroo.Stack.Core, so it works in a console app:

C#
using Klyroo.Stack;

foreach (var module in KlyrooStackCatalog.Modules)
{
    Console.WriteLine($"{module.Id,-20} {module.UiPackage,-22} {module.CorePackage ?? "-"}");
}

var owner = KlyrooStackCatalog.ResolveComponentModule("KlyDataListTable<Order>");
Console.WriteLine(owner?.Id);                       // klyroo-table
Console.WriteLine(KlyrooStackCatalog.GetModule("Klyroo.Form.Core")?.Name);   // Klyroo.Form

ResolveComponentModule ignores generic arguments and case, and returns null for a name that no module lists. It only knows the names in each module's KeyComponents, which is a short list of the main types, not every component. GetModule accepts a repository id (klyroo-table), a library name (Klyroo.Table) or either package name. The resolve-module tool of the MCP server gives the same answer to an agent, with the install commands and the documentation paths.

Test an app that uses the stack

Goal: verify a registration, a component and a catalog lookup with xUnit and bUnit.

Create a test project with the Razor SDK so bUnit can render components. These are the package versions this repository's own tests use:

XML
<Project Sdk="Microsoft.NET.Sdk.Razor">
  <PropertyGroup>
    <TargetFramework>net11.0</TargetFramework>
    <OutputType>Exe</OutputType>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <IsPackable>false</IsPackable>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="xunit.v3" Version="4.0.3" />
    <PackageReference Include="bunit" Version="2.15.2" />
    <PackageReference Include="Klyroo.Stack" Version="0.1.0-preview.1" />
  </ItemGroup>
</Project>
C#
using Bunit;
using Klyroo.Agent;
using Klyroo.Dashboard;
using Klyroo.Form;
using Klyroo.Query;
using Klyroo.Stack;
using Microsoft.Extensions.DependencyInjection;
using Xunit;

namespace Shop.Tests;

public sealed class StackTests : BunitContext
{
    [Fact]
    public void Catalog_resolves_a_component_to_the_library_that_owns_it()
    {
        var module = KlyrooStackCatalog.ResolveComponentModule("KlyDataList<Product>");

        Assert.Equal("klyroo-table", module?.Id);
        Assert.Equal("Klyroo.Table.Core", module?.CorePackage);
        Assert.Null(KlyrooStackCatalog.ResolveComponentModule("NotAComponent"));
    }

    [Fact]
    public void AddKlyrooStack_registers_the_scoped_services_of_every_library()
    {
        Services.AddKlyrooStack();

        Assert.NotNull(Services.GetRequiredService<QueryState>());
        Assert.NotNull(Services.GetRequiredService<FormService>());
        Assert.NotNull(Services.GetRequiredService<AgentBridgeService>());
    }

    [Fact]
    public void Stat_shows_the_change_against_its_comparison_value()
    {
        Services.AddKlyrooStack();
        JSInterop.Mode = JSRuntimeMode.Loose;

        var cut = Render<KlyDashboardStat>(p => p
            .Add(x => x.Label, "Total MRR")
            .Add(x => x.Value, 240_000)
            .Add(x => x.Compare, 200_000));

        Assert.Contains("+20%", cut.Markup);
    }
}

Run it with dotnet run (xUnit v3 test projects are executables) or dotnet test. JSInterop.Mode = JSRuntimeMode.Loose lets components call into JavaScript during a test without you stubbing each call: Klyroo components hand focus, overlays and positioning to the browser, and bUnit has no browser. A test that asserts on that browser behavior needs an end-to-end test, not bUnit.

Let an agent fill a form

Goal: expose a Klyroo.Form controller to an AI agent and let it set values by field label.

AddKlyrooAgent() (part of AddKlyrooStack()) registers AgentBridgeService as a scoped service. Register a controller on it, then act on the form by label:

C#
using Klyroo.Agent;
using Klyroo.Form;
using Klyroo.Stack;
using Microsoft.Extensions.DependencyInjection;

var services = new ServiceCollection().AddKlyrooStack().BuildServiceProvider();
var agent = services.GetRequiredService<AgentBridgeService>();

var schema = FormSchema.For<QuickSetup>(s =>
{
    s.Title = "Quick setup";
    s.Field(m => m.Org, f => f.Label("Organization"));
});
var org = schema.Field(m => m.Org);
var form = new FormController<QuickSetup>(schema);
agent.RegisterForm(form);

var result = await agent.ActAsync([new AgentActStep("Organization", "setValue", ["Acme"])]);
Console.WriteLine(result.Ok);                       // True
Console.WriteLine(form.Get(org));                   // Acme

sealed class QuickSetup
{
    public string Org { get; set; } = "";
}

The step targets the field by its label (Organization); its key (Org, the name of the member) works too. RegisterForm takes an IFormRuntime, so a FormController<TModel> and a DynamicFormController register the same way. The model cannot write a password or one-time code field, nor a field that belongs to another step of a wizard: name a sensitive field in allowSensitiveWrites when you want the model to fill it, and move through the steps with the nextStep action. The same pattern works for dashboards (RegisterDashboard) and spreadsheet importers (RegisterSpreadsheet). The agent library has its own repository and guides: see klyroo-agent.

Connect a coding agent to the Klyroo.UI documentation

Goal: let Claude Code, Cursor or another MCP client look up components and parameters instead of inventing them.

Install the tool and register it with your client:

Shell
dotnet tool install --global Klyroo.Stack.Mcp --prerelease
claude mcp add --transport stdio klyroo -- klyroo-stack-mcp

For a client that reads an mcpServers JSON file, use { "mcpServers": { "klyroo": { "command": "klyroo-stack-mcp" } } }. Once connected, the agent finds components with search-components, reads their parameters with get-component-metadata and copies working markup with get-example. The server instructions tell it to use the metadata before writing markup.

Two options are worth knowing. --tools search-components,get-component limits the tools a client sees, which keeps the tool list short for clients that load every description. --site-url https://docs.example.com prefixes page paths in the answers with your own address once the documentation site is deployed. The server answers from the documentation bundled when the tool was built, so update the tool to get newer documentation.

The server has component pages for Klyroo.UI and Klyroo.Table, and the documentation pages of every other library at /<library>/docs/<page>, for example /spreadsheet/docs/guides. The pages of this hub, the templates and the getting started among them, are at /stack/docs/<page>. search-documentation searches all of them.

resolve-module is the tool to call when the agent does not know which library owns a name. It takes a component or controller (KlyDataList, DashboardController, FormService), a library or package (Klyroo.Spreadsheet), a repository (klyroo-form) or a template (klyroo-admin), and answers from KlyrooStackCatalog: the library, its Blazor and headless packages with the install commands, the template that shows it, its agent skill and the pages to read. A name that is only a Klyroo.UI component page (KlyHeader) resolves through the package that ships it.

Start a project from a template

Goal: get a runnable app with the meta-package, the stylesheets, a shell and a few pages that use the libraries the way they are meant to be used.

Shell
dotnet new install Klyroo.Templates::0.1.0-preview.1
dotnet new klyroo-saas -n MyShop
cd MyShop
dotnet run

dotnet new list klyroo shows the four templates. The two web templates are complete starters with sample data in memory, so they run with no database, and both share the same plumbing: the stock .NET 11 Blazor Web App parts (MapStaticAssets, the exception handler, HSTS, HTTPS redirection, a not-found page, launchSettings.json, appsettings.json and a .gitignore), KlyApp with KlyFormProvider and KlyFilePreviewProvider in the layout, a color mode button, and Klyroo.UI.Server for the cookies of the request.

Template Shell Pages
klyroo-saas KlyHeader with the navigation, the product name and a color mode button Overview: a DashboardController with a plan filter and four resources, DashboardPersistence and JSON type infos. Accounts: a KlyDataList with a Provider, filters with counts, search, paging, euro prices, a bulk delete and an edit row action, and a "New account" button that opens a FormService drawer. Usage: the typed blocks of Klyroo.UI (KlyStatGroup, KlyMeter, KlyFacts, KlyBreakdown, KlyTimeline), a KlySecretBlock and a file preview
klyroo-admin KlyDashboardGroup with a resizable sidebar and a navbar on every page Dashboard: stats, a gauge, a line chart, bars, a table and a feed. Customers: a KlyDataList over in-memory rows with selection, a sum row, bulk export to the file preview, an edit drawer and a link to each customer. Customer: KlyUser, KlyFacts, KlyMeter, KlyTimeline and KlyAlert blocks. Import: KlySpreadsheetImport with a schema (a required field, a select with aliases, a number with a rule), a sample file, and the rows added to the list

klyroo-headless creates a console app that references only Klyroo.Stack.Core, and klyroo-maui a .NET MAUI Blazor Hybrid app whose layout wraps the body in KlyApp with the two providers.

Options. --interactivity Server|WebAssembly|Auto (default Server) picks how the pages run. With Server there is one project. With WebAssembly or Auto the template creates MyShop (the server: Program.cs, App.razor, wwwroot) and MyShop.Client (the layout, the pages, the sample data and Routes.razor, because a page that runs in the browser has to live in the client assembly), plus MyShop.slnx; the server project references the client project and both call AddKlyrooStack() and AddAppServices(). --product-name "Acme Cloud" sets the name the pages show; without it the project name is written as words (MyShop becomes "My Shop"). The render mode of the app is one line, AppRender.Mode, and it is the value that DashboardPersistence.Attach receives, which is what hands the data of the prerender to the interactive render in every mode.

The target framework. --Framework net10.0|net11.0 (default net10.0) sets TargetFramework in every project and the version of the Microsoft packages the template references (Microsoft.AspNetCore.Components.WebAssembly(.Server), Microsoft.Extensions.Logging.Debug). Two things differ on net11.0: the layout of the web templates renders <BasePath />, a .NET 11 component, where net10.0 writes <base href="/" />, and the headless template turns on the runtime-async compiler feature, which only .NET 11 supports. Klyroo.Stack and Klyroo.Stack.Core ship both net10.0 and net11.0 assemblies, so either choice restores the same package version.

The version. The generated .csproj references Klyroo.Stack at the version of the Klyroo.Templates package you installed. Each template.json holds a constant symbol, KlyrooVersion, with a placeholder value; a pre-pack target in Klyroo.Templates.csproj writes a copy of every template.json with $(Version) and packs the copy. A release changes the version in build/Version.props and nowhere else, and a test fails when a template file carries a version of its own.

Where the sample data lives. The store of each app is a scoped service, so with Interactive Server the data starts again with every circuit (a full page reload) and with WebAssembly with every browser tab. Navigating with the links of the app keeps it. Replace the bodies of the store with your data access: the pages only call its methods, and each read takes the cancellation token that Klyroo cancels when a newer request replaces it.

Style a generated app

Goal: know which classes work in the markup of a generated app, and how to switch to Tailwind.

The web templates use the zero-setup path that Getting started describes: klyroo.preflight.css and klyroo.css from Klyroo.UI, then klyroo-stack.css from Klyroo.Stack, then the app.css of the app. The first three are precompiled, so the app needs neither Node nor a Tailwind build, and the first build needs no network. The consequence is that the sheets only hold the classes the Klyroo components use. A utility such as md:grid-cols-2 or space-y-6 that you write in your own markup is not in them and does nothing, because no Tailwind run reads your pages. The templates therefore keep their layout in wwwroot/app.css, in plain CSS on the Klyroo tokens (var(--klyroo-text-muted) and the others), which follows the theme and the color mode.

A test of this repository checks the markup of the klyroo-saas, klyroo-admin and klyroo-maui templates: every class in a class or Class attribute has to be defined by one of the sheets or by the app.css of the template.

To write Tailwind utilities in your markup instead, compile Tailwind in the app with KlyrooTailwind, as the Klyroo.UI guide Compile Tailwind in your app explains, and load its output in place of the three Klyroo sheets. Klyroo.Table then needs the extra import that the Klyroo.Table guide describes, and so do the other libraries whose classes the Klyroo.UI theme does not list. Do not load klyroo.css or klyroo-stack.css next to a Tailwind build: two sheets that declare the same utilities in one cascade layer override each other.

Open a form or a file preview in the MAUI template

Goal: use FormService and FilePreviewService in the klyroo-maui app, which has no App.razor and no server.

Shell
dotnet new klyroo-maui -n Notes
cd Notes
dotnet build -f net10.0-android

The template targets net10.0-android by default; pass --Framework net11.0 to generate net11.0-android and build it with the .NET 11 SDK and its maui-android workload.

The .NET MAUI workload for your platform has to be installed (dotnet workload install maui-android, or maui). A BlazorWebView has no server that renders <head>, so the template splits the root of the app between two files. MainPage.xaml hosts Routes in #app and a HeadOutlet in head::after, and Components/Layout/MainLayout.razor puts <KlyHead /> (the theme variables and the fonts, sent to the head through that outlet), then KlyApp around the body with KlyFormProvider and KlyFilePreviewProvider inside it:

Razor
<KlyHead />

<KlyApp>
    <main class="app-main">
        @Body
    </main>

    <KlyFormProvider />
    <KlyFilePreviewProvider />
</KlyApp>

The providers have to sit in the layout, inside KlyApp, because the services open their overlays there: FormService.CreateFormAsync finds no host and never completes when the provider is missing. With them in place a page only injects the service. The home page of the template opens a form in a drawer and shows a toast with what was typed:

Razor
@inject FormService Forms
@inject IToastService Toasts

<KlyButton Label="Add a note" OnClick="AddNoteAsync" />

@code {
    private async Task AddNoteAsync()
    {
        var outcome = await Forms.CreateFormAsync(NoteSchema, mode: FormShellMode.Drawer);

        if (outcome is { IsCompleted: true, Model: { } note })
        {
            await Toasts.Add(new KlyToast { Title = "Note saved", Description = note.Text });
        }
    }

    private sealed class Note
    {
        public string Text { get; set; } = "";
    }

    private static readonly FormSchema<Note> NoteSchema = FormSchema.For<Note>(s =>
    {
        s.FormKey = "note";
        s.Title = "New note";
        s.Field(n => n.Text, f => f.Label("Note").AsTextarea().Required());
    });
}

A preview works the same way: inject FilePreviewService and call Open with a FilePreviewFile. The layout classes of the page are in wwwroot/app.css, which index.html loads after the three precompiled Klyroo sheets: those sheets hold only the classes of the Klyroo components, so min-h-dvh or max-w-3xl in your own markup would do nothing (the template had both before). _Imports.razor lists the namespaces of all eight libraries, so a page can use any of them without adding a @using.

A project generated from the template was built for net10.0-android (.NET 10 SDK) and for net11.0-android (.NET 11 SDK) with the maui-android workload, without warnings. It was not run on a device or an emulator, and the iOS, Mac Catalyst and Windows targets were not built.

Publish the headless template with NativeAOT

Goal: produce a native binary that uses the headless engines.

Shell
dotnet new klyroo-headless -n Worker
cd Worker
dotnet publish -c Release -r linux-x64
./bin/Release/net10.0/linux-x64/publish/Worker

The template sets PublishAot and references Klyroo.Stack.Core, whose engines are marked IsAotCompatible. The program prints a line that shows each engine working: a query, a spreadsheet import, a CSV preview, a form controller, a KPI format and an undo stack. Use the runtime identifier of your machine instead of linux-x64. NativeAOT needs the platform's native toolchain (a C compiler and linker on Linux); that requirement comes from the .NET SDK, not from Klyroo.

Verify the templates against local packages

Goal: prove that the templates work for someone who has only the packages, before a release or after changing a template.

The projects of the templates reference Klyroo.Stack by version, not by path, so they can only be checked against packed packages. Two scripts do it, and the templates-from-local-feed job of .github/workflows/ci.yml runs the same two commands:

Shell
build/pack-feed.sh /tmp/klyroo-feed
build/verify-templates.sh /tmp/klyroo-feed /tmp/klyroo-apps

pack-feed.sh runs dotnet pack in the nine repositories in dependency order (Klyroo.UI first, this repository and its templates last) into one folder. verify-templates.sh writes a nuget.config next to the apps that maps Klyroo.* to that folder and everything else to nuget.org, so a Klyroo package can only come from the feed. It then installs Klyroo.Templates from the feed, generates klyroo-saas in the three interactivity modes, klyroo-admin in two of them and klyroo-headless, builds each with warnings as errors, starts the web apps and requests their pages (each answer has to contain an h1 and the Klyroo stylesheet, and the log of the app must hold no fail), and publishes the headless app with NativeAOT and runs the binary.

Set DOTNET_CLI_HOME and NUGET_PACKAGES to empty folders first to keep your own caches out of it: a package cached from an earlier build with the same version would hide a problem of the new one. NativeAOT needs a C toolchain (clang and zlib1g-dev on Ubuntu); on a machine that has only gcc, set AOT_ARGS="-p:CppCompilerAndLinker=gcc".

Run the MCP server and the documentation site from source

Goal: work on the hub itself.

The projects reference the sibling repositories by relative path, so clone klyroo-ui, klyroo-query, klyroo-table, klyroo-form, klyroo-dashboard, klyroo-display, klyroo-spreadsheet and klyroo-agent next to this repository first. Then:

Shell
dotnet build Klyroo.Stack.slnx -c Release
dotnet test Klyroo.Stack.slnx -c Release --no-build
dotnet run --project src/Klyroo.Stack.Mcp -- --list-tools
dotnet run --project site/Klyroo.Stack.Site

Building src/Klyroo.Stack.Mcp.Core runs build/Klyroo.Stack.DocsBundle, which reads the sources of the site and of Klyroo.UI and embeds the result as docs-bundle.json. The test projects in the solution cover the MCP server, the generated llms.txt and the demo supervisor of the site. The site starts the live template demos as child processes; set Klyroo__Templates__Enabled=false to run it without them.