DEV Community

Cover image for Syntax Highlighting in Blazor with No JavaScript. The Story Behind Prismizor
jsakamoto
jsakamoto

Posted on

Syntax Highlighting in Blazor with No JavaScript. The Story Behind Prismizor

Have you ever seen this in a Blazor WebAssembly app? You open a page that is prerendered on the server, and the code samples on it are just plain text at first. A few moments later, after Blazor starts, the colors appear.

I really hated that moment. 😣

In this article, I'd like to tell you the story of how that small annoyance made me port Prism.js to C#, with the help of an AI coding agent. The result is "Prismizor", a syntax highlighting component for Blazor.

Before I start

Please note that there is no original idea of mine in Prismizor. The grammars, the way it tokenizes code, the HTML it makes, and the themes all come from Prism.js. I only moved them into C#.


😖 The flash of plain code

I had been using Prism.js in my Blazor apps for a long time. Prism.js is a great library.

But it works in a certain order. First, the browser shows the code block as plain text. Then, Prism.js runs and adds colors to it.

In many web apps, that gap is too short to notice. But in Blazor WebAssembly with server-side prerendering, it is not.

Let me explain why. With prerendering, the browser gets HTML from the server right away. Of course, the code block is in that HTML, but it has no colors yet. Next, the browser downloads the .NET runtime and the app. Then Blazor starts, my component renders, and only after that can it call Prism.js from OnAfterRender.

On a first visit, that can take seconds. All that time, readers have to look at plain text.

A Blazor WebAssembly page that uses Prism.js. The code block shows as plain text first, and the colors appear a few seconds later.

Yes, it works. But it doesn't look good, and I really wanted to get rid of it.


😩 And static SSR made it worse

And there was one more problem. That was static SSR, which means Blazor without interactivity.

With interactive rendering, calling Prism.js is not so bad. I can get a reference to the element with @ref, and call Prism.js in the OnAfterRenderAsync method, like the code below. As you can see, most of the code is still C#.

@inject IJSRuntime JS

<pre><code @ref="codeElement" class="language-csharp">@Code</code></pre>

@code {
    private ElementReference codeElement;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await this.JS.InvokeVoidAsync("Prism.highlightElement", this.codeElement);
    }
}
Enter fullscreen mode Exit fullscreen mode

However, static SSR has no OnAfterRender. This means there is no place in C# to call JavaScript after rendering. So everything moves to the JavaScript side. I had to think about when to run Prism.js. I also had to think about how to run it again when enhanced navigation updates the page without a full reload.

Of course, it can be done. But I chose Blazor because I wanted to build web apps in C#. Even so, I was spending my time on JavaScript. 😅


🤩 What I really wanted

So, what I really wanted became clear. I wanted a syntax highlighter that has these three things.

  • Native to Blazor. It is a Blazor component, written in C#.
  • Small on WebAssembly. It doesn't make the download much bigger.
  • Colors in the first HTML. The HTML from the server already has the colors, even in static SSR.

🔍 Surely someone has built this already

At first, I looked for existing libraries. Fortunately, there were many good ones. Unfortunately, none of them had all three things.

Most of them were wrappers around JavaScript highlighters, such as "Brism", "HighlightBlazor", and "PSC.Blazor.Components.CodeSnippet". They are handy. But they highlight code in the browser, so the HTML from the server has no colors.

I also found three libraries that run in C# only. Let me show them.

  • ColorCode.HTML from the .NET Community Toolkit supports many languages and returns HTML right away. But it is not a Blazor component, and it has not been updated since July 2023.
  • Blism is a simple and clean highlighter made for Blazor from the start. It supports five languages, and the author welcomes pull requests to add more. But I needed many languages right away, and I could not tell when my pull requests would be merged.
  • S97SP.Prism.Blazor has "Prism" in its name, but it is its own highlighter, not a direct port. It highlights code in the background, so with stream rendering, the text "Processing code..." shows first. That is very close to the problem I wanted to solve.

Of course, each of them is a fine project with its own goals. If their goals match yours, please take a look at them. They just were not what I needed.

So, nothing fit. I was stuck. 😥


💡 Wait. It's the age of AI coding agents

But, one day, an idea came to me.

Wait a minute. Why don't I just ask an AI coding agent to port Prism.js to C#?

Porting a big library like Prism.js by myself would take far too much time. But an AI coding agent could do the heavy work instead of me.


🚀 The more I thought, the better it looked

The more I thought about this idea, the better it looked to me.

First, my existing CSS would just work. A faithful port makes the same HTML as Prism.js, such as <span class="token keyword">. So the theme CSS from my old Blazor + Prism.js setup (yes, the one with the flash 😅) would work without any change.

Second, I would get every language of Prism.js as it is. That is 288 languages! Compare that with the five languages that I had found before.

In other words, I would not build a new highlighter from zero. Instead, I would bring the whole Prism.js ecosystem into Blazor, including its themes, its languages, and many years of work by its community.


🤔 But which library should I port?

But Prism.js was not the only choice. For example, "Shiki" is very popular these days. It uses the same TextMate grammars as VS Code, so code looks just like it does in the editor.

The problem is, TextMate grammars need a special regular expression engine called "Oniguruma". To run Shiki in Blazor, I would have to port Oniguruma, too. That would make the app bigger, and my "small on WebAssembly" wish would be broken.

