/fast-blazor

Blazor component library for FluentUI. Microsoft's official wrapper around the FluentUI Web Components for use with .NET 6.0 or higher Blazor applications

Primary LanguageC#MIT LicenseMIT

Microsoft.Fast

License: MIT .NET C# Nuget Nuget

Validate PRs Validate Security

Discord Twitter

We appreciate your star, it helps!

Introduction

The Microsoft.Fast.Components.FluentUI package provides a set of Blazor component wrappers around Microsoft's official FluentUI Web Components. The FluentUI Web Components are built on FAST and work in every major browser. To get up and running with the library, see the 'Getting Started' section below.

The source for the library is hosted in the Fast Blazor repository at GitHub. Documentation on the components is available at the demo site and at docs.microsoft.com.

The source for @fluentui/web-components is hosted in the Fluent UI mono-repository. Documentation on the components is available on docs.microsoft.com.

When upgrading from an earlier version

If you are upgrading from an earlier version of the library, please see the what's new for information on (breaking) changes.

Getting Started

To get started using the Fluent UI Web Components for Blazor, you will first need to install the official Nuget package for Fluent UI in the project you would like to use the library and components. You can use the following command:

dotnet add package Microsoft.Fast.Components.FluentUI

Scripts

Next, you need to add the web components script. You can either add the script from CDN directly, or you can install it with NPM, whichever you prefer.

To add the script from CDN use the following markup:

<script type="module" src="https://cdn.jsdelivr.net/npm/@fluentui/web-components/dist/web-components.min.js"></script>

📓 Note

If you prefer to use another CDN, that is entirely possible. Just make sure it is offering the Fluent UI package and you are getting the right web-components.min.js file)

The markup above always references the latest release of the components. When deploying to production, you will want to ship with a specific version. Here's an example of the markup for that:

<script type="module" src="https://cdn.jsdelivr.net/npm/@fluentui/web-components@2.0.2/dist/web-components.min.js"></script>

The script tag is normally placed in your index.html (_Layout.cshtml for Blazor server project) file in the script section at the bottom of the <body>.

If you wish to leverage NPM instead, run the following command:

npm install --save @fluentui/web-components

You can locate the single file script build in the following location:

node_modules/@fluentui/web-components/dist/web-components.min.js

Copy this to your wwwroot/script folder and reference it with a script tag as described above.

📓 Note

If you are setting up Fluent UI Web Components on a Blazor Server project, you will need to escape the @ character by repeating it in the source link. For more information check out the Razor Pages syntax documentation.

Styles

In order for this library to work as expected, you will need to add the composed scoped CSS file for the components. This can be done by adding the following line to the section of your index.html or _Layout.cshtml file in the project you installed the package:

<link href="{PROJECT_NAME}.styles.css" rel="stylesheet" /> 

It is possible that the line is already in place (but commented out).

Reboot

Reboot is a collection of element-specific CSS changes in a single file to help kick-start building a site with the Fluent UI Web Components for Blazor. It provides an elegant, consistent, and simple baseline to build upon.

If you want to use Reboot, you'll need to add to your index.html or _Layout.cshtml file a line that includes the stylesheet (.css file). This can be done by adding the following line to the <head> section:

<link href="_content/Microsoft.Fast.Components.FluentUI/css/reboot.css" rel="stylesheet" />

It is entirely possible to build a site without using Reboot. If you choose not to use it, please do add the variables.css file (which is otherwise imported through the reboot.css file) to your index.html or _Layout.cshtml file in the <head> section like this:

<link href="_content/Microsoft.Fast.Components.FluentUI/css/variables.css" rel="stylesheet" />

The file contains a number of CSS variables that are required to be defined for the components to work correctly.

Code

In your Program.cs file you need to add the following:

builder.Services.AddFluentUIComponents();

This addition makes sure all the necessary services the library uses are setup in a correct way.

When using the 2.1 or higher version of the library, you might need to make some changes here. Please refer to the what's new document for more information.

If you're running your application on Blazor Server, make sure a default HttpClient is available by adding the following:

builder.Services.AddHttpClient();

Using the FluentUI Web Components

With the package installed and the script configured, you can begin using the Fluent UI Web Components in the same way as any other Blazor component. Just be sure to add the following using statement to your views:

@using Microsoft.Fast.Components.FluentUI

Here's a small example of a FluentCard with a FluentButton that uses the Fluent "Accent" appearance:

@using Microsoft.Fast.Components.FluentUI

<FluentCard>
  <h2>Hello World!</h2>
  <FluentButton Appearance="@Appearance.Accent">Click Me</FluentButton>
</FluentCard>

