// 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, ``) } /// 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, "
\n"), CodeSpan { code } => put(&o, `${escapeHtml(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, ``) renderInlines(&o, children, options) put(&o, "") } }, 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, `${escapeHtml(plainText(alt))}`) } }, } } } fn renderItem(mut o: Out, item: ListItem, tight: boolean, options: Options): void { put(&o, "
  • ") if item.checked != null { put( &o, item.checked ? " " : " ", ) } renderBlocks(&o, item.children, tight, options) put(&o, "
  • ") cr(&o) } fn renderCells(mut o: Out, tag: string, cells: TableCell[], align: Align[], options: Options) { put(&o, "\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, `\n`) } put(&o, "\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, "
    ") cr(&o) }, CodeBlock { info, code } => { cr(&o) let language = info.trim().split(" ")[0].split("\t")[0] put( &o, language != "" ? `
    ` : "
    ",
            )
            put(&o, escapeHtml(code))
            put(&o, "
    ") cr(&o) }, HtmlBlock { html } => { cr(&o) if isEscaping(o) { put(&o, `

    ${escapeHtml(html)}

    `) } else { put(&o, html) } cr(&o) }, Blockquote { children } => { cr(&o) put(&o, "
    \n") renderBlocks(&o, children, false, options) cr(&o) put(&o, "
    ") cr(&o) }, BulletList { tight: itemsTight, items } => { cr(&o) put(&o, "") cr(&o) }, OrderedList { tight: itemsTight, start, items } => { cr(&o) put(&o, start != 1 ? `
      \n` : "
        \n") for item of items { renderItem(&o, item, itemsTight, options) } put(&o, "
      ") cr(&o) }, Table { align, head, rows } => { cr(&o) put(&o, "\n\n") renderCells(&o, "th", head, align, options) put(&o, "\n") if rows.length > 0 { put(&o, "\n") for row of rows { renderCells(&o, "td", row, align, options) } put(&o, "\n") } put(&o, "
      ") 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 }