On the other hand, the grammars of Prism.js are written with normal JavaScript regular expressions. This means they can run on the Regex class of .NET. So if your app already uses the Regex class, Prismizor adds nothing more for the regex engine.

That's why I chose Prism.js.


🔧 One rule I gave the AI

Now the direction was set. I asked the AI to do the port, and I gave it one rule that it must never break.

When you publish a Blazor WebAssembly app, IL trimming must remove the grammars of the languages that the app doesn't use.

Because 288 languages means a lot of code. If all of them went to the browser, my "small on WebAssembly" wish would be gone. I wanted the browser to load only the grammars that the app really uses.

To make this work, each language is a separate static property, such as PrismizorLanguages.CSharp. And there is no dictionary that finds a language by its name. If there were a dictionary like that, it would keep every language in the app, and the trimmer could not remove any of them.

Here is the result. The full library is 1.59 MB. But when an app uses only C#, the library file becomes 79,637 bytes, and only 8,987 bytes after Brotli compression.

⚙️ How the port works

By the way, I didn't ask the AI to translate 288 grammar files one by one. Let me explain how the port works.

  1. A Node script loads the real Prism.js 1.30.0, takes out the grammar of every language, and saves it as JSON.
  2. A C# generator reads the JSON and writes C# code for each language.
  3. Some languages use small extra programs in Prism.js, called hooks. For example, PHP inside HTML and code blocks inside Markdown need them. These hooks were ported to C# one by one.

Then, how can I know the port is right? The answer is, the tests compare the output with the real Prism.js byte by byte.

The tests run the real Prism.js to make the expected HTML. Then they give the same code to Prismizor and compare the two HTML outputs. One of the tests gives the same input to every grammar, all 289 of them (the 288 languages plus plain text). And all 328 tests pass on both .NET 10 and .NET 11.


🎉 And so, Prismizor was born

And that is how "Prismizor" was born.

Please look at the animation below. It shows Prism.js and Prismizor, side by side.

Prism.js and Prismizor side by side. With Prism.js, the code shows as plain text before the colors appear. With Prismizor, the code has colors from the start.

As you can see, there is no flash anymore. The colors are there from the very first paint.

Using it is very easy. First, add the package.

dotnet add package Toolbelt.Blazor.Prismizor
Enter fullscreen mode Exit fullscreen mode

Next, add @using Toolbelt.Blazor.Prismizor to your _Imports.razor, and link a theme CSS file. The package includes the eight themes of Prism.js.

<link rel="stylesheet" href="_content/Toolbelt.Blazor.Prismizor/themes/prism.min.css" />
Enter fullscreen mode Exit fullscreen mode

Then, give the code and the language to the CodeBlock component, like this.

<CodeBlock Code="@code" Language="@PrismizorLanguages.CSharp" />
Enter fullscreen mode Exit fullscreen mode

That's all. It works with Blazor Server, Blazor WebAssembly, and static SSR. And no JavaScript runs in the browser.

Because the HTML is the same as the one Prism.js makes, any theme made for Prism.js works, too, such as the ones in prism-themes. Do you want both light and dark? Then, just use the media attribute. It is only CSS, with no code.

<link rel="stylesheet" href="_content/Toolbelt.Blazor.Prismizor/themes/prism.min.css" media="(prefers-color-scheme: light)" />
<link rel="stylesheet" href="_content/Toolbelt.Blazor.Prismizor/themes/prism-tomorrow.min.css" media="(prefers-color-scheme: dark)" />
Enter fullscreen mode Exit fullscreen mode

By the way, the home page of Prismizor is also a Blazor WebAssembly app. It is prerendered into static HTML at publishing time with BlazorWasmPreRendering.Build. Please open it and look at the code blocks. You will see that they have colors from the first moment. And in the Try it section, you can pick a language and a theme, and see the result right away.

https://jsakamoto.github.io/Toolbelt.Blazor.Prismizor/

📝 What is different from Prism.js

But of course, it is not a perfect copy of Prism.js.

  • The plugin system of Prism.js is not supported. Plugins such as Line Numbers, Show Language, and Autoloader don't work.
  • \b and \s in the patterns follow the rules of .NET, not JavaScript. So for some non-ASCII text, the result may be different from Prism.js.

For more details, please see the README in the GitHub repository below.

https://github.com/jsakamoto/Toolbelt.Blazor.Prismizor


❤️ Thank you, Prism.js

Let me say it again. There is no originality of mine in Prismizor. Every idea in it belongs to Prism.js.

I am deeply thankful to Lea Verou and all the contributors of Prism.js. Over many years, their work built the grammars of 288 languages and the beautiful themes. Without their work, Prismizor would not exist.

And also, this was possible only because Prism.js is open source under the MIT License. Anyone can read the code, learn from it, and build on it. Thanks to that, I could bring Prism.js into Blazor in a native way. I feel this is the greatest thing about open source.

Prismizor is also released under the MIT License. If it helps you, feel free to use it, read it, and build on it, too.

Now, you can use the power of Prism.js natively in Blazor. Please give it a try!

If you have any ideas or feedback, I would be happy if you let me know in the comments on this post! 👇

❤️ Happy coding!

Top comments (0)