Skip to content
How-to guides Guides

Guides

Each section solves one task. The code is complete for the task it shows. For the reasoning behind it, read Concepts.

On this page

Change the palette and the design tokens

Goal: make the primary color blue, use a gray that suits it, and add a color of your own.

Map the semantic colors to Tailwind palettes in AddKlyrooUi. Klyroo.UI computes the fill, the text color and the color used on top of the fill for light and dark mode, and it keeps the contrast ratios (4.5:1 for text, 3:1 for fills). Put KlyThemeStyle in <head> so the page receives the result.

C#
using Klyroo.UI;

builder.Services.AddKlyrooUi(o =>
{
    o.Colors.Primary = KlyPalette.Blue;
    o.Colors.Neutral = KlyPalette.Zinc;
    o.Colors.Add("tertiary", KlyPalette.Indigo);
    o.Defaults.Color = KlyColor.Secondary;
    o.Defaults.Size = KlySize.Sm;
});
Razor
<KlyButton Label="Publish" Color="@("tertiary")" />

Neutral also drives the text, background and border tokens. o.Defaults applies to the components whose Color or Size is not set; an explicit parameter always wins. A palette that cannot meet the contrast rules throws an InvalidOperationException that names the color and the rule, unless you set o.Colors.AllowLowContrast. For a palette of your own, use KlyPalette.Custom("brand", shades) with all eleven shades from 50 to 950.

Everything is also a CSS variable, so you can rebrand without C#, with or without Tailwind. Override the variables in both :root and .dark:

CSS
:root {
  --klyroo-radius: 0.5rem;
  --klyroo-primary: var(--color-teal-700);
  --klyroo-primary-text: var(--color-teal-800);
}
.dark {
  --klyroo-primary: var(--color-teal-400);
  --klyroo-primary-text: var(--color-teal-300);
}

The variables are the colors (--klyroo-primary, -secondary, -success, -info, -warning, -error, -neutral, each with a -text and a -contrast variant), the text tokens (--klyroo-text, -text-toned, -text-muted, -text-dimmed, -text-highlighted, -text-inverted), the surfaces (--klyroo-bg, -bg-muted, -bg-elevated, -bg-accented, -bg-overlay, -bg-inverted), the borders (--klyroo-border, -border-muted, -border-accented, -border-inverted), --klyroo-radius, --klyroo-container, --klyroo-header-height, --klyroo-control and the two font stacks. Your unlayered :root rule beats the library's dark values, which is why a color overridden only in :root keeps its light value in dark mode.

A color you define by hand needs three variables on its data-color selector:

CSS
[data-color='brand'] {
  --kly-color: #0f766e;
  --kly-color-text: #115e59;
  --kly-color-contrast: #fff;
}

Restyle components

Goal: change how a component looks everywhere, in one subtree, or in one place.

There are four levels, from the broadest to the narrowest. Each is merged after the previous one with tailwind-merge, so a conflicting class from a narrower level wins.

C#
using Klyroo.UI;

builder.Services.AddKlyrooUi(o =>
{
    o.Button.Slot("base", "rounded-full");
    o.Card.Slot("root", "shadow-sm");
    o.Button.Variant("size", "md", "base", "min-w-24");
});
Razor
<KlyTheme For="typeof(KlyButton)" Ui="@(new ButtonUi { Base = "uppercase tracking-wide" })">
    <KlyButton Label="Save" />
    <KlyButton Label="Cancel" Variant="ButtonVariant.Ghost" />
</KlyTheme>

<KlyButton Label="Save" Class="px-6" Ui="@(new ButtonUi { Label = "font-bold" })" />

AddKlyrooUi configures the theme of every instance. KlyTheme applies overrides to every component of a type below it. Ui targets one slot of one instance, with one property per slot (ButtonUi.Base, CardUi.Header, and so on). Class adds classes to the root slot of one instance.

Two limits are worth knowing. A theme becomes read-only the first time a component renders with it, because the resolved classes are cached: change it in AddKlyrooUi, which runs before the first render, and expect an InvalidOperationException otherwise. And KlyTheme is a cascading value, so it does not cross a render mode boundary: put one inside each interactive island, or use AddKlyrooUi for what must apply everywhere.

Utilities you write in Class and Ui need Tailwind compiled by your app, or a class that already exists in klyroo.css, because the precompiled stylesheet only contains the classes the library itself uses.

Compile Tailwind in your app

Goal: use Tailwind utilities in your markup, together with the components, without installing Node.

Set one property in the project that owns the stylesheet. The build downloads the official Tailwind standalone CLI once, checks it against a SHA-256 that ships in the package, and compiles your stylesheet on every build.

XML
<PropertyGroup>
  <KlyrooTailwind>true</KlyrooTailwind>
</PropertyGroup>

Create Styles/app.css. Every build copies the Klyroo theme to obj/klyroo/klyroo.theme.css; importing it after Tailwind gives you the tokens, the dark variant, the utilities that follow them and the list of classes the components use:

CSS
@import "tailwindcss";
@import "../obj/klyroo/klyroo.theme.css";

Link the result instead of klyroo.css and klyroo.preflight.css:

Razor
<link rel="stylesheet" href="@Assets["app.css"]" />

The compiled file is generated under obj and added to the static web assets, so it is served at app.css in a web project and at _content/<Project>/app.css in a Razor class library. The properties are:

Property Default Meaning
KlyrooTailwind false Turns the feature on.
KlyrooTailwindInput Styles/app.css The stylesheet, relative to the project.
KlyrooTailwindAssetPath app.css Where it is served, below the base path of the project.
KlyrooTailwindMinify true in Release Minifies the output.
KlyrooTailwindExecutable none A Tailwind binary to use instead of the download.
KlyrooTailwindVersion 4.3.5 The release to download. Only the default has an embedded checksum, so use KlyrooTailwindExecutable for another one.
KlyrooTailwindCacheDir ~/.klyroo/tailwind (Linux, macOS), %LOCALAPPDATA%\Klyroo\tailwind (Windows) Where the binaries are kept, shared by every project of the user.
KlyrooTailwindAdditionalInput none Files outside the project that the stylesheet reads, so editing them rebuilds the CSS.
KlyrooOffline false Never touches the network.

