跳到正文
DEV Community· Jeff Tsai·· 48 分鐘前AI 評分48

Polhem.Markdown:適用於 Avalonia 和 Blazor 的 Markdown 檢視器及編輯器

Polhem.Markdown: A Markdown Viewer and Editor for Avalonia and Blazor

AI 導讀

Polhem.Markdown 是一套 .NET Markdown 套件,為 Avalonia 和 Blazor 提供檢視器及編輯器,讓兩種前端以同一文件模型呈現 Markdown。版本 0.3.1 支援 GitHub Flavored Markdown、語法高亮、Mermaid 圖表和數學公式,並內置安全規則;專案以 MIT 授權開源。

正文

The same text renders the same way in both front ends, with no extra syntax packages to install

This post is based on version 0.3.1. The packages are still 0.x, so a minor release may still change the API; any change will be noted in the CHANGELOG.

Polhem.Markdown is a set of Markdown packages for .NET. It provides two components each for Avalonia and Blazor:

  • MarkdownViewer: displays Markdown, with support for GitHub Flavored Markdown, syntax highlighting, Mermaid diagrams and math.
  • MarkdownEditor: edits the Markdown source, with a MarkdownViewer next to it for a live preview.

My project has Avalonia desktop and mobile apps as well as a Blazor web front end, and both need to display Markdown replies from AI. My first plan was to pick an existing package for each side. But two packages parse on their own and decide on their own how things look, so the same text ends up looking different in the two front ends, and the security rules have to be written twice. So I decided to build my own set.

The source is on GitHub under the MIT license. It does not depend on the Polhem framework, so other projects can use it directly.

The same reply in the Blazor and Avalonia viewers


1️⃣ The packages

Package Contents
Polhem.Markdown Parses with Markdig, converts the result into its own document model, and applies the security policy
Polhem.Markdown.Avalonia The MarkdownViewer and MarkdownEditor controls for Avalonia
Polhem.Markdown.Blazor The MarkdownViewer and MarkdownEditor components for Blazor

An application references only the package for its own front end, and Polhem.Markdown comes along with it:

dotnet add package Polhem.Markdown.Avalonia
dotnet add package Polhem.Markdown.Blazor

The target framework is net10.0, and the Avalonia side uses Avalonia 12.


2️⃣ How it differs from similar packages

In November 2026, I looked through the open-source Markdown packages for Avalonia and Blazor on NuGet and read the source of a few of the more downloaded ones. There are plenty of viewers that support a single front end. Here is what this set deliberately does differently.

Both front ends draw the same model

I did not find an open-source package that supports both Avalonia and Blazor. With one package on each side, the parser, the supported syntax and the handling of unrecognized syntax may all differ.

The core package of Polhem.Markdown converts Markdig's syntax tree into its own model, and both viewers draw only that model. Tests guard this too: each side takes the same sample text, which covers every node, and checks that every kind of node is drawn (including the shapes of Mermaid diagrams and the parts of math formulas). If the model gains a node and one viewer does not keep up, its tests fail, so new syntax cannot show up on only one side.

Also, Markdig's types do not appear in the public API, which is also checked by a test, so switching parsers later would not affect consumers.

Syntax is built into the main package, and Blazor loads no third-party scripts

A common approach is for the main package to handle only the basic syntax, with Mermaid, math and syntax highlighting in separate extension packages. On the Blazor side, scripts such as mermaid.js and highlight.js are usually loaded in the browser.

This set puts all of it in the main package. The viewers lay out and draw Mermaid flowcharts and sequence diagrams themselves. Math is parsed once in the core; Blazor outputs MathML, which browsers support natively, and Avalonia does its own layout (the reasons are in ADR-002). Syntax highlighting is also done in C#.

So the Blazor viewer does not need to load any third-party scripts, and there is no CDN that might be unreachable. Only browser operations such as scrolling to a heading or copying code go through Blazor's JS interop.

A built-in security policy

What the viewer displays is mostly replies from AI models, and a model's output can be steered by a third party (for example, through instructions hidden in a web page it read). So the links, images and HTML in the text have to be treated as untrusted input.

A common approach on the Blazor side is to put the HTML produced by Markdig straight into the page. Raw HTML embedded in the Markdown is output as well, and links starting with javascript: can still be clicked. This set puts the rules in the core package, and both viewers apply the same ones:

  • Raw HTML is limited to a small allowlist. <div align>, <details>, <sup>, <kbd>, <img> and <picture>, which READMEs commonly use, are converted into nodes in the model. All other HTML is dropped, and <script> is removed together with its content.
  • Link schemes have an allowlist. By default, only http, https and mailto links can be clicked.
  • Image schemes have an allowlist too. By default, only https images are loaded.

