Skip to content

Extras

MarkdownViewer

Bit.BlazorUI.ExtrasMdViewerMD

BitMarkdownViewer parses Markdown into an AST and renders it straight to the Blazor render tree - no JavaScript interop, no third-party packages. Composable pipelines add exactly the flavors a document needs, untrusted input is sanitized and bounded by default, and the parsed tree, the rendering of any node and the words the renderers write are all yours to change.

CSS variables

The public custom properties this component reads off its root, for what no parameter covers.

Every variable is read with a fallback and never declared by the component, so it inherits like any other custom property: set one on :root (or in a [bit-theme] block) to restyle every instance, on any ancestor to restyle the ones inside it, or on the Style of one instance to restyle it - and any instance nested inside it, which inherits the value too; a parameter changes one alone, as does the real CSS property on the instance's Style / Styles when that property does not inherit (opacity: 1 keeps one disabled instance undimmed without undimming a disabled one inside it), while an inherited one such as color or font-family also reaches the nested instances that do not set it themselves. Leave a variable unset and the component falls back to the theme token beside it.

BitMarkdownViewer CSS variables

Name Default value Description
--bit-MarkdownViewer-color var(--bit-clr-fg-pri) Text color of the document.
--bit-MarkdownViewer-font-family inherit Font of the document.
--bit-MarkdownViewer-font-size inherit Font size of the document; its headings and code spans scale with it.
--bit-MarkdownViewer-line-height 1.6 Line height of the document.
--bit-MarkdownViewer-block-spacing 1em Room under each block (paragraph, list, table, code block, ...).
--bit-MarkdownViewer-scroll-margin 0 Room kept above a heading or a footnote an in-page link scrolls to - the height of a sticky app bar.
--bit-MarkdownViewer-heading-color inherit Text color of the headings (h6 falls back to var(--bit-clr-fg-sec)).
--bit-MarkdownViewer-heading-font-family inherit Font of the headings.
--bit-MarkdownViewer-heading-font-weight var(--bit-tpg-fw-semibold) Weight of the headings.
--bit-MarkdownViewer-heading-border-color var(--bit-clr-brd-sec) Rule under the h1 and h2 headings.
--bit-MarkdownViewer-link-color var(--bit-clr-pri-fg) Text color of the links.
--bit-MarkdownViewer-link-hover-color var(--bit-MarkdownViewer-link-color) Text color of a link under the pointer.
--bit-MarkdownViewer-link-decoration underline text-decoration-line of the links at rest. Keep a non-color cue if you remove it (WCAG 1.4.1).
--bit-MarkdownViewer-code-font-family var(--bit-tpg-font-family-mono) Font of the code spans, code blocks and math.
--bit-MarkdownViewer-code-color inherit Text color of the code spans.
--bit-MarkdownViewer-code-background color-mix(in srgb, var(--bit-clr-fg-pri) 8%, transparent) Background of the code spans.
--bit-MarkdownViewer-code-radius var(--bit-shp-radius-control) Corner radius of the code spans.
--bit-MarkdownViewer-code-block-color inherit Text color of the code blocks.
--bit-MarkdownViewer-code-block-background color-mix(in srgb, var(--bit-clr-fg-pri) 5%, transparent) Background of the code blocks.
--bit-MarkdownViewer-code-block-padding spacing(2) Padding of the code blocks.
--bit-MarkdownViewer-code-block-radius var(--bit-shp-radius-surface) Corner radius of the code blocks.
--bit-MarkdownViewer-blockquote-color var(--bit-clr-fg-sec) Text color of the block quotes.
--bit-MarkdownViewer-blockquote-border-color var(--bit-clr-brd-pri) Bar down the start edge of the block quotes.
--bit-MarkdownViewer-table-border-color var(--bit-clr-brd-pri) Borders of the table cells.
--bit-MarkdownViewer-table-header-background transparent Background of the header row.
--bit-MarkdownViewer-table-stripe-background color-mix(in srgb, var(--bit-clr-fg-pri) 4%, transparent) Background of every second body row.
--bit-MarkdownViewer-table-cell-padding spacing(0.75) spacing(1.625) Padding of the table cells.
--bit-MarkdownViewer-rule-color var(--bit-clr-brd-pri) Color of the thematic break (hr) and of the rule above the footnotes.
--bit-MarkdownViewer-rule-thickness 0.25em Thickness of the thematic break (hr).
--bit-MarkdownViewer-mark-color inherit Text color of the highlighted (==mark==) text.
--bit-MarkdownViewer-mark-background color-mix(in srgb, var(--bit-clr-wrn) 35%, transparent) Background of the highlighted (==mark==) text.
--bit-MarkdownViewer-container-background color-mix(in srgb, var(--bit-clr-fg-pri) 4%, transparent) Background of the ::: containers.
--bit-MarkdownViewer-note-color var(--bit-clr-inf-fg) Bar and title of the NOTE alerts and of the note/info containers.
--bit-MarkdownViewer-tip-color var(--bit-clr-suc-fg) Bar and title of the TIP alerts and of the tip/success containers.
--bit-MarkdownViewer-important-color var(--bit-clr-pri-fg) Bar and title of the IMPORTANT alerts.
--bit-MarkdownViewer-warning-color var(--bit-clr-wrn-fg) Bar and title of the WARNING alerts and of the warning containers.
--bit-MarkdownViewer-caution-color var(--bit-clr-err-fg) Bar and title of the CAUTION alerts and of the caution/danger containers.