The CLI finds your .razor, .cs and .html files from the project folder. For a shared project, add an @source line to the stylesheet and list the same files as additional inputs:

XML
<ItemGroup>
  <KlyrooTailwindAdditionalInput Include="../Shared/**/*.razor;../Shared/**/*.cs" />
</ItemGroup>
CSS
@source "../../Shared";

If the Blazor template left a wwwroot/app.css, delete it or change KlyrooTailwindAssetPath: two assets at one route is an error (KLYTW004). When the binary cannot be downloaded the build fails with KLYTW001; fill the cache with one online build and set KlyrooOffline, or point KlyrooTailwindExecutable at a binary you installed.

Under dotnet watch, run dotnet build -t:KlyrooTailwindWatch in a second terminal. It runs the CLI with its own file watcher on the same output. You still reload the page by hand.

If you already run Tailwind yourself, skip KlyrooTailwind, import obj/klyroo/klyroo.theme.css after Tailwind in your own pipeline, and load your compiled sheet only.

Self-host fonts

Goal: use a web font without a request to a font provider when the page runs.

Name the font in the project that renders the page (the server project of an Auto app) and put KlyFonts in <head>. The build downloads only the weights and subsets you list, writes @font-face rules with a metrics-adjusted fallback face, and preloads the main face.

XML
<ItemGroup>
  <KlyrooFont Include="Public Sans" Role="sans" Weights="400;700" Subsets="latin;latin-ext" />
  <KlyrooFont Include="Geist Mono" Role="mono" Weights="400..600" Subsets="latin" />
</ItemGroup>
Razor
<head>
    <KlyFonts />
    <link rel="stylesheet" href="@Assets["_content/Klyroo.UI/klyroo.css"]" />
</head>

A font with Role="sans" or Role="mono" becomes the font of the page through --klyroo-font-sans or --klyroo-font-mono, in both stylesheet modes. The metadata of an item are Role, Provider (google, bunny, fontsource or local), Weights, Styles, Subsets, Display, Preload, Src (a folder of your own files, which selects the local provider) and Category (sans, serif or mono, for the fallback face). Without Provider, the providers of KlyrooFontsProviderPriority (google;bunny;fontsource) are tried in order.

Declaring the items in a Blazor WebAssembly project is an error (KLYFONT010), because the server renders the head and KlyFonts reads the manifest of the entry assembly. A font that cannot be resolved is a warning in Debug and an error in Release (KlyrooFontsFailOnError). Answers are cached in obj/klyroo/fonts-cache; KlyrooOffline never touches the network. KlyrooFonts=false turns the feature off.

Use and replace icons

Goal: draw any icon by name, and change the icons the components use.

KlyIcon takes a Lucide name (search), the Iconify form (ph:house) or the prefixed form (i-ph-house). The build scans your .razor, .cshtml and .cs files for icon names written as literals, downloads what it lacks from the Iconify API, and compiles the icons into your assembly. Nothing is requested when the page runs.

Razor
<KlyIcon Name="ph:house" Size="KlySize.Lg" />
<KlyButton Label="Open" LeadingIcon="@KlyIcons.Named("i-lucide-folder-open")" />

A name built at runtime is invisible to the scan: declare it in the project file. A folder of SVG files is a collection of your own, named prefix:file-name:

XML
<ItemGroup>
  <KlyrooIcon Include="ph:cube;ph:cube-fill" />
  <KlyrooIconCollection Include="Assets/icons" Prefix="custom" />
  <KlyrooIconScanDirectory Include="../Shared" />
</ItemGroup>

The icons that components draw come from KlyrooOptions.Icons, each with a Lucide default. Assign a name to replace one everywhere, or register markup in code:

C#
using Klyroo.UI;

builder.Services.AddKlyrooUi(o =>
{
    o.Icons.Close = "ph:x";
    o.Icons.Loading = "i-mdi-loading";
    o.Icons.Register("brand:mark", "<path d=\"M3 3h18v18H3z\" />", 24, 24);
});

Register takes the body of an svg element and RegisterSvg takes a whole SVG file, which it sanitizes. Both are for markup you own: never register content from end users. Every icon the build bundles is read as XML and rewritten from an allowlist of SVG elements and attributes, so scripts, event handlers and external references never reach the page. An icon that cannot be found renders an empty icon marked data-kly-missing-icon. At build time a missing icon is a warning in Debug and an error in Release (KlyrooIconsFailOnError). KlyrooIcons=false turns the scan off, and KlyrooIconsScan=false keeps the items but stops reading your sources.

Serve responsive images

Goal: render images with a srcset that an image service or your own server produces.

Components that show a picture render a KlyImage. Without a provider it keeps the source and only adds width, height and loading. Pick a provider in AddKlyrooUi, in the server project and in the WebAssembly client alike:

C#
using Klyroo.UI;
using Klyroo.UI.Images;

builder.Services.AddKlyrooUi(o =>
{
    o.Images.Domains.Add("images.example.com");
    o.Images.AddCloudinary("my-cloud", makeDefault: true);
    o.Images.Presets["thumb"] = new KlyImageOptions { Format = KlyImageFormat.WebP, Quality = 60 };
});
Razor
<KlyImage Src="/img/team.jpg" Alt="The team on stage" Width="640" Height="360"
          Sizes="100vw sm:50vw md:640px" Densities="@(new[] { 1, 2 })" Format="KlyImageFormat.WebP" />
<KlyAvatar Src="/img/ada.jpg" Alt="Ada Lovelace" ImageOptions="@(new KlyImageOptions { Preset = "thumb" })" />

