Skip to content

DashboardPage

On this page

The page and the grid of an analytical dashboard. KlyDashboardPage takes a DashboardController and draws the title, a refresh button, the view tabs and one control per filter, and it re-renders when the controller changes. KlyDashboardGrid lays the blocks out on 12 columns and sets the defaults of Menu and Freshness for the blocks inside it. The state lives in the controller (package Klyroo.Dashboard.Core), which has no UI dependency.

Examples

Controller, filter and staged resources

The Essential resource loads first, then the Background one. A DashboardFilterControl only holds a selection and a filter change reloads nothing by itself: the loaders read the filter and the handler of ChangedEvent calls RefreshAsync. The Source of a block drives only its state (skeleton, error, empty, content), the block never reads Data, so the values are passed through its own parameters. Dispose the controller with the page.

Orders

Revenue and orders for the selected channels

Revenue

98.3K +10.4%
vs 89K previous period

Orders

643

Revenue by region

EMEA 42.3K
Americas 36.4K
APAC 19.6K
Razor
@implements IDisposable

<KlyDashboardPage Dashboard="_dashboard" Title="Orders" Description="Revenue and orders for the selected channels" Sticky="false">
    <KlyDashboardGrid>
        <KlyDashboardStat Source="_summary" Label="Revenue" Span="4" Value="_summary.Data?.Revenue"
                          Compare="_summary.Data?.PreviousRevenue" Format="DashboardFormatPreset.Compact" />
        <KlyDashboardStat Source="_summary" Label="Orders" Span="4" Value="_summary.Data?.Orders"
                          Format="DashboardFormatPreset.Integer" />
        <KlyDashboardBars Source="_regions" Title="Revenue by region" Span="4" Items="_regions.Data"
                          Format="DashboardFormatPreset.Compact" />
    </KlyDashboardGrid>
</KlyDashboardPage>

@code {
    private sealed record Sale(string Region, string Channel, double Revenue, double Previous, int Orders);
    private sealed record Summary(double Revenue, double PreviousRevenue, double Orders);

    private static readonly Sale[] Sales =
    [
        new("EMEA", "Web", 21_300, 18_600, 140), new("EMEA", "Retail", 12_800, 13_100, 85), new("EMEA", "Partner", 8_200, 7_000, 52),
        new("Americas", "Web", 18_900, 17_200, 120), new("Americas", "Retail", 11_400, 10_900, 74), new("Americas", "Partner", 6_100, 6_400, 41),
        new("APAC", "Web", 9_600, 7_100, 66), new("APAC", "Retail", 5_300, 4_800, 35), new("APAC", "Partner", 4_700, 3_900, 30),
    ];

    private readonly DashboardController _dashboard = new("orders");
    private DashboardFilterControl _channel = default!;
    private DashboardResource<Summary> _summary = default!;
    private DashboardResource<IReadOnlyList<DashboardBarItem>> _regions = default!;

    protected override async Task OnInitializedAsync()
    {
        _channel = _dashboard.AddFilter(new DashboardFilterControl(
            "channel", "Channel",
            items: [new("Web", "Web"), new("Retail", "Retail"), new("Partner", "Partner")],
            multiple: true, placeholder: "All channels"));

        // Essential resources load first; the Background one starts when they are done.
        _summary = _dashboard.RegisterResource(new DashboardResource<Summary>("summary", _ =>
        {
            var rows = Selected().ToList();
            return Task.FromResult(new Summary(rows.Sum(s => s.Revenue), rows.Sum(s => s.Previous), rows.Sum(s => s.Orders)));
        }));
        _regions = _dashboard.RegisterResource(new DashboardResource<IReadOnlyList<DashboardBarItem>>("regions", _ =>
            Task.FromResult<IReadOnlyList<DashboardBarItem>>([.. Selected()
                .GroupBy(s => s.Region)
                .Select(g => new DashboardBarItem(g.Key, g.Sum(s => s.Revenue)))]),
            DashboardQueryStage.Background));

        _channel.ChangedEvent += Reload;
        await _dashboard.RefreshAsync();
    }

    // A filter does not reload anything by itself: the loaders read it, and this handler asks for the reload.
    private void Reload() => _ = _dashboard.RefreshAsync();

    private IEnumerable<Sale> Selected() =>
        _channel.Values.Count == 0 ? Sales : Sales.Where(s => _channel.Values.Contains(s.Channel));

    public void Dispose()
    {
        _channel.ChangedEvent -= Reload;
        _dashboard.Dispose();
    }
}