💡 Tip

You can add @using Microsoft.Fast.Components.FluentUI to the namespace collection in _Imports.razor, so you don't have to add it to every razor page that uses one of the components.

Configuring the Design System

The Fluent UI Web Components are built on FAST's Adaptive UI technology, which enables design customization and personalization, while automatically maintaining accessibility. This is accomplished through setting various "Design Tokens". The library exposes all of the (over 160) Design Tokens, which you can use both from code as in a declarative way in your .razor pages. See https://docs.microsoft.com/en-us/fluent-ui/web-components/design-system/design-tokens for more information on how Design Tokens work

Option 1: Using Design Tokens from C# code

Given the following .razor page fragment:

<FluentButton @ref="ref1" Appearance="Appearance.Filled">A button</FluentButton>
<FluentButton @ref="ref2" Appearance="Appearance.Filled">Another button</FluentButton>
<FluentButton @ref="ref3" Appearance="Appearance.Filled">And one more</FluentButton>
<FluentButton @ref="ref4" Appearance="Appearance.Filled" @onclick=OnClick>Last button</FluentButton>

You can use Design Tokens to manipulate the styles from C# code as follows:

[Inject]
private BaseLayerLuminance BaseLayerLuminance { get; set; } = default!;

[Inject]
private AccentBaseColor AccentBaseColor { get; set; } = default!;

[Inject]
private BodyFont BodyFont { get; set; } = default!;

[Inject]
private StrokeWidth StrokeWidth { get; set; } = default!;

[Inject]
private ControlCornerRadius ControlCornerRadius { get; set; } = default!;

private FluentButton? ref1;
private FluentButton? ref2;
private FluentButton? ref3;
private FluentButton? ref4;

protected override async Task OnAfterRenderAsync(bool firstRender)
{
	if (firstRender)
	{
		//Set to dark mode
		await BaseLayerLuminance.SetValueFor(ref1!.Element, (float)0.15);

		//Set to Excel color
		await AccentBaseColor.SetValueFor(ref2!.Element, "#185ABD".ToSwatch());

		//Set the font
		await BodyFont.SetValueFor(ref3!.Element, "Comic Sans MS");

		//Set 'border' width for ref4
		await StrokeWidth.SetValueFor(ref4!.Element, 7);
		//And change conrner radius as well
		await ControlCornerRadius.SetValueFor(ref4!.Element, 15);

		StateHasChanged();
	}
}

public async Task OnClick()
{
	//Remove the wide border
	await StrokeWidth.DeleteValueFor(ref4!.Element);
}

As can be seen in the code above (with the ref4.Element), it is possible to apply multiple tokens to the same component.

For Design Tokens that work with a color value, you must call the ToSwatch() extension method on a string value or use one of the Swatch constructors. This makes sure the color is using a format that Design Tokens can handle. A Swatch has a lot of commonality with the System.Drawing.Color struct. Instead of the values of the components being between 0 and 255, in a Swatch they are expressed as a value between 0 and 1.

📓 Note

The Design Tokens are manipulated through JavaScript interop working with an ElementReference. There is no JavaScript element until after the component is rendered. This means you can only work with the Design Tokens from code after the component has been rendered in OnAfterRenderAsync and not in any earlier lifecycle methods.

Option 2: Using Design Tokens as components

The Design Tokens can also be used as components in a .razor page directely. It looks like this:

<BaseLayerLuminance Value="(float?)0.15">
	<FluentCard BackReference="@context">
		<div class="contents">
			Dark
			<FluentButton Appearance="Appearance.Accent">Accent</FluentButton>
			<FluentButton Appearance="Appearance.Stealth">Stealth</FluentButton>
			<FluentButton Appearance="Appearance.Outline">Outline</FluentButton>
			<FluentButton Appearance="Appearance.Lightweight">Lightweight</FluentButton>
		</div>
	</FluentCard>
</BaseLayerLuminance>

To make this work, a link needs to be created between the Design Token component and its child components. This is done with the BackReference="@context" construct.

📓 Note

Only one Design Token component at a time can be used this way. If you need to set more tokens, use the code approach as described in Option 1 above.

Option 3: Using the <FluentDesignSystemProvider>

The third way to customize the design in Blazor is to wrap the entire block you want to manipulate in a <FluentDesignSystemProvider>. This special element has a number of properties you can set to configure a subset of the tokens. Not all tokens are available/supported and we recommend this to only be used as a fall-back mechanism. The preferred method of working with the design tokens is to manipulate them from code as described in option 1.

Here's an example of changing the "accent base color" and switching the system into dark mode (in the file app.razor):