The allowlists and the base for relative URLs are set in MarkdownOptions. For example, to resolve relative links against the document's own URL and allow local images:

viewer.Options = new MarkdownOptions
{
    BaseUri = new Uri("https://example.com/docs/"),
    AllowedImageSchemes = { "file" },
};

SVG images are the one place where the two sides deliberately differ. Blazor hands them to the browser, where scripts inside an SVG do not run. Avalonia has no browser, so an SVG has to be decoded inside the application's own process. A review found that a crafted SVG could overflow the renderer's stack and terminate the app outright, without even an exception to catch. So the Avalonia version only draws SVGs from trusted badge services (the badges commonly seen on READMEs); the reasons are in ADR-001.

The editor and the viewer share the same parse

Markdown editors are not rare, but the widely downloaded open-source packages mostly do either the viewer or the editor. Those with an editor usually highlight the source with a separate set of rules, which does not always agree with how the preview parses it.

The editor in this set highlights according to the viewer's interpretation: whatever the editor marks as a heading is a heading in the preview. Every node in the model records its position in the source, so the editor and the preview can scroll together, and Ctrl-clicking (Command on macOS) in the preview jumps back to the source.

The Blazor editor does not wrap a JavaScript editor. It uses a native <textarea> for input and draws the colors behind it, so IME input (for Chinese, for example) and screen readers behave the same as in any other input box on the page.

Streaming and publishing

AI replies arrive in chunks. Each time a chunk arrives, just set the Markdown property again. The viewer compares the source and rebuilds only the blocks that changed, so the display does not flash as a whole, and no separate Append API is needed.

On the publishing side, CI publishes and runs the core package's test program with Native AOT, and also publishes the Blazor WebAssembly sample with trimming (removing unused code at publish time). If a change stops working after trimming, the build fails. The Avalonia sample also has an iOS version that runs on the simulator.


3️⃣ Supported Markdown syntax

The goal is to match how GitHub displays .md files. Both viewers support every item in the table below:

