Skip to curriculum
Jump to the editor

23.6. Rich text to HTML

Hard
Topics
30–50 min

Rich-text editors save a document as JSON, not as HTML: a tree of blocks (paragraphs, headings, lists) whose text nodes carry marks such as bold, italic or a link. To show a saved comment, an email preview or a page on the server, you serialize that tree to HTML. Two things make it harder than it looks. Marks are per text node, but the HTML should not close and reopen <strong> between every pair of nodes. And the document came from a user, so text must be escaped and a link to javascript: must never become a working link.

Write toHTML(doc) in rich-text.js.

Signature

JAVASCRIPT
function toHTML(doc) // returns a string of HTML

doc is { type: "doc", content: [ …blocks ] }. A node's content and attrs may be missing; read them as [] and {}.

NodeHoldsHTML
paragraphinline nodes<p>…</p>
headinginline nodes; attrs.level from 1 to 6, 1 when missing<h1>…</h1> to <h6>…</h6>
blockquoteblocks<blockquote>…</blockquote>
bulletListlistItem nodes<ul>…</ul>
orderedListlistItem nodes; attrs.start, 1 when missing<ol>…</ol>, or <ol start="3"> when start is not 1
listItemblocks<li>…</li>
codeBlocktext nodes; attrs.language<pre><code class="language-js">…</code></pre>
horizontalRulenothing<hr>
text (inline)text, and marks, a listthe escaped text inside its marks' tags
hardBreak (inline)nothing<br>

Marks: link (attrs.href) is <a href="…">, bold is <strong>, italic is <em>, strike is <s>, code is <code>.

Requirements

  1. Text and attribute values are escaped: & to &amp;, < to &lt;, > to &gt;, " to &quot;, ' to &#39;.
  2. Marks nest in a fixed order, outermost first: link, bold, italic, strike, code, whatever order a node lists them in.
  3. Within one block, a mark that the next text node also has stays open. A mark is closed only when the next node lacks it or the fixed order forces it, and every mark is closed at the end of the block. Two links are the same mark only when their href is the same.
  4. Empty text nodes produce nothing and close nothing. A hardBreak writes <br> and leaves the open marks as they are.
  5. A link is kept only when new URL(href, base) gives the protocol http:, https: or mailto:, so relative links (/docs, #top) are kept. Any other link (javascript:, data:, an invalid URL) is dropped: its text and its other marks remain.
  6. A code block joins the text of its children, ignores their marks and escapes the result. Its class is written only when language is made of letters, digits, _, + and -.
  7. A TypeError is thrown for: a root that is not a doc, an unknown block, inline or mark type (including names such as toString), a non-listItem inside a list, a heading level that is not an integer from 1 to 6, and a list start that is not an integer.
  8. The document is never changed, not even the order of a node's marks.

Examples

JAVASCRIPT
toHTML({
  type: "doc",
  content: [
    { type: "heading", attrs: { level: 2 }, content: [{ type: "text", text: "Notes" }] },
    {
      type: "paragraph",
      content: [
        { type: "text", text: "Read ", marks: [{ type: "bold" }] },
        { type: "text", text: "this", marks: [{ type: "italic" }, { type: "bold" }] },
        { type: "text", text: " & that" },
      ],
    },
  ],
});
// "<h2>Notes</h2><p><strong>Read <em>this</em></strong> &amp; that</p>"
JAVASCRIPT
// One paragraph whose text node has the marks [{ type: "link", attrs: { href: "javascript:alert(1)" } }, { type: "bold" }]
// "<p><strong>click</strong></p>": the link is dropped, bold is kept
JAVASCRIPT
// A bulletList with one listItem holding a paragraph "a" and a nested bulletList with "b"
// "<ul><li><p>a</p><ul><li><p>b</p></li></ul></li></ul>"

Environment

  • Plain JavaScript in a browser page; the tests call the global toHTML from rich-text.js.
  • Images, tables, mentions, colours and other node types are not part of this problem: they throw. Turning HTML back into JSON is not part of it either.
  • Any built-in is allowed, including URL. The tests also parse your HTML to check every character's marks.

Hints

  1. Blocks hold blocks. Which function can render a block's children, whatever kind they are?
  2. For inline content, keep a stack of the marks that are open. Before writing the next text node, how many of the open marks can stay?
  3. Array.prototype.sort sorts in place. Whose array would you be sorting?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…