<FluentDesignSystemProvider AccentBaseColor="#464EB8" BaseLayerLuminance="0">
	<Router AppAssembly="@typeof(App).Assembly">
		<Found Context="routeData">
			<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
		</Found>
		<NotFound>
			<PageTitle>Not found</PageTitle>
			<LayoutView Layout="@typeof(MainLayout)">
				<p role="alert">Sorry, there's nothing at this address.</p>
			</LayoutView>
		</NotFound>
	</Router>
</FluentDesignSystemProvider>

📓 Note

FluentDesignSystemProvider token attributes can be changed on-the-fly like any other Blazor component attribute.

Colors for integration with specific Microsoft products

If you are configuring the components for integration into a specific Microsoft product, the following table provides AccentBaseColor values you can use. The library offers an OfficeColor enumeration which contains the specific accent colors for 17 different Office applications.

Product AccentBaseColor
Office #D83B01
Word #185ABD
Excel #107C41
PowerPoint #C43E1C
Teams #6264A7
OneNote #7719AA
SharePoint #03787C
Stream #BC1948

For a list of all available token attributes, see here. More examples for other components can be found in the examples folder of this repository.

Blazor Hybrid

Starting with the 2.0 release, you can also use this library in your Blazor Hybrid projects. Setup is almost the same as described in the "Getting started" section above, but to get everything to work you'll need to take two extra steps:

  1. You need to add a MAUI specific IStaticAssetService implementation.
    Due to some issues, this file can't be part of the library (yet) so this needs to be added manually to your MAUI Blazor project.
    Create a new class in you project called FileBasedStaticAssetService.cs Replace it's contents with the following:
using System.Net;
using Microsoft.Fast.Components.FluentUI.Infrastructure;

namespace Microsoft.Fast.Components.FluentUI;

public class FileBasedStaticAssetService : IStaticAssetService
{
	private readonly CacheStorageAccessor _cacheStorageAccessor;

	public FileBasedStaticAssetService(CacheStorageAccessor cacheStorageAccessor)
	{
		_cacheStorageAccessor = cacheStorageAccessor;
	}

	public async Task<string> GetAsync(string assetUrl, bool useCache = false)
	{
		string result = null;

		HttpRequestMessage message = CreateMessage(assetUrl);


		if (useCache)
		{
			// Get the result from the cache
			result = await _cacheStorageAccessor.GetAsync(message);
		}

		if (string.IsNullOrEmpty(result))
		{
			//It not in the cache (or cache not used), read the asset from disk
			result = await ReadData(assetUrl);

			if (!string.IsNullOrEmpty(result))
			{
				if (useCache)
				{
					// If successful, create the response and store in the cache (when used)
					HttpResponseMessage response = new()
					{
						StatusCode = HttpStatusCode.OK,
						Content = new StringContent(result)
					};

					await _cacheStorageAccessor.PutAsync(message, response);
				}
			}
		}

		return result;
	}

	private static HttpRequestMessage CreateMessage(string url) => new(HttpMethod.Get, url);

	private static async Task<string> ReadData(string file)
	{
		using var stream = await FileSystem.OpenAppPackageFileAsync($"wwwroot/{file}");
		using var reader = new StreamReader(stream);

		return await reader.ReadToEndAsync();
	}
}
  1. You need to make some changes in your MauiProgram.cs file
    Make sure the following is added before the return builder.Build() line:
builder.Services.AddFluentUIComponents(options =>
{
		options.HostingModel = BlazorHostingModel.Hybrid;
});
builder.Services.AddScoped<IStaticAssetService, FileBasedStaticAssetService>();

Use the DataGrid component with EF Core

If you want to use the FluentDataGrid with data provided through EF Core, you need to install an additional package so the grid knows how to resolve queries asynchronously for efficiency. .

Installation

Install the package by running the command:

dotnet add package Microsoft.Fast.Components.FluentUI.DataGrid.EntityFrameworkAdapter

Usage

In your Program.cs file you need to add the following after the builder.Services.AddFluentUIComponents(); line:

builder.Services.AddDataGridEntityFrameworkAdapter();

Joining the Community

Looking to get answers to questions or engage with us in real-time? Our community is most active on Discord. Submit requests and issues on GitHub, or join us by contributing on some good first issues via GitHub.

If you don't find a component you're looking for, it's best to create the issue in our FAST repo here and limit issues on this repo to bugs in the Blazor component wrappers or Blazor-specific features.

We look forward to building an amazing open source community with you!

Contact

  • Join the community and chat with us in real-time on Discord.
  • Submit requests and issues on GitHub.
  • Contribute by helping out on some of our recommended first issues on GitHub.

Additional resources