Color Scheme Preference Detector

blazor wasm

The Color Scheme Preference Detector is a Nuget library that I recently developed to make it easy to tell if a user prefers dark or light themes, which I saw could be used with Blazor. Here is a small article to explain its origin and operation.

The origin of the idea of the library

The idea for this library came to me while reading a article by Scott Hanselman. In his article, which I recommend you read, Scott mentioned how he checked user preferences for the theme (dark or light) with a few lines of Javascript. After answering him on Twitter that this would make a good library to use with Blazor via interop, he simply replied with a gif that said "Do it". Shortly after that evening, the library was available on Github and Nuget!

Operation

To check user preferences, we can use the media queryprefers-color-scheme", which lets you know if the user prefers a dark or light theme. Still inspired by Scott's article, I created a Razor Class Library with this simple file Javascript who takes care of checking:

The operation is therefore rather simple, we start by checking if the browser supports the function matchMedia, otherwise we return a default value for a light theme. If it supports it, which is the case for recent browsers, we check the preference of the media query to return true / false depending on preference towards the dark theme.

Interop for use with Blazor

The next step was to have an interface, which would be injected where necessary, with the class that takes care of calling the method of the JavaScript module. In the end, we end up with this class to do this work:

You can see here that I used JavaScript isolation with a module, so the JavaScript function prefersDarkMode is not a global method available everywhere. And so with this in place, all you need to do to use this function is inject the interface IColorSchemePreferenceDetector where it is needed.

Conclusion

As you may have noticed, it's very easy to develop a class that interops with JavaScript, which ultimately allows us to hide this layer when using with Blazor. I leave you the links to the Nuget library, the sources on Github, if you ever want to consult or use them. If you have any other cool library ideas like this that might be useful, please let me know, this just might be the next library I am developing!

Nuget: https://www.nuget.org/packages/BracketShow.ColorSchemePreferenceDetector/

Github: https://github.com/BracketShow/ColorSchemePreferenceDetector

Bruno

Author: Bruno

By day, I am a developer, team leader and co-host of the Bracket Show. By evening, I am a husband and the father of two wonderful children. The time I have left after all of this I spend trying to get moving, playing and writing video game reviews, as well as preparing material for the Bracket Show recordings and for this blog. Through it all, I am also passionate about music and microbreweries.