Watch
1
0
Fork
You've already forked packages
0
packages/markdown/lib/render.weft
Weft packages 306b143104 packages/ at markup-kit dd1e6eb5270e
A snapshot of packages/ in the Weft repository; the official packages are published from these commits.

Markup-Kit-Commit: dd1e6eb5270e62e0c8b6c202b3d01f0da6e00ddc
2026-11-19 20:43:26 +00:00

255 lines
7 KiB
Text

// The HTML renderer: the output CommonMark's and GFM's spec tests expect.
import type {
Align,
Block,
Document,
HtmlMode,
Inline,
ListItem,
Options,
TableCell,
UrlKind,
} from "../ast"
import { escapeHtml } from "./chars"
import { DEFAULT_SCHEMES, isSafeUrl, sanitize } from "./sanitize"
type Out = {
parts: string[],
atLineStart: boolean,
mode: HtmlMode,
schemes: string[],
offset: float,
target: string?,
}
fn put(mut o: Out, text: string) {
if text != "" {
o.parts.push(text)
o.atLineStart = text.endsWith("\n")
}
}
fn targetOf(o: Out): string? {
return o.target
}
fn isEscaping(o: Out): boolean {
return o.mode == "escape"
}
fn isAtLineStart(o: Out): boolean {
return o.atLineStart
}
fn cr(mut o: Out) {
if !isAtLineStart(o) {
put(&o, "\n")
}
}
fn rawHtml(o: Out, html: string): string {
return o.mode == "escape" ? escapeHtml(html) : html
}
fn plainText(inlines: Inline[]): string {
let mut out: string[] = []
for n of inlines {
match n {
Str { text } => out.push(text),
SoftBreak | HardBreak => out.push(" "),
CodeSpan { code } => out.push(code),
Emphasis { children } | Strong { children } | Strikethrough { children } => out.push(
plainText(children),
),
Link { children } => out.push(plainText(children)),
Picture { alt } => out.push(plainText(alt)),
HtmlInline { html } => out.push(html),
}
}
return out.join("")
}
fn wrap(mut o: Out, tag: string, children: Inline[], options: Options): void {
put(&o, `<${tag}>`)
renderInlines(&o, children, options)
put(&o, `</${tag}>`)
}
/// The URL to render, or `null` when it isn't safe to.
fn finalUrl(url: string, kind: UrlKind, o: Out, options: Options): string? {
let rewrite = options.rewriteUrl
let rewritten = rewrite != null ? rewrite(url, kind) ?? url : url
return o.mode == "trust" || isSafeUrl(rewritten, o.schemes, kind == "image") ? rewritten : null
}
fn renderInlines(mut o: Out, inlines: Inline[], options: Options): void {
for n of inlines {
match n {
Str { text } => put(&o, escapeHtml(text)),
SoftBreak => put(&o, "\n"),
HardBreak => put(&o, "<br />\n"),
CodeSpan { code } => put(&o, `<code>${escapeHtml(code)}</code>`),
Emphasis { children } => wrap(&o, "em", children, options),
Strong { children } => wrap(&o, "strong", children, options),
Strikethrough { children } => wrap(&o, "del", children, options),
HtmlInline { html } => {
let raw = rawHtml(o, html)
put(&o, raw)
},
Link { url, title, children } => {
let href = finalUrl(url, "link", o, options)
if href == null {
renderInlines(&o, children, options)
} else {
let titled = title != null && title != "" ? ` title="${escapeHtml(title)}"` : ""
let linkTarget = targetOf(o)
let target = linkTarget != null ? ` target="${escapeHtml(linkTarget)}"` : ""
let rel = linkTarget == "_blank" ? " rel=\"noopener noreferrer\"" : ""
put(&o, `<a href="${escapeHtml(href)}"${titled}${target}${rel}>`)
renderInlines(&o, children, options)
put(&o, "</a>")
}
},
Picture { url, title, alt } => {
let src = finalUrl(url, "image", o, options)
if src == null {
put(&o, escapeHtml(plainText(alt)))
} else {
let titled = title != null && title != "" ? ` title="${escapeHtml(title)}"` : ""
put(&o, `<img src="${escapeHtml(src)}" alt="${escapeHtml(plainText(alt))}"${titled} />`)
}
},
}
}
}
fn renderItem(mut o: Out, item: ListItem, tight: boolean, options: Options): void {
put(&o, "<li>")
if item.checked != null {
put(
&o,
item.checked
? "<input checked=\"\" disabled=\"\" type=\"checkbox\"> "
: "<input disabled=\"\" type=\"checkbox\"> ",
)
}
renderBlocks(&o, item.children, tight, options)
put(&o, "</li>")
cr(&o)
}
fn renderCells(mut o: Out, tag: string, cells: TableCell[], align: Align[], options: Options) {
put(&o, "<tr>\n")
for [i, cell] of cells.entries() {
let a = align.at(i) ?? null
put(&o, a != null ? `<${tag} align="${a}">` : `<${tag}>`)
renderInlines(&o, cell.children, options)
put(&o, `</${tag}>\n`)
}
put(&o, "</tr>\n")
}
fn renderBlocks(mut o: Out, blocks: Block[], tight: boolean, options: Options): void {
for block of blocks {
match block {
Paragraph { children } => {
if tight {
renderInlines(&o, children, options)
} else {
cr(&o)
wrap(&o, "p", children, options)
cr(&o)
}
},
Heading { level, children } => {
let shifted = level + o.offset
let shown = shifted > 6 ? 6 : shifted < 1 ? 1 : shifted
cr(&o)
wrap(&o, `h${shown}`, children, options)
cr(&o)
},
ThematicBreak => {
cr(&o)
put(&o, "<hr />")
cr(&o)
},
CodeBlock { info, code } => {
cr(&o)
let language = info.trim().split(" ")[0].split("\t")[0]
put(
&o,
language != "" ? `<pre><code class="language-${escapeHtml(language)}">` : "<pre><code>",
)
put(&o, escapeHtml(code))
put(&o, "</code></pre>")
cr(&o)
},
HtmlBlock { html } => {
cr(&o)
if isEscaping(o) {
put(&o, `<p>${escapeHtml(html)}</p>`)
} else {
put(&o, html)
}
cr(&o)
},
Blockquote { children } => {
cr(&o)
put(&o, "<blockquote>\n")
renderBlocks(&o, children, false, options)
cr(&o)
put(&o, "</blockquote>")
cr(&o)
},
BulletList { tight: itemsTight, items } => {
cr(&o)
put(&o, "<ul>\n")
for item of items {
renderItem(&o, item, itemsTight, options)
}
put(&o, "</ul>")
cr(&o)
},
OrderedList { tight: itemsTight, start, items } => {
cr(&o)
put(&o, start != 1 ? `<ol start="${start}">\n` : "<ol>\n")
for item of items {
renderItem(&o, item, itemsTight, options)
}
put(&o, "</ol>")
cr(&o)
},
Table { align, head, rows } => {
cr(&o)
put(&o, "<table>\n<thead>\n")
renderCells(&o, "th", head, align, options)
put(&o, "</thead>\n")
if rows.length > 0 {
put(&o, "<tbody>\n")
for row of rows {
renderCells(&o, "td", row, align, options)
}
put(&o, "</tbody>\n")
}
put(&o, "</table>")
cr(&o)
},
}
}
}
/// Renders a document to HTML.
export fn renderDocument(doc: Document, options: Options): string {
let mode = options.html ?? "escape"
let mut o: Out = {
parts: [],
atLineStart: true,
mode,
schemes: options.schemes ?? DEFAULT_SCHEMES,
offset: options.headingOffset ?? 0,
target: options.linkTarget,
}
renderBlocks(&o, doc.children, false, options)
let html = o.parts.join("")
return mode == "sanitize" ? sanitize(html, options.policy) : html
}