Width and Height are whole numbers of CSS pixels (int?), so write Width="640". A text that holds an integer, with or without a px suffix, is also accepted when it reaches the component through a dictionary of attributes (@attributes) or a lowercase width="640"; any other text throws an InvalidOperationException that names the component and the parameter. Format is a KlyImageFormat (WebP, Avif, Jpeg, Png, Gif, Svg, Auto, Jxl) and Densities a list of whole numbers ([1, 2]). Jxl (JPEG XL) is named in the URL by Cloudinary (f_jxl), imgix (fm=jxl) and a TemplateImageProvider ({format}); the other built-in providers leave the format out and serve the original, and the local optimizer does not produce it. A format outside that list goes through Modifiers: a custom IKlyImageProvider reads it from KlyImageModifiers.Extra and writes it into its URL; the built-in providers ignore the modifiers. Placeholder takes a KlyImagePlaceholder: KlyImagePlaceholder.Url("/img/team-tiny.jpg") for a small image you already have, or KlyImagePlaceholder.Auto to ask the provider for a tiny, blurred version of the image itself.

Klyroo.UI.Images holds Cloudinary, imgix, ImageKit, Cloudflare Images, Netlify, Vercel, Bunny and a URL template provider. Alt is required: pass an empty string for a decorative image. A remote src goes only to the providers that fetch remote images (Cloudflare, Netlify, Vercel and the local one) when its host is in o.Images.Domains.

To resize on your own server, add Klyroo.UI.Images.Local to the server project. It maps an endpoint that resizes and converts with libvips:

C#
using Klyroo.UI;

builder.Services.AddKlyrooUi();
builder.Services.AddKlyrooImagesLocal(o =>
{
    o.CacheDirectory = "/var/cache/my-app/images";
    o.Version = "2026-11-20";
    o.AllowedRemoteHosts.Add("images.example.com");
});

var app = builder.Build();
app.MapKlyrooImages();

In a WebAssembly client register only the URL builder with o.Images.AddLocal(makeDefault: true); it has no server dependency. The endpoint is _klyroo/img, relative to <base href>, so an app served below a path base reaches its own optimizer in every render mode. Call app.UseRouting() right after UsePathBase. Behind a reverse proxy, call UseForwardedHeaders first, because the rate limit tells clients apart by address.

Limits of the local endpoint

The endpoint is meant to face the internet, so every request is bounded. The options are on KlyLocalImagesOptions.

  • Sources. Local sources are files below the web root (or FileProvider), with image extensions only. Dot segments, backslashes and absolute paths are rejected with 400. Remote images are fetched only from AllowedRemoteHosts (403 otherwise), on the default port of the scheme unless the entry names one, with a size limit, a timeout, redirects only to the same scheme, host and port, no credentials in the URL and a content type check. Loopback, private, link-local and other special-use addresses are refused unless AllowPrivateNetworkAddresses is on.
  • Sizes. Width and height are clamped to MaxWidth and MaxHeight, widths are rounded up to a fixed list and qualities to multiples of 5, so a client cannot ask for every combination. A request without a size is scaled down to the maximum. The formats produced are webp, avif, jpeg, png and gif (one frame).
  • Cost. Identical requests share one computation. Processing is limited to MaxConcurrency images at a time, and a request that waits longer than QueueTimeout for a slot gets 503. Each client may start RateLimitPermits computations per RateLimitWindow (600 per minute by default, 429 with Retry-After beyond; cached variants are free).
  • Cache. A source keeps at most MaxVariantsPerSource variants and a new one replaces the least recently used. The disk cache is limited to MaxCacheBytes and trimmed by last access. Responses carry an ETag and answer 304. With Version set, every URL carries it and is cached as immutable for a year, so change it when your images change.
  • SVG. An SVG is recognized by its root element, served as it is with a sandboxing Content-Security-Policy, and rasterized only when RasterizeSvg is on (off by default) and a raster format is requested. libvips loads only JPEG, PNG, WebP, AVIF or HEIC, and GIF here, and animated GIF and WebP files are served untouched.

Localize the app

Goal: show the app in the language of the user, change a few texts, and add a language.

Twelve locales are built in: English, French, German, Spanish, Italian, Portuguese, Brazilian Portuguese, Dutch, Japanese, Simplified Chinese, Arabic and Russian. Only English and French have been reviewed by native speakers (KlyLocales.ReviewedCodes); the others are drafts. A component picks its locale from CultureInfo.CurrentUICulture: the exact code, then its parent cultures, then English. On the server, request localization sets the culture of every request, so no component code is needed:

C#
using Klyroo.UI;

var uiCultures = KlyLocales.All.Select(locale => locale.Code).ToArray();
app.UseRequestLocalization(new RequestLocalizationOptions()
    .SetDefaultCulture("en")
    .AddSupportedCultures([.. uiCultures, "en-GB"])
    .AddSupportedUICultures(uiCultures));

Render KlyCultureMeta in <head> and, in a WebAssembly client, give the runtime the culture the server used before it starts. Without this the client starts from the language of the browser, which can differ.

C#
using Klyroo.UI;

var host = builder.Build();
await host.Services.ApplyServerCultureAsync(KlyLocales.All.Select(locale => locale.Code));
await host.RunAsync();

Change a few messages, or add a locale, in AddKlyrooUi. A message with placeholders keeps them in a translation, and a message that holds a count (ShowMore, InDays, DayCount) is a function of the count, so a language chooses its own plural forms.

C#
using Klyroo.UI;

var australian = KlyLocales.Extend(KlyLocales.En, code: "en-AU", name: "English (Australia)",
    messages: m => m with { SearchCommands = "Find a command..." });

builder.Services.AddKlyrooUi(o => o.Locales = [.. KlyLocales.All, australian]);

KlyLocaleSelect lists o.Locales, writes the culture cookie and reloads the page. o.Locale fixes one locale for the whole app, and KlyApp takes a Locale parameter for a subtree. Locale and Locales become read-only when the first component resolves a locale. An Arabic locale is right to left: KlyApp writes lang and dir, and the components use logical utilities and mirror their arrows. Dates and numbers use the regional culture of the user when it speaks the language of the locale, so an en-GB user with the English locale keeps 20/11/2026.

