3
0
mirror of https://github.com/larvit/adf-codec.git synced 2026-11-19 06:35:44 +01:00

Write emoji, status, date and URL card as HTML elements, not the carry

This commit is contained in:
2026-11-04 13:36:50 +01:00
committed by Lillem4n
parent 7ca6114f5d
commit 7c17447a87
14 changed files with 236 additions and 24 deletions
+36 -5
View File
@@ -140,6 +140,37 @@ test('carries every other node in an adf-carry element holding its JSON', () =>
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;text&quot;:&quot;@Mikael&quot;},&quot;type&quot;:&quot;mention&quot;}">@Mikael</span></p>\n')
})
test('writes an emoji, status, date and URL card as their elements, their attributes data-* sorted by name', () => {
const inline = (node: AdfNode): string => html(adfToHtml(document(paragraph(text('See '), node))))
assert.equal(inline({ attrs: { id: '1f389', localId: 'e1', shortName: ':tada:', text: '🎉' }, type: 'emoji' }), '<p>See <span class="adf-emoji" data-id="1f389" data-local-id="e1" data-short-name=":tada:">🎉</span></p>\n')
assert.equal(inline({ attrs: { text: '<3' }, type: 'emoji' }), '<p>See <span class="adf-emoji">&lt;3</span></p>\n')
assert.equal(inline({ attrs: { color: 'yellow', localId: 's1', style: 'bold', text: 'In review' }, type: 'status' }), '<p>See <span class="adf-status" data-color="yellow" data-local-id="s1" data-style="bold">In review</span></p>\n')
assert.equal(inline({ attrs: { localId: 'd1', timestamp: '1756080000000' }, type: 'date' }), '<p>See <time class="adf-date" datetime="2025-08-25" data-local-id="d1" data-timestamp="1756080000000">2025-08-25</time></p>\n')
assert.equal(inline({ attrs: { localId: 'c1', url: 'https://example.com/spec?a=1&b=2' }, type: 'inlineCard' }), '<p>See <a class="adf-inline-card" href="https://example.com/spec?a=1&amp;b=2" data-local-id="c1">https://example.com/spec?a=1&amp;b=2</a></p>\n')
})
test('carries an emoji, status, date or URL card the element cannot hold', () => {
const carried = (node: AdfNode): boolean => html(adfToHtml(document(paragraph(node)))).includes('adf-carry')
const comment: AdfMark = { attrs: { annotationType: 'inlineComment', id: 'c1' }, type: 'annotation' }
assert.equal(carried({ attrs: { text: '🎉' }, marks: [comment], type: 'emoji' }), true)
assert.equal(carried({ attrs: { shortName: ':tada:' }, type: 'emoji' }), true)
assert.equal(carried({ attrs: { text: '' }, type: 'emoji' }), true)
assert.equal(carried({ attrs: { text: 'a\u0001' }, type: 'emoji' }), true)
assert.equal(carried({ attrs: { size: 'big', text: '🎉' }, type: 'emoji' }), true)
assert.equal(carried({ attrs: { id: 5, text: '🎉' }, type: 'emoji' }), true)
assert.equal(carried({ attrs: { text: '🎉' }, content: [], type: 'emoji' }), true)
assert.equal(carried({ attrs: { color: 'red' }, type: 'status' }), true)
assert.equal(carried({ attrs: { timestamp: 'soon' }, type: 'date' }), true)
assert.equal(carried({ attrs: { timestamp: 1756080000000 }, type: 'date' }), true)
assert.equal(carried({ type: 'date' }), true)
assert.equal(carried({ attrs: { data: { name: 'Roadmap' } }, type: 'inlineCard' }), true)
assert.equal(carried({ attrs: { data: { name: 'Roadmap' }, url: 'https://example.com/' }, type: 'inlineCard' }), true)
assert.equal(carried({ attrs: { url: 'https://example.com/' }, marks: [{ attrs: { href: 'https://example.org/' }, type: 'link' }], type: 'inlineCard' }), true)
assert.equal(carried({ attrs: { url: '' }, type: 'inlineCard' }), true)
assert.equal(carried({ attrs: { url: 'https://example.com/\u0001' }, type: 'inlineCard' }), true)
assert.equal(carried({ attrs: { id: '5b10a2', text: '@Mikael' }, type: 'mention' }), true)
})
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' }
assert.equal(shown(html(adfToHtml(document(panel)))), '<p>Check the collation.</p><p>Then import.</p>')
@@ -199,11 +230,11 @@ test('shows a code block in a span carry as text, its line feeds line breaks', (
test('shows the content a carried node holds in an attribute, and links a card or an external image to its URL', () => {
const inline = (node: AdfNode): string => shown(html(adfToHtml(document(paragraph(node)))))
assert.equal(inline({ attrs: { timestamp: '1700000000000' }, type: 'date' }), '2023-11-14')
assert.equal(inline({ attrs: { shortName: ':smile:', text: '😄' }, type: 'emoji' }), '😄')
assert.equal(inline({ attrs: { timestamp: '1700000000000' }, marks: [{ attrs: { annotationType: 'inlineComment', id: 'c1' }, type: 'annotation' }], type: 'date' }), '2023-11-14')
assert.equal(inline({ attrs: { shortName: ':smile:', text: '😄' }, marks: [{ attrs: { annotationType: 'inlineComment', id: 'c1' }, type: 'annotation' }], type: 'emoji' }), '😄')
assert.equal(inline({ attrs: { id: '5b10a2' }, type: 'mention' }), '@5b10a2')
assert.equal(inline({ attrs: { color: 'green', text: 'Done' }, type: 'status' }), 'Done')
assert.equal(inline({ attrs: { url: 'https://example.com/<card>' }, type: 'inlineCard' }), '<a href="https://example.com/&lt;card&gt;">https://example.com/&lt;card&gt;</a>')
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' }))))
@@ -296,7 +327,7 @@ test('writes every URL as the ADF holds it, escaped, whatever its scheme', () =>
assert.equal(linked('data:text/html,<b>x</b>'), '<p><a href="data:text/html,&lt;b&gt;x&lt;/b&gt;">x</a></p>\n')
const image: AdfNode = { attrs: { layout: 'center' }, content: [{ attrs: { type: 'external', url: 'vbscript:x' }, type: 'media' }], type: 'mediaSingle' }
assert.equal(html(adfToHtml(document(image))), '<p><img src="vbscript:x"></p>\n')
assert.equal(shown(html(adfToHtml(document(paragraph({ attrs: { url: 'javascript:alert(1)' }, type: 'inlineCard' }))))), '<a href="javascript:alert(1)">javascript:alert(1)</a>')
assert.equal(html(adfToHtml(document(paragraph({ attrs: { url: 'javascript:alert(1)' }, type: 'inlineCard' })))), '<p><a class="adf-inline-card" href="javascript:alert(1)">javascript:alert(1)</a></p>\n')
})
test('writes a container holding no content key as its element holding nothing', () => {
+3
View File
@@ -4,6 +4,7 @@ import { carriedInline } from './carry-element.ts'
import { elementOfMark } from '../mark-elements.ts'
import { holdsOnlyAttributes, isSpellableText, isUnmarkedSpellableText, nodeAttrs, nodeContent, nodeMarks } from '../../adf/document.ts'
import { linkAttrs } from '../../adf/mark-attributes.ts'
import { nodeElement } from './node-element.ts'
import { success, type ConvertErrorPath, type Result } from '../../result.ts'
import { writableValue } from '../escaping.ts'
@@ -25,6 +26,8 @@ export function inlineHtml(nodes: readonly AdfNode[], path: ConvertErrorPath): R
function tryInlineNode(node: AdfNode): string | undefined {
if (node.type === 'hardBreak') return holdsOnlyAttributes(node, []) && nodeContent(node).length === 0 ? '<br>' : undefined
const element = nodeElement(node)
if (element !== undefined) return element
const text = isSpellableText(node) ? writableText(node.text) : undefined
if (text === undefined) return undefined
const marks = nodeMarks(node)
+18
View File
@@ -0,0 +1,18 @@
import type { AdfNode } from '../../adf/document.ts'
import { dataAttributes } from '../data-attributes.ts'
import { elementOfNodeType } from '../node-element.ts'
import { nodeAttrs } from '../../adf/document.ts'
import { shownText } from '../../adf/shown-text.ts'
import { writableValue } from '../escaping.ts'
// `undefined` where the node is no emoji, status, date or URL card, or holds what its element cannot write: it rides the carry.
export function nodeElement(node: AdfNode): string | undefined {
const model = elementOfNodeType(node.type)
if (model === undefined || node.content !== undefined) return undefined
const data = dataAttributes(node, model.vocabulary, model.content === undefined ? [] : [model.content])
const held = model.content === undefined ? shownText(node) : nodeAttrs(node)[model.content]
const shown = typeof held === 'string' && held !== '' ? writableValue(held) : undefined
if (data === undefined || shown === undefined) return undefined
const leading = model.leading === undefined ? '' : ` ${model.leading}="${shown}"`
return `<${model.element} class="${model.class}"${leading}${data}>${shown}</${model.element}>`
}
+31
View File
@@ -0,0 +1,31 @@
import type { AttributeVocabulary } from '../adf/attribute-vocabulary.ts'
import { inlineNodeModel } from '../adf/inline-nodes.ts'
// An inline node HTML writes as its own element instead of the carry (docs/decisions.md §The HTML dialect). `content` is the attribute its text is, none for a date, whose text is the day its `timestamp` falls on; `leading` is the attribute standing first after the class, holding that same text.
export type NodeElement = {
class: string
content: string | undefined
element: 'a' | 'span' | 'time'
leading: 'datetime' | 'href' | undefined
vocabulary: AttributeVocabulary
}
const nodeElements: Readonly<Record<string, NodeElement>> = {
date: { class: 'adf-date', content: undefined, element: 'time', leading: 'datetime', vocabulary: attributesOf('date') },
emoji: { class: 'adf-emoji', content: 'text', element: 'span', leading: undefined, vocabulary: attributesOf('emoji') },
// A card's `data` is not written yet, so a card holding it rides the carry.
inlineCard: { class: 'adf-inline-card', content: 'url', element: 'a', leading: 'href', vocabulary: { localId: 'string', url: 'string' } },
status: { class: 'adf-status', content: 'text', element: 'span', leading: undefined, vocabulary: attributesOf('status') },
}
function attributesOf(type: string): AttributeVocabulary {
return inlineNodeModel(type)?.attributes ?? {}
}
export function elementOfNodeType(type: string): NodeElement | undefined {
return Object.hasOwn(nodeElements, type) ? nodeElements[type] : undefined
}
export function nodeTypeOfElement(element: string, className: string): [string, NodeElement] | undefined {
return Object.entries(nodeElements).find(([, candidate]) => candidate.element === element && candidate.class === className)
}
+45
View File
@@ -191,6 +191,29 @@ test('reads a carry element holding a node HTML writes as its own element as tha
assert.deepEqual(read(htmlToAdf(`<ul>\n<li>\n${carry('div', paragraph(text('x')), '<p>x</p>')}\n</li>\n</ul>\n`)), document({ content: [item(paragraph(text('x')))], type: 'bulletList' }))
})
test('reads an emoji, status, date and URL card from their elements', () => {
const inline = (node: AdfNode): AdfDocument | string => read(htmlToAdf(adfToHtmlText(document(paragraph(text('See '), node)))))
const nodes: AdfNode[] = [
{ attrs: { id: '1f389', localId: 'e1', shortName: ':tada:', text: '🎉' }, type: 'emoji' },
{ attrs: { text: '<3 &' }, type: 'emoji' },
{ attrs: { color: 'yellow', localId: 's1', style: 'bold', text: 'In "review"' }, type: 'status' },
{ attrs: { localId: 'd1', timestamp: '1756080000000' }, type: 'date' },
{ attrs: { localId: 'c1', url: 'https://example.com/spec?a=1&b=2' }, type: 'inlineCard' },
]
for (const node of nodes) assert.deepEqual(inline(node), document(paragraph(text('See '), node)))
assert.deepEqual(read(htmlToAdf('<p><span class="adf-emoji">a&nbsp;&quot;b</span></p>\n')), document(paragraph({ attrs: { text: 'a\u00a0"b' }, type: 'emoji' })))
})
test('reads a carry element holding an emoji, status, date or URL card as that node', () => {
const emoji: AdfNode = { attrs: { text: '🎉' }, type: 'emoji' }
assert.deepEqual(read(htmlToAdf(`<p>${carry('span', emoji, '🎉')}</p>\n`)), document(paragraph(emoji)))
})
function adfToHtmlText(doc: AdfDocument): string {
const written = adfToHtml(doc)
return written.ok ? written.value : written.error.message
}
// Each group's cases, the HTML and its refusal.
const refusals: Readonly<Record<string, readonly (readonly [string, string])[]>> = {
'refuses block shapes adfToHtml would not write': [
@@ -240,6 +263,28 @@ const refusals: Readonly<Record<string, readonly (readonly [string, string])[]>>
[`<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>Ask ${carry('span', mention, '')}</p>\n`, 'unmappable-html at /content/0/content/1 line 1 offset 0'],
],
'refuses an emoji, status, date or URL card element that is not as adfToHtml writes it': [
['<p><span class="adf-emoji"></span></p>\n', 'unmappable-html at /content/0/content/0 line 1 offset 0'],
['<p><span class="adf-emoji">a<b>b</b></span></p>\n', 'unmappable-html at /content/0/content/0 line 1 offset 0'],
['<p><span class="adf-emoji">a</p>\n', 'unmappable-html at /content/0/content/0 line 1 offset 0'],
['<p><span class="adf-emoji">a&b</span></p>\n', 'unmappable-html at /content/0/content/0 line 1 offset 0'],
['<p><span class="adf-emoji" data-short-name=":a:" data-id="1">a</span></p>\n', 'unmappable-html at /content/0/content/0 line 1 offset 0'],
['<p><span class="adf-emoji" data-size="big">a</span></p>\n', 'unsupported-node-shape at /content/0/content/0 line 1 offset 0'],
['<p><span class="adf-emoji" data-text="a">a</span></p>\n', 'unsupported-node-shape at /content/0/content/0 line 1 offset 0'],
['<p><span class="adf-emoji" id="x">a</span></p>\n', 'unmappable-html at /content/0/content/0 line 1 offset 0'],
['<p><span class="adf-status" class="adf-status">a</span></p>\n', 'unmappable-html at /content/0/content/0 line 1 offset 0'],
['<p><time class="adf-date" data-timestamp="1756080000000">2025-08-25</time></p>\n', 'unmappable-html at /content/0/content/0 line 1 offset 0'],
['<p><time class="adf-date" datetime="2025-08-26" data-timestamp="1756080000000">2025-08-26</time></p>\n', 'unmappable-html at /content/0/content/0 line 1 offset 0'],
['<p><time class="adf-date" datetime="2025-08-25" data-timestamp="1756080000000">Today</time></p>\n', 'unmappable-html at /content/0/content/0 line 1 offset 0'],
['<p><time class="adf-date" datetime="2025-08-25">2025-08-25</time></p>\n', 'unmappable-html at /content/0/content/0 line 1 offset 0'],
['<p><time class="adf-date" datetime="x" data-timestamp="x">x</time></p>\n', 'unmappable-html at /content/0/content/0 line 1 offset 0'],
['<p><time datetime="2025-08-25">2025-08-25</time></p>\n', 'unmappable-html at /content/0 line 1 offset 0'],
['<p><a class="adf-inline-card" href="https://example.com/">Spec</a></p>\n', 'unmappable-html at /content/0/content/0 line 1 offset 0'],
['<p><a class="adf-inline-card">https://example.com/</a></p>\n', 'unmappable-html at /content/0/content/0 line 1 offset 0'],
['<p><a class="adf-inline-card" href="">a</a></p>\n', 'unmappable-html at /content/0/content/0 line 1 offset 0'],
['<p><a class="adf-inline-card" href="https://example.com/" title="t">https://example.com/</a></p>\n', 'unmappable-html at /content/0/content/0 line 1 offset 0'],
['<p><a class="adf-inline-card" href="https://example.com/" data-data="{}">https://example.com/</a></p>\n', 'unsupported-node-shape at /content/0/content/0 line 1 offset 0'],
],
'refuses the document\'s carry anywhere but as the whole document, a line feed ending it': [
[documentCarry, 'unmappable-html at / line 1 offset 0'],
[`${documentCarry}\n\n`, `unmappable-html at / line 2 offset ${documentCarry.length + 1}`],
+2 -2
View File
@@ -7,10 +7,10 @@ import { carryContent } from '../carry-content.ts'
import { centeredImage, externalMedia } from '../../adf/plain-image.ts'
import { containerElements, headingElements, headingLevel, readListStart, type ContainerType } from '../block-elements.ts'
import { firstParagraphForm } from '../first-paragraph.ts'
import { foundAt, misread, positionIn, readStartTag, refused, startTagName, type Place, type ReadNode, type StartTag } from './source.ts'
import { foundAt, misread, misspelledText, positionIn, readStartTag, refused, startTagName, type Place, type ReadNode, type StartTag } from './source.ts'
import { largestNesting } from '../../nesting.ts'
import { misspelledAt, unescapedValue } from '../escaping.ts'
import { misspelledText, readInline } from './inline.ts'
import { readInline } from './inline.ts'
import { nodeAttrs } from '../../adf/document.ts'
import { notAString } from '../../not-a-string.ts'
import { positioned, success } from '../../result.ts'
+4 -5
View File
@@ -1,12 +1,13 @@
import type { AdfMark, AdfNode } from '../../adf/document.ts'
import type { ParseError, Result } from '../../result.ts'
import { foundAt, misread, readStartTag, refused, type Place, type ReadNode, type StartTag } from './source.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 { misspelledAt, unescapedValue } from '../escaping.ts'
import { readAnchorAttributes } from '../anchor-element.ts'
import { readCarry } from './carry-element.ts'
import { readNodeElement } from './node-element.ts'
import { success } from '../../result.ts'
// The inline nodes from `index` up to the first tag opening none, which the caller reads.
@@ -28,6 +29,8 @@ export function readInline(html: string, index: number, place: Place): Result<{
function readTagged(html: string, index: number, place: Place): ReadNode | undefined {
const tag = readStartTag(html, index)
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
}
@@ -69,10 +72,6 @@ function readText(html: string, index: number, marks: AdfMark[], place: Place):
return success({ end, node: marks.length === 0 ? { text, type: 'text' } : { marks, text, type: 'text' } })
}
export function misspelledText<T>(html: string, index: number, place: Place): Result<T, ParseError> {
return refused('unmappable-html', `text escapes & as &amp;, < as &lt; and > as &gt;, and holds no character HTML cannot hold: ${foundAt(html, index)}`, html, index, place)
}
function markOf(tag: StartTag): AdfMark | undefined {
if (tag.name === 'a') {
const link = readAnchorAttributes(tag.attributes)
+34
View File
@@ -0,0 +1,34 @@
import type { AdfAttributes, AdfNode } from '../../adf/document.ts'
import { foundAt, misspelledText, refused, type Place, type ReadNode, type StartTag } from './source.ts'
import { nodeTypeOfElement, type NodeElement } from '../node-element.ts'
import { readDataAttributes } from '../data-attributes.ts'
import { shownText } from '../../adf/shown-text.ts'
import { success } from '../../result.ts'
import { unescapedValue } from '../escaping.ts'
// `undefined` where the tag opens no emoji, status, date or URL card element; one that does reads as the node `nodeElement` wrote it from, or is refused.
export function readNodeElement(html: string, tag: StartTag, place: Place): ReadNode | undefined {
const [kind, ...rest] = tag.attributes
const found = kind?.[0] === 'class' ? nodeTypeOfElement(tag.name, kind[1]) : undefined
if (found === undefined) return undefined
const [type, model] = found
if (model.leading !== undefined && rest[0]?.[0] !== model.leading) return refused('unmappable-html', `<${tag.name} class="${model.class}"> holds ${model.leading} first, before its data-* attributes: ${foundAt(html, tag.start)}`, html, tag.start, place)
const data = readDataAttributes(rest, tag.name, model.vocabulary, model.content === undefined ? [] : [model.content], model.leading)
if (data.fault !== undefined) return refused(data.fault.code, data.fault.message, html, tag.start, place)
const closer = `</${tag.name}>`
const stop = html.indexOf('<', tag.end)
const end = stop < 0 ? html.length : stop
const shown = unescapedValue(html.slice(tag.end, end), 'text')
if (shown === undefined) return misspelledText(html, tag.end, place)
if (!html.startsWith(closer, end)) return refused('unmappable-html', `<${tag.name} class="${model.class}"> holds its text, then ${closer}: ${foundAt(html, end)}`, html, end, place)
const node = nodeOf(type, model, data.value, shown)
const expected = model.content === undefined ? shownText(node) : shown
if (expected === undefined || expected === '' || shown !== expected || (model.leading !== undefined && rest[0]?.[1] !== expected)) {
return refused('unmappable-html', `<${tag.name} class="${model.class}"> shows what adfToHtml writes for its node, ${model.leading === undefined ? '' : `${model.leading} the same, `}then ${closer}; to change the node, edit its data-* attributes: ${foundAt(html, tag.end)}`, html, tag.end, place)
}
return success({ end: end + closer.length, node })
}
function nodeOf(type: string, model: NodeElement, data: AdfAttributes, shown: string): AdfNode {
return { attrs: model.content === undefined ? data : { ...data, [model.content]: shown }, type }
}
+4
View File
@@ -45,6 +45,10 @@ export function foundAt(html: string, index: number): string {
return `found ${spelled}${index + found.length < html.length ? '…' : ''}`
}
export function misspelledText<T>(html: string, index: number, place: Place): Result<T, ParseError> {
return refused('unmappable-html', `text escapes & as &amp;, < as &lt; and > as &gt;, and holds no character HTML cannot hold: ${foundAt(html, index)}`, html, index, place)
}
// The position of the start of `line` in `html` as handed in, for a line counted after each `\r\n` became a line feed.
export function positionIn(html: string, { line }: SourcePosition): SourcePosition {
let offset = 0