MarkdownText
A model reply, rendered
Headings, tables, fenced code, blockquotes and links — the constructs LLM replies actually use —
from one markdown prop. No sanitizer to configure: safety is built into the renderer.
Order summary
Your store processed 12 orders today — zero payment failures.
| Status | Count |
|---|---|
| Paid | 11 |
| COD | 1 |
Retry a failed sync with:
breeze sync --orders --since=today
COD orders confirm automatically once the call completes.
Full details in the orders dashboard.
Inside ChatMessage
ChatMessage accepts the same source via its markdown prop and renders it
through this pipeline — one prop replaces the render-then-inject dance around html.
Hostile input stays text
The source below carries raw HTML, an inline event handler, and three unsafe link protocols. All of it renders as visible, inert text — nothing executes, no anchor keeps an unsafe protocol.
A reply that tries everything at once:
<script>alert("xss")</script>Inline <img src=x onerror=alert(1)> injection, a javascript link, a data link, and an entity-smuggled protocol.
Raw HTML: escaped or stripped
The same source under both settings. escape — the default — shows the markup as
visible text; strip removes the tags and keeps the text they surrounded, for both inline
and block-level HTML. Neither ever inserts it as markup, so this changes what a reader sees, not what
the browser runs. Note the last line: prose that merely contains angle brackets is text, not HTML, so
it survives both.
rawHtml='escape' (default)
An inline <b>bold</b> tag, written as HTML.
<div>A whole block of raw HTML.</div>And prose where a < b and c > d, which is text rather than markup.
rawHtml='strip'
An inline bold tag, written as HTML.
A whole block of raw HTML.And prose where a < b and c > d, which is text rather than markup.
A table wider than the message
The table scrolls inside itself, so the message around it does not. Its columns stay aligned across header and body while it does.
| Order ID | Customer | Payment method | Status | Amount | Created |
|---|---|---|---|---|---|
| ORD-100001 | Priya Raghunathan | Netbanking (HDFC) | Completed | 12,500.00 | 2026-09-01 10:22 |
| ORD-100002 | Sundaram Venkatesh | UPI Collect | Pending capture | 3,499.50 | 2026-09-01 11:04 |
A named table region
Passing tableLabel names the scroll region, which is what makes role="region" useful. Without it the wrapper is still keyboard-scrollable but announces
no landmark, because an unnamed region is worse than none.
| Order ID | Customer | Payment method | Status | Amount | Created |
|---|---|---|---|---|---|
| ORD-100001 | Priya Raghunathan | Netbanking (HDFC) | Completed | 12,500.00 | 2026-09-01 10:22 |
| ORD-100002 | Sundaram Venkatesh | UPI Collect | Pending capture | 3,499.50 | 2026-09-01 11:04 |
Line breaks
Default follows the markdown spec (single newlines flow together); breaks renders
them as <br> — the mode most chat transcripts want.
breaks=false
roses are red violets are blue
breaks=true
roses are red
violets are blue
Documentation
Renders markdown as HTML through a sanitized-by-construction pipeline, built for chat and agent surfaces where the text comes from a model or a user rather than from the app's own templates. There is no sanitizer to configure and no way to make it render more: raw HTML in the source (block or inline) is escaped and shown as text — or stripped of tags while retaining text with sanitize.rawHtml — but never inserted as markup, links and images only keep their URL when its protocol is on the allow-list (http:, https:, mailto:, tel: for links; http:/https: for images; relative URLs pass), and everything else in the output is generated by the markdown parser itself. The transform is a pure string operation — no DOM involved — so it renders identically during SSR and in the browser, with no hydration mismatch.
GFM is enabled (tables, strikethrough, task lists, autolinks). The same pipeline is available as the exported renderMarkdown(markdown, options?) utility for cases that need the HTML string itself — it is what ChatMessage's markdown prop uses internally.
The marked package is a peer dependency, needed only when you actually use MarkdownText, renderMarkdown, or ChatMessage's markdown prop (npm 7+ and pnpm install peers automatically; add marked to your project's dependencies if your package manager does not). ChatMessage loads the pipeline on demand, so existing consumers that never touch the markdown prop keep their install contract unchanged.
Usage
<script>
import { MarkdownText, ChatMessage } from '@juspay/svelte-ui-components';
const reply = `## Results\n\nYour store processed **12 orders** today:\n\n| Status | Count |\n| --- | --- |\n| Paid | 11 |\n| COD | 1 |`;
</script>
<!-- Standalone -->
<MarkdownText markdown={reply} />
<!-- Chat: ChatMessage renders markdown through the same pipeline -->
<ChatMessage role="assistant" markdown={reply} />
<script>
import { renderMarkdown } from '@juspay/svelte-ui-components';
// The utility form, when you need the HTML string itself.
const html = renderMarkdown('**bold** and `code`', { breaks: true });
// Inline mode: no block elements, safe to place inside an existing <p>.
const inline = renderMarkdown('**bold** summary', { inline: true });
</script>
Props
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| markdown | string |
Yes | - |
Markdown source. Raw HTML is escaped by default; strip mode removes tags and retains text; unsafe link/image protocols are stripped while their text stays. |
| breaks | boolean |
No | false |
Render single newlines as <br> (GFM "breaks" mode). |
| testId | string |
No | - |
data-pw (and native testID) on the root element. |
| classes | string |
No | - |
Class string on the root element. |
| tableLabel | string |
No | - |
Names the scrollable table region: adds role="region" and aria-label to the wrapper. Without it the wrapper is still focusable and scrollable but announces no landmark. |
| tableWrapperClass | string |
No | - |
An extra class on the scrollable table wrapper, added alongside the built-in markdown-table-wrapper rather than replacing it. See Wide tables below. |
| unwrapFence | boolean |
No | false |
Remove a fence that wraps the entire value and is labelled ```markdown or ```md, then render what was inside as markdown. Models routinely wrap a whole answer that way, which otherwise renders as a code block of source. Off by default. See below. |
| sanitize | MarkdownSanitizeOptions |
No | - |
Narrows the link/image protocol allow-list, the set of tags allowed to render as themselves, whether task-list checkboxes render, and whether raw HTML is escaped, dropped, or rendered through a sanitizer the caller supplies (htmlSanitizer). See the Security model section below. |
Security model
Raw HTML does not pass through unless you supply a sanitizer.
<script>, event-handler attributes, iframes — source HTML is escaped by default, or stripped to escaped text content whensanitize.rawHtmlis'strip'. This is deliberate for chat: models emit markdown, not HTML, and dropping passthrough removes the entire injection surface instead of trying to filter it. If you genuinely need raw HTML rendered, see Rendering raw HTML below — you supply the sanitizer, and omitting it keeps the escaping.URL protocol allow-list.
[x](javascript:…)and[x](data:…)render as plain text without an anchor;renders the alt text without an<img>. Entity-smuggled protocols (jav	ascript:) fail scheme parsing and are treated as relative paths, where attribute-escaping keeps them inert.External links are tab-safe.
http:/https:links open withtarget="_blank" rel="noopener noreferrer"(the same default the library's Button/Card apply); relative,mailto:andtel:links keep same-tab navigation. Autolinks and bare URLs go through the same protocol guard as explicit links.Pre-sanitized HTML has its own prop. If you already hold trusted, sanitized HTML, use
ChatMessage'shtmlprop —markdownis for untrusted source text.The allow-list can be narrowed, never widened. Pass
sanitize={{ allowedProtocols: [...] }}when your own link policy is stricter than the library default (for example, no livemailto:/tel:in a support chat). It is intersected with the library's own allow-list for each surface (links vs. images), so listing an unsafe scheme likejavascript:is a no-op, not a hole. Omittingsanitizekeeps today's defaults exactly as they are — this is additive, not a replacement for the built-in list:<!-- Only http(s) links/images; mailto: and tel: are dropped, keeping their text. --> <MarkdownText {markdown} sanitize={{ allowedProtocols: ['http:', 'https:'] }} />The tag allow-list narrows from "everything", never from a preset list. Unlike
allowedProtocols, there is no built-in default to intersect with — every tagmarked's GFM output can produce (a,img,strong,em,del,code,pre,blockquote,ul,ol,table,hr,h1–h6) renders normally untilsanitize.allowedTagsis supplied. Once it is, a disallowed tag drops itself but keeps its parsed inner content, which is rendered through this same allow-list — the same "keep the content, drop the element" contract the protocol allow-list uses. That inner content only reads as plain text when nothing inside it is allowed either; a nested tag that is itself inallowedTagsstill comes through as real markup (sanitize={{ allowedTags: ['strong'] }}on# **Loud** Titledrops the<h1>but keeps<strong>Loud</strong>). An unrecognised name is ignored, not an error. This list governs markdown-generated tags only; raw HTML from the source is never affected by it, and is disposed of bysanitize.rawHtmlinstead:<!-- Headings, lists and tables render as plain text; links/emphasis still render. --> <MarkdownText {markdown} sanitize={{ allowedTags: ['a', 'strong', 'em'] }} />Task-list checkboxes can render as plain text instead. GFM task items (
- [ ] done) already render adisabledcheckbox by default — it never submits or toggles — sosanitize={{ disableTaskLists: true }}is a presentation choice, not a safety one, for surfaces that would rather show the list item's text with no checkbox glyph at all. Defaults tofalse, keeping today's checkbox rendering.Raw HTML can be dropped instead of escaped. Escaping is the default and stays the default, but "escape it" and "drop it" are different products, not different levels of safety. A transcript rendering agent- or user-authored prose usually wants a stray
<div>to leave no trace, rather than to appear as visible tag text; withoutsanitize={{ rawHtml: 'strip' }}that surface has to pre-mangle the source with its own regex before it ever reaches this component. Neither setting inserts raw HTML into the live DOM. Strip mode uses an inert, DOM-independent HTML parser to extract text, then escapes it. Scripts and styles are never executed; their contents remain visible text.Both inline and block HTML retain text:
Source 'escape'(default)'strip'a <b>bold</b> worda <b>bold</b> worda bold word<script>alert(1)</script><script>alert(1)</script>alert(1)(text only)a < b and c > da < b and c > da < b and c > dTags, attributes, declarations and comments are removed; text is retained, including inside block-level HTML. Entity references are decoded by the inert parser and escaped again before output, so encoded HTML cannot become executable markup. Fenced code and prose containing ordinary angle brackets keep their existing rendering.
parse5is a runtime dependency of the pipeline, not a browser DOM API.<!-- Stray HTML in a transcript disappears instead of showing as tag text. --> <MarkdownText {markdown} sanitize={{ rawHtml: 'strip' }} />
Rendering raw HTML
Web components.
sui-markdown-textdeclaressanitizeas an object property, sohtmlSanitizercan only be supplied from script --element.sanitize = { rawHtml: 'sanitize', htmlSanitizer }. There is no attribute form, because an attribute is a string and this option is a function. A vanilla-JS consumer settingsanitizeas an HTML attribute gets escaping, the default, rather than an error.
Set sanitize.rawHtml to 'sanitize' and supply sanitize.htmlSanitizer. Your function is called
once per render, with the whole assembled document, and what it returns is what gets rendered.
DOMPurify is not bundled with this library and is not a peer dependency — install a sanitizer in
your own app (npm i dompurify, or anything else you trust). Nothing here imports one.
Configure it explicitly. DOMPurify.sanitize(html) with no options uses a broad default
allow-list that varies by version and environment, and because your function now sees the whole
document, the allow-list has to cover the tags this component emits as well as the ones you let
authors write:
<script lang="ts">
import DOMPurify from 'dompurify';
import { MarkdownText } from '@juspay/svelte-ui-components';
// What MarkdownText itself emits, plus the raw-HTML tags you choose to allow.
// Anything missing here is dropped from YOUR markdown output too, not just
// from author-written HTML.
const ALLOWED_TAGS = [
'p',
'br',
'hr',
'span',
'div',
'strong',
'em',
'del',
'code',
'pre',
'blockquote',
'ul',
'ol',
'li',
'input',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'a',
'img',
'table',
'thead',
'tbody',
'tr',
'th',
'td'
];
const ALLOWED_ATTR = [
'href',
'title',
'target',
'rel',
'src',
'alt',
'width',
'height',
'class',
'align',
'colspan',
'rowspan',
'type',
'checked',
'disabled'
];
</script>
<MarkdownText
{markdown}
sanitize={{
rawHtml: 'sanitize',
htmlSanitizer: (html) => DOMPurify.sanitize(html, { ALLOWED_TAGS, ALLOWED_ATTR })
}}
/>
You own the policy. Whatever your function returns is rendered as markup, unmodified. This component does not re-check it, and cannot: re-escaping the result would turn the feature back into
'escape'. A permissive configuration here is a live XSS surface in your application, so treat the allow-list above as a starting point to narrow, not a default to copy.
The library does not implement HTML sanitization and does not depend on a sanitizer. That is a deliberate limit, not an omission. Escaping everything is a provably safe default, so a sanitizer written here could only ever subtract from it — and HTML sanitization is a specialist problem: mutation XSS, namespace confusion, and divergence between how a server-side parser and a browser read the same bytes. Injection keeps that code in your dependency tree, where it can be audited and updated on its own schedule, and the signature says plainly that the returned string is your responsibility.
Three properties worth knowing:
- Omitting the sanitizer keeps the escaping.
rawHtml: 'sanitize'with nohtmlSanitizerbehaves exactly like'escape'. A half-configured surface does not start emitting raw HTML. - A failing sanitizer falls back to escaping. If yours throws, or returns anything that is not a
string, the document is re-rendered with
'escape'. The unsanitized assembly is never emitted, and the fallback is always the safe path that was already there. - The protocol allow-list covers markdown syntax, NOT raw HTML.
[click](javascript:alert(1))renders as plain text with no anchor, as it always has. But<a href="javascript:alert(1)">click</a>written as raw HTML is emitted exactly as your sanitizer returns it — this component does not re-check it. That is the trust boundary doing what it says, and it is the single most important thing to get right in your configuration: DOMPurify stripsjavascript:hrefs by default, so do not turn that off. External-link hardening (rel="noopener noreferrer") is applied after your sanitizer runs, so a restrictive configuration cannot strip it. - It has to work on the server too.
MarkdownTextrenders the result through{@html}, so on a server-rendered page the sanitizer runs twice: once during SSR and once on hydration. A browser-only sanitizer — DOMPurify with no DOM around it — throws during SSR, falls back to escaped output there, then succeeds on the client, and the two renders disagree. Give it a server implementation (DOMPurify withjsdom, for instance), or leaverawHtmlat its default on server-rendered routes. The fallback itself is deterministic: a throwing sanitizer produces exactly what'escape'produces, which is asserted in the tests. - Your sanitizer sees markdown-generated HTML too. This is the cost of the one-pass design, and
the thing to configure for: the input is the full document, so an allow-list must include the tags
this component emits (
p,strong,em,code,pre,ul,ol,li,blockquote,a,img,tableand friends), not only the tags you expect authors to write.
Why one pass rather than one call per raw-HTML token: marked splits a block-level container into
separate opening and closing tokens, with the markdown between them as its own block. A sanitizer
parses its input and serialises the tree back, so handed <div class="callout"> on its own it
returns <div class="callout"></div> and drops the matching </div> entirely — and the content the
author wrapped renders outside its container. Sanitizing the assembled document is the only point
at which the container and its contents are both present and balanced.
Wide tables
Ask a model for a summary and it answers with a table, and a chat bubble is rarely wide enough for one. Each table is wrapped in a scrollable region, so the table scrolls horizontally and the message around it does not, while header and body keep sharing one set of column edges.
The wrapper exists rather than scrolling the table directly because display: block
on a <table> — which is what makes overflow-x apply to the element itself —
also strips the table's semantics, and assistive technology loses row and column
navigation on exactly the content that most needs it. Table.svelte reaches the
same shape with its .table-scroll wrapper.
| declaration | on | why it is needed |
|---|---|---|
display: block + overflow-x: auto |
.markdown-table-wrapper |
makes the wrapper the scroll container, leaving the table a table |
max-width: 100% |
.markdown-table-wrapper |
bounds the scroll container to the message, so the table overflows the wrapper instead of the page |
width: max-content + min-width: 100% |
table |
gives it something to overflow with, while a narrow table still fills the message |
tabindex="0" |
.markdown-table-wrapper |
a box with overflow-x: auto cannot be scrolled with arrow keys unless it can hold focus; without this the scrolling is mouse-only |
overflow-wrap: normal |
th, td |
the container sets overflow-wrap: anywhere so a long unbroken string cannot force the message wide; inside a table that makes every character a break opportunity, so max-content collapses to min-content and the table stops scrolling |
:focus-visible outline |
.markdown-table-wrapper |
a tab stop with no visible focus ring is a dead end for a keyboard user; the ring's colour is --markdown-text-focus-outline-color |
Remove any one of them and a wide table compresses to fit, loses its semantics,
cannot be reached from the keyboard, or gives no sign that it has been reached. Cells keep white-space: normal, so a table
that does fit still wraps inside its cells rather than being forced onto one line.
Pass tableLabel to name the region:
<MarkdownText {markdown} tableLabel="Recent orders" />
That adds role="region" and aria-label. Without it the wrapper stays
keyboard-scrollable but announces no landmark, since a region the user cannot
identify is worse than no region at all.
markdown-table-wrapper is itself a stable public class name — style it
directly in your own stylesheet if you would rather theme the wrapper that way
than reach for CSS variables. If your app already has its own class for this
(its own scroll/border/token treatment) and you want the rendered markup to
carry that class instead, pass tableWrapperClass:
<MarkdownText {markdown} tableWrapperClass="markdown-table-scroll" />
The wrapper then carries both: class="markdown-table-wrapper markdown-table-scroll".
It is added, never substituted, and that is deliberate. The wrapper is a
tabindex="0" scroll container, and the three things that make it one —
overflow-x: auto, the :focus-visible ring, and the table's max-content
width — are scoped to .markdown-table-wrapper in the component's own styles.
A Svelte scoped selector cannot be templated to a class name supplied at
runtime, so replacing the class would leave a focusable element that cannot
scroll and shows no focus ring: a keyboard dead end, and a regression of the
fix that made wide tables scrollable in the first place.
Adding costs you nothing. Your own selector matches the wrapper exactly as it would have, and you can still override any built-in declaration by specificity if you want different scroll or focus treatment.
markdown-table-wrapper is a stable public class. Theme against it directly if
you would rather not pass a prop at all.
Omitting tableWrapperClass, or passing an empty or whitespace-only string,
leaves the wrapper with just markdown-table-wrapper. The value is
HTML-attribute-escaped the same way tableLabel is, so it cannot break out of
the class="..." attribute it is placed in.
CSS Variables
| Variable | Default | Description |
|---|---|---|
--markdown-text-font-size |
inherit |
Base font size. |
--markdown-text-line-height |
1.5 |
Base line height. |
--markdown-text-color |
inherit |
Text color. |
--markdown-text-paragraph-margin |
0 0 0.5em 0 |
Paragraph spacing. |
--markdown-text-heading-margin |
0.8em 0 0.4em 0 |
Heading spacing. |
--markdown-text-link-color |
#6d28d9 |
Link color. |
--markdown-text-code-font-family |
ui-monospace, monospace |
Inline code / code block font. |
--markdown-text-code-background |
rgba(0, 0, 0, 0.05) |
Inline code background. |
--markdown-text-pre-background |
rgba(0, 0, 0, 0.05) |
Code block background. |
--markdown-text-list-margin |
0.4em 0 |
List outer spacing. |
--markdown-text-list-padding |
1.4em |
List indent. |
--markdown-text-blockquote-border-color |
rgba(0, 0, 0, 0.15) |
Blockquote left rule. |
--markdown-text-blockquote-color |
inherit |
Blockquote text color. |
--markdown-text-blockquote-opacity |
0.85 |
Blockquote de-emphasis. |
--markdown-text-table-border-color |
rgba(0, 0, 0, 0.12) |
Table cell borders. |
--markdown-text-table-header-background |
rgba(0, 0, 0, 0.04) |
Table header background. |
--markdown-text-image-border-radius |
8px |
Image corner radius. |
--markdown-text-hr-color |
rgba(0, 0, 0, 0.12) |
Horizontal rule color. |
--markdown-text-focus-outline-color |
#3b82f6 |
Focus ring on a table wrapper. |
unwrapFence
A model asked for markdown very often returns it wrapped:
```markdown
# Quarterly summary
Revenue rose **12%**.
```
Rendered literally that is a code block, so the reader sees source instead of a
document. unwrapFence opts into removing exactly that wrapper.
It is opt-in, and it only ever matches a fence that is the whole value. That narrowness is the point: an unanchored implementation will happily unwrap a message that quotes a fenced sample while explaining markdown, turning the sample into live markup. Every one of these is left untouched:
| Source | Why it is not unwrapped |
|---|---|
| Prose before or after the fence | The fence is not the whole body |
``` with no info string |
May be code the author meant to show |
```python |
Labelled as another language |
A body still containing ``` |
Ambiguous — the outer pair may not be the wrapper |
Tilde fences (~~~markdown) are unwrapped too, and the info string is matched
case-insensitively with surrounding whitespace tolerated.
Unwrapping happens before parsing, so it changes nothing about sanitization: raw HTML inside an unwrapped body is still escaped or stripped exactly as it would be anywhere else.
Type Reference
export type MarkdownTextProperties = {
markdown: string;
breaks?: boolean;
testId?: string;
classes?: string;
tableLabel?: string;
tableWrapperClass?: string;
sanitize?: MarkdownSanitizeOptions;
unwrapFence?: boolean;
};
export type MarkdownSanitizeOptions = {
// Intersected with the library's own default allow-list per surface (links,
// images), so it can only narrow what renders, never widen it.
allowedProtocols?: string[];
// No preset default to intersect with -- every tag renders until this is
// supplied, then it narrows from "everything". A disallowed tag keeps its
// text and drops the element.
allowedTags?: string[];
// Render task-list items as plain text instead of a (already-disabled)
// checkbox. Defaults to false.
disableTaskLists?: boolean;
// Escape raw HTML from the source as visible text (the default), drop it,
// or keep it and run htmlSanitizer over the assembled output.
rawHtml?: MarkdownRawHtmlMode;
// Consulted only while rawHtml is 'sanitize'. Called once with the whole
// assembled document -- markdown-generated HTML included -- and returns the
// markup to render; a throw or non-string falls back to escaping. This
// library does not implement sanitization itself -- pass DOMPurify's
// `sanitize`, or anything you trust.
htmlSanitizer?: (html: string) => string;
};
export type MarkdownRawHtmlMode = 'escape' | 'strip' | 'sanitize';
export type RenderMarkdownOptions = {
breaks?: boolean;
inline?: boolean;
tableLabel?: string;
tableWrapperClass?: string;
sanitize?: MarkdownSanitizeOptions;
unwrapFence?: boolean;
};
Keyboard access to code
Code blocks that overflow horizontally are labelled regions. Tab moves focus to the region and the arrow keys scroll it. The extra Tab stop is removed when the code fits. Use --markdown-text-code-focus-outline to style the focus indicator.
Escaped Markdown renderer
Import renderEscapedMarkdown for synchronous rendering with escaped raw HTML. It supports the shared Markdown features, table labels, and link and image restrictions. Use renderMarkdown when you need the raw HTML stripping or caller sanitizer options.