Skip to content
All components CodeBlock

CodeBlock

On this page

A block of source code with a label, syntax highlighting and a copy button (KlyCodeBlock), and a value that stays masked until the user reveals it (KlySecretBlock). The highlighter (CodeHighlighter in Klyroo.Display.Core) colors thirteen languages with the colors of the Klyroo.UI theme, and the text of a block is exactly the code, with any markup in it escaped.

Examples

Languages, label and copy

Language is a CodeLanguage and selects the colors. Without a Label the block shows the name of the language, and without a Language the code is plain text. Copy turns the copy button off and Highlight false renders the code without colors. The copy button copies the code as given and needs an interactive render mode, so statically rendered it does nothing.

Order.cs
public record Order(int Id, decimal Total)
{
    public string Label => $"Order {Id}";

    public bool IsLarge(decimal threshold = 100m) => Total > threshold;
}
json
{
  "name": "orders",
  "private": true,
  "retries": 3,
  "tags": ["billing", null]
}
Order.cs, without colors
public record Order(int Id, decimal Total)
{
    public string Label => $"Order {Id}";

    public bool IsLarge(decimal threshold = 100m) => Total > threshold;
}
notes.txt
Without a Language the code is plain text,
and <b>markup</b> in it stays text.
Razor
<div class="flex w-full flex-col gap-4">
    <KlyCodeBlock Code="@_csharp" Language="CodeLanguage.CSharp" Label="Order.cs" />
    <KlyCodeBlock Code="@_json" Language="CodeLanguage.Json" Copy="false" />
    <KlyCodeBlock Code="@_csharp" Language="CodeLanguage.CSharp" Label="Order.cs, without colors" Highlight="false" />
    <KlyCodeBlock Code="@_plain" Label="notes.txt" />
</div>

@code {
    private const string _csharp = """
        public record Order(int Id, decimal Total)
        {
            public string Label => $"Order {Id}";

            public bool IsLarge(decimal threshold = 100m) => Total > threshold;
        }
        """;

    private const string _json = """
        {
          "name": "orders",
          "private": true,
          "retries": 3,
          "tags": ["billing", null]
        }
        """;

    private const string _plain = "Without a Language the code is plain text,\nand <b>markup</b> in it stays text.";
}

Line numbers and emphasized lines

LineNumbers draws the numbers with CSS, so selecting and copying the code never picks them up. HighlightLines takes line numbers counted from 1: an int is one line and new CodeLineRange(4, 5) is a run, and the emphasized lines get a neutral fill and a marker in the gutter. Lines past the end of the code are ignored.

Orders.sql
SELECT id, total
FROM orders
WHERE status = 'paid'
  AND total > 100
  AND shipped_at IS NULL;
Orders.sql, lines 2, 4 and 5 emphasized
SELECT id, total
FROM orders
WHERE status = 'paid'
  AND total > 100
  AND shipped_at IS NULL;
Emphasis without numbers
SELECT id, total
FROM orders
WHERE status = 'paid'
  AND total > 100
  AND shipped_at IS NULL;
Razor
<div class="flex w-full flex-col gap-4">
    <KlyCodeBlock Code="@_query" Language="CodeLanguage.Sql" Label="Orders.sql" LineNumbers />
    <KlyCodeBlock Code="@_query" Language="CodeLanguage.Sql" Label="Orders.sql, lines 2, 4 and 5 emphasized" LineNumbers
                  HighlightLines="@([2, new CodeLineRange(4, 5)])" />
    <KlyCodeBlock Code="@_query" Language="CodeLanguage.Sql" Label="Emphasis without numbers" HighlightLines="@([3])" />
</div>

@code {
    private const string _query = """
        SELECT id, total
        FROM orders
        WHERE status = 'paid'
          AND total > 100
          AND shipped_at IS NULL;
        """;
}

Language from a file name

CodeHighlighter.ResolveFileName turns a file name or a URL into a CodeLanguage, and ResolveLanguage does the same for a name, an alias or an extension. A name that is not supported gives null, which is plain text. CodeHighlighter.Languages lists every supported language.