Validate a form in every render mode

Goal: a form that validates with data annotations and works in static rendering, Server, WebAssembly and Auto.

Getting started builds one. The rules that make it work everywhere:

  • Give the form a FormName and match it in [SupplyParameterFromForm(FormName = "...")].
  • Create the model with Model ??= new() in OnInitialized: on a post the framework has filled it.
  • Use Type="ButtonType.Submit" on the button. A button with OnClick is disabled until the page is interactive.
  • Put the message in the annotation. KlyFormField shows the message of its For expression and ties the label, the description and the error to the control with the right ids. ShowSummary lists every message above the fields.
  • Validation runs on the server on a post. Never rely on the browser alone.

Use a plain EditForm when you want Blazor's own parts with Klyroo controls:

Razor
@using System.ComponentModel.DataAnnotations

<EditForm Model="Model" FormName="signup" OnValidSubmit="Submit" class="flex max-w-sm flex-col gap-4" novalidate>
    <DataAnnotationsValidator />
    <KlyFormField Label="Email" Required Field="FieldIdentifier.Create(() => Model!.Email)">
        <KlyInput Type="InputType.Email" @bind-Value="Model!.Email" />
    </KlyFormField>
    <KlyFormField Label="About you" Help="Markdown is supported." Field="FieldIdentifier.Create(() => Model!.Bio)">
        <KlyTextarea @bind-Value="Model!.Bio" Rows="3" />
    </KlyFormField>
    <KlySwitch @bind-Value="Model!.Newsletter" Label="Send me the newsletter" />
    <KlyButton Type="ButtonType.Submit" Label="Create account" Block />
</EditForm>

@code {
    [SupplyParameterFromForm(FormName = "signup")]
    private SignUp? Model { get; set; }

    protected override void OnInitialized() => Model ??= new();

    private void Submit() { }

    private sealed class SignUp
    {
        [Required, EmailAddress]
        public string? Email { get; set; }

        public string? Bio { get; set; }

        public bool Newsletter { get; set; }
    }
}

Inside an EditForm, a control posts under the name of the bound property; outside one, give it Name. KlyForm Enhance turns on Blazor's enhanced form handling, so the post is a fetch and the page is patched. To show an error that does not come from validation, such as a server error, pass Error to KlyFormField.

Bind inputs to the types of your model

Goal: bind a select to an int foreign key, an enum or a Guid, a number field to an int, a date field to a DateTime, with the validation of the real property.

The list controls (KlySelect, KlySelectMenu, KlyInputMenu, KlyListbox), the number field (KlyInputNumber), the date field (KlyInputDate) and KlySlider are generic: they bind to the type of the property, and Blazor infers it from @bind-Value. The EditContext field is the property itself, so For, data annotations and the posted name work as for any other input.

Razor
<EditForm Model="Model" FormName="order" OnValidSubmit="Submit" novalidate>
    <DataAnnotationsValidator />
    <KlyFormField Label="Category" Required Field="FieldIdentifier.Create(() => Model!.CategoryId)">
        <KlySelect @bind-Value="Model!.CategoryId" Items="_categories" Placeholder="Choose a category" />
    </KlyFormField>
    <KlyFormField Label="Status" Field="FieldIdentifier.Create(() => Model!.Status)">
        <KlySelect @bind-Value="Model!.Status" Items="_statuses" />
    </KlyFormField>
    <KlyFormField Label="Quantity" Field="FieldIdentifier.Create(() => Model!.Quantity)">
        <KlyInputNumber @bind-Value="Model!.Quantity" Min="1" Max="100" />
    </KlyFormField>
    <KlyFormField Label="Due" Field="FieldIdentifier.Create(() => Model!.Due)">
        <KlyInputDate @bind-Value="Model!.Due" />
    </KlyFormField>
    <KlyButton Type="ButtonType.Submit" Label="Save" />
</EditForm>

@code {
    private enum OrderStatus { Draft, InProgress, Done }

    private sealed class Order
    {
        [Range(1, int.MaxValue, ErrorMessage = "Choose a category.")]
        public int CategoryId { get; set; }

        public OrderStatus Status { get; set; }

        [Range(1, 100)]
        public int Quantity { get; set; } = 1;

        public DateTime Due { get; set; } = DateTime.Today;
    }

    // The key of a row is the value, a column is the label. An enum is listed by its members: "In progress", not InProgress.
    private readonly IReadOnlyList<KlySelectItem<int>> _categories = KlySelectItems.From(Catalog.Categories, c => c.Id, c => c.Name);
    private readonly IReadOnlyList<KlySelectItem<OrderStatus>> _statuses = KlySelectItems.FromEnum<OrderStatus>();
}

What each control binds to:

Control Binds to Notes
KlySelect<TValue> string, int, long, an enum, Guid, DateTime... and the nullable form of a value type TValue is the type of KlySelectItem<TValue>.Value. Use int? and KlySelectItems.AsNullable() when no option may be selected: clearing sets null. With a non-nullable type, no option selected is default (0, Guid.Empty), which shows the placeholder unless an option has that value.
KlySelectMenu<TValue>, KlyListbox<TValue> IReadOnlyList<TValue> Single and multiple selection both bind a list, as before. Create (a typed value that is not an option) needs strings.
KlyInputMenu<TValue> string (typed text, or the chosen option with Strict) or any other type Only a string can be typed free: with another type the field is strict, and the value is the chosen option's. Emptying a strict field bound to a type that cannot be empty (int, an enum, a Guid) keeps the old value and the field shows its label again, since default is a value; int?, string and the other nullable types clear to null.
KlyInputNumber<TNumber>, KlySlider<TNumber> sbyte, byte, short, ushort, int, uint, long, ulong, float, double, decimal, and their nullable forms Min, Max and Step stay decimal (the number field) and double (the slider) so Min="0" works for every type. Clearing the number field of a non-nullable property sets zero; an integer type rounds to the nearest whole number, halves away from zero (2.5 is 3, -2.5 is -3), and a text beyond the range of the type (even beyond decimal) takes its MinValue or MaxValue. A nullable slider with no value rests on its minimum.
KlyInputDate<TValue> DateOnly, DateTime, DateTimeOffset, and their nullable forms Min and Max stay DateOnly. Picking a day keeps the time of day of the current value, and the kind of a DateTime or the offset of a DateTimeOffset (the offset is kept, not converted to a time zone); a value that had none (null before, or the default) starts at midnight, a DateTimeOffset in the offset of the server's local time zone on that day.

