# Markdown

    Markdown text=answer streaming=live font-size=15

Markdown, laid out: what react-markdown (with remark-gfm) and Streamdown are
to a React app. It is a component of the kit, in Mote (`kit/code.mote`), and
it has two halves:

- **Reading** is the `syntax` battery's (`batteries/syntax/lib.rs`, Rust, in
  a worker): `syntax.parse(text, "markdown")` gives the document as a tree
  ready to draw, with everything decided: which marks are emphasis, where a
  link goes, a heading's id, a footnote's number. Any page can ask for that
  tree and draw it its own way (docs/card.md, "text to a tree").
- **Drawing** is Mote: each node becomes a real element (`h1`…`h6`, `p`,
  `ul`, `ol`, `li`, `blockquote`, `table`, `pre`, `a`, `em`, `strong`,
  `code`, `img`, `sup`, `hr`), styled on the element, code coloured by
  `Highlight`.

Gallery: `examples/kit/markdown.mote`. Test: `tests/kit_markdown.real.mjs`
(every construct below, as the HTML it becomes; the hostile addresses; a
text cut at every position).

| prop        | type   |                                                                 |
|-------------|--------|-----------------------------------------------------------------|
| `text`      | string | the Markdown. Drawn again whenever it changes.                  |
| `streaming` | bool   | the text is still arriving (see Streaming). Left out: false.    |

Styles written on it are honoured; it takes the `font-size` written on it
(everything inside is in `em`), and its first and last block have no outer
margin, so it sits flush in a chat bubble or a card. It raises no events.

The battery answers from a worker, so the element is drawn a moment after
its text is given (a millisecond or two; the first time on a page, the time
it takes to start the worker). Until the first answer it is empty; after
that it shows what it had until the new answer comes. While an answer is
awaited it carries `data-busy`. If the battery fails, the text is shown as
it is written.

## What is supported

CommonMark:

- Headings: `# ATX` (1 to 6, closing `#`s allowed) and setext (`===`, `---`).
  Each gets a slug `id` (lower case, punctuation dropped, spaces to `-`; a
  repeat gets `-1`, `-2`).
- Paragraphs; hard breaks by two trailing spaces or a trailing backslash.
- Emphasis and strong with the left- and right-flanking delimiter rules and
  the rule of three: `***a** b*`, `snake_case_words` (untouched), `__init__`.
  Note that by those rules `2*3*4` *is* emphasis (`*` works inside words;
  `_` does not); `2 * 3 * 4` is not.
