The ecosystem · packages/markdown
Markdown, parsed in Roc and rendered as markup
A Markdown parser in plain Roc: CommonMark, plus GitHub's tables, strikethrough, task lists, bare links and footnotes. The <Markdown> component renders it as the platform's markup, so a post is one tag. Raw HTML shows as text and a link that could run script points nowhere, unless you say otherwise. Frontmatter is read into a record you declare, and a folder of posts becomes a typed list, checked when the app is built.
Use it for text people write in Markdown: a blog, docs pages, release notes, a comment preview. The parser, the component and the frontmatter reader are plain Roc, so they run the same on the server, in the browser and in a test.
A first page#
Name the package in the app's header, as for charts: markdown: "../packages/markdown/main.roc". A component then imports markdown.Markdown and gives it Markdown, here a file of the site's own, imported as text:
### A morning by the river
We left at sunrise and walked the river path for an hour. A **heron**
stood on the far bank, two *wagtails* ran along the shingle, and a
kingfisher went by too fast for the camera.
- [x] Binoculars
- [x] Something warm to drink
- [ ] A faster camera
| Bird | Seen |
| :--- | ---: |
| Heron | 1 |
| Wagtail | 2 |
| Kingfisher | 1 |
> The best hour is the first one after sunrise.
The path is on [the county's walking map](https://example.com/walks).import markdown.Markdown
import "MarkdownFiles/walk.md" as walk : Str
view = |{}| <Markdown source={walk} />What it renders
A morning by the river
We left at sunrise and walked the river path for an hour. A heron stood on the far bank, two wagtails ran along the shingle, and a kingfisher went by too fast for the camera.
- Binoculars
- Something warm to drink
- A faster camera
| Bird | Seen |
|---|---|
| Heron | 1 |
| Wagtail | 2 |
| Kingfisher | 1 |
The best hour is the first one after sunrise.
The path is on the county's walking map.
The HTML it renders
<div class="markdown"><h3 id="a-morning-by-the-river">A morning by the river</h3><p>We left at sunrise and walked the river path for an hour. A <strong>heron</strong>
stood on the far bank, two <em>wagtails</em> ran along the shingle, and a
kingfisher went by too fast for the camera.</p><ul><li class="task"><input type="checkbox" checked disabled> Binoculars</li><li class="task"><input type="checkbox" checked disabled> Something warm to drink</li><li class="task"><input type="checkbox" disabled> A faster camera</li></ul><table><thead><tr><th align="left">Bird</th><th align="right">Seen</th></tr></thead><tbody><tr><td align="left">Heron</td><td align="right">1</td></tr><tr><td align="left">Wagtail</td><td align="right">2</td></tr><tr><td align="left">Kingfisher</td><td align="right">1</td></tr></tbody></table><blockquote><p>The best hour is the first one after sunrise.</p></blockquote><p>The path is on <a href="https://example.com/walks">the county's walking map</a>.</p></div>The component renders wherever the page does: on the server, or here, when the site was built. Each heading gets an id from its text, as on GitHub (a-morning-by-the-river). A tight list (no blank lines between items) has no <p> around its items.
rocx copies the component from the package's components/ into the app (Generated/markdown/Markdown.roc), because a package can't import the platform's Html for server and browser at once. rocx generate does it, and rocx dev and rocx build run that first. There is nothing to register: it is a package, not a plugin.
The document is data#
Md.parse turns Markdown into a document: a list of Blocks (paragraphs, headings, lists…), each holding Inlines (text, emphasis, links…), plain Roc values any function can walk. A table of contents is the list of headings; a reading time is a word count. Parse once, and give the document to <Markdown> as doc:
doc = Md.parse(guide)
<div class="guide">
<nav aria-label="The guide's sections">
<p class="time">{Md.reading_minutes(doc).to_str()} min read · {Md.words(doc).to_str()} words</p>
<ul>{...Md.headings(doc).map(|h| <li class:sub={h.level > 3}><a href={"#${h.id}"}>{h.text}</a></li>)}</ul>
</nav>
<Markdown doc={doc} />
</div>What it renders
Before you go
Check the tide table: the lower path floods at high water.
What to bring
Binoculars, a notebook, and a pencil, which writes in the rain.
On the path
Walk slowly and stop often. Most birds hear you before you see them, so stand still for a minute at each bend and let them come back.
Afterwards
Write down what you saw while you remember it: the time, the place, and how many.
Two headings with the same text get intro and intro-1, so each link finds its own heading. Blocks and inlines compare with ==, so a test can check a parse without rendering it.
Hooks#
A hook draws one kind of node your own way. <Markdown> has hooks for heading, code, link and image, plus footnote and notes for footnotes. A hook gets what the node says, its children already rendered, and returns the element. Here headings get an anchor, code blocks are drawn by this site's <Code> (with these docs' highlighter), and links to other sites open in a new tab:
### Counting what you see
A counter is a signal and a button:
```roc
(count!, set_count!) = create_signal!(0)
<button on:click={|| set_count!(count!() + 1)}>{count!().to_str()}</button>
```
The `.rocx` file it is in is plain Roc around the markup. More on
[roc-lang.org](https://www.roc-lang.org).<Markdown
source={sample}
heading={|h| Html.element("h${h.level.to_str()}", [Html.attr("id", h.id)], h.children.append(<a class="anchor" href={"#${h.id}"} aria-label="Link to this section">#</a>))}
code={|block| <Code title={block.lang} source={block.text.drop_suffix("\n")} markup={block.lang == "html"} numbers={Bool.False} />}
link={|l| if (l.url.starts_with("https://")) <a href={l.url} target="_blank" rel="noopener">{...l.children}</a> else Markdown.link(l)}
/>What it renders
Counting what you see#
A counter is a signal and a button:
(count!, set_count!) = create_signal!(0)
<button on:click={|| set_count!(count!() + 1)}>{count!().to_str()}</button>The .rocx file it is in is plain Roc around the markup. More on
roc-lang.org.
The defaults are public (Markdown.heading, Markdown.code, Markdown.link, Markdown.image, Markdown.footnote, Markdown.notes), so a hook can fall back on them, as the link hook above does.
To colour code, Markdown.highlight(lines) makes a code hook from any highlighter. lines(text, lang) returns the code's lines, each a list of tokens ({ kind : Str, text : Str }). A token with a kind becomes a <span class="t-kind"> for your CSS to colour.
<Markdown>#
| Prop | What it is |
|---|---|
source : Str | The Markdown. |
doc : List(Block) | Or the document, already parsed for something else too (a table of contents). |
raw : [Escape, Drop] | Raw HTML in the source: shown as text (Escape, the default) or left out (Drop). |
class : Str | The class of the <div> it renders in: "markdown" by default. |
heading : Markdown.Heading -> Html | Draws a heading, given { level, id, text, children }. The default is <h2 id="…"> for a level 2. |
code : Markdown.Code -> Html | Draws a code block, given { lang, info, text }. lang is the info string's first word (roc after three backticks), or "". The default is <pre><code class="language-roc">. |
link : Markdown.Link -> Html | Draws a link, given { url, title, children }. |
image : Markdown.Image -> Html | Draws an image, given { url, title, alt }. |
footnote : Markdown.Footnote -> Html | Draws a footnote's reference in the text, given { number, href, id }. |
notes : List(Markdown.Note) -> Html | Draws the notes at the end, given each one's { number, id, children, backs }. |
Every prop has a default: give source or doc, and <Markdown source={text} /> is a whole use. The component is pure (its view has no !): it makes markup from its props and runs nothing after.
Footnotes#
Footnotes are GitHub's: [^salt] in the text refers to a note, and [^salt]: About 2% of the flour's weight. on its own line is the note. Notes are numbered in the order the text first refers to them, and put at the end. A note nothing refers to is left out; a reference to a missing note stays text, as on GitHub. The default hooks draw what GitHub draws: a numbered <sup> link, and a list of notes, each with a link back (↩) to every reference. The back links are labelled in English, so a page in another language gives its own notes hook. Md.footnote_problems(source) lists what is wrong with a file's footnotes, for a build or a test.
Safe by default#
Markdown may hold raw HTML, and a link may point at javascript:. Neither reaches the page as written, unless you say so:
A <b>bold</b> claim, and [a link](javascript:alert(1)) that would run script.
<script>alert("hello")</script><Markdown source={unsafe} />
<Markdown source={unsafe} raw={Drop} />By default: the HTML as text
A <b>bold</b> claim, and a link that would run script.
<script>alert("hello")</script>
With raw={Drop}: the HTML left out
A bold claim, and a link that would run script.
Either way, the link's href is about:invalid#rocx-unsafe-url. A URL may be relative, or start with http:, https:, mailto: or tel:. Anything else is replaced, even with tabs or line breaks hidden in it, as the platform does for every href (Safety).
For HTML text from a source you wrote yourself, Md.to_html_with(doc, { raw: Trusted }) writes raw HTML as it is and checks no URLs. <Markdown> has no such option: the platform's Html can't put a string into a page as markup.
Frontmatter and collections#
Frontmatter is YAML between two --- lines at the top of a post. Declare its shape as a record type: a nominal type (:=), so fields can have defaults (??), with parser_for : _, so Roc writes its parser. The field types decide each value: 2026 is a number for a U64 field and text for a Str one.
---
title: The heron on the far bank
date: 2026-11-14
tags: [birds, river]
---
### Still as a post
It stood in the shallows for twenty minutes, then took a fish in one movement.A collection is a folder of such files, as in Astro. Collection.load reads each file's frontmatter into the record and parses its body. In a top-level value, the files are read when the app is built, so bad frontmatter fails the build, naming the file and the field: winter: draft: expected true or false, found "maybe". This page lists its two posts by hand:
import markdown.Collection
import markdown.Md
import "MarkdownFiles/posts/heron.md" as heron : Str
import "MarkdownFiles/posts/winter.md" as winter : Str
Post := { title : Str, date : Str, tags : List(Str) ?? [], draft : Bool ?? Bool.False }.{
parser_for : _
}
all : List(Collection.Entry(MarkdownPosts.Post))
all =
match Collection.load([{ path: "heron.md", source: heron }, { path: "winter.md", source: winter }]) {
Ok(entries) => entries
Err(failed) => crash Collection.describe(failed)
}What it renders
The heron on the far bank
heronFeeding birds in winter
winter
An entry is { id, data, body, doc }: its path without .md, its frontmatter, its body, and the body parsed. Frontmatter.read(source) does the same for one file. The YAML reader covers what frontmatter uses: maps, lists (- item or [a, b]), inline maps, quoted and plain text, | and > blocks, comments, and null, which leaves a field to its default. It doesn't read anchors, aliases or tags.
The modules#
roc test packages/markdown/main.roc runs the package's tests, 202 of them examples from the CommonMark and GitHub Flavored Markdown specs. The package's README has the full API.
| Module | What it does |
|---|---|
Md | parse(source) makes the document. to_html(doc) writes it as HTML text (for a feed or an email), and to_html_with(doc, { raw, ids }) with options. Also headings, slug, words, reading_minutes, safe_url, href, escape, and the footnote helpers. |
Block | A block: Paragraph, Heading, Code, Quote, Unordered, Ordered, Table, Raw (an HTML block), Rule, Footnotes. A list's item is { task : [None, Open, Done], blocks }. Block.plain(doc) is the document's words. |
Inline | What text is made of: Text, Code, Emph, Strong, Strike, Link, Image, Raw, Footnote, Break, SoftBreak. Inline.plain is the words. |
Frontmatter | read(source) decodes the frontmatter into your record and returns the body too; split(source) separates them without decoding. |
Yaml | The YAML frontmatter is written in: parse, decode (into any type with a parser), get, describe(problem). |
Collection | Files as entries: load, entry, find, describe, and the type Collection.Entry(data). |
In the browser#
This page's examples are rendered once, when the site is built, inside <NoHydration>: the browser keeps the server's markup, and none of the parser is in its wasm. Do the same for a post or a docs page. Hydrating <Markdown> carries the parser to the browser: about 225 KB more wasm (73 KB gzipped), measured in a small app.
A live preview is worth that. Keep the text in a signal, draft!, set by a <textarea>'s on:input.value, and render it in a hole: {Markdown.view({ source: draft!() })}. The hole renders again whenever the draft changes.
What works, and what doesn't yet#
Works today:
- The parser passes 649 of CommonMark 0.31.2's 652 examples. The other three are bare links (
https://…,www.…,someone@example.com), which GitHub's extension links and CommonMark leaves as text. Every GitHub extension example passes except the tag filter. <Markdown>, its hooks andMarkdown.highlight, on the server and in the browser.- Frontmatter read into a record, collections found under
content/, and a bad file failing the build.
Not yet (each a proposal in packages/markdown/PROPOSALS.md):
- Trusted raw HTML in
<Markdown>, or HTML from an allowlist. - The highlighter these docs use, in a package of its own, so any app can colour code.
- An RSS or Atom feed for a collection.
examples/journalwrites its own Atom feed. - A component that never hydrates, so
<Markdown>stays out of the wasm without<NoHydration>around it.
Limits: a reference's label is case folded for ASCII, Latin-1, Latin Extended-A, Greek, Cyrillic and ß, not all of Unicode. No heading attributes ({#id}), smart quotes or maths.
The component: packages/markdown/components/Markdown.rocx
import pf.Html
import markdown.Block
import markdown.Inline
import markdown.Md
## `source`, Markdown, as markup: `<Markdown source={post.body} />`. It renders where the page
## renders (on the server, and in the browser when a page is built there), and runs nothing after.
##
## Safe by default: raw HTML in the source is shown as text (`raw={Drop}` leaves it out), and a link
## whose URL could run script (`javascript:`) points nowhere, as the platform's `Html` has every
## `href`. Give `doc` instead of `source` when you have parsed it already (to make a table of
## contents from the same parse).
##
## Each kind of node that an app may want drawn its own way has a hook, given what the node says
## and its children already rendered: `heading` (an anchor beside it), `code` (highlighting:
## `Markdown.highlight`), `link` (outside links in a new tab), `image` (lazy loading), and a
## footnote's reference (`footnote`) and the notes at the end (`notes`: a heading in the page's
## language, say). The defaults are `Markdown.heading`, `Markdown.code`, `Markdown.link`,
## `Markdown.image`, `Markdown.footnote` and `Markdown.notes`, for a hook to fall back on.
Markdown := [].{
Props := {
source : Str ?? "",
doc : List(Block) ?? [],
raw : [Escape, Drop] ?? Escape,
class : Str ?? "markdown",
heading : (Markdown.Heading -> Html) ?? Markdown.heading,
code : (Markdown.Code -> Html) ?? Markdown.code,
link : (Markdown.Link -> Html) ?? Markdown.link,
image : (Markdown.Image -> Html) ?? Markdown.image,
footnote : (Markdown.Footnote -> Html) ?? Markdown.footnote,
notes : (List(Markdown.Note) -> Html) ?? Markdown.notes,
}
## A heading: its level (1 to 6), its id (unique in the document), its text, and its content.
Heading : { level : U64, id : Str, text : Str, children : List(Html) }
## A code block: its language (the info string's first word, `""` for none), the whole info
## string, and the code.
Code : { lang : Str, info : Str, text : Str }
Link : { url : Str, title : Str, children : List(Html) }
Image : { url : Str, title : Str, alt : Str }
## A footnote's reference in the text: its note's number, where the note is (`#fn-salt`), and
## this reference's own anchor (`fnref-salt`), which the note links back to.
Footnote : { number : U64, href : Str, id : Str }
## A note, at the document's end: its number, its anchor (`fn-salt`), what it says (rendered),
## and where each reference to it is (`#fnref-salt`, `#fnref-salt-2`), for the links back.
Note : { number : U64, id : Str, children : List(Html), backs : List(Str) }
## A highlighter's token: the kind of thing it is (`keyword`, `string`; `""` for plain), and its
## text. `site/Ui/Highlight.roc`'s tokens are these.
Token : { kind : Str, text : Str }
view : Markdown.Props -> Html
view = |props| {
blocks = if (props.doc.is_empty()) Md.parse(props.source) else props.doc
<div class={props.class}>{...render_blocks(blocks, props)}</div>
}
## `<h2 id="…">…</h2>`.
heading : Markdown.Heading -> Html
heading = |found| Html.element("h${found.level.to_str()}", [Html.optional("id", found.id)], found.children)
## `<pre><code class="language-roc">…</code></pre>`.
code : Markdown.Code -> Html
code = |block| <pre><code class??={language(block.lang)}>{block.text}</code></pre>
## `<a href="…" title="…">…</a>`.
link : Markdown.Link -> Html
link = |found| <a href={Md.href(found.url)} title??={found.title}>{...found.children}</a>
## `<img src="…" alt="…">`.
image : Markdown.Image -> Html
image = |found| <img src={Md.href(found.url)} alt={found.alt} title??={found.title} />
## `<sup class="footnote-ref"><a href="#fn-salt" id="fnref-salt">1</a></sup>`, as GitHub has it.
footnote : Markdown.Footnote -> Html
footnote = |found| <sup class="footnote-ref"><a href={found.href} id={found.id}>{found.number.to_str()}</a></sup>
## `<section class="footnotes"><ol><li id="fn-salt">…</li></ol></section>`, each note followed by
## a link back to each reference to it (`↩`, labelled "Back to reference 1" in English: a hook
## says it in another language).
notes : List(Markdown.Note) -> Html
notes = |found|
<section class="footnotes">
<ol>
{...found.map(|note| <li id={note.id}>{...note.children.concat(note.backs.map_with_index(|href, i| <a href={href} class="footnote-backref" aria-label={"Back to reference ${note.number.to_str()}${if (i == 0) "" else "-${(i + 1).to_str()}"}"}>↩</a>))}</li>)}
</ol>
</section>
## A `code` hook that colours code with a highlighter: `lines(text, lang)` is the code's lines,
## each a list of tokens, and each token that has a kind is a `<span class="t-kind">`. A
## highlighter that doesn't know the language can give each line as one plain token.
##
## <Markdown source={text} code={Markdown.highlight(|text, _| Highlight.lines(text, Code))} />
highlight : (Str, Str -> List(List(Markdown.Token))) -> (Markdown.Code -> Html)
highlight = |lines| |block| {
found = lines(block.text.drop_suffix("\n"), block.lang)
last = found.len()
<pre><code class??={language(block.lang)}>{...found.map_with_index(|tokens, index| line(tokens, index + 1 == last))}</code></pre>
}
<story name="Prose">
<Markdown source={"# A heading\n\nSome *emphasis*, some **strong**, `code` and a [link](https://example.com).\n\n- one\n- two\n\n> A quote."} />
</story>
<story name="Tables and tasks">
<Markdown source={"| Name | Count |\n|:-----|------:|\n| Apples | 3 |\n| Pears | 12 |\n\n- [x] parse\n- [ ] render"} />
</story>
<story name="Footnotes">
<Markdown source={"Bread keeps for days[^salt], longer in a cloth[^cloth].\n\n[^salt]: About 2% of the flour's weight.\n[^cloth]: Linen, not plastic."} />
</story>
<story name="Raw HTML, escaped">
<Markdown source={"<script>alert(1)</script>\n\nA <b>bold</b> claim, and [a bad link](javascript:alert(1))."} />
</story>
}
language : Str -> Str
language = |lang| if (lang.is_empty()) "" else "language-${lang}"
## One line of highlighted code, and its line ending unless it is the last.
line : List(Markdown.Token), Bool -> Html
line = |tokens, last| <>{...tokens.map(token)}{if (last) <></> else Html.text("\n")}</>
token : Markdown.Token -> Html
token = |{ kind, text }| if (kind.is_empty()) Html.text(text) else <span class={"t-${kind}"}>{text}</span>
render_blocks : List(Block), Markdown.Props -> List(Html)
render_blocks = |blocks, props| blocks.map(|block| render_block(block, props))
render_block : Block, Markdown.Props -> Html
render_block = |block, props|
match block {
Paragraph(content) => <p>{...inlines(content, props)}</p>
Heading(found) => (props.heading)({ level: found.level, id: found.id, text: Inline.plain(found.content), children: inlines(found.content, props) })
Code(found) => (props.code)({ lang: found.lang, info: found.info, text: found.text })
Quote(inner) => <blockquote>{...render_blocks(inner, props)}</blockquote>
Unordered(list) => <ul>{...list.items.map(|item| render_item(item, list.tight, props))}</ul>
Ordered(list) => <ol start??={if (list.start == 1) "" else list.start.to_str()}>{...list.items.map(|item| render_item(item, list.tight, props))}</ol>
Table(table) => {
cell = |tag, index, content| Html.element(tag, [Html.optional("align", align(table.align.get(index) ?? Default))], inlines(content, props))
row = |tag, cells| <tr>{...cells.map_with_index(|content, index| cell(tag, index, content))}</tr>
body = if (table.rows.is_empty()) <></> else <tbody>{...table.rows.map(|cells| row("td", cells))}</tbody>
<table><thead>{row("th", table.head)}</thead>{body}</table>
}
Raw(html) =>
match props.raw {
Escape => <p>{html}</p>
Drop => <></>
}
Rule => <hr />
Footnotes(found) =>
(props.notes)(
found.map(
|note| {
number: note.number,
id: Md.footnote_id(note.label),
children: render_blocks(note.blocks, props),
backs: List.repeat(0, note.refs).map_with_index(|_, i| "#${Md.footnote_ref_id(note.label, i + 1)}"),
},
),
)
}
## An item: in a tight list, its paragraphs without their `<p>`; a task's box first.
render_item : Block.Item, Bool, Markdown.Props -> Html
render_item = |item, tight, props| {
box = match item.task {
None => []
Open => [<input type="checkbox" disabled />, Html.text(" ")]
Done => [<input type="checkbox" checked disabled />, Html.text(" ")]
}
content = item.blocks.join_map(
|block|
match block {
Paragraph(inner) if tight => inlines(inner, props)
_ => [render_block(block, props)]
},
)
<li class:task={item.task != None}>{...box.concat(content)}</li>
}
align : [Default, Left, Center, Right] -> Str
align = |way|
match way {
Default => ""
Left => "left"
Center => "center"
Right => "right"
}
inlines : List(Inline), Markdown.Props -> List(Html)
inlines = |content, props| content.map(|inline| render_inline(inline, props))
render_inline : Inline, Markdown.Props -> Html
render_inline = |inline, props|
match inline {
Text(text) => Html.text(text)
Code(code) => <code>{code}</code>
Emph(inner) => <em>{...inlines(inner, props)}</em>
Strong(inner) => <strong>{...inlines(inner, props)}</strong>
Strike(inner) => <del>{...inlines(inner, props)}</del>
Link(found) => (props.link)({ url: found.url, title: found.title, children: inlines(found.content, props) })
Image(found) => (props.image)({ url: found.url, title: found.title, alt: found.alt })
Raw(html) =>
match props.raw {
Escape => Html.text(html)
Drop => <></>
}
Footnote(found) => (props.footnote)({ number: found.number, href: "#${Md.footnote_id(found.label)}", id: Md.footnote_ref_id(found.label, found.nth) })
Break => <br />
SoftBreak => Html.text("\n")
}The examples: site/Demos/MarkdownPosts.rocx and the others
import pf.Html
import markdown.Markdown
import "MarkdownFiles/walk.md" as walk : Str
## The markdown page's first example: a short Markdown file, rendered by `<Markdown>` when the
## site is built.
MarkdownDemo := [].{
view : {} -> Html
view = |{}| <Markdown source={walk} />
}import pf.Html
import markdown.Markdown
import markdown.Md
import "MarkdownFiles/guide.md" as guide : Str
## The markdown page's table of contents: the guide parsed once, its headings listed (each a link
## to its id) with its reading time, and the same parse rendered.
MarkdownToc := [].{
view : {} -> Html
view = |{}| {
doc = Md.parse(guide)
<div class="guide">
<nav aria-label="The guide's sections">
<p class="time">{Md.reading_minutes(doc).to_str()} min read · {Md.words(doc).to_str()} words</p>
<ul>{...Md.headings(doc).map(|h| <li class:sub={h.level > 3}><a href={"#${h.id}"}>{h.text}</a></li>)}</ul>
</nav>
<Markdown doc={doc} />
</div>
}
<style>
.guide {
display: grid;
grid-template-columns: minmax(11rem, 0.4fr) minmax(0, 1fr);
gap: var(--space-5);
align-items: start;
}
nav {
padding: var(--space-3) var(--space-4);
border-radius: var(--radius);
background: var(--fill);
font-size: var(--size-sm);
}
.time {
margin: 0 0 var(--space-2);
color: var(--text-muted);
}
ul {
margin: 0;
padding-left: var(--space-4);
}
.sub {
margin-left: var(--space-4);
list-style: circle;
}
@media (max-width: 40rem) {
.guide {
grid-template-columns: minmax(0, 1fr);
}
}
</style>
}import pf.Html
import markdown.Markdown
import "MarkdownFiles/hooks.md" as sample : Str
import ../Ui/Code
## The markdown page's hooks: each heading with an anchor after it, each code block drawn by the
## site's own `<Code>` (coloured by the docs' highlighter), and links to other sites opened in a new
## tab, the rest as `Markdown.link` draws them.
MarkdownHooks := [].{
view : {} -> Html
view = |{}|
<Markdown
source={sample}
heading={|h| Html.element("h${h.level.to_str()}", [Html.attr("id", h.id)], h.children.append(<a class="anchor" href={"#${h.id}"} aria-label="Link to this section">#</a>))}
code={|block| <Code title={block.lang} source={block.text.drop_suffix("\n")} markup={block.lang == "html"} numbers={Bool.False} />}
link={|l| if (l.url.starts_with("https://")) <a href={l.url} target="_blank" rel="noopener">{...l.children}</a> else Markdown.link(l)}
/>
<style>
.anchor {
margin-left: var(--space-2);
color: var(--text-faint);
text-decoration: none;
}
.anchor:hover,
.anchor:focus {
color: var(--accent-strong);
}
</style>
}import pf.Html
import markdown.Markdown
import "MarkdownFiles/unsafe.md" as unsafe : Str
## The markdown page's safety: Markdown with raw HTML and a `javascript:` link in it, rendered as
## `<Markdown>` does by default (the HTML shown as text, the link pointing nowhere) or with
## `raw={Drop}` (the HTML left out).
MarkdownSafety := [].{
view : { drop : Bool } -> Html
view = |{ drop }|
if drop {
<Markdown source={unsafe} raw={Drop} />
} else {
<Markdown source={unsafe} />
}
}import pf.Html
import markdown.Collection
import markdown.Md
import "MarkdownFiles/posts/heron.md" as heron : Str
import "MarkdownFiles/posts/winter.md" as winter : Str
## The markdown page's collection: two Markdown files whose frontmatter is a `Post`, read when the
## site is built, so a file whose frontmatter is wrong fails the build, naming the file and the
## field. Each post shows its title, date, tags and reading time; a draft says so.
MarkdownPosts := [].{
Post := { title : Str, date : Str, tags : List(Str) ?? [], draft : Bool ?? Bool.False }.{
parser_for : _
}
all : List(Collection.Entry(MarkdownPosts.Post))
all =
match Collection.load([{ path: "heron.md", source: heron }, { path: "winter.md", source: winter }]) {
Ok(entries) => entries
Err(failed) => crash Collection.describe(failed)
}
view : {} -> Html
view = |{}|
<ul class="posts">
{...MarkdownPosts.all.map(|post| <li><p class="title">{post.data.title}</p><p class="meta">{post.data.date} · {Md.reading_minutes(post.doc).to_str()} min · {Str.join_with(post.data.tags, ", ")}{if (post.data.draft) " · draft" else ""}</p><p class="id"><code>{post.id}</code></p></li>)}
</ul>
<style>
.posts {
display: grid;
gap: var(--space-3);
margin: 0;
padding: 0;
list-style: none;
}
li {
padding: var(--space-3) var(--space-4);
border-radius: var(--radius);
background: var(--bg-raised);
}
p {
margin: 0;
}
.title {
font-weight: 600;
}
.meta {
color: var(--text-muted);
font-size: var(--size-sm);
}
.id {
font-size: var(--size-xs);
}
</style>
}