Browse the documentation

Blazor apps

Two Blazor samples whose components keep their markup in Razor files and their logic in Typhon modules. BlazorApp renders on the server, and BlazorWasm runs in the browser.

samples/BlazorApp in the Typhon repository is a Blazor web app with interactive server rendering. Every component keeps its markup in a .razor file and its logic in a .ty file next to it: state, event handlers, lifecycle methods, computed properties and injected services. The startup code in main.ty and the services are Typhon modules too, and the project contains no C# file. samples/BlazorWasm is its counterpart on Blazor WebAssembly, described in the section Blazor WebAssembly.

Pages

PageWhat it shows
/A static server-rendered page with OnInitialized and a list rendered with @foreach.
/counter, /counter/{start}Fields, @onclick handlers, @bind, a route parameter, OnParametersSet and computed properties.
/todosAn injected singleton service, an EditForm validated by DataAnnotations attributes, and a live search.
/weatherAn async lifecycle method, an async handler, the statistics module and a child component that draws an SVG bar chart.

Markup and code-behind

The Razor compiler turns Counter.razor into a partial C# class. Typhon compiles counter.ty into a static class for the module, with the module’s classes nested in it. Typhon’s class cannot be the other half of Razor’s partial class, so it is the component’s base class. An excerpt of counter.ty:

from typing import Annotated
from Microsoft.AspNetCore.Components import ComponentBase, Parameter


class CounterBase(ComponentBase):
    start: Annotated[int, Parameter()] = 0
    count: int = 0
    step: int = 1
    history: list[int]

    def OnParametersSet(self) -> None:
        self.count = self.start
        self.history = [self.start]

    def increment(self) -> None:
        self.add(self.step)

    def add(self, amount: int) -> None:
        self.count += amount
        self.history.append(self.count)

    @property
    def parity(self) -> str:
        return "even" if self.count % 2 == 0 else "odd"

And of Counter.razor:

@page "/counter"
@page "/counter/{start:long}"
@rendermode InteractiveServer
@inherits counter.CounterBase

<p role="status">Current count: <strong>@count</strong> (@parity)</p>
<button class="primary" @onclick="increment">Add @step</button>
<button @onclick="() => add(-1)">Subtract 1</button>

The markup uses the members of the Typhon class like those of a C# base class:

  • Fields. Class-level annotations and attributes assigned in methods become public properties, so @count and @bind="step" work on them. A Python int is a C# long, so a route parameter takes the long constraint.
  • Computed values. A @property becomes a C# property, as @parity shows.
  • Event handlers. Methods are event handlers, and an async def handler returns a Task that Blazor awaits.
  • Lifecycle methods. A method named like a virtual member of ComponentBase overrides it with that member’s access. def OnParametersSet(self) becomes protected override void OnParametersSet().
  • Parameters, services and validation. typing.Annotated puts .NET attributes on a property: Parameter() for a parameter, Inject() for a service, and DataAnnotations attributes such as Required() on a form model.

What the Razor compiler cannot see

The Razor compiler and Typhon are both source generators in the same compilation, and neither sees the code the other generates. The C# compiler checks every name the markup uses, so a misspelled member is an error on its line of the .razor file. The Razor compiler itself, however, knows nothing about the Typhon classes:

  • main.ty cannot import the App component that the Razor compiler generates, so it names it in a string: app.MapRazorComponents["Components.App"]().
  • A child component whose base class is a Typhon class needs @implements IComponent to be recognized as a component. Its parameters are passed untyped and matched by name when the page renders.
  • The Razor editor offers no completion for the Typhon members.

The sample’s README describes these limits in detail. For typed parameters of child components, it suggests putting the Typhon classes in a class library that the Razor project references, because the Razor compiler reads referenced assemblies.

Running the sample

dotnet run --project samples/BlazorApp

The app listens on http://localhost:5080, and -- --urls http://127.0.0.1:5000 selects another address. The Razor compiler runs as part of the build, so the sample needs its project, and typhon run cannot run main.ty.

Blazor WebAssembly

samples/BlazorWasm is a standalone Blazor WebAssembly app built the same way: each component inherits a Typhon class, and the startup code and the service are Typhon modules. The browser downloads the .NET runtime and the app once, and the Python code then runs in the page. dotnet publish produces static files that any web server can serve, and no server code runs.

PageWhat it shows
/counterThe counter of BlazorApp, unchanged except that it has no render mode.
/todosA service that keeps the to-do list in the browser’s localStorage through JavaScript interop, stored as CSV with the csv module.
/mandelbrotThe Mandelbrot set computed in plain Python and drawn as SVG, with tiles that zoom in on a click.

The component code is the same as in BlazorApp. The differences lie around it:

  • main.ty builds a WebAssemblyHostBuilder, names the root component in a string and ends with await builder.Build().RunAsync(). A __main__ block that awaits compiles to an async Main.
  • In the browser, the IJSRuntime that Blazor injects is an IJSInProcessRuntime, so calls to JavaScript can be synchronous. The service casts it with cast(IJSInProcessRuntime, js) and then calls self.js.Invoke[str]("localStorage.getItem", KEY).
  • .NET on WebAssembly has a single thread, which it shares with the page. Before a long computation, the Mandelbrot page calls StateHasChanged() and await asyncio.sleep(0.02), so that the browser shows “Computing…” first.
dotnet run --project samples/BlazorWasm
dotnet publish samples/BlazorWasm -c Release

The development server listens on http://localhost:5090. The published app is about 10 MB, or 3.3 MB with Brotli compression. In a test in headless Chromium, the Release build computed the whole set at 240 by 160 points in about 20 ms, and the to-do list was still there after a reload.