Loading stages and a failing query

A block shows a skeleton until its own resource is ready. When a loader throws, only its block shows the error message and a Retry button while the rest of the dashboard keeps working. The message of the exception is shown to the user as is, so throw one that is safe to display. The state of the controller only combines the Essential resources, so a failed Background resource leaves it Ready. This example waits 500 ms for its Background query, so a statically rendered page takes that long to appear.

Loading stages

Controller state: Ready

Visitors

48,200

Visitors by month (Background, 500 ms)

  • Visitors
Bar chart
CategoryVisitors
Jan9,800
Feb11,200
Mar12,700
Apr14,500

Visits by source (fails once)

Razor
@implements IDisposable

<KlyDashboardPage Dashboard="_dashboard" Title="Loading stages" Sticky="false" Description="@($"Controller state: {_dashboard.State}")">
    <KlyDashboardGrid>
        <KlyDashboardStat Source="_visitors" Label="Visitors" Span="4" Value="_visitors.Data" Format="DashboardFormatPreset.Integer" />
        <KlyDashboardChart Source="_trend" Title="Visitors by month (Background, 500 ms)" Span="8" Height="140"
                           Categories="_months" Series="_trend.Data" Format="DashboardFormatPreset.Integer" />
        <KlyDashboardBars Source="_sources" Title="Visits by source (fails once)" Span="12" Items="_sources.Data" Format="DashboardFormatPreset.Integer" />
    </KlyDashboardGrid>
</KlyDashboardPage>

@code {
    private readonly DashboardController _dashboard = new("stages");
    private DashboardResource<double> _visitors = default!;
    private DashboardResource<IReadOnlyList<DashboardChartSeries>> _trend = default!;
    private DashboardResource<IReadOnlyList<DashboardBarItem>> _sources = default!;
    private int _attempts;
    private static readonly IReadOnlyList<string> _months = ["Jan", "Feb", "Mar", "Apr"];

    protected override async Task OnInitializedAsync()
    {
        _visitors = _dashboard.RegisterResource(new DashboardResource<double>("visitors",
            _ => Task.FromResult(48_200d)));

        _trend = _dashboard.RegisterResource(new DashboardResource<IReadOnlyList<DashboardChartSeries>>("trend", async ct =>
        {
            await Task.Delay(500, ct);
            return [new DashboardChartSeries("visitors", "Visitors", [9_800, 11_200, 12_700, 14_500])];
        }, DashboardQueryStage.Background));

        // The first load throws: only this block shows the message and a Retry button, the others keep working.
        _sources = _dashboard.RegisterResource(new DashboardResource<IReadOnlyList<DashboardBarItem>>("sources", _ =>
        {
            if (_attempts++ == 0) throw new InvalidOperationException("The analytics service is not reachable.");
            return Task.FromResult<IReadOnlyList<DashboardBarItem>>([new("Search", 21_000), new("Direct", 14_300), new("Social", 12_900)]);
        }, DashboardQueryStage.Background));

        await _dashboard.RefreshAsync();
    }

    public void Dispose() => _dashboard.Dispose();
}

Views and a Deferred resource

The page draws the tabs when at least two views are enabled and sets CurrentView, but the content of each view is your markup, chosen from CurrentView. A Deferred resource is skipped by RefreshAsync until it is activated, here by the first render of the card bound to it, so the activity query has not run while the Overview tab is shown.