The values travel to the browser as invariant text (numbers and dates in the invariant culture, enums by name, Guid in the D format, a DateTime as ISO 8601) and the control hands back the value of the option with that text, so a value is never parsed: the exact DateTime or Guid of the option comes back. Equal values have one text, so they always match: a decimal has no trailing zeros (1.00m and 1m are the same option), a DateTime is compared without its Kind, a DateTimeOffset by its UTC instant, and a multiple selection never holds the same option twice. The number field still shows and reads the number in the culture you give it; only what is posted is invariant.

KlySelectItem (strings) is KlySelectItem<string>: new KlySelectItem("fr", "France") and lists of it work as before. The generic controls take an IReadOnlyList<IKlySelectItem<TValue>>, an interface that is covariant in the value, so a list of KlySelectItem fits a control bound to a string or a string?. For a value type that is nullable on the property (int?), the items must be KlySelectItem<int?>: build them with KlySelectItems.From(...).AsNullable(), because a list of KlySelectItem<int> is not one.

A remote source returns the same items: KlyOptionsProvider returns a KlyOptionsResult of KlySelectItem<int> for a KlySelectMenu<int>; the menu throws a clear error when an option has another type. KlySelectedOptionsResolver receives the text of the values (the strings, "42", the name of an enum member) and returns the items that name them.

Two things the compiler cannot infer for a generic component:

  • A ValueChanged that is a method group or a lambda with an untyped parameter (ValueChanged="OnPick", ValueChanged="@(v => _x = v)") cannot be typed before TValue is known. Use @bind-Value, or give the type: <KlySelect TValue="string" Items="_items" Value="@_x" ValueChanged="OnPick" />. Write string, not string?: the generated code rejects the annotation, and the control still accepts a null value.
  • A component with no Value and no Items of a typed list (a remote menu with only OptionsProvider) has nothing to infer from either: give TValue.

React to a click on a chart

Goal: drill down when the user picks a bar, a point or a slice.

KlyChart.OnSelect is raised by a click on a bar, a point of a line or area chart or a donut slice, and by Enter or Space on the row the arrow keys have moved the focus to. Only a chart with a handler is clickable: it gets a pointer cursor, and its keyboard hint says that Enter selects.

Razor
<KlyChart TItem="Sale" TIndex="string" Data="_sales" Index="@(s => s.Month)" Categories="_categories" Type="KlyChartType.Bar" OnSelect="Pick" />

@code {
    private void Pick(KlyChartSelectEventArgs<Sale, string> pick) => Filter = $"{pick.Index}: {pick.SeriesKey} = {pick.Value}";
}

KlyChart<TItem, TIndex> has two type arguments: the row type and the type of the x value that Index returns (a string, a DateOnly, a number). Blazor infers both from Data and Index, so you can leave TItem and TIndex out when you have no handler. A handler written as a method group, as above, needs them spelled out because Blazor cannot infer through it; with inferred types write the handler as a lambda that names the argument type: OnSelect="@((KlyChartSelectEventArgs<Sale, DateOnly> pick) => Pick(pick))".

The arguments carry the position of the row (Row), its Index (the x value, typed as TIndex), the SeriesKey and SeriesIndex of the series that was picked, its Value (null for a gap) and the row Item. A click on a bar reports the bar under the pointer, a click on a line or area chart the series whose point is nearest the pointer, a slice the single category; from the keyboard, with several series, no series is named (SeriesIndex is -1, SeriesKey and Value are null) and your handler chooses from Item, while a chart with one series always names it. Enter and Space select the row the arrow keys are on, not the one the pointer hovers. The pick is reported by the browser, so it needs an interactive render, and it needs Tooltip (the default), since the row of the keyboard is the highlighted one.

Show read-only information

Goal: present figures, facts, amounts and history without writing the markup of each one.

Each kind of read-only block is a component of its own with only its own parameters, so a misuse does not compile. Every block takes Surface (KlySurface.Plain, Muted, Bordered or Elevated; each block has its own default), Loading (a skeleton instead of the content), a Ui record to restyle its slots and the usual Class. Items are records (new KlyFact("Plan") { Value = "Pro" }), colors are KlyColor, icons are names ("check") or any icon markup, and the buttons and badges inside a block are KlyActionItem and KlyBadgeItem.

A figure with its change and a sparkline, and several small figures in a row. KlyStat and KlyStatGroup are generic over the number type (any built-in number type, or its nullable form, which shows a dash when it has no value), and Blazor infers it from Value or Items: write a number as an expression (Value="@_mrr", Value="@(12400m)"), because a bare attribute value is text. The value is formatted with Format and Culture, Unit stays text, and the delta is a number too: its sign picks the color of the badge (up, down or flat) unless you set DeltaDirection, which you do for a change where a drop is good news (a cost, an error rate).

Razor
<KlyStat Title="MRR" Value="@_mrr" Format="C0" Culture="@_en" Delta="@_change" DeltaFormat="+0.0;-0.0" DeltaUnit="%"
         Trend="@(new double[] { 10, 14, 13, 19 })" Caption="vs last month" />

<KlyStat Title="Error rate" Value="@_errors" Format="P1" Delta="@(-0.4)" DeltaDirection="KlyDeltaDirection.Up" />

<KlyStatGroup Title="This week" Items="@(new[]
{
    new KlyStatItem<int>("Errors", 12) { Color = KlyColor.Error },
    new KlyStatItem<int>("Users", 340) { Caption = "+8" },
})" />