API

Every parameter, public member, sub-class and enum this component exposes.

BitMarkdownViewer parameters

Name Type Default value Description
CodeBlockTemplate RenderFragment<BitMarkdownCodeBlockNode>? null Renders every fenced or indented code block instead of the default pre/code - for a syntax highlighter, a copy button or a diagram renderer. The language is Info, the source Content. The output is outside the viewer's stylesheet.
HeadingIdPrefix string? null Prepended to every heading id and to the in-page links that point at one, so documents sharing a page (chat messages, comments) never repeat an id, and untrusted {#id} headings cannot take one the page uses.
HeadingLevelOffset int 0 Shifts every heading down by this many levels (with 1, # renders as h2), clamped to h1-h6, so the document's outline nests under the page it is placed in.
ImageRendering BitMarkdownViewerImageRendering BitMarkdownViewerImageRendering.SameOrigin Which images may load. A remote image is fetched the moment it renders, leaking whatever its URL encodes; SameOrigin blocks cross-origin images, None blocks all, All is for trusted sources. A blocked image keeps its alt text.
ImageTemplate RenderFragment<BitMarkdownImageNode>? null Renders every image instead of the default img - for a lightbox or a placeholder. The ImageRendering policy has already run, so a blocked image arrives with an empty Url.
Inline bool false Renders the root as a span and drops the paragraph wrappers, so a short piece of Markdown can sit inside a sentence, a cell or a label. Other blocks still render as themselves.
LinkTemplate RenderFragment<BitMarkdownLinkNode>? null Renders every link instead of the default anchor - to route through the router or decorate external links. The URL is already sanitized; read the text with BitMarkdownInlineHelpers.PlainText(context.Children).
Markdown string? null The Markdown source to render.
MaxLength int 0 When greater than zero, the source is truncated to this many characters before parsing (never inside a surrogate pair). 0 means no limit.
MaxNestingDepth int 100 The maximum block/inline nesting depth; deeper content renders as plain text. An always-on guard against stack exhaustion by hostile input; values <= 0 fall back to 100.
OnParsed EventCallback<BitMarkdownDocumentNode> Raised after each parse with the document about to be rendered - to read a table of contents or front matter out of it, or rewrite it.
OnTaskChanged EventCallback<BitMarkdownViewerTaskChangedEventArgs> Raised when a task-list checkbox is ticked, with the source rewritten to match. Setting it is what enables the checkboxes (unless the viewer is disabled); the viewer never changes Markdown itself.
Pipeline BitMarkdownPipeline? null The flavors the source is parsed with. Defaults to the CommonMark core; use BitMarkdownPipelines (Basic, GitHub, Advanced) or build one with BitMarkdownPipelineBuilder.
StripBidiControlCharacters bool false Strips the Unicode bidirectional control characters before parsing, neutralizing 'Trojan Source' (CVE-2021-42574) spoofing. Recommended for untrusted or AI-generated Markdown.

BitMarkdownViewer public members

Name Type Default value Description
Document BitMarkdownDocumentNode The most recently parsed document. Useful for reading structure out of the source (headings, links, images) without parsing it a second time.

BitComponentBase parameters

Name Type Default value Description
AriaLabel string? null Gets or sets the accessible label for the component, used by assistive technologies.
Class string? null Gets or sets the CSS class name(s) to apply to the rendered element.
Dir BitDir? null Gets or sets the text directionality for the component's content.
Disabled bool false Gets or sets a value indicating whether the component is disabled and cannot respond to user interaction.
ForceAnimation bool false Gets or sets a value indicating whether the component's animations play at their full duration even when reduced motion is requested.
HtmlAttributes Dictionary<string, object> new Dictionary<string, object>() Captures additional HTML attributes to be applied to the rendered element, in addition to the component's parameters. An attribute written on the component wins over an entry of the same name.
Id string? null Gets or sets the unique identifier for the component's root element.
Style string? null Gets or sets the CSS style string to apply to the rendered element.
TabIndex string? null Gets or sets the tab order index for the component when navigating with the keyboard.
Visibility BitVisibility BitVisibility.Visible Gets or sets the visibility state (visible, hidden, or collapsed) of the component.

BitComponentBase public members

Name Type Default value Description
UniqueId Guid Guid.NewGuid() Gets the readonly unique identifier for the component's root element, assigned when the component instance is constructed.
RootElement ElementReference Gets the reference to the root HTML element associated with this component.

BitMarkdownPipelines properties

The ready-made, cached pipelines. Each is built once and shared, so passing one costs nothing per render.

Name Type Default value Description
Basic static BitMarkdownPipeline The basic CommonMark core only: headings, emphasis, links, images, lists, block quotes, code, link reference definitions and character references.
GitHub static BitMarkdownPipeline The GitHub flavors: pipe tables, strikethrough, task lists, autolink literals, footnotes and alerts, on top of the core.
Advanced static BitMarkdownPipeline The GitHub flavors plus front matter, the emphasis extras, containers, definition lists, abbreviations, figures, :shortcode: emoji and automatic heading ids.

BitMarkdownPipelineBuilder properties

Composes a pipeline from the flavors you want. A freshly created builder holds only the CommonMark core; each Use... call adds one extension, and Build() produces the immutable pipeline. The same extension is only applied once.

Name Type Default value Description
UsePipeTables BitMarkdownPipelineBuilder UsePipeTables() Adds GitHub-style pipe tables with per-column alignment.
UseStrikethrough BitMarkdownPipelineBuilder UseStrikethrough() Adds ~~strikethrough~~.
UseTaskLists BitMarkdownPipelineBuilder UseTaskLists() Adds GitHub task lists (- [ ] / - [x]).
UseAutoLinks BitMarkdownPipelineBuilder UseAutoLinks() Adds autolink literals, so bare URLs and email addresses become links.
UseEmojis BitMarkdownPipelineBuilder UseEmojis() Adds :shortcode: emoji replacement, using the built-in map.
UseEmojis BitMarkdownPipelineBuilder UseEmojis(IReadOnlyDictionary<string, string> overrides) Adds :shortcode: emoji replacement, extending the built-in map with per-pipeline overrides. An override replaces the built-in shortcode of the same name.
UseAutoIdentifiers BitMarkdownPipelineBuilder UseAutoIdentifiers() Gives every heading a unique, URL-friendly id slug so it can be deep-linked.
UseEmphasisExtras BitMarkdownPipelineBuilder UseEmphasisExtras() Adds the emphasis flavors beyond * , _ and ~~ : ~subscript~, ^superscript^, ++inserted++ and ==highlighted==, rendered as <sub>, <sup>, <ins> and <mark>. Implies strikethrough, because subscript shares the ~ character with it.
UseContainers BitMarkdownPipelineBuilder UseContainers() Adds custom containers: ':::name optional title' ... ':::' renders as a div classed after the name, which is how documentation sites write admonitions and layout blocks. Containers nest, and the name 'details' renders a real <details> with the title as its <summary>.
UseDefinitionLists BitMarkdownPipelineBuilder UseDefinitionLists() Adds definition lists: a term on its own line followed by ': its definition' renders as a real <dl> of <dt> and <dd>.
UseAbbreviations BitMarkdownPipelineBuilder UseAbbreviations() Adds abbreviations: '*[HTML]: HyperText Markup Language' declares a term once and every whole-word occurrence of it becomes an <abbr> carrying the expansion.
UseMathematics BitMarkdownPipelineBuilder UseMathematics() Adds mathematics: $inline$ and $$display$$ are kept verbatim - safe from Markdown's own emphasis and escape rules - and marked as span.math-inline / div.math-display for a client-side typesetter such as KaTeX or MathJax.
UseFigures BitMarkdownPipelineBuilder UseFigures() Adds figures: an image alone in a paragraph and written with a title renders as a <figure> with that title as its <figcaption>.
UseFrontMatter BitMarkdownPipelineBuilder UseFrontMatter() Adds YAML (---) and TOML (+++) front matter, so a metadata block at the top of the document is parsed into a BitMarkdownFrontMatterNode that renders nothing instead of showing up as a thematic break and a heading.
UseSmartyPants BitMarkdownPipelineBuilder UseSmartyPants() Adds typographic replacement: curly quotes, en and em dashes, ellipses and guillemets. Code spans, code blocks and URLs keep every character as written.
UseAutoIdentifiers BitMarkdownPipelineBuilder UseAutoIdentifiers(bool anchorLinks) Gives every heading a unique, URL-friendly id slug so it can be deep-linked, and - when anchorLinks is true - appends a permalink to each heading. A heading may also name its own id by ending with {#the-id}, which is removed from the rendered text.
UseFootnotes BitMarkdownPipelineBuilder UseFootnotes() Adds GitHub-style footnotes: a [^label] reference plus a [^label]: definition. Included in the GitHub bundle, because a footnote definition is also a valid link reference definition.
UseAlerts BitMarkdownPipelineBuilder UseAlerts() Adds GitHub alerts: > [!NOTE], > [!TIP], > [!IMPORTANT], > [!WARNING] and > [!CAUTION] block quotes render as titled callouts.
UseStrings BitMarkdownPipelineBuilder UseStrings(BitMarkdownStrings strings) Sets the words the renderers write themselves - alert titles, footnote back-links, the accessible names of the regions and controls the markup adds - so a rendered document can be in a language other than English.
UseUrlRewriter BitMarkdownPipelineBuilder UseUrlRewriter(Func<BitMarkdownUrlRewriteContext, string?> rewrite) Rewrites every link and image destination through a function of your own. The result is sanitized again on the way out, so a rewriter can never reintroduce an unsafe destination; returning null drops the destination and keeps the text.
UseBaseUrl BitMarkdownPipelineBuilder UseBaseUrl(string baseUrl) Resolves every relative link and image destination against baseUrl - what a README needs before it can be rendered anywhere but the repository it came from. Absolute destinations and in-page fragments are left alone.
UseLinkOptions BitMarkdownPipelineBuilder UseLinkOptions(BitMarkdownLinkTarget externalTarget, string? externalRel, BitMarkdownLinkTarget internalTarget, string? internalRel) Chooses the target and rel a rendered link carries, replacing the defaults (external links open in a new tab with 'noopener noreferrer'). Pass 'noopener noreferrer nofollow ugc' for links a site's own readers wrote.
UseSoftLineAsHardLine BitMarkdownPipelineBuilder UseSoftLineAsHardLine() Renders every single newline as a line break, the way a chat or comment box does.
UseGitHubFlavored BitMarkdownPipelineBuilder UseGitHubFlavored() Adds the full GitHub bundle: pipe tables, strikethrough, task lists, autolinks, footnotes and alerts.
UseAdvanced BitMarkdownPipelineBuilder UseAdvanced() Adds the GitHub flavors plus front matter, the emphasis extras, containers, definition lists, abbreviations, figures, emoji and auto-identifiers.
Use BitMarkdownPipelineBuilder Use(IBitMarkdownExtension extension) Adds a custom extension. An extension registers block parsers, inline parsers, delimiter processors, AST processors and/or renderers; everything it registers must be stateless, since a built pipeline is shared across concurrent parses.
Build BitMarkdownPipeline Build() Builds the immutable, reusable pipeline.

BitMarkdownPipeline properties

An immutable, reusable Markdown processing configuration produced by a BitMarkdownPipelineBuilder. Pipelines are thread-safe and should be cached and shared rather than rebuilt per render.

Name Type Default value Description
Parse BitMarkdownDocumentNode Parse(string? markdown) Parses Markdown source into an AST, applying all AST processors.
CreateRenderer BitMarkdownRenderer CreateRenderer() Creates a renderer bound to this pipeline's node renderers.

BitMarkdownDocumentNode properties

The root of a parsed Markdown document. Inherits from BitMarkdownNode.

Name Type Default value Description
Children List<BitMarkdownNode> [] The top-level child nodes of the document.
ChildNodes IList<BitMarkdownNode> The node's single child collection (returns Children).

BitMarkdownNode properties

The abstract base type for every node produced by the parser. Nodes expose their mutable child collections so that AST processors (plugins) can traverse and rewrite the tree generically, even for node types they did not define. BitMarkdownAstHelper.Descendants(node) walks the whole tree iteratively, so even pathologically nested documents cannot overflow the stack.

Name Type Default value Description
ChildNodes virtual IList<BitMarkdownNode>? null The node's single child collection, if it has exactly one. Container nodes override this; leaf nodes return null.
ChildLists virtual IEnumerable<IList<BitMarkdownNode>> All mutable child collections owned by this node. Defaults to the single ChildNodes collection; nodes with several (e.g. a table's cells) override this to expose each one.

BitMarkdownFrontMatterNode properties

The metadata block a document may open with, fenced by --- (YAML) or +++ (TOML). It describes the file rather than belonging to it, so it renders nothing and is read back off the AST. Requires the front matter flavor; without it a leading --- is ordinary Markdown.

Name Type Default value Description
Fence string --- The fence that opened the block, either --- or +++.
Text string The raw text between the fences, with the line endings normalized to . Hand it to whichever serializer you already use.
IsToml bool false True when the block was fenced with +++, i.e. TOML rather than YAML.
Find static BitMarkdownFrontMatterNode? Find(BitMarkdownDocumentNode document) Returns the document's front matter block, or null when it has none.

BitMarkdownViewerTaskChangedEventArgs properties

What the viewer reports when a reader ticks or unticks a task-list checkbox.

Name Type Default value Description
Index int 0 The checkbox's position in the document, counted from 0 in reading order.
Checked bool false Its new state.
Markdown string The source with that one marker rewritten, ready to be stored. Produced by BitMarkdownTaskList.Toggle, which counts the same markers the viewer drew and skips any inside code blocks.

BitMarkdownUrlRewriteContext properties

What a URL rewriter is told about the destination it is being asked to rewrite.

Name Type Default value Description
Url string The sanitized destination, exactly as it would otherwise be rendered.
IsImage bool false True for an image source, false for a link destination.
IsRelative bool false True when the URL has no scheme and does not begin with '//'. An in-page fragment (#section) is not relative in this sense, since resolving it elsewhere would break every heading link in the document.

BitMarkdownStrings properties

The words the renderers write into a document themselves, rather than taking them from the source. All strings default to English. The numbered ones take their number through {0}; FootnoteBackReferenceOccurrence takes the footnote's number and the citation's through {0} and {1}.

Name Type Default value Description
AlertNote string Note The title of a > [!NOTE] alert.
AlertTip string Tip The title of a > [!TIP] alert.
AlertImportant string Important The title of a > [!IMPORTANT] alert.
AlertWarning string Warning The title of a > [!WARNING] alert.
AlertCaution string Caution The title of a > [!CAUTION] alert.
Footnotes string Footnotes The heading of the footnotes section, read by a screen reader only; each footnote reference is described by it.
FootnoteBackReference string Back to reference {0} The accessible name of a footnote's back-link, given the footnote's number.
FootnoteBackReferenceOccurrence string Back to reference {0}-{1} The accessible name of one of several back-links on the same footnote, given the footnote's number and the citation's.
NewTab string (opens in a new tab) Read out after the text of a link that opens in a new tab; not shown. An empty string leaves it out.
CodeBlock string Code block The accessible name of a code block, which scrolls and so is a tab stop.
Table string Table The accessible name of the scrollable region a table sits in.
PermalinkTo string Permalink to {0} The accessible name of a heading's permalink, given the heading's text.
PermalinkToSection string Permalink to this section The accessible name of a permalink whose heading has no text of its own.
Task string Task {0} The accessible name of an interactive task-list checkbox whose item has no text, given its number (a box is otherwise named after its item).

BitMarkdownAstHelper properties

Helpers for reading and rewriting a parsed document. Every walk here is iterative, so even a pathologically nested document cannot overflow the stack.

Name Type Default value Description
Descendants static IEnumerable<BitMarkdownNode> Descendants(BitMarkdownNode node) Enumerates every node in the tree, in document order, excluding the root.
VisitChildLists static void VisitChildLists(BitMarkdownNode node, Action<IList<BitMarkdownNode>> action) Invokes the action for every child collection in the tree, depth-first. The action may add, remove or replace entries in place, which is how an AST processor rewrites the tree.
ToPlainText static string ToPlainText(BitMarkdownNode node) Renders the subtree as plain text: what the document says, with none of the markup it says it with and none of the link destinations. Blocks are separated by a blank line. This is the text a search index, an excerpt or a meta description is built from.

BitMarkdownRenderer properties

Walks an AST and dispatches each node to a matching node renderer. Renderers are probed in reverse registration order, so the last renderer registered for a node type wins, allowing pipeline extensions to override the core renderers.

Name Type Default value Description
Strings BitMarkdownStrings The words the renderers write themselves.
DocumentUrl string? null The page the output is placed in (init-only). When set, an in-page destination (#id) is written as this address plus the fragment, so a <base href> cannot send it to another page. The viewer sets it for you.
ResolveInPageUrl string ResolveInPageUrl(string url) Returns an in-page destination prefixed with DocumentUrl, anything else unchanged. A custom node renderer writing an href should go through it.
WriteNodes void WriteNodes(RenderTreeBuilder builder, IEnumerable<BitMarkdownNode> nodes) Renders a sequence of nodes.
WriteNode void WriteNode(RenderTreeBuilder builder, BitMarkdownNode node) Renders a single node using the matching renderer (last registered wins).

BitMarkdownViewerImageRendering enum

Name Value Description
All 0 All images are rendered and loaded automatically, including remote ones. Suitable only when the Markdown source is fully trusted.
SameOrigin 1 Only same-origin images (relative paths, anchors, same-document references and embedded data: images) are loaded. Cross-origin images (http:, https: and protocol-relative //) are blocked. The recommended mode for untrusted or AI-generated Markdown.
None 2 No image is allowed to load; every image source is stripped and only the alt text remains. The strictest option.

BitMarkdownAlertKind enum

Name Value Description
Note 0 Useful information the reader should notice even when skimming.
Tip 1 Optional advice for doing something better.
Important 2 Key information the reader needs to succeed.
Warning 3 Urgent information that needs immediate attention to avoid a problem.
Caution 4 Advice about the risks or negative outcomes of an action.

BitVisibility enum

Name Value Description
Visible 0 The content of the component is visible.
Hidden 1 The content of the component is hidden, but the space it takes on the page remains (visibility:hidden).
Collapsed 2 The component is hidden (display:none).

BitDir enum

Name Value Description
Ltr 0 Ltr (left to right) is to be used for languages that are written from the left to the right (like English).
Rtl 1 Rtl (right to left) is to be used for languages that are written from the right to the left (like Arabic).
Auto 2 Auto lets the user agent decide. It uses a basic algorithm as it parses the characters inside the element until it finds a character with a strong directionality, then applies that directionality to the whole element.

Feedback

Found a mistake, a gap, or something that could be clearer? Every page and every component is one click from its source.