3
0
mirror of https://github.com/larvit/adf-codec.git synced 2026-11-18 06:05:43 +01:00

Write media, colours, alignment, panels, expands and task lists as HTML in adfToHtml and read them back in htmlToAdf

This commit is contained in:
2026-11-15 00:03:44 +01:00
committed by Lillem4n
parent 4f81a65254
commit f5c8a48706
24 changed files with 1062 additions and 123 deletions
+12
View File
@@ -2,6 +2,18 @@
## Unreleased
- `adfToHtml` writes a media single, a media group and a caption as `<figure class="adf-media-single">` holding an
`<img>` and a `<figcaption>`, and as `<div class="adf-media-group">` of `<span class="adf-file">` files, where
`0.3.1` wrote the carry element, and `htmlToAdf` reads them back. A link around the image is the media's link
mark. The carry element `0.3.1` wrote for them still reads.
- `adfToHtml` writes underline as `<u>`, subscript and superscript as `<sub>` and `<sup>`, a text colour as
`<span style="color:…">`, a background colour as `<mark style="background-color:…">` and a paragraph's or
heading's alignment as `style="text-align:…"`, where `0.3.1` wrote the carry element, and `htmlToAdf` reads them
back. The carry element `0.3.1` wrote for them still reads. Indentation still rides the carry element.
- `adfToHtml` writes a panel as `<div class="adf-panel">`, an expand and a nested expand as `<details>` with the
title in a `<summary>`, a task list as `<ul class="adf-task-list">` of items each a checkbox then its text, and a
decision list as `<ul class="adf-decision-list">`, where `0.3.1` wrote the carry element, and `htmlToAdf` reads
them back. The carry element `0.3.1` wrote for them still reads.
- `adfToHtml` writes a `strike` mark as `<del>`, where `0.3.1` wrote the carry element, and `htmlToAdf` reads
`<del>` as `strike`. The carry element `0.3.1` wrote for it still reads.
- `adfToPlainText` writes a document as text with no markup, for a search index, a notification or an
+11 -4
View File
@@ -472,6 +472,7 @@ Ping !adf:mention[@Mikael]{id=5b10a2} — !adf:status[In review]{color=yellow}
| `panel` | a container, the type its argument: `!adf:panel info` |
| `subsup`, `textColor`, `underline` | inline directive marks around their text, `!adf:textColor[**Overdue**]{color="#ae2e24"}` |
| `syncBlock`, `bodiedSyncBlock` | a leaf and a container |
| `taskList`, `taskItem` | `<ul class="adf-task-list">`, `<li class="adf-task" data-state="DONE"><input type="checkbox" checked="" disabled=""> text</li>` |
| `table`, `tableRow`, `tableCell`, `tableHeader` richer than a pipe table | containers nesting block content |
| `taskList`, `taskItem`, `blockTaskItem` | containers, the state an argument: `!adf:taskItem DONE` |
| any other node type, or a node where its spelling cannot stand | the opaque carry: a code fence ```` ```adf:<type> ```` holding the node's JSON, or inline `!adf:carry{json="…"}` |
@@ -567,15 +568,21 @@ content. No stylesheet ships. The complete dialect:
| `bulletList`, `orderedList`, `listItem` | `<ul>`, `<ol>`, `<ol start="3">` for an `order` of 3, and `<li>`; an item's first paragraph stands bare, `<li>Bolt</li>`, or as `<li><p data-local-id="p1">Bolt</p></li>` where it holds an attribute |
| `codeBlock` | `<pre><code class="language-js">`, no `class` without a language |
| `date`, `emoji`, `mention`, `status` | `<time class="adf-date" datetime="2025-08-25" data-timestamp="…">2025-08-25</time>`, `<span class="adf-emoji" data-id="1f389" data-short-name=":tada:">🎉</span>`, `<span class="adf-mention" data-id="5b10a2">@Mikael</span>`, `<span class="adf-status" data-color="yellow">In review</span>` |
| `decisionList`, `decisionItem` | `<ul class="adf-decision-list">`, `<li class="adf-decision" data-state="DECIDED">` |
| `expand`, `nestedExpand` | `<details class="adf-expand">`, `<details class="adf-nested-expand">`, a `<summary>` holding the `title` |
| `hardBreak` | `<br>` |
| `heading` | `<h1>` to `<h6>` |
| `heading` | `<h1>` to `<h6>`; `style="text-align:center"` for a centered one, `text-align:right` for one aligned to the end |
| `inlineCard` holding a `url`, or `data` and no `url` | `<a class="adf-inline-card" href="…">…</a>`; for `data`, `href` is the URL `data` holds, the text its name, else that URL, and `data-data` the whole `data` as JSON |
| `link` | `<a href="…" title="…">` |
| `mediaSingle` holding an external `media`, centered, uncaptioned, holding no other attribute such as `width` or `localId` | `<p><img src="…" alt="…"></p>`, the image inside `<a>` where a link marks it; an image holding such an attribute, as editor-written ones do, rides the carry element |
| `paragraph` | `<p>` |
| `mediaGroup` | `<div class="adf-media-group">` holding a `<span class="adf-file" data-id="…" data-type="file"></span>` for each `media` |
| `mediaSingle` holding an external `media`, centered, uncaptioned, holding no other attribute such as `width` or `localId` | `<p><img src="…" alt="…"></p>`, the image inside `<a>` where a link marks it |
| any other `mediaSingle` | `<figure class="adf-media-single" data-layout="wide">` holding the `<img>`, then the caption as `<figcaption>` |
| `panel` | `<div class="adf-panel" data-panel-type="info">` |
| `paragraph` | `<p>`; `style="text-align:center"` or `text-align:right`, as on a heading |
| `rule` | `<hr>` |
| `table`, `tableRow`, `tableCell`, `tableHeader` | `<table>`, `<thead>` for a first row of `tableHeader` cells alone, `<tbody>`, `<tr>`, `<td>` and `<th>`; a cell's first paragraph stands as an item's does, and `<td colspan="2" rowspan="2" style="background-color:#fffae6" data-colwidth="120,80">` writes its attributes |
| `text` marked `code`, `em`, `strike`, `strong` | `<code>`, `<em>`, `<del>`, `<strong>`, the first mark outermost |
| `text` marked `code`, `em`, `strike`, `strong`, `subsup`, `underline` | `<code>`, `<em>`, `<del>`, `<strong>`, `<sub>` or `<sup>`, `<u>`, the first mark outermost |
| `text` marked `textColor`, `backgroundColor` | `<span style="color:#ae2e24">`, `<mark style="background-color:#fffae6">` |
| an attribute its type holds that its element does not write, such as `localId`, on a paragraph, heading, quote, list, list item, table, row, cell, code block, rule, emoji, mention, status, date or card | `data-*` named as HTML's `dataset` names it: `<p data-local-id="a1f3">` |
| any other node, or a node holding what its element cannot, except a shape Atlassian's schema forbids, which is refused ([The errors](#the-errors)) | `<div class="adf-carry" data-adf="{…}"><p>its content</p></div>`, a `<span>` inline |
+20 -3
View File
@@ -420,7 +420,7 @@ for HTML+, its Rovo MCP server's HTML for agents; a published spec reopens the g
The HTML dialect mirrors the markdown flavour: semantic elements, stable `adf-*` classes, `data-*`
for what HTML cannot express, text always escaped. No stylesheet ships.
The spellings, `spec/html.md`, are seven writer panels' (2026-10-23, -24, 2026-11-04, -05 and -14), each of a
The spellings, `spec/html.md`, are eight writer panels' (2026-10-23, -24, 2026-11-04, -05 and -14), each of a
product manager, an engineer and a support agent. The first picked each of these 3 of 3:
- an image standing alone as `<p><img …></p>`, over `<figure>` and a bare `<img>`;
@@ -495,6 +495,23 @@ table is a section per corpus example, led by a summary table expected `<s>` or
`text-decoration:line-through`. They chose `<del>` because its name says the text is removed, and
GFM's renderers write `<del>` for `~~`.
An eighth panel (2026-11-14, three readers in the same roles; seven for indentation) picked, 3 of 3:
- a `mediaSingle` as `<figure class="adf-media-single" data-*>` holding an `<img>`, inside `<a>` where
a link marks it, and a `<figcaption>`; a `mediaGroup` as `<div class="adf-media-group">` holding a
`<span class="adf-file" data-*>` for each file;
- `<u>`, `<sub>` and `<sup>`, `<span style="color:…">` and `<mark style="background-color:…">`;
- `style="text-align:center"` and `text-align:right` for an `alignment` of `center` and `end`;
- `<details class="adf-expand">` and `<details class="adf-nested-expand">` with the `title` as the
`<summary>` and `<div class="adf-panel" data-panel-type="…">`;
- a task list as `<ul class="adf-task-list">` of `<li class="adf-task" data-state="DONE">` holding
`<input type="checkbox" checked="" disabled="">` and the text, a decision list the same with
`adf-decision-list`, `adf-decision` and no checkbox. `checked=""` and `disabled=""` are spelled with
a value because the attribute grammar has no bare attribute.
For an `indentation` mark, five of seven picked `data-indent-level`; whether a `margin-left` style
goes with it split 4 to 3, so it rides the carry until `todo.md` item 184 is answered.
## `htmlToAdf` also reads the dialect as a browser serializes it
2026-10-28, the maintainer. Goal 6. Valid while a viewer/editor app may show `adfToHtml`'s HTML in a
@@ -1298,8 +1315,8 @@ the copy is refused as `unmappable-html` rather than saved. They expected:
- The `strike` mark in Emphasis and strikethrough as `<s>relay</s>` or `<del>relay</del>`, which
`adfToHtml` writes as `<del>` (§The HTML dialect).
`todo.md` item 134 will write the rest; its writer panel picks the spelling with these
expectations as input. The Date row drew 1 of 3 not reasonable, so four more readers (bot,
The writer panel of §The HTML dialect picked the rest of the spellings with these
expectations as input; `blockTaskItem` and a nested task list ride the carry. The Date row drew 1 of 3 not reasonable, so four more readers (bot,
reader of the markdown, export/indexing, viewer/editor) read it, and 5 of 7 found it reasonable.
`adfToLosslessMarkdown` keeps writing `!adf:date{timestamp=1756080000000}`. The two who rejected
it wanted the day shown, as `!adf:date[2025-08-25]{timestamp=…}`.
+13 -4
View File
@@ -373,9 +373,15 @@ Weather permitting.
`adfToHtml`, round-trip holds:
```html
<div class="adf-carry" data-adf="{&quot;attrs&quot;:{&quot;panelType&quot;:&quot;warning&quot;},&quot;content&quot;:[{&quot;content&quot;:[{&quot;text&quot;:&quot;Check the collation before importing.&quot;,&quot;type&quot;:&quot;text&quot;}],&quot;type&quot;:&quot;paragraph&quot;}],&quot;type&quot;:&quot;panel&quot;}"><p>Check the collation before importing.</p></div>
<div class="adf-carry" data-adf="{&quot;attrs&quot;:{&quot;localId&quot;:&quot;01a0337c-561a-75aa-b629-3801f68839ad&quot;,&quot;panelType&quot;:&quot;info&quot;},&quot;content&quot;:[{&quot;content&quot;:[{&quot;text&quot;:&quot;Backups run at 02:00.&quot;,&quot;type&quot;:&quot;text&quot;}],&quot;type&quot;:&quot;paragraph&quot;}],&quot;type&quot;:&quot;panel&quot;}"><p>Backups run at 02:00.</p></div>
<div class="adf-carry" data-adf="{&quot;attrs&quot;:{&quot;panelColor&quot;:&quot;#c9372c&quot;,&quot;panelIcon&quot;:&quot;:rainbow:&quot;,&quot;panelIconId&quot;:&quot;1f308&quot;,&quot;panelIconText&quot;:&quot;🌈&quot;,&quot;panelType&quot;:&quot;custom&quot;},&quot;content&quot;:[{&quot;content&quot;:[{&quot;text&quot;:&quot;Weather permitting.&quot;,&quot;type&quot;:&quot;text&quot;}],&quot;type&quot;:&quot;paragraph&quot;}],&quot;type&quot;:&quot;panel&quot;}"><p>Weather permitting.</p></div>
<div class="adf-panel" data-panel-type="warning">
<p>Check the collation before importing.</p>
</div>
<div class="adf-panel" data-local-id="01a0337c-561a-75aa-b629-3801f68839ad" data-panel-type="info">
<p>Backups run at 02:00.</p>
</div>
<div class="adf-panel" data-panel-color="#c9372c" data-panel-icon=":rainbow:" data-panel-icon-id="1f308" data-panel-icon-text="🌈" data-panel-type="custom">
<p>Weather permitting.</p>
</div>
```
## Task list
@@ -588,5 +594,8 @@ The card below has no spelling yet.
```html
<div class="adf-carry" data-adf="{&quot;attrs&quot;:{&quot;url&quot;:&quot;https://example.com/roadmap&quot;},&quot;type&quot;:&quot;blockCard&quot;}"><p><a href="https://example.com/roadmap">https://example.com/roadmap</a></p></div>
<div class="adf-carry" data-adf="{&quot;attrs&quot;:{&quot;panelType&quot;:&quot;info&quot;},&quot;content&quot;:[{&quot;content&quot;:[{&quot;text&quot;:&quot;The card below has no spelling yet.&quot;,&quot;type&quot;:&quot;text&quot;}],&quot;type&quot;:&quot;paragraph&quot;},{&quot;attrs&quot;:{&quot;layout&quot;:&quot;wide&quot;,&quot;url&quot;:&quot;https://example.com/board&quot;,&quot;width&quot;:100},&quot;type&quot;:&quot;embedCard&quot;}],&quot;type&quot;:&quot;panel&quot;}"><p>The card below has no spelling yet.</p><p><a href="https://example.com/board">https://example.com/board</a></p></div>
<div class="adf-panel" data-panel-type="info">
<p>The card below has no spelling yet.</p>
<div class="adf-carry" data-adf="{&quot;attrs&quot;:{&quot;layout&quot;:&quot;wide&quot;,&quot;url&quot;:&quot;https://example.com/board&quot;,&quot;width&quot;:100},&quot;type&quot;:&quot;embedCard&quot;}"><p><a href="https://example.com/board">https://example.com/board</a></p></div>
</div>
```
+17
View File
@@ -1110,3 +1110,20 @@ Read most (opens and searches):
- `src/plain-text/adf-to-plain-text.ts` 2
- `CHANGELOG.md` 1
- `docker-runner.sh` 1
## Reading cost, chunk a559b3cc15ee, finished 2026-11-14T22:28:07Z
155854 new input tokens before the first commit.
Read most (opens and searches):
- `docs/decisions.md` 11
- `spec/html.md` 7
- `CHANGELOG.md` 6
- `README.md` 5
- `todo.md` 4
- `src/html/emit/adf-to-html.test.ts` 3
- `ci.sh` 2
- `src/html/parse/html-to-adf.test.ts` 2
- `.gitignore` 1
- `AGENTS.md` 1
+34 -7
View File
@@ -16,17 +16,32 @@ Blocks are separated by a line feed, and a document holding any ends with one. A
| `codeBlock` | `<pre><code class="language-js">…</code></pre>`, the language one token holding no ASCII whitespace (a tab, line feed, form feed, carriage return or space); no `class` where it holds no `language` |
| `heading`, `level` 1 to 6 | `<h1>…</h1>` to `<h6>…</h6>` |
| `listItem` | its first paragraph straight after `<li>`: bare where it holds content and no attribute, `<li>Bolt</li>`, and as its `<p>` element where it holds an attribute, `<li><p data-local-id="p1">Bolt</p></li>`; where other blocks follow, each after a line feed, and a line feed before `</li>`. Where the first block is no paragraph, holds neither content nor an attribute, or rides the carry: `<li>`, a line feed, its blocks, a line feed, `</li>` |
| `decisionList` | `<ul class="adf-decision-list">`, a line feed, its items a line each, a line feed, `</ul>`; each `decisionItem` is `<li class="adf-decision" data-state="DECIDED">` around its inline content |
| `expand`, `nestedExpand` | `<details class="adf-expand">`, `<details class="adf-nested-expand">`, a line feed, a `<summary>` holding the `title` where there is one, its blocks, each after a line feed, a line feed, `</details>` |
| `mediaGroup` | `<div class="adf-media-group">` holding a `<span class="adf-file" data-id="…" data-type="file"></span>` for each `media`, none between |
| `mediaSingle`, centered, holding one external `media` | `<p><img src="…" alt="…"></p>`, no `alt` where the media holds none; `<p><a href="…"><img …></a></p>` where a link marks it |
| `mediaSingle`, any other | `<figure class="adf-media-single" data-layout="wide">`, its `media` as the `<img>` below, then its caption as `<figcaption>…</figcaption>`, on one line, `</figure>`; the `<img>` inside `<a href="…">` where a link marks the media |
| `orderedList` | as `bulletList` with `<ol>`; `<ol start="3">` for an `order` of 3, a safe integer other than `-0`; no `start` where the list holds no `order` |
| `paragraph` | `<p>…</p>` |
| `panel` | `<div class="adf-panel" data-panel-type="info">`, a line feed, its blocks a line each, a line feed, `</div>` |
| `paragraph` | `<p>…</p>`; `<p style="text-align:center">` for an `alignment` mark of `center` and `text-align:right` for `end`, as on a heading |
| `rule` | `<hr>` |
| `taskList` | `<ul class="adf-task-list">`, a line feed, its items a line each, a line feed, `</ul>`; each `taskItem` is `<li class="adf-task" data-state="TODO"><input type="checkbox" disabled="">`, a space, then its inline content, the checkbox `checked=""` as well where `state` is `DONE`, and the space left out where it holds none |
| `table` | `<table>`, a line feed, its sections parted by a line feed, a line feed, `</table>`: a `<thead>` where its first row holds cells that are all `tableHeader`, and a `<tbody>` for the other rows where there are any. Each section is its tag, a line feed, its rows a line each, a line feed, its closing tag |
| `tableCell`, `tableHeader` | `<td>`, `<th>`, each holding its blocks as a `listItem` does: `<td>Bolt M8</td>`; attributes `colspan`, `rowspan`, `style="background-color:#fffae6"` for `background`, and `data-colwidth="120,80"` for `colwidth`, first and in that order |
| `tableRow` | `<tr>`, its cells with no line feed between them, `</tr>` |
A container holding no `content` key is its element holding nothing: `<blockquote></blockquote>`,
`<ul></ul>`, `<li></li>`, `<table></table>`, `<tr></tr>`, `<td></td>`; so is a paragraph or heading,
`<p></p>`.
`<ul></ul>`, `<li></li>`, `<table></table>`, `<tr></tr>`, `<td></td>`, `<div class="adf-panel"></div>`,
`<details class="adf-expand"></details>`; so is a paragraph or heading, `<p></p>`.
A media is `<img src="…" alt="…" height="…" width="…">`: `src` its `url`, each other attribute left out where
the media holds none, `height` and `width` a positive safe integer each. A media holding no `url` is
`<img class="adf-media">` with no `src`. Its `type` is a `data-*` attribute, left out where the media is
external and holds a `url`.
A `<summary>` holds the escaped `title`, `<summary></summary>` for an empty one, and an expand with no
`title` has none. `panelType` is `data-panel-type`, and a task item's or decision item's `state`
is `data-state`, among the other attributes below.
```html
<table>
@@ -42,9 +57,9 @@ A container holding no `content` key is its element holding nothing: `<blockquot
A table and each of its rows count one nesting level; a cell doesn't count, nor does a list item.
On a paragraph, heading, quote, list, list item, table, row, cell, code block or rule, each attribute its type holds
On a paragraph, heading, quote, list, list item, table, row, cell, code block, rule, panel, expand, task or decision list or item, or media group, each attribute its type holds
(`spec/flavour.md` §Block nodes) that the element does not write as `level`, `order`, `language`,
`colspan`, `rowspan`, `background` or `colwidth` is a `data-*` attribute, named as HTML's `dataset` names it, `localId` as `data-local-id`, after the
`colspan`, `rowspan`, `background`, `colwidth`, an expand's `title`, or an `<img>`'s `alt`, `height`, `url` and `width` is a `data-*` attribute, named as HTML's `dataset` names it, `localId` as `data-local-id`, after the
element's own attributes and sorted by name. A string is its value; any other value is its JSON,
compact: `<ol start="3" data-local-id="91177a27-b0ff">`, `<pre data-wrap="true"><code>`. A code
block's `data-*` attributes stand on its `<pre>`.
@@ -54,7 +69,8 @@ block's `data-*` attributes stand on its `<pre>`.
| ADF | HTML |
| --- | --- |
| `date` | `<time class="adf-date" datetime="2025-08-25" data-timestamp="1756080000000">2025-08-25</time>`, the day in UTC |
| `code`, `em`, `strike`, `strong` | `<code>`, `<em>`, `<del>`, `<strong>` around the text |
| `backgroundColor`, `textColor` | `<mark style="background-color:#fffae6">`, `<span style="color:#bf2600">` around the text; the colour a `#` and letters and digits, or letters and digits alone |
| `code`, `em`, `strike`, `strong`, `underline` | `<code>`, `<em>`, `<del>`, `<strong>`, `<u>` around the text |
| `emoji` | `<span class="adf-emoji" data-id="1f389" data-short-name=":tada:">🎉</span>`, its `text` the content |
| `hardBreak` | `<br>` |
| `inlineCard`, holding a `url` | `<a class="adf-inline-card" href="https://example.com/spec">https://example.com/spec</a>` |
@@ -62,6 +78,7 @@ block's `data-*` attributes stand on its `<pre>`.
| `link`, holding `href` and an optional `title` | `<a href="…" title="…">` around the text |
| `mention` | `<span class="adf-mention" data-access-level="CONTAINER" data-id="5b10a2" data-user-type="DEFAULT">@Mikael</span>`, its `text` the content |
| `status` | `<span class="adf-status" data-color="yellow">In review</span>`, its `text` the content |
| `subsup` | `<sub>` or `<sup>` around the text, for a `type` of `sub` or `sup` |
| `text` | its text, escaped |
A `date`, `emoji`, `inlineCard`, `mention` or `status` writes each other attribute its type holds as a
@@ -92,7 +109,7 @@ it reads back as the node it holds, so HTML stored while a node rode the carry r
later release writes it as its own element.
```html
<div class="adf-carry" data-adf="{&quot;attrs&quot;:{&quot;panelType&quot;:&quot;info&quot;},…,&quot;type&quot;:&quot;panel&quot;}"><p>Read the <a href="https://spec.commonmark.org/">CommonMark spec</a> first.</p><p>Then import.</p></div>
<div class="adf-carry" data-adf="{&quot;attrs&quot;:{&quot;extensionKey&quot;:&quot;toc&quot;},…,&quot;type&quot;:&quot;bodiedExtension&quot;}"><p>Read the <a href="https://spec.commonmark.org/">CommonMark spec</a> first.</p><p>Then import.</p></div>
<p>Ask <span class="adf-carry" data-adf="{&quot;attrs&quot;:{&quot;id&quot;:&quot;5b10a2&quot;},&quot;type&quot;:&quot;mention&quot;}">@5b10a2</span></p>
```
@@ -142,6 +159,14 @@ later release writes it as its own element.
- a code block holding more than one text node, a marked one, or a language holding ASCII
whitespace;
- a hard break holding an attribute;
- a `mediaSingle` holding anything but one `media`, then at most one `caption`, or a `mediaGroup`
holding anything but `media`; a `media` holding more than one mark, a mark that is no link, or a
`height` or `width` that is not a positive safe integer;
- a paragraph or heading holding a mark besides one `center` or `end` alignment, a `textColor`
or `backgroundColor` whose `color` is not letters and digits after an optional `#`;
- a `panel` or `expand` holding an attribute its type does not hold as that kind; a `taskItem`
whose `state` is not `DONE` or `TODO`, or a task or decision list holding a node that is no
item of its own kind, `blockTaskItem` included: the whole list rides the carry;
- a list holding a node that is no `listItem`, or an item holding a mark, an empty key or an
attribute its type does not hold: the whole list rides the carry;
- a table holding a node that is no `tableRow`, a row holding a node that is no cell, or a table,
@@ -183,6 +208,8 @@ that node in either spelling: an edit there would be lost, so it is `unmappable-
is not the day its `data-timestamp` names, a card without `data-data` whose `href` and text are
not one URL, and a card with `data-data` whose `href` is not the URL its `data` holds or whose
text is not its name, else that URL, are `unmappable-html`.
- A task item whose checkbox is checked where its `data-state` is `TODO`, or not where it is `DONE`,
and one whose `data-state` is neither, are `unmappable-html`.
- A `data-*` attribute that its element does not take, such as `data-level` on `<h1>`, or that holds
a value outside its attribute's kind or not written as compact JSON, is `unsupported-node-shape`.
- A carry element's `data-adf` holding invalid JSON is `unmappable-html`. JSON that is no ADF node,
+33
View File
@@ -0,0 +1,33 @@
import type { AdfAttributes, AdfMark, AdfNode } from '../adf/document.ts'
import type { AttributeVocabulary } from '../adf/attribute-vocabulary.ts'
import type { Read } from '../result.ts'
import { dataAttributes, readDataAttributes } from './data-attributes.ts'
import { nodeAttrs, nodeMarks } from '../adf/document.ts'
// The `text-align` value each alignment names.
const alignments: ReadonlyMap<string, string> = new Map([
['center', 'center'],
['end', 'right'],
])
// A paragraph's or heading's attributes: its alignment mark as a `style` attribute, then the rest as `dataAttributes` writes them; `undefined` where it holds a mark besides one alignment the style spells.
export function textBlockAttributes(node: AdfNode, vocabulary: AttributeVocabulary, written: readonly string[]): string | undefined {
const [mark, ...others] = nodeMarks(node)
if (mark === undefined) return dataAttributes(node, vocabulary, written)
const attrs = nodeAttrs(mark)
const textAlign = others.length === 0 && mark.type === 'alignment' && Object.keys(attrs).length === 1 ? alignments.get(String(attrs['align'])) : undefined
const bare: AdfNode = { ...node }
delete bare.marks
const data = textAlign === undefined ? undefined : dataAttributes(bare, vocabulary, written)
return data === undefined ? undefined : ` style="text-align:${textAlign}"${data}`
}
// The attributes and marks a paragraph's or heading's start tag holds, as `textBlockAttributes` writes them.
export function readTextBlockAttributes(pairs: readonly (readonly [string, string])[], element: string, vocabulary: AttributeVocabulary, written: readonly string[]): Read<{ attrs: AdfAttributes; marks: AdfMark[] }> {
const [first] = pairs
const align = first?.[0] === 'style' ? [...alignments].find(([, textAlign]) => first[1] === `text-align:${textAlign}`)?.[0] : undefined
if (first?.[0] === 'style' && align === undefined) return { fault: { code: 'unmappable-html', message: `style on <${element}> holds text-align:center or text-align:right` } }
const data = readDataAttributes(align === undefined ? pairs : pairs.slice(1), element, vocabulary, written)
if (data.fault !== undefined) return data
return { value: { attrs: data.value, marks: align === undefined ? [] : [{ attrs: { align }, type: 'alignment' }] } }
}
+35
View File
@@ -0,0 +1,35 @@
import type { AttributeVocabulary } from '../adf/attribute-vocabulary.ts'
import { blockNodes } from '../adf/block-nodes.ts'
export type ExpandType = 'expand' | 'nestedExpand'
export type TaskListType = 'decisionList' | 'taskList'
const expandTypes: readonly ExpandType[] = ['expand', 'nestedExpand']
const listTypes: readonly TaskListType[] = ['decisionList', 'taskList']
export const expandClasses: Readonly<Record<ExpandType, string>> = { expand: 'adf-expand', nestedExpand: 'adf-nested-expand' }
export const panelClass = 'adf-panel'
// The panel type and an item's state are no attribute of the vocabularies, which a directive spells as its argument; here each is a data-* attribute like the rest.
export const panelAttributes: AttributeVocabulary = { ...blockNodes.panel.attributes, panelType: 'string' }
// A task or decision list, its items' type, class and attributes.
export const taskLists: Readonly<Record<TaskListType, { item: 'decisionItem' | 'taskItem'; itemAttributes: AttributeVocabulary; itemClass: string; listClass: string }>> = {
decisionList: { item: 'decisionItem', itemAttributes: blockNodes.decisionItem.attributes, itemClass: 'adf-decision', listClass: 'adf-decision-list' },
taskList: { item: 'taskItem', itemAttributes: { ...blockNodes.taskItem.attributes, state: 'string' }, itemClass: 'adf-task', listClass: 'adf-task-list' },
}
// The type of the task or decision list whose `<ul>` has the class; `undefined` for any other.
export function taskListOfClass(className: string | undefined): TaskListType | undefined {
return listTypes.find((type) => taskLists[type].listClass === className)
}
// The task or decision list type `type` names; `undefined` for any other.
export function taskListOfType(type: string): TaskListType | undefined {
return listTypes.find((candidate) => candidate === type)
}
// The expand type whose `<details>` has the class; `undefined` for any other.
export function expandOfClass(className: string | undefined): ExpandType | undefined {
return expandTypes.find((type) => expandClasses[type] === className)
}
+4 -4
View File
@@ -2,6 +2,7 @@ import type { AdfAttributes, AdfNode } from '../adf/document.ts'
import type { JsonValue } from '../json-value.ts'
import type { Read } from '../result.ts'
import { blockNodes } from '../adf/block-nodes.ts'
import { colourDeclaration, readColour } from './colour-style.ts'
import { dataAttributes, dataValue, readDataAttributes } from './data-attributes.ts'
import { isNumberList } from '../adf/attribute-vocabulary.ts'
import { nodeAttrs } from '../adf/document.ts'
@@ -10,8 +11,6 @@ import { serializeCanonicalJson } from '../canonical-json.ts'
const elementWritten = ['background', 'colspan', 'colwidth', 'rowspan']
const leading = ['colspan', 'rowspan', 'style', 'data-colwidth']
const span = /^[1-9][0-9]*$/
// Letters and digits alone, so no value can end the `background-color` declaration or call `url()`.
const styled = /^background-color:(#?[0-9a-zA-Z]+)$/
export function isHeaderRow(row: { content?: AdfNode[] }): boolean {
const cells = row.content ?? []
@@ -49,7 +48,8 @@ function spanAttribute(name: string, value: JsonValue | undefined): string | und
function styleAttribute(background: JsonValue | undefined): string | undefined {
if (background === undefined) return ''
return typeof background === 'string' && styled.test(`background-color:${background}`) ? ` style="background-color:${background}"` : undefined
const declaration = colourDeclaration('background-color', background)
return declaration === undefined ? undefined : ` style="${declaration}"`
}
function widthsAttribute(colwidth: JsonValue | undefined): string | undefined {
@@ -63,7 +63,7 @@ function ownKey(name: string): string {
}
function ownValue(name: string, spelled: string): JsonValue | undefined {
if (name === 'style') return styled.exec(spelled)?.[1]
if (name === 'style') return readColour('background-color', spelled)
if (name === 'data-colwidth') return dataValue(`[${spelled}]`, 'numbers')
const value = Number(spelled)
return span.test(spelled) && Number.isSafeInteger(value) ? value : undefined
+15
View File
@@ -0,0 +1,15 @@
import type { JsonValue } from '../json-value.ts'
// Letters and digits alone, after an optional `#`, so no value can end the declaration or call `url()`.
const colour = /^#?[0-9a-zA-Z]+$/
// `property:colour`, `undefined` where the value is no colour the declaration can hold.
export function colourDeclaration(property: string, value: JsonValue | undefined): string | undefined {
return typeof value === 'string' && colour.test(value) ? `${property}:${value}` : undefined
}
// The colour a `property:colour` declaration holds, `undefined` where it holds another property or no such colour.
export function readColour(property: string, declaration: string): string | undefined {
const value = declaration.slice(property.length + 1)
return declaration.startsWith(`${property}:`) && colour.test(value) ? value : undefined
}
+208 -23
View File
@@ -88,8 +88,8 @@ test('carries text holding a character HTML text cannot hold, escaping it in the
assert.equal(carriedSpans(text(value)), 1, JSON.stringify(value))
}
assert.equal(carriedSpans(text('😄 a b')), 0)
assert.equal(html(adfToHtml(document(paragraph(text('a\u0085﷐b', { type: 'underline' }))))).includes('&quot;text&quot;:&quot;a\\u0085\\ufdd0b&quot;'), true)
assert.equal(html(adfToHtml(document(paragraph(text('a\u{1fffe}b', { type: 'underline' }))))).includes('&quot;text&quot;:&quot;a\\ud83f\\udffeb&quot;'), true)
assert.equal(html(adfToHtml(document(paragraph(text('a\u0085﷐b', { type: 'odd' }))))).includes('&quot;text&quot;:&quot;a\\u0085\\ufdd0b&quot;'), true)
assert.equal(html(adfToHtml(document(paragraph(text('a\u{1fffe}b', { type: 'odd' }))))).includes('&quot;text&quot;:&quot;a\\ud83f\\udffeb&quot;'), true)
})
test('writes lists tight, and an item\'s blocks after its first paragraph as elements on lines of their own', () => {
@@ -106,7 +106,7 @@ test('writes an item\'s first paragraph as its element on the item\'s line where
assert.equal(listed(held), `<ul>\n<li><p data-local-id="${ids.paragraph}">Bolt</p></li>\n</ul>\n`)
assert.equal(listed(held, { content: [item(paragraph(text('M8')))], type: 'bulletList' }), `<ul>\n<li><p data-local-id="${ids.paragraph}">Bolt</p>\n<ul>\n<li>M8</li>\n</ul>\n</li>\n</ul>\n`)
assert.equal(listed({ attrs: { localId: ids.paragraph }, type: 'paragraph' }), `<ul>\n<li><p data-local-id="${ids.paragraph}"></p></li>\n</ul>\n`)
assert.equal(listed({ content: [text('Bolt')], marks: [{ attrs: { align: 'center' }, type: 'alignment' }], type: 'paragraph' }).startsWith('<ul>\n<li>\n<div class="adf-carry"'), true)
assert.equal(listed({ content: [text('Bolt')], marks: [{ attrs: { level: 1 }, type: 'indentation' }], type: 'paragraph' }).startsWith('<ul>\n<li>\n<div class="adf-carry"'), true)
})
test('writes the attributes an element cannot express as data-* attributes on it, sorted, a value that is no string as JSON', () => {
@@ -134,11 +134,117 @@ test('writes an external image standing alone in a paragraph, a link around it w
assert.equal(html(adfToHtml(document(linked))), '<p><a href="https://example.com/"><img src="https://example.com/moon.jpg"></a></p>\n')
})
test('writes a mediaSingle holding more than the plain image as a figure, its media as an image and its caption as a figcaption', () => {
const external: AdfNode = { attrs: { alt: 'The moon', height: 600, type: 'external', url: 'https://example.com/moon.jpg', width: 800 }, type: 'media' }
const caption: AdfNode = { attrs: { localId: ids.item }, content: [text('The moon, '), text('at night', { type: 'em' })], type: 'caption' }
const single = (attrs: AdfAttributes, ...content: AdfNode[]): AdfNode => ({ attrs, content, type: 'mediaSingle' })
assert.equal(
html(adfToHtml(document(single({ layout: 'center', localId: ids.list, width: 50, widthType: 'pixel' }, external, caption)))),
`<figure class="adf-media-single" data-layout="center" data-local-id="${ids.list}" data-width="50" data-width-type="pixel"><img src="https://example.com/moon.jpg" alt="The moon" height="600" width="800"><figcaption data-local-id="${ids.item}">The moon, <em>at night</em></figcaption></figure>\n`,
)
assert.equal(html(adfToHtml(document(single({ layout: 'wide' }, { attrs: { type: 'external', url: 'https://example.com/moon.jpg' }, type: 'media' })))), '<figure class="adf-media-single" data-layout="wide"><img src="https://example.com/moon.jpg"></figure>\n')
assert.equal(html(adfToHtml(document(single({ layout: 'center' }, { attrs: { alt: '', type: 'external', url: 'https://example.com/moon.jpg' }, type: 'media' })))), '<figure class="adf-media-single" data-layout="center"><img src="https://example.com/moon.jpg" alt=""></figure>\n')
assert.equal(html(adfToHtml(document({ content: [{ attrs: { type: 'external', url: 'https://example.com/moon.jpg' }, type: 'media' }], type: 'mediaSingle' }))), '<figure class="adf-media-single"><img src="https://example.com/moon.jpg"></figure>\n')
assert.equal(html(adfToHtml(document(single({ layout: 'wide' }, { ...external, marks: [{ attrs: { href: 'https://example.com/', title: 'Home' }, type: 'link' }] })))), '<figure class="adf-media-single" data-layout="wide"><a href="https://example.com/" title="Home"><img src="https://example.com/moon.jpg" alt="The moon" height="600" width="800"></a></figure>\n')
assert.equal(html(adfToHtml(document(single({ layout: 'center' }, external, { type: 'caption' })))), '<figure class="adf-media-single" data-layout="center"><img src="https://example.com/moon.jpg" alt="The moon" height="600" width="800"><figcaption></figcaption></figure>\n')
})
test('writes a media holding no url as an image with no src of class adf-media, its type in data-type', () => {
const file: AdfNode = { attrs: { alt: 'Launch photo', collection: ids.collection, height: 600, id: ids.file, occurrenceKey: ids.item, type: 'file', width: 800 }, type: 'media' }
assert.equal(
html(adfToHtml(document({ attrs: { layout: 'wide' }, content: [file], type: 'mediaSingle' }))),
`<figure class="adf-media-single" data-layout="wide"><img class="adf-media" alt="Launch photo" height="600" width="800" data-collection="${ids.collection}" data-id="${ids.file}" data-occurrence-key="${ids.item}" data-type="file"></figure>\n`,
)
assert.equal(html(adfToHtml(document({ content: [{ attrs: { type: 'external' }, type: 'media' }], type: 'mediaSingle' }))), '<figure class="adf-media-single"><img class="adf-media" data-type="external"></figure>\n')
assert.equal(html(adfToHtml(document({ content: [{ attrs: { type: 'file', url: 'https://example.com/moon.jpg' }, type: 'media' }], type: 'mediaSingle' }))), '<figure class="adf-media-single"><img src="https://example.com/moon.jpg" data-type="file"></figure>\n')
assert.equal(html(adfToHtml(document({ content: [{ type: 'media' }], type: 'mediaSingle' }))), '<figure class="adf-media-single"><img class="adf-media"></figure>\n')
})
test('writes a mediaGroup as a div of spans, each media holding every attribute as data-*', () => {
const media = (id: string): AdfNode => ({ attrs: { collection: ids.collection, id, type: 'file' }, type: 'media' })
assert.equal(
html(adfToHtml(document({ content: [media(ids.file), { attrs: { alt: 'Moon', type: 'external', url: 'https://example.com/moon.jpg' }, type: 'media' }], type: 'mediaGroup' }))),
`<div class="adf-media-group"><span class="adf-file" data-collection="${ids.collection}" data-id="${ids.file}" data-type="file"></span><span class="adf-file" data-alt="Moon" data-type="external" data-url="https://example.com/moon.jpg"></span></div>\n`,
)
assert.equal(html(adfToHtml(document({ type: 'mediaGroup' }))), '<div class="adf-media-group"></div>\n')
})
test('carries a media node HTML cannot spell: a width that is no whole number, an unknown attribute, a mark besides a link, or a shape the schema lacks', () => {
const external: AdfAttributes = { type: 'external', url: 'https://example.com/moon.jpg' }
const single = (...content: AdfNode[]): AdfNode => ({ attrs: { layout: 'wide' }, content, type: 'mediaSingle' })
const media = (attrs: AdfAttributes, ...marks: AdfMark[]): AdfNode => (marks.length === 0 ? { attrs, type: 'media' } : { attrs, marks, type: 'media' })
assert.equal(carriedBlock(single(media({ ...external, width: 800.5 }))), true)
assert.equal(carriedBlock(single(media({ ...external, width: -1 }))), true)
assert.equal(carriedBlock(single(media({ ...external, extra: 'x' }))), true)
assert.equal(carriedBlock(single(media({ type: 'external', url: 'https://example.com/\0' }))), true)
assert.equal(carriedBlock(single(media({ alt: 'x\0', type: 'external', url: 'https://example.com/a' }))), true)
assert.equal(carriedBlock(single(media({ url: 'https://example.com/moon.jpg' }))), true)
assert.equal(carriedBlock(single(media(external, { attrs: { color: 'red' }, type: 'border' }))), true)
assert.equal(carriedBlock(single(media(external, { attrs: { href: 'https://example.com/', x: 1 }, type: 'link' }))), true)
assert.equal(carriedBlock(single(media(external), { content: [text('a')], type: 'caption' }, media(external))), true)
assert.equal(carriedBlock(single({ content: [text('a')], type: 'caption' })), true)
assert.equal(carriedBlock(single(media(external), { content: [text('a')], marks: [{ type: 'em' }], type: 'caption' })), true)
assert.equal(carriedBlock({ attrs: { layout: 'wide', extra: 1 }, content: [media(external)], type: 'mediaSingle' }), true)
assert.equal(carriedBlock({ attrs: { layout: 'wide' }, content: [media(external)], marks: [{ type: 'em' }], type: 'mediaSingle' }), true)
assert.equal(carriedBlock({ attrs: { id: 'x' }, content: [{ attrs: external, type: 'media' }], type: 'mediaGroup' }), true)
assert.equal(carriedBlock({ content: [media(external, { attrs: { href: 'https://example.com/' }, type: 'link' })], type: 'mediaGroup' }), true)
assert.equal(carriedBlock({ content: [{ content: [text('a')], type: 'paragraph' }], type: 'mediaGroup' }), true)
})
test('writes underline, subscript, superscript and the two colours as elements, a colour in a style attribute', () => {
const marked = (...marks: AdfMark[]): string => html(adfToHtml(document(paragraph(text('x', ...marks)))))
assert.equal(marked({ type: 'underline' }), '<p><u>x</u></p>\n')
assert.equal(marked({ attrs: { type: 'sub' }, type: 'subsup' }), '<p><sub>x</sub></p>\n')
assert.equal(marked({ attrs: { type: 'sup' }, type: 'subsup' }), '<p><sup>x</sup></p>\n')
assert.equal(marked({ attrs: { color: '#ff5630' }, type: 'textColor' }), '<p><span style="color:#ff5630">x</span></p>\n')
assert.equal(marked({ attrs: { color: '#fffae6' }, type: 'backgroundColor' }), '<p><mark style="background-color:#fffae6">x</mark></p>\n')
assert.equal(marked({ type: 'strong' }, { type: 'underline' }, { attrs: { color: 'red' }, type: 'textColor' }), '<p><strong><u><span style="color:red">x</span></u></strong></p>\n')
})
test('carries text holding a mark HTML cannot spell: attributes besides those the element takes, a colour that is no plain value, or a type that is neither sub nor sup', () => {
const carriedText = (mark: AdfMark): boolean => html(adfToHtml(document(paragraph(text('x', mark))))).includes('adf-carry')
for (const mark of [
{ attrs: {}, type: 'underline' },
{ attrs: { type: 'sub' }, type: 'underline' },
{ attrs: { type: 'big' }, type: 'subsup' },
{ attrs: { type: 'sub', x: 1 }, type: 'subsup' },
{ type: 'subsup' },
{ type: 'textColor' },
{ attrs: { color: 'red', x: 1 }, type: 'textColor' },
{ attrs: { color: 7 }, type: 'textColor' },
{ attrs: { color: '' }, type: 'textColor' },
{ attrs: { color: 'red;x:y' }, type: 'textColor' },
{ attrs: { color: 'rgb(1,2,3)' }, type: 'backgroundColor' },
{ attrs: { color: '#fff\n' }, type: 'backgroundColor' },
{ type: 'backgroundColor' },
]) assert.equal(carriedText(mark), true, JSON.stringify(mark))
})
test('writes a paragraph or heading marked with center or end alignment as a style attribute, end as right', () => {
const aligned = (align: string, node: AdfNode = paragraph(text('x'))): string => html(adfToHtml(document({ ...node, marks: [{ attrs: { align }, type: 'alignment' }] })))
assert.equal(aligned('center'), '<p style="text-align:center">x</p>\n')
assert.equal(aligned('end'), '<p style="text-align:right">x</p>\n')
assert.equal(aligned('center', { attrs: { level: 2 }, content: [text('x')], type: 'heading' }), '<h2 style="text-align:center">x</h2>\n')
assert.equal(aligned('end', { attrs: { localId: ids.paragraph }, type: 'paragraph' }), `<p style="text-align:right" data-local-id="${ids.paragraph}"></p>\n`)
assert.equal(html(adfToHtml(document({ content: [item({ content: [text('x')], marks: [{ attrs: { align: 'center' }, type: 'alignment' }], type: 'paragraph' })], type: 'bulletList' }))), '<ul>\n<li><p style="text-align:center">x</p></li>\n</ul>\n')
})
test('carries a paragraph or heading holding an alignment HTML cannot spell, or a mark besides it', () => {
const carriedBlockOf = (...marks: AdfMark[]): boolean => carriedBlock({ content: [text('x')], marks, type: 'paragraph' })
assert.equal(carriedBlockOf({ attrs: { align: 'start' }, type: 'alignment' }), true)
assert.equal(carriedBlockOf({ attrs: { align: 'center', x: 1 }, type: 'alignment' }), true)
assert.equal(carriedBlockOf({ type: 'alignment' }), true)
assert.equal(carriedBlockOf({ attrs: { level: 1 }, type: 'indentation' }), true)
assert.equal(carriedBlockOf({ attrs: { align: 'center' }, type: 'alignment' }, { attrs: { align: 'end' }, type: 'alignment' }), true)
assert.equal(carriedBlockOf({ attrs: { align: 'center' }, type: 'alignment' }, { attrs: { level: 1 }, type: 'indentation' }), true)
assert.equal(carriedBlock({ attrs: { level: 1 }, content: [text('x')], marks: [{ attrs: { level: 1 }, type: 'indentation' }], type: 'heading' }), true)
})
test('carries every other node in an adf-carry element holding its JSON', () => {
const panel: AdfNode = { attrs: { panelType: 'info' }, content: [paragraph(text('Check the collation.'))], type: 'panel' }
const panel: AdfNode = { attrs: { panelType: 'info' }, content: [paragraph(text('Check the collation.'))], type: 'bodiedExtension' }
assert.equal(
html(adfToHtml(document(panel))),
'<div class="adf-carry" data-adf="{&quot;attrs&quot;:{&quot;panelType&quot;:&quot;info&quot;},&quot;content&quot;:[{&quot;content&quot;:[{&quot;text&quot;:&quot;Check the collation.&quot;,&quot;type&quot;:&quot;text&quot;}],&quot;type&quot;:&quot;paragraph&quot;}],&quot;type&quot;:&quot;panel&quot;}"><p>Check the collation.</p></div>\n',
'<div class="adf-carry" data-adf="{&quot;attrs&quot;:{&quot;panelType&quot;:&quot;info&quot;},&quot;content&quot;:[{&quot;content&quot;:[{&quot;text&quot;:&quot;Check the collation.&quot;,&quot;type&quot;:&quot;text&quot;}],&quot;type&quot;:&quot;paragraph&quot;}],&quot;type&quot;:&quot;bodiedExtension&quot;}"><p>Check the collation.</p></div>\n',
)
const mention: AdfNode = { attrs: { id: '5b10a2' }, type: 'mention' }
assert.equal(html(adfToHtml(document(paragraph(text('Ask '), mention)))), '<p>Ask <span class="adf-carry" data-adf="{&quot;attrs&quot;:{&quot;id&quot;:&quot;5b10a2&quot;},&quot;type&quot;:&quot;mention&quot;}">@5b10a2</span></p>\n')
@@ -193,43 +299,43 @@ test('carries an emoji, mention, status, date or card holding what its element c
})
test('shows each block a carried node holds as a paragraph in a div', () => {
const panel: AdfNode = { attrs: { panelType: 'info' }, content: [paragraph(text('Check the collation.')), paragraph(text('Then import.'))], type: 'panel' }
const panel: AdfNode = { attrs: { panelType: 'info' }, content: [paragraph(text('Check the collation.')), paragraph(text('Then import.'))], type: 'bodiedExtension' }
assert.equal(shown(html(adfToHtml(document(panel)))), '<p>Check the collation.</p><p>Then import.</p>')
})
test('shows a carried node\'s content after a block it holds as a paragraph of its own', () => {
assert.equal(shown(html(adfToHtml(document({ content: [paragraph(text('a')), text('b')], type: 'panel' })))), '<p>a</p><p>b</p>')
assert.equal(shown(html(adfToHtml(document({ content: [paragraph(text('a')), text('b')], type: 'bodiedExtension' })))), '<p>a</p><p>b</p>')
})
test('shows text a link marks in a carried node as a link, leaving out a title that is no string', () => {
const link: AdfMark = { attrs: { href: 'https://spec.commonmark.org/', title: 'The spec' }, type: 'link' }
const panel: AdfNode = { content: [paragraph(text('Read the '), text('CommonMark spec', link), text(' first.'))], type: 'panel' }
const panel: AdfNode = { content: [paragraph(text('Read the '), text('CommonMark spec', link), text(' first.'))], type: 'bodiedExtension' }
assert.equal(shown(html(adfToHtml(document(panel)))), '<p>Read the <a href="https://spec.commonmark.org/" title="The spec">CommonMark spec</a> first.</p>')
assert.equal(shown(html(adfToHtml(document(paragraph(text('x', { type: 'underline' }, link)))))), '<a href="https://spec.commonmark.org/" title="The spec">x</a>')
assert.equal(shown(html(adfToHtml(document(paragraph(text('x', { type: 'odd' }, link)))))), '<a href="https://spec.commonmark.org/" title="The spec">x</a>')
assert.equal(shown(html(adfToHtml(document(paragraph(text('x', { attrs: { href: 'https://spec.commonmark.org/', title: 5 }, type: 'link' })))))), '<a href="https://spec.commonmark.org/">x</a>')
})
test('shows a hard break, and a line feed in carried text outside a code block, as a line break', () => {
assert.equal(shown(html(adfToHtml(document({ content: [paragraph(text('Then'), { type: 'hardBreak' }, text('import.'))], type: 'panel' })))), '<p>Then<br>import.</p>')
assert.equal(shown(html(adfToHtml(document({ content: [paragraph(text('Then\nimport.'))], type: 'panel' })))), '<p>Then<br>import.</p>')
assert.equal(shown(html(adfToHtml(document(paragraph(text('a\nb', { type: 'underline' })))))), 'a<br>b')
assert.equal(shown(html(adfToHtml(document({ content: [paragraph(text('Then'), { type: 'hardBreak' }, text('import.'))], type: 'bodiedExtension' })))), '<p>Then<br>import.</p>')
assert.equal(shown(html(adfToHtml(document({ content: [paragraph(text('Then\nimport.'))], type: 'bodiedExtension' })))), '<p>Then<br>import.</p>')
assert.equal(shown(html(adfToHtml(document(paragraph(text('a\nb', { type: 'odd' })))))), 'a<br>b')
})
test('shows an expand\'s title as a paragraph of its own', () => {
assert.equal(shown(html(adfToHtml(document({ attrs: { title: 'Details' }, content: [paragraph(text('Inside'))], type: 'expand' })))), '<p>Details</p><p>Inside</p>')
assert.equal(shown(html(adfToHtml(document({ attrs: { extra: 1, title: 'Details' }, content: [paragraph(text('Inside'))], type: 'expand' })))), '<p>Details</p><p>Inside</p>')
})
test('parts the blocks a span carry shows with line breaks', () => {
assert.equal(shown(html(adfToHtml(document(paragraph({ content: [paragraph(text('a')), paragraph(text('b'))], type: 'panel' }))))), 'a<br>b')
assert.equal(shown(html(adfToHtml(document(paragraph({ content: [paragraph(text('a')), paragraph(text('b'))], type: 'bodiedExtension' }))))), 'a<br>b')
})
test('drops from what a carry element shows the characters HTML cannot hold, and the link of a URL holding one', () => {
assert.equal(shown(html(adfToHtml(document(paragraph(text('a\u0001b\r', { type: 'underline' }, { attrs: { href: 'https://example.com/\u0001' }, type: 'link' })))))), 'ab')
assert.equal(shown(html(adfToHtml(document(paragraph(text('a\u0001b\r', { type: 'odd' }, { attrs: { href: 'https://example.com/\u0001' }, type: 'link' })))))), 'ab')
})
test('shows a code block in a div carry as pre and code, keeping its line feeds and spaces', () => {
const code: AdfNode = { attrs: { language: 'python' }, content: [text('if ready:\n deploy()')], type: 'codeBlock' }
assert.equal(shown(html(adfToHtml(document({ attrs: { panelType: 'info' }, content: [paragraph(text('Run this:')), code], type: 'panel' })))), '<p>Run this:</p><pre><code class="language-python">if ready:\n deploy()</code></pre>')
assert.equal(shown(html(adfToHtml(document({ attrs: { panelType: 'info' }, content: [paragraph(text('Run this:')), code], type: 'bodiedExtension' })))), '<p>Run this:</p><pre><code class="language-python">if ready:\n deploy()</code></pre>')
assert.equal(shown(html(adfToHtml(document({ content: [text('a\r\n b'), text('c')], type: 'codeBlock' })))), '<pre><code>a\n bc</code></pre>')
})
@@ -256,8 +362,8 @@ test('shows the content a carried node holds in an attribute, and links a card o
assert.equal(inline({ attrs: { color: 'green', text: 'Done' }, marks: [{ attrs: { annotationType: 'inlineComment', id: 'c1' }, type: 'annotation' }], type: 'status' }), 'Done')
assert.equal(inline({ attrs: { url: 'https://example.com/<card>' }, marks: [{ attrs: { annotationType: 'inlineComment', id: 'c1' }, type: 'annotation' }], type: 'inlineCard' }), '<a href="https://example.com/&lt;card&gt;">https://example.com/&lt;card&gt;</a>')
assert.equal(inline({ attrs: { data: { name: 'Roadmap' } }, type: 'inlineCard' }), 'Roadmap')
assert.equal(inline(text('underlined', { type: 'underline' })), 'underlined')
const image = (media: AdfNode): string => shown(html(adfToHtml(document({ attrs: { layout: 'wide' }, content: [media], type: 'mediaSingle' }))))
assert.equal(inline(text('underlined', { type: 'odd' })), 'underlined')
const image = (media: AdfNode): string => shown(html(adfToHtml(document({ attrs: { layout: 'wide', extra: 1 }, content: [media], type: 'mediaSingle' }))))
assert.equal(image({ attrs: { alt: 'The moon', type: 'external', url: 'https://example.com/moon.jpg' }, type: 'media' }), '<p><a href="https://example.com/moon.jpg">The moon</a></p>')
assert.equal(image({ attrs: { type: 'external', url: 'https://example.com/moon.jpg' }, type: 'media' }), '<p><a href="https://example.com/moon.jpg">https://example.com/moon.jpg</a></p>')
assert.equal(image({ attrs: { alt: 'The moon', type: 'external', url: 'https://example.com/moon.jpg' }, marks: [{ attrs: { title: 'No target' }, type: 'link' }], type: 'media' }), '<p><a href="https://example.com/moon.jpg">The moon</a></p>')
@@ -265,11 +371,11 @@ test('shows the content a carried node holds in an attribute, and links a card o
test('shows a carried image marked by a link to another target as that link, then a link to the image reading image', () => {
const link: AdfMark = { attrs: { href: 'https://example.com/' }, type: 'link' }
const image = (attrs: AdfAttributes): string => shown(html(adfToHtml(document({ attrs: { layout: 'wide' }, content: [{ attrs, marks: [link], type: 'media' }], type: 'mediaSingle' }))))
const image = (attrs: AdfAttributes): string => shown(html(adfToHtml(document({ attrs: { layout: 'wide', extra: 1 }, content: [{ attrs, marks: [link], type: 'media' }], type: 'mediaSingle' }))))
assert.equal(image({ alt: 'The moon', type: 'external', url: 'https://example.com/moon.jpg' }), '<p><a href="https://example.com/">The moon</a> (<a href="https://example.com/moon.jpg">image</a>)</p>')
assert.equal(image({ type: 'external', url: 'https://example.com/moon.jpg' }), '<p><a href="https://example.com/">https://example.com/</a> (<a href="https://example.com/moon.jpg">image</a>)</p>')
assert.equal(image({ alt: 'The moon', type: 'external', url: 'https://example.com/' }), '<p><a href="https://example.com/">The moon</a></p>')
const blank = shown(html(adfToHtml(document({ attrs: { layout: 'wide' }, content: [{ attrs: { type: 'external', url: 'https://example.com/moon.jpg' }, marks: [{ attrs: { href: ' ' }, type: 'link' }], type: 'media' }], type: 'mediaSingle' }))))
const blank = shown(html(adfToHtml(document({ attrs: { layout: 'wide', extra: 1 }, content: [{ attrs: { type: 'external', url: 'https://example.com/moon.jpg' }, marks: [{ attrs: { href: ' ' }, type: 'link' }], type: 'media' }], type: 'mediaSingle' }))))
assert.equal(blank, '<p><a href=" ">https://example.com/moon.jpg</a> (<a href="https://example.com/moon.jpg">image</a>)</p>')
const inline = (mark: AdfMark): string => shown(html(adfToHtml(document(paragraph({ attrs: { alt: 'The moon', type: 'external', url: 'https://example.com/moon.jpg' }, marks: [mark], type: 'mediaInline' })))))
assert.equal(inline(link), '<a href="https://example.com/">The moon</a> (<a href="https://example.com/moon.jpg">image</a>)')
@@ -285,7 +391,7 @@ test('refuses an inline card a link marks, which Atlassian\'s schema does not al
assert.deepEqual(!refused.ok && refused.error.path, ['content', 0, 'content', 1])
assert.match(!refused.ok ? refused.error.message : '', /inlineCard.*link/)
}
const carried = adfToHtml(document({ content: [paragraph(cards[0] ?? text('x'))], type: 'panel' }))
const carried = adfToHtml(document({ content: [paragraph(cards[0] ?? text('x'))], type: 'bodiedExtension' }))
assert.deepEqual(!carried.ok && carried.error.path, ['content', 0, 'content', 0, 'content', 0])
const nested = adfToHtml(document({ content: [{ content: [paragraph(cards[0] ?? text('x'))], type: 'listItem' }], type: 'bulletList' }))
assert.deepEqual(!nested.ok && nested.error.path, ['content', 0, 'content', 0, 'content', 0, 'content', 0])
@@ -397,8 +503,7 @@ test('carries a node holding what its element cannot', () => {
assert.equal(carriedBlock({ content: [text('x\0')], type: 'codeBlock' }), true)
assert.equal(carriedBlock(item(paragraph(text('x')))), true)
assert.equal(carriedBlock(text('x')), true)
assert.equal(carriedBlock({ attrs: { layout: 'wide' }, content: [{ attrs: { type: 'external', url: 'https://example.com/a.png' }, type: 'media' }], type: 'mediaSingle' }), true)
assert.equal(carriedBlock({ attrs: { layout: 'center' }, content: [{ attrs: { alt: '', type: 'external', url: 'https://example.com/a.png' }, type: 'media' }], type: 'mediaSingle' }), true)
assert.equal(carriedBlock({ attrs: { layout: 'wide', extra: 1 }, content: [{ attrs: { type: 'external', url: 'https://example.com/a.png' }, type: 'media' }], type: 'mediaSingle' }), true)
})
test('carries inline what its element cannot hold, and a text node that would join the unmarked one before it', () => {
@@ -492,3 +597,83 @@ test('writes HTML exactly as long as V8\'s longest string', () => {
const written = adfToHtml(document(block, block, block, block, block, block, block, block))
assert.equal(written.ok && written.value.length, 536870888)
})
test('writes a panel as a div of its class, its panel type and other attributes data-* sorted by name, its blocks a line each', () => {
const panel: AdfNode = { attrs: { localId: 'p1', panelColor: '#fff', panelType: 'custom' }, content: [paragraph(text('Check the collation.')), paragraph(text('Then import.'))], type: 'panel' }
assert.equal(html(adfToHtml(document(panel))), '<div class="adf-panel" data-local-id="p1" data-panel-color="#fff" data-panel-type="custom">\n<p>Check the collation.</p>\n<p>Then import.</p>\n</div>\n')
assert.equal(html(adfToHtml(document({ attrs: { panelType: 'note' }, type: 'panel' }))), '<div class="adf-panel" data-panel-type="note"></div>\n')
assert.equal(html(adfToHtml(document({ content: [paragraph(text('a'))], type: 'panel' }))), '<div class="adf-panel">\n<p>a</p>\n</div>\n')
const inner: AdfNode = { attrs: { panelType: 'warning' }, content: [paragraph(text('b'))], type: 'panel' }
assert.equal(html(adfToHtml(document({ attrs: { panelType: 'info' }, content: [inner, { content: [item(paragraph(text('c')))], type: 'bulletList' }], type: 'panel' }))), '<div class="adf-panel" data-panel-type="info">\n<div class="adf-panel" data-panel-type="warning">\n<p>b</p>\n</div>\n<ul>\n<li>c</li>\n</ul>\n</div>\n')
})
test('carries a panel holding what its element cannot', () => {
const carriedPanel = (node: AdfNode): boolean => html(adfToHtml(document(node))).startsWith('<div class="adf-carry"')
assert.equal(carriedPanel({ attrs: { panelType: 'info' }, content: [], type: 'panel' }), true)
assert.equal(carriedPanel({ attrs: { panelType: 7 }, content: [paragraph(text('a'))], type: 'panel' }), true)
assert.equal(carriedPanel({ attrs: { extra: 1, panelType: 'info' }, content: [paragraph(text('a'))], type: 'panel' }), true)
assert.equal(carriedPanel({ attrs: {}, content: [paragraph(text('a'))], type: 'panel' }), true)
assert.equal(carriedPanel({ attrs: { panelType: 'info' }, content: [paragraph(text('a'))], marks: [{ type: 'odd' }], type: 'panel' }), true)
assert.equal(carriedPanel({ attrs: { panelType: 'in\u0001fo' }, content: [paragraph(text('a'))], type: 'panel' }), true)
})
test('writes an expand and a nested expand as details, the title as the first line, in a summary', () => {
const expand: AdfNode = { attrs: { localId: 'x1', title: 'Details & more' }, content: [paragraph(text('Inside'))], type: 'expand' }
assert.equal(html(adfToHtml(document(expand))), '<details class="adf-expand" data-local-id="x1">\n<summary>Details &amp; more</summary>\n<p>Inside</p>\n</details>\n')
assert.equal(html(adfToHtml(document({ attrs: { title: 'T' }, content: [paragraph(text('Inside'))], type: 'nestedExpand' }))), '<details class="adf-nested-expand">\n<summary>T</summary>\n<p>Inside</p>\n</details>\n')
assert.equal(html(adfToHtml(document({ content: [paragraph(text('Inside'))], type: 'expand' }))), '<details class="adf-expand">\n<p>Inside</p>\n</details>\n')
assert.equal(html(adfToHtml(document({ attrs: { title: '' }, content: [paragraph(text('Inside'))], type: 'expand' }))), '<details class="adf-expand">\n<summary></summary>\n<p>Inside</p>\n</details>\n')
assert.equal(html(adfToHtml(document({ attrs: { title: 'T' }, type: 'expand' }))), '<details class="adf-expand">\n<summary>T</summary>\n</details>\n')
assert.equal(html(adfToHtml(document({ type: 'expand' }))), '<details class="adf-expand"></details>\n')
})
test('carries an expand holding what its element cannot', () => {
const carriedExpand = (node: AdfNode): boolean => html(adfToHtml(document(node))).startsWith('<div class="adf-carry"')
assert.equal(carriedExpand({ attrs: { title: 7 }, content: [paragraph(text('a'))], type: 'expand' }), true)
assert.equal(carriedExpand({ attrs: { title: 'a\u0001' }, content: [paragraph(text('a'))], type: 'expand' }), true)
assert.equal(carriedExpand({ attrs: { extra: 1, title: 'a' }, content: [paragraph(text('a'))], type: 'expand' }), true)
assert.equal(carriedExpand({ attrs: { title: 'a' }, content: [], type: 'expand' }), true)
})
test('writes a task list as a list of items, each a checkbox that is checked where the task is done, then its text', () => {
const done: AdfNode = { attrs: { localId: 't1', state: 'DONE' }, content: [text('Ship '), text('it', { type: 'strong' })], type: 'taskItem' }
const todo: AdfNode = { attrs: { localId: 't2', state: 'TODO' }, type: 'taskItem' }
assert.equal(
html(adfToHtml(document({ attrs: { localId: 'l1' }, content: [done, todo, { attrs: { state: 'TODO' }, content: [text(' <a>')], type: 'taskItem' }], type: 'taskList' }))),
'<ul class="adf-task-list" data-local-id="l1">\n<li class="adf-task" data-local-id="t1" data-state="DONE"><input type="checkbox" checked="" disabled=""> Ship <strong>it</strong></li>\n<li class="adf-task" data-local-id="t2" data-state="TODO"><input type="checkbox" disabled=""></li>\n<li class="adf-task" data-state="TODO"><input type="checkbox" disabled=""> &lt;a&gt;</li>\n</ul>\n',
)
assert.equal(html(adfToHtml(document({ type: 'taskList' }))), '<ul class="adf-task-list"></ul>\n')
})
test('writes a decision list as a list of items, each its text', () => {
const decided: AdfNode = { attrs: { localId: 'd2', state: 'DECIDED' }, content: [text('Use HTML')], type: 'decisionItem' }
assert.equal(html(adfToHtml(document({ attrs: { localId: 'd1' }, content: [decided, { attrs: { state: 'UNDECIDED' }, type: 'decisionItem' }], type: 'decisionList' }))), '<ul class="adf-decision-list" data-local-id="d1">\n<li class="adf-decision" data-local-id="d2" data-state="DECIDED">Use HTML</li>\n<li class="adf-decision" data-state="UNDECIDED"></li>\n</ul>\n')
assert.equal(html(adfToHtml(document({ type: 'decisionList' }))), '<ul class="adf-decision-list"></ul>\n')
})
test('carries a task or decision list holding what its elements cannot', () => {
const carriedList = (node: AdfNode): boolean => html(adfToHtml(document(node))).startsWith('<div class="adf-carry"')
const task = (attrs: AdfAttributes | undefined, ...content: AdfNode[]): AdfNode => ({ ...(attrs === undefined ? {} : { attrs }), ...(content.length === 0 ? {} : { content }), type: 'taskItem' })
const listOf = (...content: AdfNode[]): AdfNode => ({ content, type: 'taskList' })
assert.equal(carriedList(listOf(task({ state: 'DONE' }, text('a')))), false)
assert.equal(carriedList(listOf(task({ state: 'MAYBE' }, text('a')))), true)
assert.equal(carriedList(listOf(task({ state: 7 }, text('a')))), true)
assert.equal(carriedList(listOf(task({ localId: 'a' }, text('a')))), true)
assert.equal(carriedList(listOf(task(undefined, text('a')))), true)
assert.equal(carriedList(listOf(task({ extra: 1, state: 'TODO' }))), true)
assert.equal(carriedList(listOf({ attrs: { state: 'TODO' }, content: [], type: 'taskItem' })), true)
assert.equal(carriedList(listOf({ attrs: { state: 'TODO' }, marks: [{ type: 'odd' }], type: 'taskItem' })), true)
assert.equal(carriedList(listOf({ attrs: { state: 'TODO' }, content: [paragraph(text('a'))], type: 'blockTaskItem' })), true)
assert.equal(carriedList(listOf(paragraph(text('a')))), true)
assert.equal(carriedList(listOf(listOf())), true)
assert.equal(carriedList({ content: [{ attrs: { state: 'DECIDED' }, content: [text('a')], type: 'taskItem' }], type: 'decisionList' }), true)
assert.equal(carriedList({ attrs: { extra: 1 }, content: [task({ state: 'TODO' })], type: 'taskList' }), true)
assert.equal(carriedList({ content: [], type: 'taskList' }), true)
assert.equal(carriedList({ content: [{ attrs: { state: 'DECIDED' }, content: [], type: 'decisionItem' }], type: 'decisionList' }), true)
})
test('refuses, at the item\'s text, a card a link marks in a task item', () => {
const card: AdfNode = { attrs: { data: { url: 'https://example.com/' }, url: 'https://example.com/' }, marks: [{ attrs: { href: 'https://example.com/' }, type: 'link' }], type: 'inlineCard' }
const refused = adfToHtml(document({ content: [{ attrs: { state: 'TODO' }, content: [card], type: 'taskItem' }], type: 'taskList' }))
assert.equal(refusal(refused), 'unsupported-node-shape at /content/0/content/0/content/0')
})
+89 -8
View File
@@ -1,6 +1,7 @@
import type { AdfDocument, AdfNode } from '../../adf/document.ts'
import { anchorOpener } from '../anchor-element.ts'
import { blockNodes } from '../../adf/block-nodes.ts'
import { expandClasses, panelAttributes, panelClass, taskLists } from '../block-classes.ts'
import { carriedBlock, carryElement } from './carry-element.ts'
import { carryContent } from '../carry-content.ts'
import { cellAttributes, isHeaderRow } from '../cell-element.ts'
@@ -14,12 +15,15 @@ import { isUnmarkedSpellableText, nodeAttrs, nodeContent, readAdfDocument, writa
import { languageClass } from '../language-class.ts'
import { largestNesting } from '../../nesting.ts'
import { longestOutput, tooLong, withinEngineLimits } from '../../length-bound.ts'
import { mediaImage } from '../media-element.ts'
import { plainImage } from '../../adf/plain-image.ts'
import { serializeCanonicalJson } from '../../canonical-json.ts'
import { itemOpener } from '../task-element.ts'
import { textBlockAttributes } from '../alignment-element.ts'
// depth: the nesting level of the block list holding the node, as `largestNesting` counts it; `attributes`: the `<li>`'s, `<td>`'s or `<th>`'s, built when its list or table checked it.
// depth: the nesting level of the block list holding the node, as `largestNesting` counts it; `attributes`: the `<li>`'s, `<td>`'s or `<th>`'s, built when its list or table checked it; `lead`: what stands before the inline content of a task or decision item.
type Block = { depth: number; kind: 'block'; node: AdfNode; path: ConvertErrorPath }
type Item = { attributes: string; depth: number; kind: 'item'; node: AdfNode; path: ConvertErrorPath; tag: string }
type Item = { attributes: string; depth: number; kind: 'item'; lead?: string; node: AdfNode; path: ConvertErrorPath; tag: string }
type Row = { depth: number; kind: 'row'; path: ConvertErrorPath; pieces: Pending[] }
type Pending = Block | Item | Row | string
@@ -63,12 +67,56 @@ function blockPieces(nodes: readonly AdfNode[], path: ConvertErrorPath, depth: n
function writeBlock(block: Block): Result<Pending[]> {
const { depth, node, path } = block
const container = node.type === 'blockquote' ? quotePieces(block) : node.type === 'table' ? tablePieces(block) : listPieces(block)
const container = blockContainer(block)
if (container !== undefined) return success(container)
const html = tryLeafBlock(node, path) ?? carriedBlock(node, path, depth)
return html.ok ? success([html.value]) : html
}
// `undefined` where the node is no container the elements write, or holds what they cannot.
function blockContainer(block: Block): Pending[] | undefined {
const { type } = block.node
if (type === 'blockquote') return quotePieces(block)
if (type === 'table') return tablePieces(block)
if (type === 'panel') return panelPieces(block)
if (type === 'expand' || type === 'nestedExpand') return expandPieces(block, type)
return type === 'decisionList' || type === 'taskList' ? taskPieces(block, type) : listPieces(block)
}
function panelPieces({ depth, node, path }: Block): Pending[] | undefined {
const attributes = dataAttributes(node, panelAttributes, [])
return attributes === undefined ? undefined : containerPieces('div', ` class="${panelClass}"${attributes}`, node.content === undefined ? undefined : blockPieces(node.content, path, depth + 1))
}
// The title stands on the first line, in a `<summary>` where the node holds one.
function expandPieces({ depth, node, path }: Block, type: keyof typeof expandClasses): Pending[] | undefined {
const attributes = dataAttributes(node, blockNodes[type].attributes, ['title'])
const title = nodeAttrs(node)['title']
const summary = title === undefined ? '' : typeof title === 'string' ? summaryElement(title) : undefined
if (attributes === undefined || summary === undefined) return undefined
const blocks = node.content === undefined ? undefined : blockPieces(node.content, path, depth + 1)
const lines = summary === '' ? blocks : [summary, ...(blocks === undefined ? [] : ['\n', ...blocks])]
return containerPieces('details', ` class="${expandClasses[type]}"${attributes}`, lines)
}
function summaryElement(title: string): string | undefined {
const text = title === '' ? '' : writableText(title)
return text === undefined ? undefined : `<summary>${text}</summary>`
}
function taskPieces({ depth, node, path }: Block, type: keyof typeof taskLists): Pending[] | undefined {
const attributes = dataAttributes(node, blockNodes[type].attributes, [])
if (attributes === undefined) return undefined
const items: Pending[] = []
for (const [index, item] of nodeContent(node).entries()) {
const opener = itemOpener(type, item)
if (opener === undefined) return undefined
if (index > 0) items.push('\n')
items.push({ ...opener, depth: depth + 1, kind: 'item', node: item, path: [...path, 'content', index], tag: 'li' })
}
return containerPieces('ul', ` class="${taskLists[type].listClass}"${attributes}`, node.content === undefined ? undefined : items)
}
function quotePieces({ depth, node, path }: Block): Pending[] | undefined {
const attributes = dataAttributes(node, blockNodes.blockquote.attributes, [])
return attributes === undefined ? undefined : containerPieces(containerElements.blockquote, attributes, node.content === undefined ? undefined : blockPieces(node.content, path, depth + 1))
@@ -146,7 +194,8 @@ function containerPieces(tag: string, attributes: string, children: Pending[] |
return [`<${tag}${attributes}>\n`, ...children, `\n</${tag}>`]
}
function writeItem({ attributes, depth, node, path, tag }: Item): Result<Pending[]> {
function writeItem({ attributes, depth, lead, node, path, tag }: Item): Result<Pending[]> {
if (lead !== undefined) return writeInlineItem(tag, attributes, lead, node, path)
if (node.content === undefined) return success([`<${tag}${attributes}></${tag}>`])
const blocks = blockPieces(node.content, path, depth)
const [first] = node.content
@@ -157,6 +206,14 @@ function writeItem({ attributes, depth, node, path, tag }: Item): Result<Pending
return success(blocks.length === 1 ? [`<${tag}${attributes}>${line.value}</${tag}>`] : [`<${tag}${attributes}>${line.value}`, ...blocks.slice(1), `\n</${tag}>`])
}
// An item holding inline content only, after its checkbox where it has one, a space apart.
function writeInlineItem(tag: string, attributes: string, lead: string, node: AdfNode, path: ConvertErrorPath): Result<Pending[]> {
const inline = inlineHtml(nodeContent(node), path)
if (!inline.ok) return inline
const gap = lead === '' || inline.value === '' ? '' : ' '
return success([`<${tag}${attributes}>${lead}${gap}${inline.value}</${tag}>`])
}
// `undefined` where the paragraph takes a line of its own.
function tryFirstParagraph(paragraph: AdfNode, path: ConvertErrorPath): Result<string> | undefined {
const form = firstParagraphForm(paragraph)
@@ -165,11 +222,35 @@ function tryFirstParagraph(paragraph: AdfNode, path: ConvertErrorPath): Result<s
}
function tryLeafBlock(node: AdfNode, path: ConvertErrorPath): Result<string> | undefined {
if (node.type === 'paragraph') return inlineElement('p', dataAttributes(node, blockNodes.paragraph.attributes, []), nodeContent(node), path)
if (node.type === 'paragraph') return inlineElement('p', textBlockAttributes(node, blockNodes.paragraph.attributes, []), nodeContent(node), path)
const heading = node.type === 'heading' ? headingElement(nodeAttrs(node)['level']) : undefined
if (heading !== undefined) return inlineElement(heading, dataAttributes(node, blockNodes.heading.attributes, ['level']), nodeContent(node), path)
const html = tryCodeBlock(node) ?? tryImage(node) ?? tryRule(node)
return html === undefined ? undefined : success(html)
if (heading !== undefined) return inlineElement(heading, textBlockAttributes(node, blockNodes.heading.attributes, ['level']), nodeContent(node), path)
const html = tryCodeBlock(node) ?? tryImage(node) ?? tryMediaGroup(node) ?? tryRule(node)
return html === undefined ? tryFigure(node, path) : success(html)
}
// `undefined` where the `mediaSingle`, its media or its caption holds what the elements cannot, so the whole node rides the carry.
function tryFigure(node: AdfNode, path: ConvertErrorPath): Result<string> | undefined {
if (node.type !== 'mediaSingle') return undefined
const [media, caption, ...others] = nodeContent(node)
const attributes = dataAttributes(node, blockNodes.mediaSingle.attributes, [])
const image = media?.type === 'media' ? mediaImage(media) : undefined
if (attributes === undefined || image === undefined || others.length > 0) return undefined
const figure = (inner: string): string => `<figure class="adf-media-single"${attributes}>${image}${inner}</figure>`
if (caption === undefined) return success(figure(''))
const figcaption = caption.type === 'caption' ? inlineElement('figcaption', dataAttributes(caption, blockNodes.caption.attributes, []), nodeContent(caption), [...path, 'content', 1]) : undefined
return figcaption?.ok === false ? figcaption : figcaption === undefined ? undefined : success(figure(figcaption.value))
}
function tryMediaGroup(node: AdfNode): string | undefined {
if (node.type !== 'mediaGroup' || dataAttributes(node, blockNodes.mediaGroup.attributes, []) === undefined) return undefined
let files = ''
for (const media of nodeContent(node)) {
const attributes = media.type === 'media' ? dataAttributes(media, blockNodes.media.attributes, []) : undefined
if (attributes === undefined) return undefined
files += `<span class="adf-file"${attributes}></span>`
}
return `<div class="adf-media-group">${files}</div>`
}
// `undefined` where `attributes` is undefined, so the node rides the carry.
+3 -5
View File
@@ -1,9 +1,9 @@
import type { AdfMark, AdfNode } from '../../adf/document.ts'
import { anchorOpener } from '../anchor-element.ts'
import { carriedInline } from './carry-element.ts'
import { elementOfMark } from '../mark-elements.ts'
import { holdsOnlyAttributes, isSpellableText, isUnmarkedSpellableText, nodeAttrs, nodeMarks } from '../../adf/document.ts'
import { linkAttrs } from '../../adf/mark-attributes.ts'
import { markTag } from '../mark-elements.ts'
import { nodeElement } from './node-element.ts'
import { success, type ConvertErrorPath, type Result } from '../../result.ts'
import { writableValue } from '../escaping.ts'
@@ -49,10 +49,8 @@ export function writableText(text: string | undefined): string | undefined {
}
function markElement(mark: AdfMark): { closer: string; opener: string } | undefined {
const { type } = mark
const element = elementOfMark(type)
if (element !== undefined) return mark.attrs === undefined ? { closer: `</${element}>`, opener: `<${element}>` } : undefined
if (type !== 'link' || Object.keys(nodeAttrs(mark)).some((key) => key !== 'href' && key !== 'title')) return undefined
if (mark.type !== 'link') return markTag(mark)
if (Object.keys(nodeAttrs(mark)).some((key) => key !== 'href' && key !== 'title')) return undefined
const link = linkAttrs(nodeAttrs(mark))
const opener = link === undefined ? undefined : anchorOpener(link)
return opener === undefined ? undefined : { closer: '</a>', opener }
+2 -2
View File
@@ -1,14 +1,14 @@
import type { AdfNode } from '../adf/document.ts'
import { blockNodes } from '../adf/block-nodes.ts'
import { dataAttributes } from './data-attributes.ts'
import { nodeContent } from '../adf/document.ts'
import { textBlockAttributes } from './alignment-element.ts'
// Where a list item's first paragraph stands: `bare` on the item's line, its `element` there, or a `block` on a line of its own.
export type FirstParagraphForm = 'bare' | 'block' | 'element'
// As the writer panels picked (docs/decisions.md §The HTML dialect); a paragraph holding neither content nor an attribute, written bare, would read back as no paragraph.
export function firstParagraphForm(paragraph: AdfNode): FirstParagraphForm {
const attributes = dataAttributes(paragraph, blockNodes.paragraph.attributes, [])
const attributes = textBlockAttributes(paragraph, blockNodes.paragraph.attributes, [])
if (attributes === undefined) return 'block'
if (attributes !== '') return 'element'
return nodeContent(paragraph).length === 0 ? 'block' : 'bare'
+42 -5
View File
@@ -1,16 +1,53 @@
// The element each mark but a link writes around text, holding no attribute; a link writes `<a>`.
import type { AdfMark } from '../adf/document.ts'
import { colourDeclaration, readColour } from './colour-style.ts'
import { nodeAttrs } from '../adf/document.ts'
type MarkTag = { closer: string; opener: string }
// The element each mark holding no attribute writes around text; a link writes `<a>`.
const markElements: ReadonlyMap<string, string> = new Map([
['code', 'code'],
['em', 'em'],
['strike', 'del'],
['strong', 'strong'],
['underline', 'u'],
])
// The element and CSS property each colour mark writes around text, its colour in a `style` attribute.
const colourElements: ReadonlyMap<string, { element: string; property: string }> = new Map([
['backgroundColor', { element: 'mark', property: 'background-color' }],
['textColor', { element: 'span', property: 'color' }],
])
const scripts = ['sub', 'sup']
export function elementOfMark(type: string): string | undefined {
return markElements.get(type)
// The element a mark but a link writes around text; `undefined` where the mark holds what no element spells.
export function markTag(mark: AdfMark): MarkTag | undefined {
const attrs = nodeAttrs(mark)
const plain = markElements.get(mark.type)
if (plain !== undefined) return mark.attrs === undefined ? tagOf(plain, '') : undefined
const { type } = attrs
if (mark.type === 'subsup') return Object.keys(attrs).length === 1 && typeof type === 'string' && scripts.includes(type) ? tagOf(type, '') : undefined
const colour = colourElements.get(mark.type)
const declaration = colour === undefined || Object.keys(attrs).length !== 1 ? undefined : colourDeclaration(colour.property, attrs['color'])
return colour === undefined || declaration === undefined ? undefined : tagOf(colour.element, ` style="${declaration}"`)
}
export function markOfElement(name: string): string | undefined {
for (const [type, element] of markElements) if (element === name) return type
// The mark a start tag but an `<a>` opens, as `markTag` writes it; `undefined` where it opens none.
export function markOfTag(name: string, attributes: readonly (readonly [string, string])[]): AdfMark | undefined {
const [style, ...others] = attributes
if (style === undefined) return markOfElement(name)
if (style[0] !== 'style' || others.length > 0) return undefined
for (const [type, { element, property }] of colourElements) {
const color = element === name ? readColour(property, style[1]) : undefined
if (color !== undefined) return { attrs: { color }, type }
}
return undefined
}
function markOfElement(name: string): AdfMark | undefined {
for (const [type, element] of markElements) if (element === name) return { type }
return scripts.includes(name) ? { attrs: { type: name }, type: 'subsup' } : undefined
}
function tagOf(element: string, attributes: string): MarkTag {
return { closer: `</${element}>`, opener: `<${element}${attributes}>` }
}
+92
View File
@@ -0,0 +1,92 @@
import type { AdfAttributes, AdfNode } from '../adf/document.ts'
import type { JsonValue } from '../json-value.ts'
import type { Read } from '../result.ts'
import { anchorOpener } from './anchor-element.ts'
import { blockNodes } from '../adf/block-nodes.ts'
import { dataAttributes, readDataAttributes } from './data-attributes.ts'
import { linkAttrs } from '../adf/mark-attributes.ts'
import { nodeAttrs } from '../adf/document.ts'
import { optionalAttribute, writableValue } from './escaping.ts'
const count = /^[1-9][0-9]*$/
const imageClass = 'adf-media'
const imageWritten = ['alt', 'height', 'url', 'width']
const sizes = ['height', 'width']
// A media as an `<img>`, holding a url as `src` and leaving its type out where it is `external`, inside the `<a>` of the link that marks it; `undefined` where the element cannot hold it, so its `mediaSingle` rides the carry.
export function mediaImage(media: AdfNode): string | undefined {
if (media.marks !== undefined && media.marks.length !== 1) return undefined
const [mark] = media.marks ?? []
const link = mark === undefined ? undefined : markedLink(mark)
const anchor = link === undefined ? '' : anchorOpener(link)
const bare: AdfNode = { ...media }
delete bare.marks
const attributes = imageAttributes(bare)
if (attributes === undefined || anchor === undefined || (mark !== undefined && link === undefined)) return undefined
return `${anchor}<img${attributes}>${link === undefined ? '' : '</a>'}`
}
// The attributes an `<img>` of the dialect holds, read as `readMediaImage` reads them; `fault` names no `src`, or a `class` besides one.
export function readMediaImage(pairs: readonly (readonly [string, string])[]): Read<AdfAttributes> {
let rest = pairs
const attrs: AdfAttributes = {}
const classed = rest[0]?.[0] === 'class'
if (classed && rest[0]?.[1] !== imageClass) return { fault: { code: 'unmappable-html', message: `an <img> in the dialect has class="${imageClass}" or none` } }
if (classed) rest = rest.slice(1)
const src = rest[0]?.[0] === 'src' ? rest[0][1] : undefined
if (src !== undefined) rest = rest.slice(1)
if (classed === (src !== undefined)) return { fault: { code: 'unmappable-html', message: `an <img> holds src, or class="${imageClass}" where its media holds no url, and never both` } }
if (src !== undefined) attrs['url'] = src
const alt = rest[0]?.[0] === 'alt' ? rest[0][1] : undefined
if (alt !== undefined) {
attrs['alt'] = alt
rest = rest.slice(1)
}
for (const name of sizes) {
const [first] = rest
if (first?.[0] !== name) continue
const size = Number(first[1])
if (!count.test(first[1]) || !Number.isSafeInteger(size)) return { fault: { code: 'unmappable-html', message: `${name} on <img> holds a positive whole number written as JavaScript writes it` } }
attrs[name] = size
rest = rest.slice(1)
}
const data = readDataAttributes(rest, 'img', blockNodes.media.attributes, imageWritten)
if (data.fault !== undefined) return data
const { type } = data.value
if (src !== undefined && type === 'external') return { fault: { code: 'unmappable-html', message: 'an <img> with src leaves out data-type where its media is external' } }
return { value: { ...attrs, ...data.value, ...(src !== undefined && type === undefined ? { type: 'external' } : {}) } }
}
// The attributes of the `<img>` a media is, `undefined` where a value has no spelling there.
function imageAttributes(media: AdfNode): string | undefined {
const { alt, height, type, url, width } = nodeAttrs(media)
const src = url === undefined ? '' : typeof url === 'string' ? srcAttribute(url) : undefined
const own = [url === undefined ? ` class="${imageClass}"` : src, altAttribute(alt), sizeAttribute('height', height), sizeAttribute('width', width)]
// A url without a type reads back as external, so only an external media may leave its type out.
const written = url !== undefined && type === 'external' ? [...imageWritten, 'type'] : imageWritten
const data = url !== undefined && typeof type !== 'string' ? undefined : dataAttributes(media, blockNodes.media.attributes, written)
const parts = [...own, data]
return parts.every((part) => part !== undefined) ? parts.join('') : undefined
}
function srcAttribute(url: string): string | undefined {
const written = writableValue(url)
return written === undefined ? undefined : ` src="${written}"`
}
function altAttribute(alt: JsonValue | undefined): string | undefined {
if (alt === undefined) return ''
return typeof alt === 'string' ? optionalAttribute('alt', alt) : undefined
}
function sizeAttribute(name: string, value: JsonValue | undefined): string | undefined {
if (value === undefined) return ''
return typeof value === 'number' && Number.isSafeInteger(value) && value > 0 ? ` ${name}="${value}"` : undefined
}
function markedLink(mark: { attrs?: AdfAttributes; type: string }): { href: string; title?: string } | undefined {
const attrs = nodeAttrs(mark)
const keys = Object.keys(attrs)
if (mark.type !== 'link' || keys.length === 0 || keys.some((key) => key !== 'href' && key !== 'title')) return undefined
return linkAttrs(attrs)
}
+158 -6
View File
@@ -48,7 +48,7 @@ function names(result: Result<AdfDocument, ParseError>, ...facts: readonly strin
const documentCarry = carry('div', { type: 'doc', version: 1 }, '')
const mention: AdfNode = { attrs: { id: ids.mention, text: '@Mikael' }, type: 'mention' }
const panel: AdfNode = { attrs: { panelType: 'info' }, content: [paragraph(text('Check the collation.'))], type: 'panel' }
const bodied: AdfNode = { attrs: { panelType: 'info' }, content: [paragraph(text('Check the collation.'))], type: 'bodiedExtension' }
const rule = JSON.stringify({ type: 'unknownBlock' }).replaceAll('"', '&quot;')
// The carry element of `node`, showing `shown`.
@@ -101,7 +101,7 @@ test('reads a line ending of CRLF as a line feed wherever the dialect has one, a
const crlf = (html: string): string => html.replaceAll('\n', '\r\n')
assert.deepEqual(read(htmlToAdf(crlf('<p>a\nb</p>\n<hr>\n<pre><code>c\n d</code></pre>\n'))), document(paragraph(text('a\nb')), { type: 'rule' }, { content: [text('c\n d')], type: 'codeBlock' }))
assert.deepEqual(read(htmlToAdf(crlf('<blockquote>\n<ul>\n<li>Bolt\n<p>b</p>\n</li>\n</ul>\n</blockquote>\n'))), document({ content: [{ content: [item(paragraph(text('Bolt')), paragraph(text('b')))], type: 'bulletList' }], type: 'blockquote' }))
assert.deepEqual(read(htmlToAdf(crlf(`${carry('div', panel, '<p>Check the collation.</p>')}\n`))), document(panel))
assert.deepEqual(read(htmlToAdf(crlf(`${carry('div', bodied, '<p>Check the collation.</p>')}\n`))), document(bodied))
assert.deepEqual(read(htmlToAdf(crlf(`${documentCarry}\n`))), { type: 'doc', version: 1 })
assert.deepEqual(read(htmlToAdf('<hr data-style="a\r\nb">\n')), document({ attrs: { style: 'a\nb' }, type: 'rule' }))
for (const html of ['<p>a\r</p>\n', '<p>a</p>\r', '<p>a</p>\r\r\n', '<p>a\r\r\nb</p>\n']) assert.equal(refusal(htmlToAdf(html)).startsWith('unmappable-html'), true, JSON.stringify(html))
@@ -122,7 +122,7 @@ test('reads a carry element showing what a browser spells it as, in any mix with
for (const opener of ['<a href="https://x.test/?a&lt;b&amp;c&gt;d" title="T&quot; ">', '<a href="https://x.test/?a<b&amp;c>d" title="T&quot;&nbsp;">']) {
assert.deepEqual(read(htmlToAdf(`<p>${carry('span', underlined, `${opener}a&lt;b</a>`)}</p>\n`)), document(paragraph(underlined)), opener)
}
const block: AdfNode = { attrs: { panelType: 'info' }, content: [paragraph(text('A "quote" here'))], type: 'panel' }
const block: AdfNode = { attrs: { panelType: 'info' }, content: [paragraph(text('A "quote" here'))], type: 'bodiedExtension' }
assert.deepEqual(read(htmlToAdf(`${carry('div', block, '<p>A "quote"&nbsp;here</p>')}\r\n`)), document(block))
})
@@ -185,6 +185,85 @@ test('reads an image standing alone in a paragraph, a link around it where one m
assert.deepEqual(read(htmlToAdf('<p><a href="https://example.com/" title="Home"><img src="https://example.com/moon.jpg"></a></p>\n')), document(linked))
})
test('reads a figure back: its media from the image, its caption from the figcaption, a link around the image as a mark', () => {
const external: AdfNode = { attrs: { alt: 'The moon', height: 600, type: 'external', url: 'https://example.com/moon.jpg', width: 800 }, type: 'media' }
const caption: AdfNode = { attrs: { localId: ids.item }, content: [text('The moon, '), text('at night', { type: 'em' })], type: 'caption' }
const figure = `<figure class="adf-media-single" data-layout="center" data-local-id="${ids.list}" data-width="50" data-width-type="pixel"><img src="https://example.com/moon.jpg" alt="The moon" height="600" width="800"><figcaption data-local-id="${ids.item}">The moon, <em>at night</em></figcaption></figure>\n`
assert.deepEqual(read(htmlToAdf(figure)), document({ attrs: { layout: 'center', localId: ids.list, width: 50, widthType: 'pixel' }, content: [external, caption], type: 'mediaSingle' }))
assert.deepEqual(read(htmlToAdf('<figure class="adf-media-single"><img src="https://example.com/moon.jpg" alt=""><figcaption></figcaption></figure>\n')), document({ content: [{ attrs: { alt: '', type: 'external', url: 'https://example.com/moon.jpg' }, type: 'media' }, { type: 'caption' }], type: 'mediaSingle' }))
const linked: AdfNode = { attrs: { type: 'external', url: 'https://example.com/moon.jpg' }, marks: [{ attrs: { href: 'https://example.com/', title: 'Home' }, type: 'link' }], type: 'media' }
assert.deepEqual(read(htmlToAdf('<figure class="adf-media-single" data-layout="wide"><a href="https://example.com/" title="Home"><img src="https://example.com/moon.jpg"></a></figure>\n')), document({ attrs: { layout: 'wide' }, content: [linked], type: 'mediaSingle' }))
const file: AdfNode = { attrs: { alt: 'Launch photo', collection: ids.list, height: 600, id: ids.item, occurrenceKey: ids.paragraph, type: 'file', width: 800 }, type: 'media' }
assert.deepEqual(read(htmlToAdf(`<figure class="adf-media-single"><img class="adf-media" alt="Launch photo" height="600" width="800" data-collection="${ids.list}" data-id="${ids.item}" data-occurrence-key="${ids.paragraph}" data-type="file"></figure>\n`)), document({ content: [file], type: 'mediaSingle' }))
assert.deepEqual(read(htmlToAdf('<figure class="adf-media-single"><img src="https://example.com/moon.jpg" data-type="file"></figure>\n')), document({ content: [{ attrs: { type: 'file', url: 'https://example.com/moon.jpg' }, type: 'media' }], type: 'mediaSingle' }))
assert.deepEqual(read(htmlToAdf('<figure class="adf-media-single"><img class="adf-media"></figure>\n')), document({ content: [{ type: 'media' }], type: 'mediaSingle' }))
})
test('reads a media group back from its spans', () => {
const group = `<div class="adf-media-group"><span class="adf-file" data-collection="${ids.list}" data-id="${ids.item}" data-type="file"></span><span class="adf-file" data-alt="Moon" data-height="600" data-type="external" data-url="https://example.com/moon.jpg"></span></div>\n`
assert.deepEqual(read(htmlToAdf(group)), document({ content: [{ attrs: { collection: ids.list, id: ids.item, type: 'file' }, type: 'media' }, { attrs: { alt: 'Moon', height: 600, type: 'external', url: 'https://example.com/moon.jpg' }, type: 'media' }], type: 'mediaGroup' }))
assert.deepEqual(read(htmlToAdf('<div class="adf-media-group"></div>\n')), document({ type: 'mediaGroup' }))
assert.deepEqual(read(htmlToAdf('<div class="adf-media-group"><span class="adf-file"></span></div>\n')), document({ content: [{ type: 'media' }], type: 'mediaGroup' }))
})
test('refuses a figure, an image or a media group the writer does not write', () => {
const figure = (inner: string, attributes = ' class="adf-media-single"'): string => `<figure${attributes}>${inner}</figure>\n`
const refused = (html: string, ...facts: readonly string[]): void => names(htmlToAdf(html), ...facts)
refused(figure('<img src="a">', ''), 'figure')
refused(figure('<img src="a">', ' data-layout="wide" class="adf-media-single"'), 'figure')
refused(figure('<img src="a">', ' class="adf-media-single" data-colour="red"'), 'data-colour')
refused(figure(''), 'img')
refused(figure('<img class="adf-media" src="a">'), 'both')
refused(figure('<img>'), 'src')
refused(figure('<img class="photo">'), 'class')
refused(figure('<img src="a" height="0">'), 'height')
refused(figure('<img src="a" width="08">'), 'width')
refused(figure('<img src="a" width="9007199254740993">'), 'width')
refused(figure('<img src="a" data-type="external">'), 'external')
refused(figure('<img src="a" data-colour="red">'), 'data-colour')
refused(figure('<img src="a" alt="x" alt="y">'), 'alt')
refused(figure('<img src="a"><figcaption>x</figcaption><figcaption>y</figcaption>'), '</figure>')
refused(figure('<img src="a"><p>x</p>'), '</figure>')
refused(figure('<a href="b"><img src="a"></figure>'), '</a>')
refused(figure('<a href="b" class="c"><img src="a"></a>'), 'img')
refused(figure('<img src="a"><figcaption>x</p></figcaption>'), 'figcaption')
refused('<div class="adf-media-group"><img src="a"></div>\n', 'adf-file')
refused('<div class="adf-media-group"><span class="adf-file" data-colour="red"></span></div>\n', 'data-colour')
refused('<div class="adf-media-group"><span class="adf-file">x</span></div>\n', '</span>')
refused('<div class="adf-media-group" data-id="x"></div>\n', 'adf-media-group')
refused('<div class="adf-media-group">\n</div>\n', 'adf-file')
refused('<div class="adf-media-group"><span class="adf-file">', 'adf-file')
refused('<div class="photo"></div>\n', 'div')
})
test('reads underline, subscript, superscript and the two colours from their elements', () => {
const marked = (inner: string): AdfDocument | string => read(htmlToAdf(`<p>${inner}</p>\n`))
assert.deepEqual(marked('<u>x</u>'), document(paragraph(text('x', { type: 'underline' }))))
assert.deepEqual(marked('<sub>x</sub>'), document(paragraph(text('x', { attrs: { type: 'sub' }, type: 'subsup' }))))
assert.deepEqual(marked('<sup>x</sup>'), document(paragraph(text('x', { attrs: { type: 'sup' }, type: 'subsup' }))))
assert.deepEqual(marked('<span style="color:#ff5630">x</span>'), document(paragraph(text('x', { attrs: { color: '#ff5630' }, type: 'textColor' }))))
assert.deepEqual(marked('<mark style="background-color:#fffae6">x</mark>'), document(paragraph(text('x', { attrs: { color: '#fffae6' }, type: 'backgroundColor' }))))
assert.deepEqual(marked('<strong><u><span style="color:red">x</span></u></strong>'), document(paragraph(text('x', { type: 'strong' }, { type: 'underline' }, { attrs: { color: 'red' }, type: 'textColor' }))))
assert.deepEqual(marked('a<span style="color:red">b</span>'), document(paragraph(text('a'), text('b', { attrs: { color: 'red' }, type: 'textColor' }))))
})
test('refuses a mark element the writer does not write', () => {
for (const inner of ['<span style="color:red;x:y">x</span>', '<span style="background-color:red">x</span>', '<mark style="color:red">x</mark>', '<mark>x</mark>', '<span style="color:">x</span>', '<span style="color:red" class="c">x</span>', '<u class="c">x</u>', '<sub style="color:red">x</sub>', '<span style="color:red"><span style="color:blue">x</span></span>']) {
assert.notEqual(refusal(htmlToAdf(`<p>${inner}</p>\n`)), 'read', inner)
}
})
test('reads a paragraph or heading with a style attribute as aligned, right as end', () => {
const alignment = (align: string): AdfMark => ({ attrs: { align }, type: 'alignment' })
assert.deepEqual(read(htmlToAdf('<p style="text-align:center">x</p>\n')), document({ content: [text('x')], marks: [alignment('center')], type: 'paragraph' }))
assert.deepEqual(read(htmlToAdf('<h2 style="text-align:right">x</h2>\n')), document({ attrs: { level: 2 }, content: [text('x')], marks: [alignment('end')], type: 'heading' }))
assert.deepEqual(read(htmlToAdf(`<p style="text-align:right" data-local-id="${ids.paragraph}"></p>\n`)), document({ attrs: { localId: ids.paragraph }, marks: [alignment('end')], type: 'paragraph' }))
assert.deepEqual(read(htmlToAdf('<ul>\n<li><p style="text-align:center">x</p></li>\n</ul>\n')), document({ content: [item({ content: [text('x')], marks: [alignment('center')], type: 'paragraph' })], type: 'bulletList' }))
for (const html of ['<p style="text-align:left">x</p>\n', '<p style="text-align:center;color:red">x</p>\n', `<p data-local-id="${ids.paragraph}" style="text-align:center">x</p>\n`, '<figure class="adf-media-single" style="text-align:center"><img src="a"></figure>\n', '<blockquote style="text-align:center">\n<p>x</p>\n</blockquote>\n']) {
assert.notEqual(refusal(htmlToAdf(html)), 'read', html)
}
})
test('refuses a carry element holding an inline card a link marks, at any depth in the node it carries', () => {
const card = { attrs: { url: 'https://e.com/r' }, marks: [{ attrs: { href: 'https://e.com/' }, type: 'link' }], type: 'inlineCard' }
for (const html of [`<p>${carry('span', card, '')}</p>\n`, `${carry('div', { content: [{ content: [card], type: 'futureNode' }], type: 'futureBlock' }, '')}\n`]) {
@@ -281,7 +360,7 @@ test('counts a table and its rows each a level, and a cell none, as adfToHtml do
})
test('reads a carry element from its data-adf, what it shows read back as adfToHtml writes it', () => {
assert.deepEqual(read(htmlToAdf(`${carry('div', panel, '<p>Check the collation.</p>')}\n<p>Ask ${carry('span', mention, '@Mikael')}</p>\n`)), document(panel, paragraph(text('Ask '), mention)))
assert.deepEqual(read(htmlToAdf(`${carry('div', bodied, '<p>Check the collation.</p>')}\n<p>Ask ${carry('span', mention, '@Mikael')}</p>\n`)), document(bodied, paragraph(text('Ask '), mention)))
assert.deepEqual(read(htmlToAdf(`<p>${carry('span', text('a\u0085b', { type: 'underline' }), 'ab').replace('\u0085', '\\u0085')}</p>\n`)), document(paragraph(text('a\u0085b', { type: 'underline' }))))
})
@@ -370,7 +449,7 @@ const refusals: Readonly<Record<string, readonly (readonly [string, string])[]>>
['<p><strong><a href="https://x.test/?a\nb&c">x</a></strong></p>\n', 'unmappable-html at /content/0/content/0 line 2 offset 38'],
],
'refuses an edit to what a carry element shows': [
[`<p>a</p>\n${carry('div', panel, '<p>Check the <b>collation</b>.</p>')}\n`, 'unmappable-html at /content/1 line 2 offset 9'],
[`<p>a</p>\n${carry('div', bodied, '<p>Check the <b>collation</b>.</p>')}\n`, 'unmappable-html at /content/1 line 2 offset 9'],
[`<p>Ask ${carry('span', mention, '')}</p>\n`, 'unmappable-html at /content/0/content/1 line 1 offset 0'],
],
'refuses an emoji, status, date or card holding a URL element that is not as adfToHtml writes it': [
@@ -513,7 +592,7 @@ const messages: readonly (readonly [string, readonly string[]])[] = [
['<p><strong><br>x</strong></p>\n', ['<br> as written here is no mark element of the dialect', 'found "<br>x</strong></p>\\n"']],
['<p><em></em></p>\n', ['a mark element holds text', 'found "</em></p>\\n"']],
['<p><strong><a href="https://x.test/?a=1&b=2">x</a></strong></p>\n', ['<a> holds its attributes as name="value"', '& as &amp;', '" as &quot;', 'found "&b=2\\">x</a></strong></p>"…']],
[`<p>a</p>\n${carry('div', panel, '<p>Check the <b>collation</b>.</p>')}\n`, ['a carry element shows what adfToHtml writes for its node', 'to change the node, edit its ADF and write the HTML again', 'found "<b>collation</b>.</p></d"…']],
[`<p>a</p>\n${carry('div', bodied, '<p>Check the <b>collation</b>.</p>')}\n`, ['a carry element shows what adfToHtml writes for its node', 'to change the node, edit its ADF and write the HTML again', 'found "<b>collation</b>.</p></d"…']],
['<p><span>a</span></p>\n', ['a <span> of the dialect is a carry element', 'found "<span>a</span></p>\\n"']],
['<div class="adf-carry" data-adf="{ &quot;type&quot;:&quot;x&quot;}"></div>\n', ['a carry element spells its node\'s JSON canonically', 'found "{ &quot;type&quot;:&quot"…']],
[`${documentCarry}\n<hr>\n`, ['a carry element holding the document stands alone', 'found "\\n<hr>\\n"']],
@@ -573,3 +652,76 @@ for (const [holding, adf] of Object.entries(written)) {
assert.deepEqual(read(htmlToAdf(html.value)), adf)
})
}
test('reads a panel back from its div, the panel type and other attributes from its data-* attributes, its blocks a line each', () => {
const nestedPanel: AdfNode = { attrs: { panelType: 'warning' }, content: [paragraph(text('b'))], type: 'panel' }
assert.deepEqual(read(htmlToAdf('<div class="adf-panel" data-local-id="p1" data-panel-color="#fff" data-panel-type="custom">\n<p>a</p>\n<p>b</p>\n</div>\n')), document({ attrs: { localId: 'p1', panelColor: '#fff', panelType: 'custom' }, content: [paragraph(text('a')), paragraph(text('b'))], type: 'panel' }))
assert.deepEqual(read(htmlToAdf('<div class="adf-panel" data-panel-type="note"></div>\n')), document({ attrs: { panelType: 'note' }, type: 'panel' }))
assert.deepEqual(read(htmlToAdf('<div class="adf-panel">\n<p>a</p>\n</div>\n')), document({ content: [paragraph(text('a'))], type: 'panel' }))
assert.deepEqual(read(htmlToAdf('<div class="adf-panel" data-panel-type="info">\n<div class="adf-panel" data-panel-type="warning">\n<p>b</p>\n</div>\n<ul>\n<li>c</li>\n</ul>\n</div>\n')), document({ attrs: { panelType: 'info' }, content: [nestedPanel, { content: [item(paragraph(text('c')))], type: 'bulletList' }], type: 'panel' }))
})
test('refuses a panel the writer does not write', () => {
const refused = (source: string): string => refusal(htmlToAdf(source))
assert.equal(refused('<div class="adf-panel" data-panel-type="info" data-extra="1">\n<p>a</p>\n</div>\n'), 'unsupported-node-shape at /content/0 line 1 offset 0')
assert.equal(refused('<div class="adf-panel" data-panel-type="info" data-local-id="p">\n<p>a</p>\n</div>\n'), 'unmappable-html at /content/0 line 1 offset 0')
assert.equal(refused('<div class="adf-panel" data-panel-type="info">\n</div>\n'), 'unmappable-html at /content/0/content/0 line 2 offset 47')
assert.equal(refused('<div class="adf-panel" data-panel-type="info"><p>a</p></div>\n'), 'unmappable-html at /content/0 line 1 offset 0')
assert.equal(refused('<div id="x" class="adf-panel">\n<p>a</p>\n</div>\n'), 'unmappable-html at /content/0 line 1 offset 0')
})
test('reads an expand and a nested expand back from their details, the title from the summary', () => {
const expand = (source: string): AdfDocument | string => read(htmlToAdf(source))
assert.deepEqual(expand('<details class="adf-expand" data-local-id="x1">\n<summary>Details &amp; more</summary>\n<p>Inside</p>\n</details>\n'), document({ attrs: { localId: 'x1', title: 'Details & more' }, content: [paragraph(text('Inside'))], type: 'expand' }))
assert.deepEqual(expand('<details class="adf-nested-expand">\n<summary>T</summary>\n<p>Inside</p>\n</details>\n'), document({ attrs: { title: 'T' }, content: [paragraph(text('Inside'))], type: 'nestedExpand' }))
assert.deepEqual(expand('<details class="adf-expand">\n<p>Inside</p>\n</details>\n'), document({ content: [paragraph(text('Inside'))], type: 'expand' }))
assert.deepEqual(expand('<details class="adf-expand">\n<summary></summary>\n<p>Inside</p>\n</details>\n'), document({ attrs: { title: '' }, content: [paragraph(text('Inside'))], type: 'expand' }))
assert.deepEqual(expand('<details class="adf-expand">\n<summary>T</summary>\n</details>\n'), document({ attrs: { title: 'T' }, type: 'expand' }))
assert.deepEqual(expand('<details class="adf-expand"></details>\n'), document({ type: 'expand' }))
assert.deepEqual(expand('<details class="adf-expand">\n<summary>a\nb</summary>\n<p>x</p>\n</details>\n'), document({ attrs: { title: 'a\nb' }, content: [paragraph(text('x'))], type: 'expand' }))
})
test('refuses an expand the writer does not write', () => {
const refused = (source: string): string => refusal(htmlToAdf(source))
assert.equal(refused('<details class="adf-expand" open="">\n<p>a</p>\n</details>\n'), 'unmappable-html at /content/0 line 1 offset 0')
assert.equal(refused('<details class="adf-expand" data-title="a">\n<p>a</p>\n</details>\n'), 'unsupported-node-shape at /content/0 line 1 offset 0')
assert.equal(refused('<details>\n<p>a</p>\n</details>\n'), 'unmappable-html at /content/0 line 1 offset 0')
assert.equal(refused('<details class="adf-expand">\n</details>\n'), 'unmappable-html at /content/0/content/0 line 2 offset 29')
assert.equal(refused('<details class="adf-expand">\n<summary>a<b>x</b></summary>\n<p>a</p>\n</details>\n'), 'unmappable-html at /content/0 line 2 offset 29')
assert.equal(refused('<details class="adf-expand">\n<summary>a</summary><p>a</p>\n</details>\n'), 'unmappable-html at /content/0 line 2 offset 29')
assert.equal(refused('<details class="adf-expand">\n<summary>a</summary>\n<summary>b</summary>\n</details>\n'), 'unmappable-html at /content/0/content/0 line 3 offset 50')
assert.equal(refused('<details class="adf-expand"><summary>a</summary></details>\n'), 'unmappable-html at /content/0 line 1 offset 0')
})
test('reads a task list back, each item\'s checkbox giving its state, and a decision list', () => {
const tasks = '<ul class="adf-task-list" data-local-id="l1">\n<li class="adf-task" data-local-id="t1" data-state="DONE"><input type="checkbox" checked="" disabled=""> Ship <strong>it</strong></li>\n<li class="adf-task" data-local-id="t2" data-state="TODO"><input type="checkbox" disabled=""></li>\n<li class="adf-task" data-state="TODO"><input type="checkbox" disabled=""> &lt;a&gt;</li>\n</ul>\n'
const done: AdfNode = { attrs: { localId: 't1', state: 'DONE' }, content: [text('Ship '), text('it', { type: 'strong' })], type: 'taskItem' }
const todo: AdfNode = { attrs: { localId: 't2', state: 'TODO' }, type: 'taskItem' }
assert.deepEqual(read(htmlToAdf(tasks)), document({ attrs: { localId: 'l1' }, content: [done, todo, { attrs: { state: 'TODO' }, content: [text(' <a>')], type: 'taskItem' }], type: 'taskList' }))
assert.deepEqual(read(htmlToAdf('<ul class="adf-task-list"></ul>\n')), document({ type: 'taskList' }))
const decisions = '<ul class="adf-decision-list" data-local-id="d1">\n<li class="adf-decision" data-local-id="d2" data-state="DECIDED">Use HTML</li>\n<li class="adf-decision" data-state="UNDECIDED"></li>\n</ul>\n'
assert.deepEqual(read(htmlToAdf(decisions)), document({ attrs: { localId: 'd1' }, content: [{ attrs: { localId: 'd2', state: 'DECIDED' }, content: [text('Use HTML')], type: 'decisionItem' }, { attrs: { state: 'UNDECIDED' }, type: 'decisionItem' }], type: 'decisionList' }))
assert.deepEqual(read(htmlToAdf('<ul class="adf-decision-list"></ul>\n')), document({ type: 'decisionList' }))
})
test('refuses a task or decision list the writer does not write', () => {
const refused = (source: string): string => refusal(htmlToAdf(source))
const box = '<input type="checkbox" disabled="">'
const list = (...items: string[]): string => `<ul class="adf-task-list">\n${items.join('\n')}\n</ul>\n`
assert.equal(refused(list(`<li class="adf-task" data-state="DONE">${box} a</li>`)), 'unmappable-html at /content/0/content/0 line 2 offset 27')
assert.equal(refused(list(`<li class="adf-task" data-state="TODO"><input type="checkbox" checked="" disabled=""> a</li>`)), 'unmappable-html at /content/0/content/0 line 2 offset 27')
assert.equal(refused(list(`<li class="adf-task" data-state="MAYBE">${box} a</li>`)), 'unmappable-html at /content/0/content/0 line 2 offset 27')
assert.equal(refused(list(`<li class="adf-task">${box} a</li>`)), 'unmappable-html at /content/0/content/0 line 2 offset 27')
assert.equal(refused(list(`<li data-state="TODO">${box} a</li>`)), 'unmappable-html at /content/0/content/0 line 2 offset 27')
assert.equal(refused(list('<li data-state="TODO">a</li>')), 'unmappable-html at /content/0/content/0 line 2 offset 27')
assert.equal(refused(list(`<li class="adf-task" data-state="TODO">${box}a</li>`)), 'unmappable-html at /content/0/content/0 line 2 offset 27')
assert.equal(refused(list(`<li class="adf-task" data-state="TODO">${box} </li>`)), 'unmappable-html at /content/0/content/0 line 2 offset 27')
assert.equal(refused(list(`<li class="adf-task" data-state="TODO">a</li>`)), 'unmappable-html at /content/0/content/0 line 2 offset 27')
assert.equal(refused(list(`<li class="adf-task" data-state="TODO"><input type="checkbox"> a</li>`)), 'unmappable-html at /content/0/content/0 line 2 offset 27')
assert.equal(refused(list(`<li class="adf-task" data-state="TODO">${box} a</li>\n<li class="adf-decision" data-state="DECIDED">b</li>`)), 'unmappable-html at /content/0/content/1 line 3 offset 109')
assert.equal(refused(list(`<li class="adf-task" data-state="TODO">${box} a\n<p>b</p></li>`)), 'unmappable-html at /content/0/content/0 line 3 offset 104')
assert.equal(refused(list(`<li class="adf-task" data-state="TODO" data-extra="1">${box} a</li>`)), 'unsupported-node-shape at /content/0/content/0 line 2 offset 27')
assert.equal(refused('<ul class="adf-task-list" data-extra="1"></ul>\n'), 'unsupported-node-shape at /content/0 line 1 offset 0')
assert.equal(refused('<ul class="adf-decision-list">\n<li class="adf-decision">a</li>\n<li>b</li>\n</ul>\n'), 'unmappable-html at /content/0/content/1 line 3 offset 63')
assert.equal(refused('<ul class="adf-task-list">\n</ul>\n'), 'unmappable-html at /content/0/content/0 line 2 offset 27')
})
+70 -29
View File
@@ -1,8 +1,9 @@
import type { AdfAttributes, AdfDocument, AdfNode } from '../../adf/document.ts'
import type { AttributeVocabulary } from '../../adf/attribute-vocabulary.ts'
import type { AdfDocument, AdfNode } from '../../adf/document.ts'
import type { FirstParagraphForm } from '../first-paragraph.ts'
import type { ParseError, Result } from '../../result.ts'
import { blockNodes } from '../../adf/block-nodes.ts'
import { expandClasses, expandOfClass, panelAttributes, panelClass, taskListOfClass, taskListOfType } from '../block-classes.ts'
import { built, readInlineBlock } from './inline-block.ts'
import { carryContent } from '../carry-content.ts'
import { centeredImage, externalMedia } from '../../adf/plain-image.ts'
import { isHeaderRow, readCellAttributes } from '../cell-element.ts'
@@ -19,8 +20,10 @@ import { readAnchorAttributes } from '../anchor-element.ts'
import { readCarry } from './carry-element.ts'
import { readCarryAttributes } from '../carry-attributes.ts'
import { readDataAttributes, readDataAttributesAfter } from '../data-attributes.ts'
import { readFigure, readMediaGroup } from './media-block.ts'
import { readImageAttributes } from '../image-element.ts'
import { readLanguageClass } from '../language-class.ts'
import { readTaskItem } from './task-item.ts'
import { serializeCanonicalJson } from '../../canonical-json.ts'
import { withinEngineLimits } from '../../length-bound.ts'
@@ -39,9 +42,11 @@ type TableSection = 'body' | 'head'
// No element name opens both a block and an inline node, so the name alone tells an item's line from its next block.
const blockReaders: ReadonlyMap<string, BlockReader> = new Map([
[containerElements.blockquote, containerReader('blockquote')],
[containerElements.bulletList, containerReader('bulletList')],
[containerElements.bulletList, readBulletList],
[containerElements.orderedList, containerReader('orderedList')],
['div', readBlockCarry],
['details', readDetails],
['div', readDiv],
['figure', (html, tag, place) => asStep(readFigure(html, tag, place))],
['hr', readRule],
['p', readParagraph],
['pre', readCodeBlock],
@@ -137,7 +142,7 @@ function closerOf(open: Open): string {
}
function readStep(html: string, index: number, place: Place, open: Open): Result<BlockStep | RowStep, ParseError> {
if (open.kind === 'list') return readItem(html, index, place, open.depth)
if (open.kind === 'list') return readItem(html, index, place, open)
if (open.kind === 'rows') return readRow(html, index, place, open)
return open.kind === 'row' ? readCell(html, index, place, open.depth) : readBlock(html, index, place, open)
}
@@ -171,21 +176,6 @@ function asFirstParagraph(read: { end: number; node: AdfNode }, found: FirstPara
return form === found ? success(read) : refused('unmappable-html', `${formRefusals[form]}: ${foundAt(html, index)}`, html, index, place)
}
// `own`: the attributes the element itself writes, such as a heading's level.
function readInlineBlock(html: string, tag: StartTag, type: string, vocabulary: AttributeVocabulary, own: AdfAttributes, place: Place): ReadNode {
const data = readDataAttributes(tag.attributes, tag.name, vocabulary, Object.keys(own))
if (data.fault !== undefined) return refused(data.fault.code, data.fault.message, html, tag.start, place)
const inline = readInline(html, tag.end, place)
if (!inline.ok) return inline
const { end, nodes } = inline.value
const closer = `</${tag.name}>`
if (!html.startsWith(closer, end)) {
const stop = misread(html, end, `${closer} ends the ${type}, and its text spells < as &lt;`, 'no inline element of the dialect')
return refused('unmappable-html', stop.message, html, stop.at, place)
}
return success({ end: end + closer.length, node: built(type, { ...own, ...data.value }, nodes) })
}
// `undefined` where no image follows the `<p>`, so it opens a paragraph.
function tryImage(html: string, index: number, place: Place): ReadNode | undefined {
const opener = readStartTag(html, index)
@@ -234,11 +224,61 @@ function readRule(html: string, tag: StartTag, place: Place): Result<BlockStep,
return data.fault === undefined ? success({ end: tag.end, kind: 'node', node: built('rule', data.value, []) }) : refused(data.fault.code, data.fault.message, html, tag.start, place)
}
function readDiv(html: string, tag: StartTag, place: Place, open: Open): Result<BlockStep, ParseError> {
const [first] = tag.attributes
const className = first?.[0] === 'class' ? first[1] : undefined
if (className === panelClass) return readPanel(html, tag, place, open)
return className === 'adf-media-group' ? asStep(readMediaGroup(html, tag, place)) : readBlockCarry(html, tag, place, open)
}
function readPanel(html: string, tag: StartTag, place: Place, open: Open): Result<BlockStep, ParseError> {
const data = readDataAttributes(tag.attributes.slice(1), tag.name, panelAttributes, [])
if (data.fault !== undefined) return refused(data.fault.code, data.fault.message, html, tag.start, place)
return readContents(html, tag, built('panel', data.value, []), place, open, 'blocks')
}
// An expand's title stands in a `<summary>` on the first line, its blocks a line each after it.
function readDetails(html: string, tag: StartTag, place: Place, open: Open): Result<BlockStep, ParseError> {
const [first, ...pairs] = tag.attributes
const type = first?.[0] === 'class' ? expandOfClass(first[1]) : undefined
if (type === undefined) return refused('unmappable-html', `<details> starts with class="${expandClasses.expand}" or class="${expandClasses.nestedExpand}": ${foundAt(html, tag.start)}`, html, tag.start, place)
const data = readDataAttributes(pairs, tag.name, blockNodes[type].attributes, ['title'])
if (data.fault !== undefined) return refused(data.fault.code, data.fault.message, html, tag.start, place)
const summary = html.startsWith('\n<summary>', tag.end) ? readSummary(html, tag.end + 1, place) : undefined
if (summary?.ok === false) return summary
if (summary === undefined) return readContents(html, tag, built(type, data.value, []), place, open, 'blocks')
const node = built(type, { ...data.value, title: summary.value.title }, [])
const { end } = summary.value
if (html.startsWith('\n</details>', end)) return success({ end: end + '\n</details>'.length, kind: 'node', node })
if (!html.startsWith('\n', end)) return refused('unmappable-html', `<summary> holds the title, then a line feed and the first block, or a line feed and </details>: ${foundAt(html, end)}`, html, end, place)
return success({ end: end + 1, kind: 'opened', open: { closer: '\n</details>', content: [], depth: open.depth + 1, kind: 'blocks', node, place } })
}
function readSummary(html: string, index: number, place: Place): Result<{ end: number; title: string }, ParseError> {
const start = index + '<summary>'.length
const close = html.indexOf('</summary>', start)
if (close < 0) return refused('unmappable-html', `<summary> ends at </summary>: ${foundAt(html, start)}`, html, start, place)
const spelled = html.slice(start, close)
const title = unescapedValue(spelled, 'text')
if (title === undefined) return misspelledText(html, start + misspelledAt(spelled, 'text'), place)
return success({ end: close + '</summary>'.length, title })
}
function readBlockCarry(html: string, tag: StartTag, place: Place, open: Open): Result<BlockStep, ParseError> {
if (readCarryAttributes(tag.attributes) === emptyDocument) return refused('unsupported-node-shape', `${documentCarryAlone}: ${foundAt(html, tag.start)}`, html, tag.start, place)
return asStep(readCarry(html, tag, 'div', largestNesting - open.depth, place))
}
// A `<ul>` is a task or decision list where its class says so.
function readBulletList(html: string, tag: StartTag, place: Place, open: Open): Result<BlockStep, ParseError> {
const [first, ...pairs] = tag.attributes
const type = first?.[0] === 'class' ? taskListOfClass(first[1]) : undefined
if (type === undefined) return readContainer(html, tag, 'bulletList', place, open)
const data = readDataAttributes(pairs, tag.name, blockNodes[type].attributes, [])
if (data.fault !== undefined) return refused(data.fault.code, data.fault.message, html, tag.start, place)
return readContents(html, tag, built(type, data.value, []), place, open, 'list')
}
function containerReader(type: ContainerType): BlockReader {
return (html, tag, place, open) => readContainer(html, tag, type, place, open)
}
@@ -256,11 +296,15 @@ function readContainer(html: string, tag: StartTag, type: ContainerType, place:
const vocabulary = blockNodes[type].attributes
const data = ordered ? readDataAttributesAfter('start', tag.attributes, tag.name, vocabulary, ['order']) : readDataAttributes(tag.attributes, tag.name, vocabulary, [])
if (data.fault !== undefined) return refused(data.fault.code, data.fault.message, html, tag.start, place)
const node = built(type, order === undefined ? data.value : { order, ...data.value }, [])
return readContents(html, tag, built(type, order === undefined ? data.value : { order, ...data.value }, []), place, open, type === 'blockquote' ? 'blocks' : 'list')
}
// The element holds nothing, or a line feed and its first block or item.
function readContents(html: string, tag: StartTag, node: AdfNode, place: Place, open: Open, kind: 'blocks' | 'list'): Result<BlockStep, ParseError> {
const closer = `</${tag.name}>`
if (html.startsWith(closer, tag.end)) return success({ end: tag.end + closer.length, kind: 'node', node })
if (!html.startsWith('\n', tag.end)) return refused('unmappable-html', `<${tag.name}> holds ${closer} straight after it, or a line feed and its first ${type === 'blockquote' ? 'block' : 'item'}: ${foundAt(html, tag.end)}`, html, tag.end, place)
return success({ end: tag.end + 1, kind: 'opened', open: { closer: `\n${closer}`, content: [], depth: open.depth + 1, kind: type === 'blockquote' ? 'blocks' : 'list', node, place } })
if (!html.startsWith('\n', tag.end)) return refused('unmappable-html', `<${tag.name}> holds ${closer} straight after it, or a line feed and its first ${kind === 'blocks' ? 'block' : 'item'}: ${foundAt(html, tag.end)}`, html, tag.end, place)
return success({ end: tag.end + 1, kind: 'opened', open: { closer: `\n${closer}`, content: [], depth: open.depth + 1, kind, node, place } })
}
function readTable(html: string, tag: StartTag, place: Place, open: Open): Result<BlockStep, ParseError> {
@@ -306,7 +350,9 @@ function readCell(html: string, index: number, place: Place, depth: number): Res
return readHolder(html, tag, built(tag.name === 'td' ? 'tableCell' : 'tableHeader', attrs.value, []), place, depth)
}
function readItem(html: string, index: number, place: Place, depth: number): Result<BlockStep, ParseError> {
function readItem(html: string, index: number, place: Place, { depth, node: list }: Open): Result<BlockStep, ParseError> {
const tasks = taskListOfType(list.type)
if (tasks !== undefined) return asStep(readTaskItem(html, index, place, tasks))
const tag = readStartTag(html, index)
if (tag?.name !== 'li') {
const stop = misread(html, index, 'a list holds <li> items, one to a line', 'no list item of the dialect')
@@ -373,8 +419,3 @@ function partedLine(html: string, end: number, nodes: AdfNode[]): AdfNode[] | un
function isBlockStart(html: string, index: number): boolean {
return blockReaders.has(startTagName(html, index) ?? '')
}
// The node an element holding no attribute or content reads as: `adfToHtml` writes a node holding an empty `attrs` or `content` as a carry.
function built(type: string, attrs: AdfAttributes, content: AdfNode[]): AdfNode {
return { ...(Object.keys(attrs).length === 0 ? {} : { attrs }), ...(content.length === 0 ? {} : { content }), type }
}
+37
View File
@@ -0,0 +1,37 @@
import type { AdfAttributes, AdfMark, AdfNode } from '../../adf/document.ts'
import type { AttributeVocabulary } from '../../adf/attribute-vocabulary.ts'
import type { Read } from '../../result.ts'
import { misread, refused, type Place, type ReadNode, type StartTag } from './source.ts'
import { readDataAttributes } from '../data-attributes.ts'
import { readInline } from './inline.ts'
import { readTextBlockAttributes } from '../alignment-element.ts'
import { success } from '../../result.ts'
// `own`: the attributes the element itself writes, such as a heading's level.
export function readInlineBlock(html: string, tag: StartTag, type: string, vocabulary: AttributeVocabulary, own: AdfAttributes, place: Place): ReadNode {
const written = Object.keys(own)
// Only a paragraph or heading takes an alignment, as a `style` attribute.
const aligned = type === 'paragraph' || type === 'heading'
const held = aligned ? readTextBlockAttributes(tag.attributes, tag.name, vocabulary, written) : readUnmarked(tag, vocabulary, written)
if (held.fault !== undefined) return refused(held.fault.code, held.fault.message, html, tag.start, place)
const inline = readInline(html, tag.end, place)
if (!inline.ok) return inline
const { end, nodes } = inline.value
const closer = `</${tag.name}>`
if (!html.startsWith(closer, end)) {
const stop = misread(html, end, `${closer} ends the ${type}, and its text spells < as &lt;`, 'no inline element of the dialect')
return refused('unmappable-html', stop.message, html, stop.at, place)
}
const node = built(type, { ...own, ...held.value.attrs }, nodes)
return success({ end: end + closer.length, node: held.value.marks.length === 0 ? node : { ...node, marks: held.value.marks } })
}
function readUnmarked(tag: StartTag, vocabulary: AttributeVocabulary, written: readonly string[]): Read<{ attrs: AdfAttributes; marks: AdfMark[] }> {
const data = readDataAttributes(tag.attributes, tag.name, vocabulary, written)
return data.fault === undefined ? { value: { attrs: data.value, marks: [] } } : data
}
// The node an element holding no attribute or content reads as: `adfToHtml` writes a node holding an empty `attrs` or `content` as a carry.
export function built(type: string, attrs: AdfAttributes, content: AdfNode[]): AdfNode {
return { ...(Object.keys(attrs).length === 0 ? {} : { attrs }), ...(content.length === 0 ? {} : { content }), type }
}
+4 -5
View File
@@ -3,7 +3,7 @@ import type { ParseError, Result } from '../../result.ts'
import { foundAt, misread, misspelledText, readStartTag, refused, type Place, type ReadNode, type StartTag } from './source.ts'
import { largestNesting } from '../../nesting.ts'
import { linkMarkFrom } from '../../adf/mark-attributes.ts'
import { markOfElement } from '../mark-elements.ts'
import { markOfTag } from '../mark-elements.ts'
import { misspelledAt, unescapedValue } from '../escaping.ts'
import { readAnchorAttributes } from '../anchor-element.ts'
import { readCarry } from './carry-element.ts'
@@ -31,8 +31,8 @@ function readTagged(html: string, index: number, place: Place): ReadNode | undef
if (tag?.name === 'br' && tag.attributes.length === 0) return success({ end: tag.end, node: { type: 'hardBreak' } })
const element = tag === undefined ? undefined : readNodeElement(html, tag, place)
if (element !== undefined) return element
if (tag?.name === 'span') return readCarry(html, tag, 'span', largestNesting, place)
return tag !== undefined && markOf(tag) !== undefined ? readMarked(html, index, place) : undefined
if (tag !== undefined && markOf(tag) !== undefined) return readMarked(html, index, place)
return tag?.name === 'span' ? readCarry(html, tag, 'span', largestNesting, place) : undefined
}
// Each text node writes its own elements, one inside the other around its text, the first mark outermost.
@@ -77,6 +77,5 @@ function markOf(tag: StartTag): AdfMark | undefined {
const link = readAnchorAttributes(tag.attributes)
return link === undefined ? undefined : linkMarkFrom(link)
}
const type = tag.attributes.length === 0 ? markOfElement(tag.name) : undefined
return type === undefined ? undefined : { type }
return markOfTag(tag.name, tag.attributes)
}
+71
View File
@@ -0,0 +1,71 @@
import type { AdfNode } from '../../adf/document.ts'
import { blockNodes } from '../../adf/block-nodes.ts'
import { built, readInlineBlock } from './inline-block.ts'
import { foundAt, readStartTag, refused, type Place, type ReadNode, type StartTag } from './source.ts'
import { linkMarkFrom } from '../../adf/mark-attributes.ts'
import { readAnchorAttributes } from '../anchor-element.ts'
import { readDataAttributes } from '../data-attributes.ts'
import { readMediaImage } from '../media-element.ts'
import { success } from '../../result.ts'
const figureClass = 'adf-media-single'
const fileClass = 'adf-file'
const groupClass = 'adf-media-group'
// A `mediaSingle` as `adfToHtml` writes it: its media's image, then its caption, on one line.
export function readFigure(html: string, tag: StartTag, place: Place): ReadNode {
const [leading, ...pairs] = tag.attributes
if (leading?.[0] !== 'class' || leading[1] !== figureClass) return refused('unmappable-html', `<figure> starts with class="${figureClass}": ${foundAt(html, tag.start)}`, html, tag.start, place)
const data = readDataAttributes(pairs, tag.name, blockNodes.mediaSingle.attributes, [])
if (data.fault !== undefined) return refused(data.fault.code, data.fault.message, html, tag.start, place)
const media = readMedia(html, tag.end, { index: 0, parent: place })
if (!media.ok) return media
const content = [media.value.node]
let { end } = media.value
const figcaption = readStartTag(html, end)
if (figcaption?.name === 'figcaption') {
const caption = readInlineBlock(html, figcaption, 'caption', blockNodes.caption.attributes, {}, { index: 1, parent: place })
if (!caption.ok) return caption
content.push(caption.value.node)
end = caption.value.end
}
return closed(html, end, '</figure>', 'its image, then its <figcaption>', built('mediaSingle', data.value, content), place)
}
// A `mediaGroup` as `adfToHtml` writes it: a span for each media, none between.
export function readMediaGroup(html: string, tag: StartTag, place: Place): ReadNode {
if (tag.attributes.length !== 1) return refused('unmappable-html', `<div class="${groupClass}"> takes no other attribute: ${foundAt(html, tag.start)}`, html, tag.start, place)
const content: AdfNode[] = []
let at = tag.end
for (let span = readStartTag(html, at); span?.name === 'span'; span = readStartTag(html, at)) {
const [leading, ...pairs] = span.attributes
const mediaPlace = { index: content.length, parent: place }
if (leading?.[0] !== 'class' || leading[1] !== fileClass) return refused('unmappable-html', `a media group holds <span class="${fileClass}"> files: ${foundAt(html, span.start)}`, html, span.start, mediaPlace)
const data = readDataAttributes(pairs, span.name, blockNodes.media.attributes, [])
if (data.fault !== undefined) return refused(data.fault.code, data.fault.message, html, span.start, mediaPlace)
if (!html.startsWith('</span>', span.end)) return refused('unmappable-html', `<span class="${fileClass}"> holds nothing, and ends at </span>: ${foundAt(html, span.end)}`, html, span.end, mediaPlace)
content.push(built('media', data.value, []))
at = span.end + '</span>'.length
}
return closed(html, at, '</div>', `its <span class="${fileClass}"> files`, built('mediaGroup', {}, content), place)
}
// The media an `<img>` reads as, and the `<a>` around it where a link marks it.
function readMedia(html: string, index: number, place: Place): ReadNode {
const opener = readStartTag(html, index)
const anchor = opener?.name === 'a' ? opener : undefined
const image = anchor === undefined ? opener : readStartTag(html, anchor.end)
const link = anchor === undefined ? undefined : readAnchorAttributes(anchor.attributes)
if (image?.name !== 'img' || (anchor !== undefined && link === undefined)) return refused('unmappable-html', `a <figure> holds an <img>, inside <a href="…"> where a link marks it: ${foundAt(html, index)}`, html, index, place)
const attrs = readMediaImage(image.attributes)
if (attrs.fault !== undefined) return refused(attrs.fault.code, attrs.fault.message, html, image.start, place)
const media = built('media', attrs.value, [])
if (link === undefined) return success({ end: image.end, node: media })
if (!html.startsWith('</a>', image.end)) return refused('unmappable-html', `<a> around an image ends at </a>: ${foundAt(html, image.end)}`, html, image.end, place)
return success({ end: image.end + '</a>'.length, node: { ...media, marks: [linkMarkFrom(link)] } })
}
function closed(html: string, end: number, closer: string, held: string, node: AdfNode, place: Place): ReadNode {
if (!html.startsWith(closer, end)) return refused('unmappable-html', `${closer.replace('/', '')} holds ${held}, then ${closer}: ${foundAt(html, end)}`, html, end, place)
return success({ end: end + closer.length, node })
}
+62
View File
@@ -0,0 +1,62 @@
import type { AdfAttributes } from '../../adf/document.ts'
import { built } from './inline-block.ts'
import { foundAt, misread, readStartTag, refused, type Place, type ReadNode } from './source.ts'
import { readDataAttributes } from '../data-attributes.ts'
import { readInline } from './inline.ts'
import { success, type Read } from '../../result.ts'
import { taskLists, type TaskListType } from '../block-classes.ts'
import { taskStates } from '../task-element.ts'
// An item of a task or decision list as `adfToHtml` writes it: its checkbox, if a task, a space, then its inline content.
export function readTaskItem(html: string, index: number, place: Place, list: TaskListType): ReadNode {
const tag = readStartTag(html, index)
if (tag?.name !== 'li') {
const stop = misread(html, index, 'a list holds <li> items, one to a line', 'no list item of the dialect')
return refused('unmappable-html', stop.message, html, stop.at, place)
}
const found = readItemAttributes(list, tag.attributes)
if (found.fault !== undefined) return refused(found.fault.code, found.fault.message, html, tag.start, place)
const { attrs, done } = found.value
let start = tag.end
if (done !== undefined) {
const box = checkbox(html, start, done)
if (!box) return refused('unmappable-html', `a task item starts with <input type="checkbox"${done ? ' checked=""' : ''} disabled="">, checked where its data-state is DONE: ${foundAt(html, start)}`, html, start, place)
start = box
}
const node = built(taskLists[list].item, attrs, [])
if (html.startsWith('</li>', start)) return success({ end: start + '</li>'.length, node })
if (done !== undefined) {
if (!html.startsWith(' ', start)) return refused('unmappable-html', `a task item's text stands a space after its checkbox: ${foundAt(html, start)}`, html, start, place)
start += 1
}
const inline = readInline(html, start, place)
if (!inline.ok) return inline
const { end, nodes } = inline.value
if (nodes.length === 0 || !html.startsWith('</li>', end)) {
const stop = nodes.length === 0 ? { at: end, message: `a task item holds text where a space follows its checkbox: ${foundAt(html, end)}` } : misread(html, end, 'an item holds inline content, then </li>, as one line', 'no inline element of the dialect')
return refused('unmappable-html', stop.message, html, stop.at, place)
}
return success({ end: end + '</li>'.length, node: { ...node, content: nodes } })
}
// `done` is `undefined` for a decision item, which has no checkbox.
function readItemAttributes(list: TaskListType, pairs: readonly (readonly [string, string])[]): Read<{ attrs: AdfAttributes; done: boolean | undefined }> {
const { itemAttributes, itemClass } = taskLists[list]
const [first, ...rest] = pairs
if (first?.[0] !== 'class' || first[1] !== itemClass) return { fault: { code: 'unmappable-html', message: `an <li> of this list has class="${itemClass}" first` } }
const data = readDataAttributes(rest, 'li', itemAttributes, [])
if (data.fault !== undefined) return { fault: data.fault }
if (list === 'decisionList') return { value: { attrs: data.value, done: undefined } }
const state = data.value['state']
const done = typeof state === 'string' ? taskStates.get(state) : undefined
if (done === undefined) return { fault: { code: 'unmappable-html', message: 'an <li> of a task list has data-state="DONE" or data-state="TODO"' } }
return { value: { attrs: data.value, done } }
}
// The end of the checkbox at `index`; `undefined` where the checkbox is not the one adfToHtml writes for `done`.
function checkbox(html: string, index: number, done: boolean): number | undefined {
const input = readStartTag(html, index)
const expected = [['type', 'checkbox'], ...(done ? [['checked', '']] : []), ['disabled', '']]
const same = input?.name === 'input' && input.attributes.length === expected.length && input.attributes.every(([name, value], at) => name === expected[at]?.[0] && value === expected[at]?.[1])
return same ? input.end : undefined
}
+22
View File
@@ -0,0 +1,22 @@
import type { AdfNode } from '../adf/document.ts'
import { dataAttributes } from './data-attributes.ts'
import { nodeAttrs } from '../adf/document.ts'
import { taskLists, type TaskListType } from './block-classes.ts'
// A task item's two states, and whether the checkbox before its text is checked.
export const taskStates: ReadonlyMap<string, boolean> = new Map([
['DONE', true],
['TODO', false],
])
// The start tag's attributes of an item of a task or decision list, and what stands before its text: a checkbox in a task, checked where it is done; `undefined` where the item holds what its element cannot.
export function itemOpener(list: TaskListType, item: AdfNode): { attributes: string; lead: string } | undefined {
const { item: type, itemAttributes, itemClass } = taskLists[list]
const data = item.type === type ? dataAttributes(item, itemAttributes, []) : undefined
if (data === undefined) return undefined
const attributes = ` class="${itemClass}"${data}`
if (list === 'decisionList') return { attributes, lead: '' }
const state = nodeAttrs(item)['state']
const done = typeof state === 'string' ? taskStates.get(state) : undefined
return done === undefined ? undefined : { attributes, lead: `<input type="checkbox"${done ? ' checked=""' : ''} disabled="">` }
}
+8 -18
View File
@@ -6,16 +6,14 @@
`Bar = 0.1`
`Next ID = 184`
`Next ID = 185`
## Items
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 135 | 0.4.0 | | | **Write media, media groups and captions as semantic HTML in `adfToHtml` and read them back in `htmlToAdf`, in place of the carry element.** | 2 | 2 | 2 | 4 | 4 | 6 by 2 | 1.6 |
| 136 | 0.4.0 | | | **Write underline, text and background colours, subscript, superscript, alignment and indentation as HTML in `adfToHtml` and read them back in `htmlToAdf`, in place of the carry element.** | 2 | 2 | 2 | 4 | 4 | 6 by 2 | 1.6 |
| 134 | 0.4.0 | | decision | **Write panels, expands, task lists and decision lists as semantic HTML in `adfToHtml` and read them back in `htmlToAdf`, in place of the carry element.** | 2 | 2 | 2 | 4 | 5 | 6 by 3 | 1.5 |
| 46 | 0.4.0 | 134, 135, 136 | | **Publish the bundle size in the README, failing the release pipeline when it drifts.** | 2 | 2 | 1 | 3 | 4 | 3 by 3 | 2.6 |
| 184 | 0.4.0 | | question | **Write indentation as HTML in `adfToHtml` and read it back in `htmlToAdf`, in place of the carry element, once the maintainer settles whether its element carries a `margin-left` style.** | 1 | 2 | 2 | 3 | 2 | 6 by 2 | 3.2 |
| 46 | 0.4.0 | | | **Publish the bundle size in the README, failing the release pipeline when it drifts.** | 2 | 2 | 1 | 3 | 4 | 3 by 3 | 2.6 |
| 174 | 0.4.0 | | defect | **Bound the passes `trimmedEdges` takes by a constant, so a line of alternating code and emphasized blanks trims in linear time.** | 3 | 1 | 2 | 4 | 7 | 9 by 3 | 1.9 |
| 51 | 0.4.0 | | | **Match a reference label to its definition under Unicode case folding.** | 2 | 1 | 2 | 3 | 4 | 4 by 2 | 1.7 |
| 148 | 0.4.0 | | | **Ship conversion between ADF and Jira wiki markup both ways, under a README goal for wiki markup.** | 3 | 2 | 2 | 5 | 7 | 3 by 5 | 0.8 |
@@ -48,23 +46,15 @@
## Details
### 135. Write media, media groups and captions as semantic HTML in `adfToHtml` and read them back in `htmlToAdf`, in place of the carry element.
### 184. Write indentation as HTML in `adfToHtml` and read it back in `htmlToAdf`, in place of the carry element, once the maintainer settles whether its element carries a `margin-left` style.
A writer panel picks the spellings; a plain external image already has one, `<p><img …></p>`.
Atlassian's editor puts `localId`, `width` and `widthType` on every `mediaSingle`, so every
editor-written image rides the carry until this item.
Item 136 wrote alignment, underline, colours, subscript and superscript as HTML and left indentation on the carry element, since the writer panel did not settle one spelling.
### 136. Write underline, text and background colours, subscript, superscript, alignment and indentation as HTML in `adfToHtml` and read them back in `htmlToAdf`, in place of the carry element.
A writer panel of seven picked `data-indent-level` for the attribute name, 5 of 7. It split on whether a `margin-left` style stands beside it: 4 readers wanted the style as well, so a browser shows the indent, and 3 wanted the data attribute alone, as the alignment style is the only presentation the dialect writes.
A writer panel picks the spellings.
Recommendation: the data attribute alone. The dialect writes no style the viewer needs to read the document, and a `margin-left` in some unit would be a second spelling of the level that has to agree with it. The level stays one value, `data-indent-level="2"`, and a block holding an indentation mark takes no other mark.
### 134. Write panels, expands, task lists and decision lists as semantic HTML in `adfToHtml` and read them back in `htmlToAdf`, in place of the carry element.
An expand is `<details><summary>`, as `htmlToAdf` reads it (`docs/decisions.md` §Foreign HTML sorts
three ways). A writer panel picks the rest. A reader panel (`docs/decisions.md`, the feature-table
entry) expected a panel as `<div class="adf-panel" data-panel-type="…">` and a task list as
`<ul class="adf-task-list">` of `<li data-state="DONE|TODO">` with a checkbox input, and the writer
panel takes these as input.
The gap to close in `docs/decisions.md`: the class is "which output the audience expects", settled by a panel, and this panel's split is less than five of seven, so it is a missing goal and the maintainer's to answer.
### 46. Publish the bundle size in the README, failing the release pipeline when it drifts.