Syntax How it is written or what it does
Headings, emphasis, blockquotes, lists, thematic breaks CommonMark
Strikethrough ~~text~~
Task lists - [x] done
Tables with column alignment :--, :-:, --:
Footnotes text[^note]
GitHub alerts > [!NOTE], [!TIP], [!IMPORTANT], [!WARNING], [!CAUTION]
Emoji shortcodes :wave:
YAML front matter Hidden, not displayed
Links to headings [setup](#setup) scrolls to that heading
Code blocks Show the language and a copy button, with syntax highlighting for common languages such as C#, JSON, SQL, XML, JavaScript and Python
Mermaid diagrams Flowcharts and sequence diagrams; other types are shown as code
Math Inline $…$, and display $$…$$ or fenced code blocks tagged math; amounts of money in the text (such as $100) stay as text
HTML commonly used in READMEs <div align>, <details>, <sup>, <kbd>, <img>, <picture>; other HTML is dropped
Images Only https by default; on Avalonia, SVG is limited to trusted badge hosts

Code blocks are readable in both the light and dark themes:

A table and syntax highlighting in the dark theme

Mermaid labels can be in Chinese:

A flowchart and a sequence diagram with Chinese labels

Math supports fractions, sums, piecewise functions and matrices:

Inline math, fractions, sums, piecewise functions and matrices

HTML commonly used in READMEs is turned into content, while <script> is removed:

Centered text, an expandable section, a removed script and footnotes


4️⃣ MarkdownViewer

Avalonia

<Window xmlns:md="using:Polhem.Markdown.Avalonia">
  <md:MarkdownViewer Markdown="{Binding Reply}" LinkActivated="OnLinkActivated" />
</Window>
private void OnLinkActivated(object? sender, MarkdownLinkActivatedEventArgs e)
{
    OpenInApp(e.Uri);
    e.Handled = true;
}

When a link is clicked, the viewer raises the LinkActivated event and the application decides what to do, for example open a form inside the app. If the event is not handled (Handled is not true), the link is opened by the operating system.

If the text contains Chinese, set CjkFontFamily. When Chinese and English are mixed, Avalonia may render bold Chinese at regular weight (AvaloniaUI/Avalonia#18199). Specifying a Chinese font keeps it bold:

<md:MarkdownViewer Markdown="{Binding Reply}"
                   CjkFontFamily="PingFang TC, Microsoft JhengHei UI, Noto Sans CJK TC" />

The default colors work in both the light and dark themes. To match your own theme, set brush properties such as LinkForeground and CodeBackground.

Blazor

Add the stylesheet to the host page:

<link rel="stylesheet" href="_content/Polhem.Markdown.Blazor/polhem-markdown.css" />
@using Polhem.Markdown.Blazor

<MarkdownViewer Markdown="@reply" />

@code {
    private string reply = "# Hello";
}

Without OnLinkActivated, links open in a new tab. Once it is set, clicks are handed to your handler.

The font and text color follow the surrounding page. The other colors and fonts are --pmd-* CSS variables; the full list and defaults are at the top of polhem-markdown.css:

.pmd {
  --pmd-link: #0969da;
  --pmd-code-font: "JetBrains Mono", monospace;
}

The Polhem framework's Blazor front end comes in a MudBlazor version and a Fluent UI version. Each version's stylesheet maps these variables to its theme's colors, so the same component fits into both looks.


5️⃣ MarkdownEditor

The editor edits the source; it is not WYSIWYG. Place it side by side with a MarkdownViewer and you have an editing screen with a live preview. The editors on the two front ends behave the same:

  • Toolbar: bold, italic, strikethrough, inline code, link, image, heading, list, task list, blockquote, code block, table and thematic break, plus undo and redo. The labels are in English by default; you can replace them, for example with Chinese, or turn the toolbar off and put your own buttons there.
  • Shortcuts and list keys: Ctrl (Command on macOS) with B, I, K or E toggles inline formatting; Enter continues a list, and Tab and Shift+Tab change an item's level.
  • Line numbers: shown by default.
  • Sync with the viewer: they scroll together, and you can jump from the preview back to the source; see the next section for how.

Avalonia

The sample text in the editor, next to the viewer that renders it

<Grid ColumnDefinitions="*,*">
  <md:MarkdownEditor x:Name="Editor" Markdown="{Binding Text}" />
  <md:MarkdownViewer Grid.Column="1" Markdown="{Binding Text}" />
</Grid>

Formatting commands can also be called from code, for example from your own menu:

Editor.ApplyFormat(MarkdownFormat.Bold);   // toggles bold on the selection, same as Ctrl+B
Editor.CycleHeading();                     // plain text → # → ## → ### → plain text

Replacing the toolbar labels with Chinese:

Editor.ToolbarLabels = item => item switch
{
    MarkdownToolbarItem.Bold => "粗體",
    MarkdownToolbarItem.Italic => "斜體",
    _ => null,   // null keeps the default label
};

The Avalonia version is built on AvaloniaEdit. The editor brings the styles it needs, so it works with any theme.

Blazor

The sample text in the Blazor editor in a browser, next to the viewer

<div style="display: grid; grid-template-columns: 1fr 1fr; height: 30rem">
    <MarkdownEditor @ref="editor" @bind-Markdown="text" aria-label="Markdown source" />
    <MarkdownViewer Markdown="@text" />
</div>

@code {
    private MarkdownEditor editor = default!;
    private string text = "# Hello";

    // Toggles bold on the selection, same as Ctrl+B
    private Task Bold() => editor.ApplyFormatAsync(MarkdownFormat.Bold);
}

The Blazor formatting commands are asynchronous (ApplyFormatAsync, CycleHeadingAsync), and the toolbar labels are replaced through ToolbarLabels in the same way.

Because the colors are drawn behind the <textarea> and must line up with its text, --pmd-code-font has to stay a monospace font. The editor fills the height its container gives it and works in all three render modes: interactive server, WebAssembly and auto. There is no search panel yet.


6️⃣ Connecting the editor and the viewer

The editor and the viewer are two independent components, and the application wires them together. These are the things to handle:

  • Updating the preview: hand the editor's text to the viewer. Updating on every keystroke works, but if you wait until typing pauses, the viewer does not have to rebuild on every key.
  • Synchronized scrolling: both sides report which position in the source (a character offset) is at the top of the view, and both can scroll to a given source position. When one side scrolls, pass its position to the other.
  • Jumping back to the source: when you Ctrl-click (Command on macOS) in the preview, the viewer raises an event carrying the source position of that content, and the application moves the editor's caret there.

Synchronized scrolling has one catch: if A's scrolling moves B, B's scrolling reports a position again, and both sides accept everything, they end up pulling each other back and forth. The samples let only the side under the mouse pointer, or the side with keyboard focus, drive the other.

Avalonia

The Avalonia viewer does not scroll by itself; the enclosing ScrollViewer does. So the viewer provides conversions: GetVerticalOffset turns a source position into a Y coordinate inside the viewer, and GetSourceOffset does the reverse.

var viewerScroll = new ScrollViewer { Content = viewer };

// Editor scrolls → the viewer follows
editor.PropertyChanged += (_, e) =>
{
    if (e.Property == MarkdownEditor.FirstVisibleSourceOffsetProperty && EditorLeads()
        && viewer.GetVerticalOffset(editor.FirstVisibleSourceOffset) is { } y)
    {
        viewerScroll.Offset = new Vector(viewerScroll.Offset.X, y);
    }
};

// Viewer scrolls → the editor follows
viewerScroll.ScrollChanged += (_, _) =>
{
    if (!EditorLeads() && viewer.GetSourceOffset(viewerScroll.Offset.Y) is { } offset)
    {
        editor.ScrollToSourceOffset(offset);
    }
};

// Ctrl- or Command-click in the preview → the editor moves to that source
viewer.SourceRequested += (_, e) =>
{
    editor.CaretOffset = e.SourceOffset;
    editor.ScrollToSourceOffset(e.SourceOffset);
    editor.Focus();
    e.Handled = true;
};

bool EditorLeads() => !viewerScroll.IsPointerOver && (editor.IsPointerOver || editor.IsKeyboardFocusWithin);

This assumes the viewer sits directly inside the ScrollViewer. If a container with padding, such as a Border, sits in between, convert the coordinates with TranslatePoint as well; the full version is in samples/MarkdownGallery/SourceSync.cs in the repo.

Blazor

The Blazor viewer finds the nearest scrolling area around it by itself (or uses the whole page if there is none). Both components report their position through FirstVisibleSourceOffsetChanged and scroll to a given position with ScrollToSourceOffsetAsync, so the wiring is symmetric:

<div @onpointerenter="() => leader = Pane.Editor" @onfocusin="() => leader = Pane.Editor">
    <MarkdownEditor @ref="editor" @bind-Markdown="text" aria-label="Markdown source"
                    FirstVisibleSourceOffsetChanged="EditorScrolled" />
</div>
<div @onpointerenter="() => leader = Pane.Viewer" @onfocusin="() => leader = Pane.Viewer">
    <MarkdownViewer @ref="viewer" Markdown="@text"
                    FirstVisibleSourceOffsetChanged="ViewerScrolled" OnSourceRequested="GoToSource" />
</div>

@code {
    private enum Pane { Editor, Viewer }

    private MarkdownEditor? editor;
    private MarkdownViewer? viewer;
    private Pane leader = Pane.Editor;
    private string text = "# Hello";

    private async Task EditorScrolled(int offset)
    {
        if (leader == Pane.Editor && viewer is not null)
            await viewer.ScrollToSourceOffsetAsync(offset);
    }

    private async Task ViewerScrolled(int offset)
    {
        if (leader == Pane.Viewer && editor is not null)
            await editor.ScrollToSourceOffsetAsync(offset);
    }

    private async Task GoToSource(MarkdownSourceRequestedEventArgs e)
    {
        if (editor is null) return;
        leader = Pane.Editor;
        await editor.SetCaretOffsetAsync(e.SourceOffset);
        await editor.ScrollToSourceOffsetAsync(e.SourceOffset);
        await editor.FocusAsync();
    }
}

To keep the example short, it uses @bind-Markdown, so the preview updates on every keystroke. For the version that waits until typing has paused for 150 milliseconds, see samples/MarkdownGallery.Blazor/Components/GalleryPage.razor in the repo.


7️⃣ Samples

The samples/ folder in the repo has three versions of the same Gallery: Avalonia desktop, Blazor Server and Blazor WebAssembly. The Gallery lists every kind of node, can switch between light and dark themes, and can "replay": it types the text out in chunks to simulate a streaming reply. Turn on the Edit switch and the editor appears next to the viewer.

git clone https://github.com/polhem-dev/polhem-markdown.git
cd polhem-markdown
dotnet run --project samples/MarkdownGallery.Desktop
dotnet run --project samples/MarkdownGallery.Blazor

✅ Conclusion

If your application has both Avalonia and Blazor front ends, or needs to display Markdown from untrusted sources (such as AI replies) without loading Mermaid or MathJax scripts into the page, give this set a try.

It is not the right fit for every project, though. The known limitations right now:

  • Only the syntax and HTML listed above are supported; all other HTML is dropped. For documents that need full HTML, displaying them in a browser is a better fit.
  • Mermaid supports only flowcharts and sequence diagrams.
  • The Avalonia viewer cannot yet select text across blocks (#1). For now each block is selectable on its own, and code blocks have a copy button.
  • The editor has no WYSIWYG mode and no export feature, and the Blazor editor does not have a search panel yet.

The packages are still 0.x, and the API may still change. Feel free to try them, and if you have any questions or suggestions, open an issue on GitHub.

Further reading


📘 Original article on HackMD, in Traditional Chinese:
👉 https://hackmd.io/@jeff377/polhem-markdown

📢 You are welcome to republish this, please credit the source.
📬 Follow for more engineering notes:
Facebook | HackMD | GitHub | NuGet

來源:DEV Community · dev.to