Operations

Updated just now

Open tickets

42

Activity query

The activity query has run 0 time(s). It is Deferred, so it waits for the Activity tab.

Razor
@implements IDisposable

<KlyDashboardPage Dashboard="_dashboard" Title="Operations" Sticky="false">
    @if (_dashboard.CurrentView == "overview")
    {
        <KlyDashboardGrid>
            <KlyDashboardStat Source="_tickets" Label="Open tickets" Span="6" Value="_tickets.Data" Format="DashboardFormatPreset.Integer" />
            <KlyDashboardCard Title="Activity query" Span="6">
                <p class="m-0 text-sm">The activity query has run @_activityLoads time(s). It is Deferred, so it waits for the Activity tab.</p>
            </KlyDashboardCard>
        </KlyDashboardGrid>
    }
    else if (_dashboard.CurrentView == "activity")
    {
        <KlyDashboardGrid>
            <KlyDashboardFeed Source="_activity" Title="Latest activity" Span="12" Items="_activity.Data" />
        </KlyDashboardGrid>
    }
</KlyDashboardPage>

@code {
    private readonly DashboardController _dashboard = new("operations");
    private DashboardResource<double> _tickets = default!;
    private DashboardResource<IReadOnlyList<DashboardFeedItem>> _activity = default!;
    private int _activityLoads;

    protected override async Task OnInitializedAsync()
    {
        _dashboard.AddView("overview", "Overview");
        _dashboard.AddView("activity", "Activity", badge: "3");

        _tickets = _dashboard.RegisterResource(new DashboardResource<double>("tickets", _ => Task.FromResult(42d)));
        _activity = _dashboard.RegisterResource(new DashboardResource<IReadOnlyList<DashboardFeedItem>>("activity", _ =>
        {
            _activityLoads++;
            var now = DateTimeOffset.UtcNow;
            return Task.FromResult<IReadOnlyList<DashboardFeedItem>>(
            [
                new("Ticket 1042 closed", now.AddMinutes(-12), "Resolved by the support team", "SK"),
                new("Ticket 1043 opened", now.AddHours(-2), "Login fails on mobile", "LM"),
                new("Ticket 1039 reassigned", now.AddHours(-5), AvatarText: "AB"),
            ]);
        }, DashboardQueryStage.Deferred));

        await _dashboard.RefreshAsync();
    }

    public void Dispose() => _dashboard.Dispose();
}

Grid columns, variants and menu

Variant Panels joins the cards into one bordered panel, Columns changes the number of equal columns (a Span is clamped to it), and Menu on the grid is the default of the blocks inside it. A block's own Menu wins, as the conversion stat shows. Below the sm breakpoint every block takes the full row. The blocks here have no Source, so their content renders at once.

Visitors

48.2K

Signups

1,320

Conversion

2.7%

Visits by source

Search 21,000
Direct 14,300
Social 12,900

Visits by source

Open

12

Closed

187

Oldest open ticket

3 days
Razor
<div class="flex w-full flex-col gap-8">
    <KlyDashboardGrid Variant="DashboardGridVariant.Panels" Menu="true">
        <KlyDashboardStat Label="Visitors" Span="4" Value="48200" Format="DashboardFormatPreset.Compact" />
        <KlyDashboardStat Label="Signups" Span="4" Value="1320" Format="DashboardFormatPreset.Integer" />
        <KlyDashboardStat Label="Conversion" Span="4" Value="0.0274" Format="DashboardFormatPreset.Ratio" Menu="false" />
        <KlyDashboardBars Title="Visits by source" Span="12" Items="_sources" Format="DashboardFormatPreset.Integer" />
    </KlyDashboardGrid>

    <KlyDashboardGrid Columns="2">
        <KlyDashboardStat Label="Open" Span="1" Value="12" Format="DashboardFormatPreset.Integer" />
        <KlyDashboardStat Label="Closed" Span="1" Value="187" Format="DashboardFormatPreset.Integer" />
        <KlyDashboardStat Label="Oldest open ticket" Span="2" TextValue="3 days" />
    </KlyDashboardGrid>