@code {
    private readonly CultureInfo _en = CultureInfo.GetCultureInfo("en-US");
    private readonly decimal _mrr = 12400m;
    private readonly decimal _change = 14.2m;
    private readonly double _errors = 0.012;
}

Label and value rows, flat or in groups, with badges, links, copy buttons and a loading placeholder. Max and Step show a Show more button. Copy buttons write to the clipboard from .NET, so they are disabled until the page is interactive:

Razor
<KlyFacts Items="@(new[]
{
    new KlyFact("Status") { Badge = new KlyBadgeItem("Paid") { Color = KlyColor.Success, Icon = "check" } },
    new KlyFact("Environment") { Value = "Production", Copy = true, Mono = true },
    new KlyFact("Site") { Value = "klyroo.dev", Href = "https://klyroo.dev" },
    new KlyFact("Plan") { Loading = true },
})" />

Amounts are decimals, formatted with Format (a .NET format string, "N2" by default) and Culture (the format culture of the locale by default), so Format="C2" with Culture="@fr" shows 1 234,50 €. Two amounts per line switch the block to two columns, and Collapsible hides the lines behind a toggle while keeping the total:

Razor
<KlyBreakdown Title="Invoice" Format="C2" Culture="@_fr" CompareColumns="@(new KlyBreakdownColumns("2026", "2025"))"
              Lines="@_lines" Total="@(new KlyBreakdownLine("Total") { Amount = 1234.5m, CompareAmount = 1100m })" Footnote="VAT included" />

@code {
    private readonly CultureInfo _fr = CultureInfo.GetCultureInfo("fr-FR");
    private readonly KlyBreakdownLine[] _lines =
    [
        new("Licenses") { Amount = 1400m, CompareAmount = 1200m, Detail = "12 seats", Badge = new KlyBadgeItem("New") },
        new("Discount") { Amount = -165.5m, Color = KlyColor.Success },
    ];
}

Before and after values per field. The old value is a del and the new one an ins. KlyDiffItem.Compare builds an item from two typed values and decides Changed by equality. The values are formatted when the block renders, with the format string you give (any .NET format string of an IFormattable type, or a (value, culture) => text function) and the Culture of the block, so the same item reads 1,200.50 in English and 1.200,50 in German:

Razor
<KlyDiff ShowUnchanged="true" Culture="@_de" Items="@(new[]
{
    KlyDiffItem.Compare("Plan", "Starter", "Team"),
    KlyDiffItem.Compare("Seats", 12, 12),
    KlyDiffItem.Compare("Price", 1200.5m, 1500m, "N2"),
    KlyDiffItem.Compare("Due", new DateOnly(2026, 3, 5), new DateOnly(2026, 4, 1), "d"),
    new KlyDiffItem("Role", "Member", "Admin") { Note = new KlyBadgeItem("Needs approval") },
})" />

@code {
    private readonly CultureInfo _de = CultureInfo.GetCultureInfo("de-DE");
}

Entity rows and lists. A record row has a leading image, avatar text or icon, a reference, a title (a link with Href, a button with OnClick), a secondary line, badges and a trailing value. A list is Plain, Steps or Checks; done items say so to assistive technology:

Razor
<KlyRecordList Title="Invoices" Count="2" Max="5" Items="@(new[]
{
    new KlyRecordItem("Acme Annual Plan") { Reference = "INV-42", Href = "/invoices/42", AvatarText = "AC", Trailing = "€12,000", TrailingCaption = "Nov 20", Badge = new KlyBadgeItem("Paid") },
})" />

<KlyList Variant="KlyListVariant.Steps" Items="@(new[]
{
    new KlyListItem("Create the account") { Done = true },
    new KlyListItem("Add a card") { Current = true, Description = "Takes two minutes" },
    new KlyListItem("Launch"),
})" />

A calendar tile in three modes, a paragraph or a quote, a section heading, and a gallery with a plus-N tile:

Razor
<KlyDateTile Mode="KlyDateTileMode.Countdown" Value="@_renewal" Title="Renewal" />
<KlyDateTile Mode="KlyDateTileMode.Range" Value="@_start" EndValue="@_end" />

<KlyText Variant="KlyTextVariant.Quote" Value="Simplicity is prerequisite for reliability." Author="Dijkstra" />
<KlyText Value="@_longText" MaxLines="3" />

<KlyHeading Title="Subscriptions" Count="42" Description="Updated 5 minutes ago" HeadingLevel="2"
            Action="@(new KlyActionItem("Export") { Href = "/export" })" />

<KlyImageGallery Images="@_photos" Max="3" Columns="3" Caption="Trip" />

<KlyImage Src="/img/box.png" Alt="A box on a shelf" Caption="A box on a shelf, Paris" Width="480" />

A gauge. KlyMeter is a role="meter" measure in a known range (disk used, quota), not the progress of a task: use KlyProgress for that. It is a bar, a ring or a scale of levels, and its parts stack with a legend:

Razor
<KlyMeter Title="Storage" Value="92" WarningThreshold="75" ErrorThreshold="90" ValueText="92 GB of 100 GB" />
<KlyMeter Layout="KlyMeterLayout.Ring" Title="Quota" Value="64" />
<KlyMeter Max="10" Parts="@(new[]
{
    new KlyMeterPart("Photos", 3) { ValueLabel = "3 GB", Color = KlyColor.Info, Icon = "image" },
    new KlyMeterPart("Video", 4) { ValueLabel = "4 GB", Color = KlyColor.Warning },
})" />
<KlyMeter Layout="KlyMeterLayout.Scale" Levels="@(new[] { "Low", "Medium", "High" })" CurrentLevel="1" />