- Code spans with any backtick run length (`` `` a ` b `` ``).
- Links and images: inline `[a](url "title")`, `<angle bracket>` destinations,
  parentheses in the URL, nested brackets in the text, titles in `"` `'` `()`;
  reference style, full `[a][ref]`, collapsed `[ref][]` and shortcut `[ref]`,
  with definitions anywhere (title on the next line allowed). No link inside
  a link.
- Autolinks `<https://…>` and `<a@b.c>`.
- Block quotes, with lazy continuation and nesting.
- Bullet (`-` `+` `*`) and ordered (`1.` `1)`) lists: tight and loose,
  nested by indentation, start numbers, a change of marker starts a new list,
  only `1.` may interrupt a paragraph, items holding paragraphs, code blocks,
  quotes and lists.
- Indented and fenced code blocks (```` ``` ```` and `~~~`, any length, with an
  info string; an unclosed fence runs to the end).
- Thematic breaks, backslash escapes, numeric entities and the common named
  ones (about 150: `&amp; &copy; &mdash; &rarr; &alpha;` …; an unknown name
  stays as written).

GitHub's additions:

- Tables, with `:--`, `:-:`, `--:` alignment, inline content in cells, `\|`
  for a pipe in a cell, short rows padded and long rows cut.
- Strikethrough `~~a~~` (and `~a~`), as a `del`.
- Task list items `- [ ]` / `- [x]`: disabled checkboxes, no bullets.
- Footnotes `[^name]` with `[^name]: text` (further paragraphs indented four
  spaces): numbered in the order the text first points at them, listed at
  the end, each with a link back for every place that points at it.
- Bare `https://…`, `www.…` and mail addresses become links.

Fenced and indented code is drawn by `Highlight` (by the fence's first info
word; a language it does not know is shown plain). Each code block has a
header with the language name (`text` when none) and a copy button that shows
a check for two seconds, and scrolls sideways.

## What is not

- **Raw HTML is never passed through.** Tags in the text are shown as text.
- Math: `$…$` and `$$…$$` are left as text.
- No definition lists, emoji shortcodes, `==mark==`, sub/superscript, or
  alert blocks (`> [!NOTE]` is a plain quote).
- Named entities outside the table are left as written (`&nope;`).
- Tabs count as four columns in indentation only.
- A few corners of CommonMark are approximated: lazy continuation is decided
  line by line rather than by the open-block stack, a link reference
  definition's destination is not checked for balanced parentheses, case
  folding of reference labels is lower-casing, and what counts as
  punctuation beside `*` and `_` is ASCII's and the common Unicode blocks,
  not the whole of Unicode's categories.
- Nothing is drawn more than 40 blocks deep or 60 marks deep (a text of ten
  thousand `>` is hostile, not deep): what is deeper is shown as its words.
- Unlike react-markdown there are no `components` overrides or plugins: a
  page that wants its own drawing asks the battery for the tree and draws
  that. Unlike Streamdown there are no Mermaid diagrams, no KaTeX, and no
  download button on tables or code.

## Safety

The text is treated as hostile (it may come from a model or a stranger):

- Nothing in the text becomes markup. The component builds elements and
  sets their text; there is no HTML string anywhere. Raw HTML, comments and
  `<script>` show as text.
- A link or image keeps its address only if it is `http:`, `https:`,
  `mailto:`, `tel:`, a relative path (or `#fragment`), or, for images only,
  `data:image/…` (png, gif, jpeg, webp, avif, bmp, ico, svg). The check is
  made after entities and escapes are decoded and with the characters a
  browser ignores (controls, spaces, tabs, soft hyphens, zero-width)
  removed, so `JaVaScRiPt:`, `java&#9;script:` and `&#106;avascript:` are
  caught. Anything else (`javascript:`, `vbscript:`, `data:text/html`,
  `file:`, `blob:` …) is dropped: the link's words or the image's alt text
  stay, as plain text. The battery decides it (such a link is not a `link`
  node at all), and the component checks the scheme again before it writes
  an `href` or a `src`.
- Addresses are percent-encoded where needed; titles and alt text are set
  as attributes' values, never written into markup.
- Links open in a new tab with `rel="noopener noreferrer"`. A `#fragment`
  link scrolls to that id inside the same element without changing the
  page's address (so it cannot disturb the page's routes). A link to a
  path (`/models`) stays in the page: in an app with routes it is the app's
  own address, and goes there as a `link` does.
- No inline event handler (`on…=`) is ever written.

## Streaming

With `streaming` on, what is unfinished at the **end** of the text is
finished for it or held back, so no half-written marker shows (the battery
does this: `syntax.parse(text, "markdown", {streaming: true})`):

- an unclosed code fence is a code block so far (a half-typed closing fence
  is not shown as code);
- unclosed `**`, `*`, `_`, `~~` and `` ` `` are closed at the end of what has
  arrived; a marker with nothing after it yet waits;
- `[text`, `[text](http://…` and `[text][ref` show the text as a link
  without an address (`a.hk-md-pending`) until the rest arrives; an image on
  its way shows nothing; a reference or footnote whose definition has not
  arrived yet (they usually come last) is shown as the link or number it
  will be;
- a last line that is only the start of something (`-`, `1.`, `#`, `---`,
  `===`, a fence, a task box) waits, so a paragraph does not flicker into a
  heading or an empty bullet; a table's first row waits for its second, and
  a row being written fills in cell by cell.

Only the end is treated this way: a `**` left open in an earlier paragraph
is shown as written. Set `streaming` false when the text is complete.

## What is kept between one text and the next

The whole text is read again each time (20,000 characters take the battery
half a millisecond), but what was drawn is kept:

- The battery gives each block right under the document a `key`: its kind
  and which of its kind it is (`paragraph:3`, `code:1`). Text added at the
  end changes no earlier key, so the `for` that draws the blocks keeps every
  row.
- Each such block crosses from the worker as text (JSON; the `packed`
  option). A block whose text is as it was is the same block, and nothing
  under it runs again.
- A block that did change is changed where it stands: a paragraph gets its
  new words, a code block its new lines. Its element is the same element.

So a selection, a pressed copy button, a loaded image and a scrolled code
block survive text arriving after them, with `streaming` or without (the
edit-and-preview pair in the gallery). Measured in the gallery, a
20,000-character answer arriving in 200 chunks costs about 1.6 ms a chunk
from the text given to the page laid out (0.5 ms of it the battery's, in the
worker); 2,000 lines given at once are drawn in about 50 ms (the battery:
2 ms), and a line added to them in about 7.

## Classes

Styles are written on the elements (Mote's way: there is no stylesheet to
override); colours are the page's roles, so light and dark follow the page.
These classes are there for a page or a test to find things by:

| class            | what                                                           |
|------------------|----------------------------------------------------------------|
| `hk-md`          | the element itself; `data-busy` while an answer is awaited, `data-streaming` |
| `hk-md-code`     | a code block's frame (card background, line border, 8px radius) |
| `hk-md-bar`      | its header                                                      |
| `hk-md-lang`     | the language name in the header                                 |
| `hk-md-copy`     | the copy button; `[data-ok]` while the check shows (`hk-md-cp`, `hk-md-ok`: its two icons, one at a time) |
| `hk`, `data-lang` | on the `pre` inside (it is `Highlight`'s): the language as written |
| `hk-md-table`    | the frame a table scrolls sideways in                           |
| `hk-md-tasks`    | a list that has task items; `hk-md-task` on each such `li`      |
| `hk-md-ref`      | a footnote's number in the text (`sup`)                         |
| `hk-md-fn`       | the footnotes at the end (`section`); `hk-md-back` its back-links |
| `hk-md-pending`  | a link whose address has not arrived yet (streaming)            |

Ids written: heading slugs, `fn-N` on a footnote, `fnref-N` (`fnref-N-2` for
a second mention) on its number. Two Markdowns on a page may repeat them; a
press on a link to `#something` looks for it inside its own element, goes
there, and leaves the page's address alone.

## What changed when it became a component

It used to be an element the runtime built (a JavaScript widget that made a
string of HTML). What a page sees differently:

- It is drawn a moment after its text is given, not in the same instant.
- There is no `node.md(text)` / `MDH(text)` giving HTML as a string: ask
  `syntax.parse` for the tree instead.
- There is no stylesheet scoped to `.hk-md`: the styles are on the elements.
- A code block's `code` has no `language-…` class; its `pre` has
  `data-lang`.
- Three things are done by reaching the element itself from the component,
  because Mote's markup cannot say them yet: a list's `start` (no such
  attribute on `ol`), struck text's `del` (no such tag: it is made inside a
  `span` that takes no room), and the press on an in-text link (a press
  handler cannot stop a link being followed). Each is a small `fn` in
  `kit/code.mote` that says so where it stands, and goes when the markup can.