</div>

@code {
    private static readonly IReadOnlyList<DashboardBarItem> _sources =
    [
        new("Search", 21_000), new("Direct", 14_300), new("Social", 12_900),
    ];
}

API

KlyDashboardPage

Page shell of a dashboard: a header with the title and a refresh button, a sticky toolbar with the view tabs and the filter controls of a DashboardController (option lists, text, number and date inputs, or your own template, depending on the filter kind), and a body for the blocks. It re-renders when the controller changes. Buttons and inputs need an interactive render mode.

Parameters

Name Type Default Description
Class string Classes added to the root element, merged last so they win over the theme.
Dashboard DashboardController The controller shown by the page: it supplies the refresh button, the view tabs and the filter pills, and the page re-renders when the controller changes. Without it only the title and the body are rendered.
Description string Text under the heading. When empty, the page shows an Updated line from Dashboard.UpdatedAt once data has loaded.
ShowFilters bool true Shows a control for each enabled filter that is not headless, chosen by its Kind : a text, number or date box, two date boxes for a range, your CustomFilter template, or a pill with an option list. Defaults to true .
ShowRefresh bool true Shows the refresh button, which calls RefreshAsync . Defaults to true .
ShowTabs bool true Shows the view tabs when the controller has at least two enabled views. Defaults to true .
Sticky bool true Keeps the toolbar of tabs and filters at the top of the page while the body scrolls. Defaults to true .
SyncUrl bool false Keeps the filters in the URL: the page applies the query string of the current URL to the filters of Dashboard once ( DashboardController.ApplyQuery , also in static SSR and in a prerender, from NavigationManager.Uri ), writes every later change back with DashboardController.MergeQuery and a replacing navigation (no history entry per change, other query parameters kept), and applies the query again when a navigation to the same page changes it. Nothing is written in a static render, which cannot navigate. A parent initializes before this child, so a page that loads its data in OnInitializedAsync should also call Dashboard.ApplyQuery there, before DashboardPersistence.Attach and LoadAsync : the first load then uses the filters of the URL, and the fingerprint of the persisted data matches between the prerender and the interactive render. The application is idempotent, so doing it in both places is harmless. Defaults to false .
Title string The page heading.
UrlPrefix string Put before the key of every filter in the URL ( sales. ), so that two dashboards on one page can share a query string. Only used with SyncUrl .

Slots

Name Type Description
Actions RenderFragment Content placed before the refresh button, for example your own buttons.
CustomFilter RenderFragment<DashboardFilterControl> Draws each enabled filter whose Kind is Custom in the toolbar. It receives the filter: show its selection from Values and change it with Value , SetValues or Reset . Without it the toolbar leaves those filters out.
ChildContent RenderFragment The body of the page, usually a KlyDashboardGrid . The page only draws the tabs: render the content of the current view yourself from DashboardController.CurrentView .

KlyDashboardGrid

A grid of equal columns (12 by default, see Columns ) that places blocks by their Span , and gives them its Menu and Freshness defaults.

Parameters

Name Type Default Description
Class string Classes added to the root element, merged last so they win over the theme.
Columns int 12 The number of equal columns of the grid, at least 1. Defaults to 12. A block's Span is clamped to it, so with Columns="3" a block of the default span 12 fills one row and Span="1" takes a third.
Freshness bool false The default of Freshness for the blocks inside the grid. Defaults to false .
Menu bool false The default of Menu for the blocks inside the grid. Defaults to false .
Variant DashboardGridVariant DashboardGridVariant.Cards Cards (the default) draws separate cards with a gap. Panels joins the cards into one bordered panel with thin dividers. Values: Cards, Panels.

Slots

Name Type Description
ChildContent RenderFragment The blocks of the grid. Each one sets its width with Span .