Existing components carry the other kinds. KlyAlert takes Details (collapsed behind a toggle), ActionItems, StatusIcon and Live (KlyAlertLive.None by default; Polite is role="status" and Assertive is role="alert", for an alert inserted after the page loaded); KlyEmpty takes ActionItems; KlyTable takes a Footer on its columns, Align, Numeric and Mono, and Max with Step; KlyUser takes a Badge and Contacts; KlyAvatarGroup shows the description and badge of each person in its tooltips; KlyAccordionItem takes Text and DefaultOpen; KlyImage takes a Caption, which wraps the image in a figure with a figcaption (nothing is wrapped without it); and KlyChart draws a conversion funnel with Type="KlyChartType.Funnel": one step per row, sized by the first category and labeled with the share of the previous step.

Razor
<KlyAlert Color="KlyColor.Warning" Variant="KlyVariant.Soft" StatusIcon="true" Live="KlyAlertLive.Polite" Title="Quota warning"
          Description="Your plan is almost full." Details="85% of the monthly volume is used."
          ActionItems="@(new[] { new KlyActionItem("Upgrade") { Href = "/billing", Variant = ButtonVariant.Solid, Color = KlyColor.Warning } })" />

<KlyChart TItem="Step" TIndex="string" Type="KlyChartType.Funnel" Data="_steps" Index="@(s => s.Label)"
          Categories="@(new[] { new KlyChartCategory<Step>("count", s => s.Count) })" />

@code {
    private sealed record Step(string Label, double Count);
    private readonly Step[] _steps = [new("Visits", 1000), new("Signups", 240), new("Paid", 36)];
}

KlyTimeline shows the same events in four layouts with Layout: Default (along a line, with Orientation), Pipeline (a row of markers), Log (compact lines that start with the date and time) and Schedule. An event has a State (Done, Current, Upcoming), a Color, an Actor, a free Date text and a real At and EndAt. In the Default layout, Active highlights the events up to an index when an event has no state, and ShowNumbers numbers the markers.

The Schedule layout is an agenda. Events are sorted by start, grouped by calendar day under a heading that says Today and Tomorrow (Now is the reference, pass it for stable server rendering), with a time column and a length. Each event keeps its own offset, so a meeting entered in another time zone shows its own wall-clock time. An event that starts at midnight and has no end, or ends at midnight or at the end of a day, is an all-day event, and an end at midnight is excluded as in calendar files (the 14th to the 16th at midnight is two days). Events without a date come last under an Unscheduled heading, and Max cuts the sorted list, so Show more reveals later events:

Razor
<KlyTimeline Layout="KlyTimelineLayout.Schedule" Now="@_now" Items="@_events" />

@code {
    private static readonly TimeSpan Paris = TimeSpan.FromHours(1);
    private readonly DateTimeOffset _now = new(2026, 3, 12, 9, 30, 0, Paris);
    private readonly KlyTimelineItem[] _events =
    [
        new("Standup") { At = new(2026, 3, 12, 9, 0, 0, Paris), EndAt = new(2026, 3, 12, 9, 30, 0, Paris), State = KlyTimelineState.Current },
        new("Design review") { Description = "Bring the mockups", At = new(2026, 3, 12, 14, 0, 0, Paris), EndAt = new(2026, 3, 12, 15, 30, 0, Paris), Actor = "Alice" },
        new("Conference") { At = new(2026, 3, 14, 0, 0, 0, Paris), EndAt = new(2026, 3, 16, 0, 0, 0, Paris) },
        new("Book the venue"),
    ];
}

The texts of the blocks (Show more, Read more, Show details, Today, All day, the length of an event...) are messages of the locale, in the twelve locales, so KlyLocales.Extend changes them like any other. A message that holds a count is a function of that count (ShowMore, InDays, DaysOverdue, DayCount, Duration), so a language keeps its plural forms.

Control the color mode

Goal: let the user pick light, dark or system, and set it from code.

KlyColorModeScript in <head> applies the stored mode before the first paint. Any of the color mode controls changes it and they all stay in sync: KlyColorModeButton, KlyColorModeSwitch, KlyColorModeSelect. The mode is stored in localStorage under klyroo-color-mode as light, dark or system, and the page gets the dark class on <html>.

Razor
<KlyColorModeButton />
<KlyColorModeSelect />
<KlyColorModeImage Light="/img/logo-light.svg" Dark="/img/logo-dark.svg" Alt="Acme" />

From JavaScript, call Klyroo.setColorMode('dark') or Klyroo.getColorMode(). From .NET, call IJSRuntime.InvokeVoidAsync("Klyroo.setColorMode", "dark"). The images and avatars of KlyColorModeImage and KlyColorModeAvatar render both versions and let CSS pick one, so there is no flash and no script.

Open a dialog from code

Goal: open a confirmation or a form in a dialog from an event handler or a service, and await how it ended.

IKlyOverlayService is registered by AddKlyrooUi (scoped). KlyApp renders the outlet that shows the dialogs, a KlyOverlayHost, so there is nothing else to place. Each dialog is a KlyModal (or a KlySlideover), so the focus trap, Escape, the return of focus to the button that opened it and the aria wiring come from those components. Like IToastService, call it from interactive code (an event handler, OnAfterRenderAsync), not from a static render.

For a yes or no question, ConfirmAsync returns a bool. Escape, a click on the backdrop and the close button count as no:

Razor
@inject IKlyOverlayService Overlays

<KlyButton Color="KlyColor.Error" OnClick="Delete">Delete</KlyButton>

@code {
    private async Task Delete()
    {
        if (await Overlays.ConfirmAsync("Delete this file?", "This cannot be undone.",
                confirmLabel: "Delete", color: KlyColor.Error))
        {
            await Files.DeleteAsync(id);
        }
    }
}

The labels default to the localized "Cancel" and "Confirm".

For your own content, write a component and open it with ShowAsync<TComponent, TResult>. TResult is the type of the value the dialog returns. The component receives a KlyOverlayContext<TResult> as a cascading parameter and ends the dialog with Close(value) or Cancel():

Razor
@* RenamePrompt.razor *@
<KlyInput @bind-Value="_name" aria-label="Name" />
<div class="mt-4 flex justify-end gap-2">
    <KlyButton Variant="ButtonVariant.Outline" OnClick="() => Overlay.Cancel()">Cancel</KlyButton>
    <KlyButton OnClick="() => Overlay.Close(_name)">Rename</KlyButton>
