{"slug": "polhem-markdown-a-markdown-viewer-and-editor-for-avalonia-and-blazor", "title": "Polhem.Markdown: A Markdown Viewer and Editor for Avalonia and Blazor", "summary": "A developer released Polhem.Markdown, an MIT-licensed set of .NET Markdown packages that provide matching MarkdownViewer and MarkdownEditor components for both Avalonia and Blazor, built on Markdig and a shared document model. The core package parses Markdown and applies a single security policy, while the viewers render GitHub Flavored Markdown, Mermaid diagrams, math and syntax highlighting entirely in C#, so the Blazor side loads no third-party scripts or CDN assets. Tests verify that every document-model node renders on both front ends, and that Markdig types stay out of the public API.", "body_md": "The same text renders the same way in both front ends, with no extra syntax packages to install\n\nThis 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](https://github.com/polhem-dev/polhem-markdown/blob/main/CHANGELOG.md).\n\nPolhem.Markdown is a set of Markdown packages for .NET. It provides two components each for Avalonia and Blazor:\n\n`MarkdownViewer`: displays Markdown, with support for GitHub Flavored Markdown, syntax highlighting, Mermaid diagrams and math.`MarkdownEditor`: edits the Markdown source, with a 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.\n\nThe source is on [GitHub](https://github.com/polhem-dev/polhem-markdown) under the MIT license. It does not depend on the [Polhem framework](https://github.com/polhem-dev/polhem), so other projects can use it directly.\n\n| Package | Contents | \n|---|---|\n| [Polhem.Markdown](https://www.nuget.org/packages/Polhem.Markdown) | Parses with [Markdig](https://github.com/xoofx/markdig) , converts the result into its own document model, and applies the security policy | \n| [Polhem.Markdown.Avalonia](https://www.nuget.org/packages/Polhem.Markdown.Avalonia) | The `MarkdownViewer` and`MarkdownEditor` controls for Avalonia | \n| [Polhem.Markdown.Blazor](https://www.nuget.org/packages/Polhem.Markdown.Blazor) | The `MarkdownViewer` and`MarkdownEditor` components for Blazor | \n\nAn application references only the package for its own front end, and `Polhem.Markdown` comes along with it:\n\n```\ndotnet add package Polhem.Markdown.Avalonia\ndotnet add package Polhem.Markdown.Blazor\n```\n\nThe target framework is `net10.0`, and the Avalonia side uses Avalonia 12.\n\nIn 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.\n\nI 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.\n\nThe 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.\n\nAlso, 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.\n\nA 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.\n\nThis 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](https://github.com/polhem-dev/polhem-markdown/blob/main/maintainers/adr/adr-002-math-one-structure-two-layouts.md)). Syntax highlighting is also done in C#.\n\nSo 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.\n\nWhat 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.\n\nA 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:\n\n`<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.`http`, `https` and `mailto` links can be clicked.\nThe 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:\n\n```\nviewer.Options = new MarkdownOptions\n{\n    BaseUri = new Uri(\"https://example.com/docs/\"),\n    AllowedImageSchemes = { \"file\" },\n};\n```\n\nSVG 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](https://github.com/polhem-dev/polhem-markdown/blob/main/maintainers/adr/adr-001-svg-from-trusted-hosts.md).\n\nMarkdown 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.\n\nThe 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.\n\nThe 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.\n\nAI 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.\n\nOn 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.\n\nThe goal is to match how GitHub displays `.md` files. Both viewers support every item in the table below:\n\n| Syntax | How it is written or what it does | \n|---|---|\n| Headings, emphasis, blockquotes, lists, thematic breaks | CommonMark | \n| Strikethrough | `~~text~~` | \n| Task lists | `- [x] done` | \n| Tables with column alignment | `:--` ,`:-:` ,`--:` | \n| Footnotes | `text[^note]` | \n| GitHub alerts | `> [!NOTE]` ,`[!TIP]` ,`[!IMPORTANT]` ,`[!WARNING]` ,`[!CAUTION]` | \n| Emoji shortcodes | `:wave:` | \n| YAML front matter | Hidden, not displayed | \n| Links to headings | `[setup](#setup)` scrolls to that heading | \n| Code blocks | Show the language and a copy button, with syntax highlighting for common languages such as C#, JSON, SQL, XML, JavaScript and Python | \n| Mermaid diagrams | Flowcharts and sequence diagrams; other types are shown as code | \n| Math | Inline `$…$` , and display`$$…$$` or fenced code blocks tagged`math` ; amounts of money in the text (such as`$100` ) stay as text | \n| HTML commonly used in READMEs | `<div align>` ,`<details>` ,`<sup>` ,`<kbd>` ,`<img>` ,`<picture>` ; other HTML is dropped | \n| Images | Only `https` by default; on Avalonia, SVG is limited to trusted badge hosts | \n\nCode blocks are readable in both the light and dark themes:\n\nMermaid labels can be in Chinese:\n\nMath supports fractions, sums, piecewise functions and matrices:\n\nHTML commonly used in READMEs is turned into content, while `<script>` is removed:\n\n```\n<Window xmlns:md=\"using:Polhem.Markdown.Avalonia\">\n  <md:MarkdownViewer Markdown=\"{Binding Reply}\" LinkActivated=\"OnLinkActivated\" />\n</Window>\nprivate void OnLinkActivated(object? sender, MarkdownLinkActivatedEventArgs e)\n{\n    OpenInApp(e.Uri);\n    e.Handled = true;\n}\n```\n\nWhen 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.\n\nIf the text contains Chinese, set `CjkFontFamily`. When Chinese and English are mixed, Avalonia may render bold Chinese at regular weight ([AvaloniaUI/Avalonia#18199](https://github.com/AvaloniaUI/Avalonia/issues/18199)). Specifying a Chinese font keeps it bold:\n\n```\n<md:MarkdownViewer Markdown=\"{Binding Reply}\"\n                   CjkFontFamily=\"PingFang TC, Microsoft JhengHei UI, Noto Sans CJK TC\" />\n```\n\nThe default colors work in both the light and dark themes. To match your own theme, set brush properties such as `LinkForeground` and `CodeBackground`.\n\nAdd the stylesheet to the host page:\n\n```\n<link rel=\"stylesheet\" href=\"_content/Polhem.Markdown.Blazor/polhem-markdown.css\" />\n@using Polhem.Markdown.Blazor\n\n<MarkdownViewer Markdown=\"@reply\" />\n\n@code {\n    private string reply = \"# Hello\";\n}\n```\n\nWithout `OnLinkActivated`, links open in a new tab. Once it is set, clicks are handed to your handler.\n\nThe 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`:\n\n```\n.pmd {\n  --pmd-link: #0969da;\n  --pmd-code-font: \"JetBrains Mono\", monospace;\n}\n```\n\nThe 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.\n\nThe 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:\n\n```\n<Grid ColumnDefinitions=\"*,*\">\n  <md:MarkdownEditor x:Name=\"Editor\" Markdown=\"{Binding Text}\" />\n  <md:MarkdownViewer Grid.Column=\"1\" Markdown=\"{Binding Text}\" />\n</Grid>\n```\n\nFormatting commands can also be called from code, for example from your own menu:\n\n```\nEditor.ApplyFormat(MarkdownFormat.Bold);   // toggles bold on the selection, same as Ctrl+B\nEditor.CycleHeading();                     // plain text → # → ## → ### → plain text\n```\n\nReplacing the toolbar labels with Chinese:\n\n``` js\nEditor.ToolbarLabels = item => item switch\n{\n    MarkdownToolbarItem.Bold => \"粗體\",\n    MarkdownToolbarItem.Italic => \"斜體\",\n    _ => null,   // null keeps the default label\n};\n```\n\nThe Avalonia version is built on [AvaloniaEdit](https://github.com/AvaloniaUI/AvaloniaEdit). The editor brings the styles it needs, so it works with any theme.\n\n```\n<div style=\"display: grid; grid-template-columns: 1fr 1fr; height: 30rem\">\n    <MarkdownEditor @ref=\"editor\" @bind-Markdown=\"text\" aria-label=\"Markdown source\" />\n    <MarkdownViewer Markdown=\"@text\" />\n</div>\n\n@code {\n    private MarkdownEditor editor = default!;\n    private string text = \"# Hello\";\n\n    // Toggles bold on the selection, same as Ctrl+B\n    private Task Bold() => editor.ApplyFormatAsync(MarkdownFormat.Bold);\n}\n```\n\nThe Blazor formatting commands are asynchronous (`ApplyFormatAsync`, `CycleHeadingAsync`), and the toolbar labels are replaced through `ToolbarLabels` in the same way.\n\nBecause 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.\n\nThe editor and the viewer are two independent components, and the application wires them together. These are the things to handle:\n\nSynchronized 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.\n\nThe 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.\n\n``` js\nvar viewerScroll = new ScrollViewer { Content = viewer };\n\n// Editor scrolls → the viewer follows\neditor.PropertyChanged += (_, e) =>\n{\n    if (e.Property == MarkdownEditor.FirstVisibleSourceOffsetProperty && EditorLeads()\n        && viewer.GetVerticalOffset(editor.FirstVisibleSourceOffset) is { } y)\n    {\n        viewerScroll.Offset = new Vector(viewerScroll.Offset.X, y);\n    }\n};\n\n// Viewer scrolls → the editor follows\nviewerScroll.ScrollChanged += (_, _) =>\n{\n    if (!EditorLeads() && viewer.GetSourceOffset(viewerScroll.Offset.Y) is { } offset)\n    {\n        editor.ScrollToSourceOffset(offset);\n    }\n};\n\n// Ctrl- or Command-click in the preview → the editor moves to that source\nviewer.SourceRequested += (_, e) =>\n{\n    editor.CaretOffset = e.SourceOffset;\n    editor.ScrollToSourceOffset(e.SourceOffset);\n    editor.Focus();\n    e.Handled = true;\n};\n\nbool EditorLeads() => !viewerScroll.IsPointerOver && (editor.IsPointerOver || editor.IsKeyboardFocusWithin);\n```\n\nThis 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.\n\nThe 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:\n\n``` js\n<div @onpointerenter=\"() => leader = Pane.Editor\" @onfocusin=\"() => leader = Pane.Editor\">\n    <MarkdownEditor @ref=\"editor\" @bind-Markdown=\"text\" aria-label=\"Markdown source\"\n                    FirstVisibleSourceOffsetChanged=\"EditorScrolled\" />\n</div>\n<div @onpointerenter=\"() => leader = Pane.Viewer\" @onfocusin=\"() => leader = Pane.Viewer\">\n    <MarkdownViewer @ref=\"viewer\" Markdown=\"@text\"\n                    FirstVisibleSourceOffsetChanged=\"ViewerScrolled\" OnSourceRequested=\"GoToSource\" />\n</div>\n\n@code {\n    private enum Pane { Editor, Viewer }\n\n    private MarkdownEditor? editor;\n    private MarkdownViewer? viewer;\n    private Pane leader = Pane.Editor;\n    private string text = \"# Hello\";\n\n    private async Task EditorScrolled(int offset)\n    {\n        if (leader == Pane.Editor && viewer is not null)\n            await viewer.ScrollToSourceOffsetAsync(offset);\n    }\n\n    private async Task ViewerScrolled(int offset)\n    {\n        if (leader == Pane.Viewer && editor is not null)\n            await editor.ScrollToSourceOffsetAsync(offset);\n    }\n\n    private async Task GoToSource(MarkdownSourceRequestedEventArgs e)\n    {\n        if (editor is null) return;\n        leader = Pane.Editor;\n        await editor.SetCaretOffsetAsync(e.SourceOffset);\n        await editor.ScrollToSourceOffsetAsync(e.SourceOffset);\n        await editor.FocusAsync();\n    }\n}\n```\n\nTo 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.\n\nThe `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.\n\n```\ngit clone https://github.com/polhem-dev/polhem-markdown.git\ncd polhem-markdown\ndotnet run --project samples/MarkdownGallery.Desktop\ndotnet run --project samples/MarkdownGallery.Blazor\n```\n\nIf 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.\n\nIt is not the right fit for every project, though. The known limitations right now:\n\nThe 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.\n\n📘 Original article on HackMD, in Traditional Chinese:\n\n👉 [https://hackmd.io/@jeff377/polhem-markdown](https://hackmd.io/@jeff377/polhem-markdown)\n\n📢 You are welcome to republish this, please credit the source.\n\n📬 Follow for more engineering notes:\n\n[Facebook](https://www.facebook.com/profile.php?id=61574839666569) ｜ [HackMD](https://hackmd.io/@jeff377) ｜ [GitHub](https://github.com/jeff377) ｜ [NuGet](https://www.nuget.org/profiles/jeff377)", "url": "https://wpnews.pro/news/polhem-markdown-a-markdown-viewer-and-editor-for-avalonia-and-blazor", "canonical_source": "https://dev.to/jeff377/polhemmarkdown-a-markdown-viewer-and-editor-for-avalonia-and-blazor-4hb0", "published_at": "2026-11-26 01:07:17+00:00", "updated_at": "2026-11-26 01:17:46.980564+00:00", "lang": "en", "topics": ["developer-tools", "ai-products"], "entities": ["Avalonia", "Blazor", "Markdig", ".NET", "NuGet", "GitHub"], "also_reported_by": [], "takeaway": "Polhem.Markdown 0.3.1 renders the same Markdig-derived document model in Avalonia and Blazor, with Mermaid, math and syntax highlighting in the core package so the Blazor viewer needs no third-party scripts or CDN.", "recommendation": null, "alternates": {"html": "https://wpnews.pro/news/polhem-markdown-a-markdown-viewer-and-editor-for-avalonia-and-blazor", "markdown": "https://wpnews.pro/news/polhem-markdown-a-markdown-viewer-and-editor-for-avalonia-and-blazor.md", "text": "https://wpnews.pro/news/polhem-markdown-a-markdown-viewer-and-editor-for-avalonia-and-blazor.txt", "jsonld": "https://wpnews.pro/news/polhem-markdown-a-markdown-viewer-and-editor-for-avalonia-and-blazor.jsonld"}}