Supported: bash, csharp, css, html, javascript, json, less, python, scss, sql, typescript, xml, yaml.

build.yml
name: build
on: [push]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - run: dotnet test
total.js
const total = orders
  .filter((order) => order.status === "paid")
  .reduce((sum, order) => sum + order.total, 0);
README.unknown
A name that is not supported resolves to null: plain text.
Razor
<div class="flex w-full flex-col gap-4">
    <p class="m-0 text-sm text-(--klyroo-text-muted)">
        Supported: @string.Join(", ", CodeHighlighter.Languages.Select(CodeHighlighter.Name)).
    </p>
    @foreach (var (name, source) in _files)
    {
        <KlyCodeBlock Code="@source" Language="CodeHighlighter.ResolveFileName(name)" Label="@name" />
    }
</div>

@code {
    private static readonly (string Name, string Code)[] _files =
    [
        ("build.yml", "name: build\non: [push]\njobs:\n  test:\n    runs-on: ubuntu-latest\n    steps:\n      - run: dotnet test"),
        ("total.js", "const total = orders\n  .filter((order) => order.status === \"paid\")\n  .reduce((sum, order) => sum + order.total, 0);"),
        ("README.unknown", "A name that is not supported resolves to null: plain text."),
    ];
}

Secret block

While the value is masked, the page contains eight bullets and the last VisibleChars characters only (4 by default). A value that is not longer than VisibleChars is fully masked. The Reveal and copy buttons need an interactive render mode, so statically rendered the secret stays masked. The copy button copies the whole value even while it is masked, and the mask is a display feature, not protection: the value is in the memory of the browser in WebAssembly.

API key
••••••••3210
Webhook secret, last 8 characters
••••••••76543210
Value as short as VisibleChars
••••••••
Without the copy button
••••••••3210
Razor
<div class="flex w-full flex-col gap-4">
    <KlySecretBlock Label="API key" Value="@_apiKey" />
    <KlySecretBlock Label="Webhook secret, last 8 characters" Value="@_apiKey" VisibleChars="8" />
    <KlySecretBlock Label="Value as short as VisibleChars" Value="a1b2" />
    <KlySecretBlock Label="Without the copy button" Value="@_apiKey" Copy="false" />
</div>

@code {
    private const string _apiKey = "sk_live_klyroo_9876543210";
}

API

KlyCodeBlock

A block of source code with a label, syntax highlighting from CodeHighlighter , a copy button, optional line numbers and emphasized lines. Show a value that must stay hidden with KlySecretBlock instead.

Parameters

Name Type Default Description
Class string Classes added to the root element, merged last so they win over the theme.
Code string The source code to show. It is plain text: markup in it is escaped.
Copy bool true Whether the block shows a copy button, which copies the code as given ( true by default). The button needs an interactive render mode.
Highlight bool true Whether the code is highlighted according to Language ( true by default). A code longer than MaxLength characters or MaxLines lines is always plain text.
HighlightLines IReadOnlyList<CodeLineRange> The lines to emphasize, counted from 1: a neutral fill and an accent marker in the gutter. Single lines and runs mix in one list: HighlightLines="@([3, new CodeLineRange(6, 9)])" . Lines past the end of the code are ignored.
Label string The label above the code. Without it, the name of Language , or the localized "Code".
Language CodeLanguage? The language of the code: it selects the syntax highlighting, and it is the label of the block when Label is not set. null (the default) shows plain text. Get it from a name, an alias or a file extension with String) or String) . Values: Bash, CSharp, Css, Html, JavaScript, Json, Less, Python, Scss, Sql, TypeScript, Xml, Yaml.
LineNumbers bool false Shows the number of each line in a gutter. The numbers are drawn by CSS, so they are not part of the text that is selected or copied.
Ui CodeBlockUi Per-instance class overrides of the slots of the block, see CodeBlockUi . They are merged after the theme, and Class wins on the root slot.

Ui slots