</div>

@code {
    [CascadingParameter] public KlyOverlayContext<string> Overlay { get; set; } = default!;
    [Parameter] public string Name { get; set; } = "";
    private string _name = "";
    protected override void OnInitialized() => _name = Name;
}
Razor
var result = await Overlays.ShowAsync<RenamePrompt, string>(
    new Dictionary<string, object?> { ["Name"] = file.Name },
    new KlyOverlayOptions { Title = "Rename file", Size = KlySize.Sm });

if (result.TryGetValue(out var name)) file.Name = name;

The parameters are a dictionary by name because Blazor creates the component and sets its parameters by name; that is the one untyped argument of the service. result.Value is the string (or default when the dialog was canceled), and result.Canceled says which way it ended. A dialog with nothing to return can use bool and call Close(true).

The TResult you pass must be the one the component declares: ShowAsync<RenamePrompt, bool> throws an ArgumentException that names both types, because the component would otherwise never receive its context and fail on Close.

To show markup without writing a component, pass a RenderFragment to ShowAsync<TResult>. The content ends the dialog through the same cascading KlyOverlayContext<TResult>, which any component in the fragment can read (the service cannot check the type such a component asks for, so keep it equal to TResult):

C#
var picked = await Overlays.ShowAsync<int>(
    builder => { builder.OpenComponent<SeatPicker>(0); builder.CloseComponent(); },
    new KlyOverlayOptions { Title = "Pick a seat" });

KlyOverlayOptions sets the Title, Description, Size, whether Escape and the backdrop dismiss it (Dismissible) and whether the header shows a close button (Close). Set Kind = KlyOverlayKind.Slideover (and Side) to get a side panel instead of a centered modal. Both methods take a CancellationToken that closes the dialog with a canceled result.

Dialogs stack: open a second one from the first and the newest sits on top, with Escape closing only that one. The task returned by ShowAsync always completes, so a caller is never left waiting. A dialog also ends as canceled when the user navigates to another page (a different path; a change of the query string or the fragment alone does not count, so a page that keeps its filters in the URL can rewrite them while a dialog is open) and when the last host disappears (the page was left, the circuit ended).

When to call it. The host attaches only in an interactive render, after the page that contains it has initialized. So call the service from an event handler or from OnAfterRenderAsync, not from OnInitialized or OnInitializedAsync: on the first load the page initializes before the host exists, and during prerendering or static rendering there is no host at all. In those cases the call throws an InvalidOperationException that says so, instead of hanging the request: it throws from the call itself, not when the returned task is awaited. It is safe to call from another thread (a timer, a background task): the dialog is added where the host renders.

If you set KlyApp.Overlays to false, place a <KlyOverlayHost /> yourself. An @rendermode island that has no KlyApp of its own needs one too. Several hosts can live in one circuit (one per island): the newest one that is still alive draws the dialogs, and when it goes away the previous one takes over without canceling anything. The dialogs are canceled only when no host remains.

Test components with bUnit

Goal: render Klyroo components in a unit test and check their markup and behavior.

A test project needs xUnit, bUnit and a reference to the project under test. With the Razor SDK it can also hold test components written in Razor. These are the versions the tests of this repository use:

XML
<Project Sdk="Microsoft.NET.Sdk.Razor">
  <PropertyGroup>
    <TargetFramework>net11.0</TargetFramework>
    <OutputType>Exe</OutputType>
    <IsTestProject>true</IsTestProject>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="xunit.v3" Version="4.0.3" />
    <PackageReference Include="bunit" Version="2.15.2" />
    <PackageReference Include="Klyroo.UI" Version="0.1.0-preview.1" />
  </ItemGroup>
</Project>

Register Klyroo in the context and tell bUnit how the page renders. A component reads RendererInfo, so the same test can check the interactive and the static behavior:

C#
using Bunit;
using Klyroo.UI;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.Extensions.DependencyInjection;
using Xunit;

public abstract class KlyrooTestContext : BunitContext
{
    protected KlyrooTestContext(Action<KlyrooOptions>? configure = null, bool interactive = true)
    {
        Services.AddKlyrooUi(configure);
        SetRendererInfo(new RendererInfo(interactive ? "Server" : "Static", interactive));
    }
}

public class ButtonTests : KlyrooTestContext
{
    [Fact]
    public void Renders_a_typed_button_with_a_label()
    {
        var cut = Render<KlyButton>(p => p.Add(b => b.Label, "Save"));

        Assert.Equal("button", cut.Find("button").GetAttribute("type"));
        Assert.Equal("Save", cut.Find("[data-slot=label]").TextContent);
    }

    [Fact]
    public void Click_invokes_the_callback()
    {
        var clicks = 0;
        var cut = Render<KlyButton>(p => p.Add(b => b.OnClick, (MouseEventArgs _) => clicks++));

        cut.Find("button").Click();

        Assert.Equal(1, clicks);
    }
}

public class StaticRenderTests : KlyrooTestContext
{
    public StaticRenderTests() : base(interactive: false) { }

    [Fact]
    public void A_button_with_a_click_handler_is_disabled_until_the_page_is_interactive()
    {
        var cut = Render<KlyButton>(p => p.Add(b => b.Label, "Save").Add(b => b.OnClick, (MouseEventArgs _) => { }));

        Assert.True(cut.Find("button").HasAttribute("disabled"));
    }

    [Fact]
    public void A_link_never_waits_for_interactivity()
    {
        var cut = Render<KlyButton>(p => p.Add(b => b.Href, "/docs").Add(b => b.Label, "Docs"));

        Assert.Equal("/docs", cut.Find("a").GetAttribute("href"));
    }
}

bUnit runs no JavaScript. The custom elements that handle opening, focus and keyboard navigation are never connected in a unit test, so test what .NET renders and the callbacks it raises, and cover the in-browser behavior with a browser test. In an end-to-end test, wait until the page is interactive before clicking a button that has an OnClick.