Ui takes a CodeBlockUi with one class string per slot, merged after the theme.

Slot Styles
Root Classes merged into the root slot of KlyCodeBlock , after the theme and the app configuration.
Header Classes merged into the header slot of KlyCodeBlock , after the theme and the app configuration.
Label Classes merged into the label slot of KlyCodeBlock , after the theme and the app configuration.
Actions Classes merged into the actions slot of KlyCodeBlock , after the theme and the app configuration.
Copy Classes merged into the copy slot of KlyCodeBlock , after the theme and the app configuration.
CopyIcon Classes merged into the copyIcon slot of KlyCodeBlock , after the theme and the app configuration.
Pre Classes merged into the pre slot of KlyCodeBlock , after the theme and the app configuration.
Line Classes merged into the line slot of KlyCodeBlock , after the theme and the app configuration.
LineIdle Classes merged into the lineIdle slot of KlyCodeBlock , after the theme and the app configuration.
LineHighlighted Classes merged into the lineHighlighted slot of KlyCodeBlock , after the theme and the app configuration.
LineNumbered Classes merged into the lineNumbered slot of KlyCodeBlock , after the theme and the app configuration.
TokenKeyword Classes merged into the tokenKeyword slot of KlyCodeBlock , after the theme and the app configuration.
TokenString Classes merged into the tokenString slot of KlyCodeBlock , after the theme and the app configuration.
TokenNumber Classes merged into the tokenNumber slot of KlyCodeBlock , after the theme and the app configuration.
TokenComment Classes merged into the tokenComment slot of KlyCodeBlock , after the theme and the app configuration.
TokenType Classes merged into the tokenType slot of KlyCodeBlock , after the theme and the app configuration.
TokenFunction Classes merged into the tokenFunction slot of KlyCodeBlock , after the theme and the app configuration.
TokenProperty Classes merged into the tokenProperty slot of KlyCodeBlock , after the theme and the app configuration.
TokenTag Classes merged into the tokenTag slot of KlyCodeBlock , after the theme and the app configuration.
TokenPunctuation Classes merged into the tokenPunctuation slot of KlyCodeBlock , after the theme and the app configuration.

KlySecretBlock

A value that is masked until the user reveals it, such as an API key or a token, with a Reveal and Conceal toggle and a copy button. It is never highlighted.

Parameters

Name Type Default Description
Class string Classes added to the root element, merged last so they win over the theme.
Copy bool true Whether the block shows a copy button, which copies the whole secret even while it is masked ( true by default). The Reveal and copy buttons need an interactive render mode.
Label string The label above the value. Without it, the localized "Secret".
Ui SecretBlockUi Per-instance class overrides of the slots of the block, see SecretBlockUi . They are merged after the theme, and Class wins on the root slot.
Value string The secret, such as an API key or a token. While it is masked it is not written to the page at all, only its last VisibleChars characters are.
VisibleChars int 4 The number of trailing characters left visible while the value is masked ( 4 by default). A longer value shows eight bullets followed by those characters. A value that is not longer than this number is fully masked, so a short secret is never shown whole.

Ui slots

Ui takes a SecretBlockUi with one class string per slot, merged after the theme.

Slot Styles
Root Classes merged into the root slot of KlySecretBlock , after the theme and the app configuration.
Header Classes merged into the header slot of KlySecretBlock , after the theme and the app configuration.
Label Classes merged into the label slot of KlySecretBlock , after the theme and the app configuration.
Actions Classes merged into the actions slot of KlySecretBlock , after the theme and the app configuration.
Toggle Classes merged into the toggle slot of KlySecretBlock , after the theme and the app configuration.
ToggleIcon Classes merged into the toggleIcon slot of KlySecretBlock , after the theme and the app configuration.
Copy Classes merged into the copy slot of KlySecretBlock , after the theme and the app configuration.
CopyIcon Classes merged into the copyIcon slot of KlySecretBlock , after the theme and the app configuration.
Pre Classes merged into the pre slot of KlySecretBlock , after the theme and the app configuration.