mirror of
https://github.com/larvit/adf-codec.git
synced 2026-11-17 21:55:44 +01:00
Answer architecture round 1: 2 🔴, 6 🟡 (0 misread); one escaping path refusing null characters, block writers returning their pieces, the HTML writer split, shared entry checks, lint between formats
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import type { AdfDocument, AdfMark, AdfNode } from '../../adf/document.ts'
|
||||
import type { AdfAttributes, AdfDocument, AdfMark, AdfNode } from '../../adf/document.ts'
|
||||
import type { Result } from '../../result.ts'
|
||||
import { adfToHtml } from '../../index.ts'
|
||||
import { largestNesting } from '../../nesting.ts'
|
||||
@@ -97,10 +97,12 @@ test('carries a node holding what its element cannot', () => {
|
||||
assert.equal(carried({ content: [], type: 'paragraph' }), true)
|
||||
assert.equal(carried({ attrs: {}, type: 'rule' }), true)
|
||||
assert.equal(carried({ attrs: { level: 7 }, content: [text('x')], type: 'heading' }), true)
|
||||
assert.equal(carried({ attrs: { localId: 'q1' }, content: [paragraph(text('x'))], type: 'blockquote' }), true)
|
||||
assert.equal(carried({ attrs: { order: 1.5 }, content: [item(paragraph(text('x')))], type: 'orderedList' }), true)
|
||||
assert.equal(carried({ content: [item(paragraph(text('x'))), paragraph(text('y'))], type: 'bulletList' }), true)
|
||||
assert.equal(carried({ content: [], type: 'bulletList' }), true)
|
||||
assert.equal(carried({ attrs: { language: 'c sharp' }, content: [text('x')], type: 'codeBlock' }), true)
|
||||
assert.equal(carried({ attrs: { language: 'a\0b' }, content: [text('x')], type: 'codeBlock' }), true)
|
||||
assert.equal(carried({ content: [text('a'), text('b')], type: 'codeBlock' }), true)
|
||||
assert.equal(carried({ content: [text('x\0')], type: 'codeBlock' }), true)
|
||||
assert.equal(carried(item(paragraph(text('x')))), true)
|
||||
@@ -135,16 +137,20 @@ test('writes a container holding no content key as its element holding nothing',
|
||||
assert.equal(html(adfToHtml(document({ type: 'blockquote' }, { type: 'bulletList' }, { type: 'orderedList' }))), '<blockquote></blockquote>\n<ul></ul>\n<ol></ol>\n')
|
||||
})
|
||||
|
||||
test('carries a link or image whose target the anchor cannot hold', () => {
|
||||
test('carries a link or image holding a value its element cannot', () => {
|
||||
const carried = (mark: AdfMark): boolean => html(adfToHtml(document(paragraph(text('x', mark))))).startsWith('<p><span class="adf-carry"')
|
||||
assert.equal(carried({ attrs: { title: 'No target' }, type: 'link' }), true)
|
||||
assert.equal(carried({ attrs: { href: 'https://example.com/\0' }, type: 'link' }), true)
|
||||
assert.equal(carried({ attrs: { href: 'https://example.com/', title: 'x\0' }, type: 'link' }), true)
|
||||
const image: AdfNode = { attrs: { layout: 'center' }, content: [{ attrs: { type: 'external', url: 'https://example.com/a.png' }, marks: [{ attrs: { href: 'https://example.com/\0' }, type: 'link' }], type: 'media' }], type: 'mediaSingle' }
|
||||
assert.equal(html(adfToHtml(document(image))).startsWith('<div class="adf-carry"'), true)
|
||||
const imageCarried = (media: AdfNode): boolean => html(adfToHtml(document({ attrs: { layout: 'center' }, content: [media], type: 'mediaSingle' }))).startsWith('<div class="adf-carry"')
|
||||
const linked = (attrs: AdfAttributes): AdfNode => ({ attrs: { type: 'external', url: 'https://example.com/a.png' }, marks: [{ attrs, type: 'link' }], type: 'media' })
|
||||
assert.equal(imageCarried(linked({ href: 'https://example.com/\0' })), true)
|
||||
assert.equal(imageCarried(linked({ href: 'https://example.com/', title: 'x\0' })), true)
|
||||
assert.equal(imageCarried({ attrs: { type: 'external', url: 'https://example.com/\0.png' }, type: 'media' }), true)
|
||||
assert.equal(imageCarried({ attrs: { alt: 'The\0moon', type: 'external', url: 'https://example.com/a.png' }, type: 'media' }), true)
|
||||
})
|
||||
|
||||
test('refuses an inline carry nesting past 500 levels, in a paragraph, a heading and a list item', () => {
|
||||
test('refuses an inline carry nesting past 500 levels, in a paragraph, a heading and a list item, the first in document order', () => {
|
||||
let deep: AdfNode = text('x')
|
||||
for (let level = 0; level < largestNesting; level += 1) deep = { content: [deep], type: 'unknownInline' }
|
||||
const refused = (block: AdfNode): string => {
|
||||
@@ -154,11 +160,22 @@ test('refuses an inline carry nesting past 500 levels, in a paragraph, a heading
|
||||
assert.equal(refused(paragraph(deep)), 'unsupported-nesting-depth at content/0/content/0')
|
||||
assert.equal(refused({ attrs: { level: 1 }, content: [deep], type: 'heading' }), 'unsupported-nesting-depth at content/0/content/0')
|
||||
assert.equal(refused({ content: [item(paragraph(deep))], type: 'bulletList' }), 'unsupported-nesting-depth at content/0/content/0/content/0/content/0')
|
||||
assert.equal(refused({ content: [item(paragraph(text('a')), paragraph(deep)), item(paragraph(deep))], type: 'bulletList' }), 'unsupported-nesting-depth at content/0/content/0/content/1/content/0')
|
||||
})
|
||||
|
||||
const tooLong = 'unsupported-node-shape: the markdown or HTML for this document, or a directive\'s plain CommonMark, would be longer than 536870888 characters, the longest this library writes'
|
||||
|
||||
test('refuses text past V8\'s longest string', () => {
|
||||
const long = 'a'.repeat(2 ** 28)
|
||||
assert.equal(html(adfToHtml(document(paragraph(text(long), text(long, { type: 'em' }), text(long))))), 'unsupported-node-shape: the markdown or HTML for this document, or a directive\'s plain CommonMark, would be longer than 536870888 characters, the longest this library writes')
|
||||
assert.equal(html(adfToHtml(document(paragraph(text(long), text(long, { type: 'em' }), text(long))))), tooLong)
|
||||
})
|
||||
|
||||
test('refuses at the block whose HTML passes V8\'s longest string, before a later block refuses', () => {
|
||||
// The two code blocks' text is the bound exactly, so only what their elements add passes it.
|
||||
const code: AdfNode = { content: [text('a'.repeat(536870888 / 2))], type: 'codeBlock' }
|
||||
let deep: AdfNode = { type: 'rule' }
|
||||
for (let level = 0; level <= largestNesting; level += 1) deep = { content: [deep], type: 'blockquote' }
|
||||
assert.equal(html(adfToHtml(document(code, code, deep))), tooLong)
|
||||
})
|
||||
|
||||
test('writes an empty document as nothing, and one holding no content key as its carry', () => {
|
||||
@@ -168,7 +185,7 @@ test('writes an empty document as nothing, and one holding no content key as its
|
||||
|
||||
test('refuses what is no document, a version HTML cannot carry, and nesting past the levels a reader reads', () => {
|
||||
assert.equal(html(adfToHtml({ type: 'doc', version: Number.NaN })), 'not-an-adf-document: an ADF document holds a version number: found NaN')
|
||||
assert.equal(html(adfToHtml({ type: 'doc', version: 2 })), 'unsupported-document-version: no HTML spelling carries ADF version 2')
|
||||
assert.equal(html(adfToHtml({ type: 'doc', version: 2 })), 'unsupported-document-version: no format this library writes carries ADF version 2')
|
||||
let deep: AdfNode = paragraph(text('x'))
|
||||
for (let level = 0; level <= largestNesting; level += 1) deep = { content: [deep], type: 'blockquote' }
|
||||
const refused = adfToHtml(document(deep))
|
||||
|
||||
+82
-198
@@ -1,88 +1,107 @@
|
||||
import type { AdfDocument, AdfMark, AdfNode } from '../../adf/document.ts'
|
||||
import { adfDocumentFault, heldTextLength, holdsOnlyAttributes, isSpellableText, isUnmarkedSpellableText, nodeAttrs, nodeContent, nodeMarks } from '../../adf/document.ts'
|
||||
import { blockNodeModel } from '../../adf/block-nodes.ts'
|
||||
import { carriedJson } from '../../adf/carried-json.ts'
|
||||
import { failure, faulted, success, type ConvertErrorPath, type Result } from '../../result.ts'
|
||||
import { joinedWithin, longestOutput, tooLong, withinEngineLimits } from '../../length-bound.ts'
|
||||
import type { AdfDocument, AdfNode } from '../../adf/document.ts'
|
||||
import { anchorOpener, inlineHtml, writableText } from './inline.ts'
|
||||
import { carriedBlock, carryElement } from './carry-element.ts'
|
||||
import { failure, success, type ConvertErrorPath, type Result } from '../../result.ts'
|
||||
import { holdsOnlyAttributes, isUnmarkedSpellableText, nodeAttrs, nodeContent, writableContent } from '../../adf/document.ts'
|
||||
import { largestNesting } from '../../nesting.ts'
|
||||
import { linkTarget, type LinkTarget } from '../../adf/mark-attributes.ts'
|
||||
import { plainImage } from '../../adf/external-image.ts'
|
||||
import { longestOutput, tooLong, withinEngineLimits } from '../../length-bound.ts'
|
||||
import { htmlValue, optionalAttribute } from './escaping.ts'
|
||||
import { plainImage } from '../../adf/plain-image.ts'
|
||||
import { serializeCanonicalJson } from '../../canonical-json.ts'
|
||||
import { shownText } from '../../adf/shown-text.ts'
|
||||
|
||||
// depth: the nesting level of the block list holding the node, as `largestNesting` counts it.
|
||||
type Block = { depth: number; node: AdfNode; path: ConvertErrorPath }
|
||||
// depth: the nesting level of the block list holding the node, as `largestNesting` counts it; inList: the node is a list's item.
|
||||
type Block = { depth: number; inList: boolean; node: AdfNode; path: ConvertErrorPath }
|
||||
type Container = { attributes: string; isList: boolean; tag: string }
|
||||
type Pending = Block | string
|
||||
|
||||
// Each names its element.
|
||||
const elementMarks: readonly string[] = ['code', 'em', 'strong']
|
||||
|
||||
export function adfToHtml(document: AdfDocument): Result<string> {
|
||||
return withinEngineLimits(() => writeHtml(document))
|
||||
}
|
||||
|
||||
// A stack rather than recursion, since each level would cost several frames: a block returns its pieces in document order, and only this loop pushes them.
|
||||
function writeHtml(document: AdfDocument): Result<string> {
|
||||
const fault = adfDocumentFault(document)
|
||||
if (fault !== undefined) return faulted(fault, [])
|
||||
if (document.version !== 1) return failure('unsupported-document-version', `no HTML spelling carries ADF version ${document.version}`, [])
|
||||
if (document.content === undefined) return success(`${carryElement('div', serializeCanonicalJson(document, 'compact'), '')}\n`)
|
||||
// Every character of text is written at least once, so this much text cannot fit, and none of it is written.
|
||||
if (heldTextLength(document.content) > longestOutput) return tooLong()
|
||||
const pending: Pending[] = []
|
||||
scheduleBlocks(pending, document.content, [], 0, '', document.content.length === 0 ? '' : '\n')
|
||||
const pieces: string[] = []
|
||||
const content = writableContent(document)
|
||||
if (!content.ok) return content
|
||||
if (content.value === undefined) return success(`${carryElement('div', serializeCanonicalJson(document, 'compact'), '')}\n`)
|
||||
const pending: Pending[] = content.value.length === 0 ? [] : [...blockPieces(content.value, [], 0, false), '\n'].reverse()
|
||||
let html = ''
|
||||
for (let next = pending.pop(); next !== undefined; next = pending.pop()) {
|
||||
if (typeof next === 'string') {
|
||||
pieces.push(next)
|
||||
// Held to the bound as it grows, so every engine stops at the block passing it.
|
||||
if (html.length + next.length > longestOutput) return tooLong()
|
||||
html += next
|
||||
continue
|
||||
}
|
||||
const written = writeBlock(next, pending)
|
||||
if (!written.ok) return written
|
||||
if (written.value !== undefined) pieces.push(written.value)
|
||||
const pieces = writeBlock(next)
|
||||
if (!pieces.ok) return pieces
|
||||
for (const piece of pieces.value.reverse()) pending.push(piece)
|
||||
}
|
||||
return joinedWithin(pieces)
|
||||
return success(html)
|
||||
}
|
||||
|
||||
// Pushed in reverse, so the walk pops them in document order: a stack rather than recursion, since each level would cost several frames.
|
||||
function scheduleBlocks(pending: Pending[], nodes: readonly AdfNode[], path: ConvertErrorPath, depth: number, opener: string, closer: string): void {
|
||||
const scheduled: Pending[] = [opener]
|
||||
function blockPieces(nodes: readonly AdfNode[], path: ConvertErrorPath, depth: number, inList: boolean): Pending[] {
|
||||
const pieces: Pending[] = []
|
||||
for (const [index, node] of nodes.entries()) {
|
||||
if (index > 0) scheduled.push('\n')
|
||||
scheduled.push({ depth, node, path: [...path, 'content', index] })
|
||||
if (index > 0) pieces.push('\n')
|
||||
pieces.push({ depth, inList, node, path: [...path, 'content', index] })
|
||||
}
|
||||
scheduled.push(closer)
|
||||
for (const item of scheduled.reverse()) pending.push(item)
|
||||
return pieces
|
||||
}
|
||||
|
||||
function tooDeep(path: ConvertErrorPath): Result<never> {
|
||||
return failure('unsupported-nesting-depth', `the document nests deeper than the ${largestNesting} levels the writer carries`, path)
|
||||
}
|
||||
|
||||
// `undefined` where the block scheduled its children rather than writing itself whole.
|
||||
function writeBlock(block: Block, pending: Pending[]): Result<string | undefined> {
|
||||
function writeBlock(block: Block): Result<Pending[]> {
|
||||
const { depth, node, path } = block
|
||||
if (depth > largestNesting) return tooDeep(path)
|
||||
const leaf = tryLeafBlock(node, path)
|
||||
if (leaf !== undefined) return leaf
|
||||
if (node.type === 'blockquote' && holdsOnlyAttributes(node, [])) return containerBlock(pending, block, 'blockquote', '')
|
||||
const list = listElement(node)
|
||||
if (list !== undefined) return scheduleList(pending, block, list)
|
||||
return carriedBlock(node, path, depth)
|
||||
if (depth > largestNesting) return failure('unsupported-nesting-depth', `the document nests deeper than the ${largestNesting} levels the writer carries`, path)
|
||||
if (block.inList) return writeItem(block)
|
||||
const container = containerElement(node)
|
||||
if (container !== undefined) return success(containerPieces(block, container))
|
||||
const html = tryLeafBlock(node, path) ?? carriedBlock(node, path, depth)
|
||||
return html.ok ? success([html.value]) : html
|
||||
}
|
||||
|
||||
// `undefined` where the node is no container, or it or a list's item holds what the elements cannot, so the whole node rides the carry.
|
||||
function containerElement(node: AdfNode): Container | undefined {
|
||||
if (node.type === 'blockquote') return holdsOnlyAttributes(node, []) ? { attributes: '', isList: false, tag: 'blockquote' } : undefined
|
||||
if (node.type === 'bulletList') return holdsOnlyAttributes(node, []) && listItemsWritable(node) ? { attributes: '', isList: true, tag: 'ul' } : undefined
|
||||
if (node.type !== 'orderedList' || !holdsOnlyAttributes(node, ['order']) || !listItemsWritable(node)) return undefined
|
||||
const order = nodeAttrs(node)['order']
|
||||
if (order === undefined) return { attributes: '', isList: true, tag: 'ol' }
|
||||
return typeof order === 'number' && Number.isSafeInteger(order) && !Object.is(order, -0) ? { attributes: ` start="${order}"`, isList: true, tag: 'ol' } : undefined
|
||||
}
|
||||
|
||||
function listItemsWritable(list: AdfNode): boolean {
|
||||
return nodeContent(list).every((item) => item.type === 'listItem' && holdsOnlyAttributes(item, []))
|
||||
}
|
||||
|
||||
function containerPieces({ depth, node, path }: Block, { attributes, isList, tag }: Container): Pending[] {
|
||||
if (node.content === undefined) return [`<${tag}${attributes}></${tag}>`]
|
||||
return [`<${tag}${attributes}>\n`, ...blockPieces(node.content, path, depth + 1, isList), `\n</${tag}>`]
|
||||
}
|
||||
|
||||
// An item's blocks sit at its own level, one below its list, as a markdown list's do; its first paragraph stands bare where it holds content, panel pick, docs/decisions.md §The HTML dialect.
|
||||
function writeItem({ depth, node, path }: Block): Result<Pending[]> {
|
||||
if (node.content === undefined) return success(['<li></li>'])
|
||||
const blocks = blockPieces(node.content, path, depth, false)
|
||||
const [first] = node.content
|
||||
if (first === undefined || first.type !== 'paragraph' || !holdsOnlyAttributes(first, []) || nodeContent(first).length === 0) return success(['<li>\n', ...blocks, '\n</li>'])
|
||||
const bare = inlineHtml(nodeContent(first), [...path, 'content', 0])
|
||||
if (!bare.ok) return bare
|
||||
// The bare paragraph's inline content stands in for its block.
|
||||
return success(blocks.length === 1 ? [`<li>${bare.value}</li>`] : [`<li>${bare.value}`, ...blocks.slice(1), '\n</li>'])
|
||||
}
|
||||
|
||||
function tryLeafBlock(node: AdfNode, path: ConvertErrorPath): Result<string> | undefined {
|
||||
if (node.type === 'paragraph' && holdsOnlyAttributes(node, [])) return inlineElement('p', '', nodeContent(node), path)
|
||||
if (node.type === 'paragraph' && holdsOnlyAttributes(node, [])) return inlineElement('p', nodeContent(node), path)
|
||||
if (node.type === 'heading' && holdsOnlyAttributes(node, ['level'])) {
|
||||
const level = nodeAttrs(node)['level']
|
||||
if (typeof level === 'number' && Number.isInteger(level) && level >= 1 && level <= 6) return inlineElement(`h${level}`, '', nodeContent(node), path)
|
||||
if (typeof level === 'number' && Number.isInteger(level) && level >= 1 && level <= 6) return inlineElement(`h${level}`, nodeContent(node), path)
|
||||
}
|
||||
const text = tryCodeBlock(node) ?? tryImage(node) ?? (node.type === 'rule' && holdsOnlyAttributes(node, []) && nodeContent(node).length === 0 ? '<hr>' : undefined)
|
||||
return text === undefined ? undefined : success(text)
|
||||
const html = tryCodeBlock(node) ?? tryImage(node) ?? (node.type === 'rule' && holdsOnlyAttributes(node, []) && nodeContent(node).length === 0 ? '<hr>' : undefined)
|
||||
return html === undefined ? undefined : success(html)
|
||||
}
|
||||
|
||||
function inlineElement(tag: string, attributes: string, nodes: readonly AdfNode[], path: ConvertErrorPath): Result<string> {
|
||||
function inlineElement(tag: string, nodes: readonly AdfNode[], path: ConvertErrorPath): Result<string> {
|
||||
const inline = inlineHtml(nodes, path)
|
||||
return inline.ok ? success(`<${tag}${attributes}>${inline.value}</${tag}>`) : inline
|
||||
return inline.ok ? success(`<${tag}>${inline.value}</${tag}>`) : inline
|
||||
}
|
||||
|
||||
// A class holds the language as one token, so a language holding whitespace rides the carry.
|
||||
@@ -90,157 +109,22 @@ function tryCodeBlock(node: AdfNode): string | undefined {
|
||||
if (node.type !== 'codeBlock' || !holdsOnlyAttributes(node, ['language'])) return undefined
|
||||
const language = nodeAttrs(node)['language']
|
||||
if (language !== undefined && (typeof language !== 'string' || !/^[^\t\n\f\r ]+$/.test(language))) return undefined
|
||||
const className = language === undefined ? '' : ` class="${escapeHtml(`language-${language}`)}"`
|
||||
const className = optionalAttribute('class', language === undefined ? undefined : `language-${language}`)
|
||||
if (className === undefined) return undefined
|
||||
if (node.content === undefined) return `<pre><code${className}></code></pre>`
|
||||
const [only, ...others] = node.content
|
||||
if (only === undefined || others.length > 0 || !writableText(only) || !isUnmarkedSpellableText(only)) return undefined
|
||||
return `<pre><code${className}>${escapeHtml(only.text)}</code></pre>`
|
||||
const code = only === undefined || others.length > 0 || !isUnmarkedSpellableText(only) ? undefined : writableText(only.text)
|
||||
return code === undefined ? undefined : `<pre><code${className}>${code}</code></pre>`
|
||||
}
|
||||
|
||||
function tryImage(node: AdfNode): string | undefined {
|
||||
const image = node.type === 'mediaSingle' ? plainImage(node) : undefined
|
||||
if (image === undefined || !writableUrl(image.url) || (image.alt !== undefined && image.alt.includes('\0'))) return undefined
|
||||
const element = `<img src="${escapeHtml(image.url)}"${image.alt === undefined ? '' : ` alt="${escapeHtml(image.alt)}"`}>`
|
||||
if (image === undefined) return undefined
|
||||
const src = htmlValue(image.url)
|
||||
const alt = optionalAttribute('alt', image.alt)
|
||||
if (src === undefined || alt === undefined) return undefined
|
||||
const element = `<img src="${src}"${alt}>`
|
||||
if (image.link === undefined) return `<p>${element}</p>`
|
||||
const anchor = anchorOpener(image.link)
|
||||
return anchor === undefined ? undefined : `<p>${anchor}${element}</a></p>`
|
||||
}
|
||||
|
||||
function containerBlock(pending: Pending[], { depth, node, path }: Block, tag: string, attributes: string): Result<string | undefined> {
|
||||
if (node.content === undefined) return success(`<${tag}${attributes}></${tag}>`)
|
||||
scheduleBlocks(pending, node.content, path, depth + 1, `<${tag}${attributes}>\n`, `\n</${tag}>`)
|
||||
return success(undefined)
|
||||
}
|
||||
|
||||
// The list's element, `undefined` where the list or an item holds what the elements cannot, so the whole list rides the carry.
|
||||
function listElement(node: AdfNode): { attributes: string; tag: string } | undefined {
|
||||
if (node.type === 'bulletList' && holdsOnlyAttributes(node, [])) return listItemsWritable(node) ? { attributes: '', tag: 'ul' } : undefined
|
||||
if (node.type !== 'orderedList' || !holdsOnlyAttributes(node, ['order']) || !listItemsWritable(node)) return undefined
|
||||
const order = nodeAttrs(node)['order']
|
||||
if (order === undefined) return { attributes: '', tag: 'ol' }
|
||||
return typeof order === 'number' && Number.isSafeInteger(order) && !Object.is(order, -0) ? { attributes: ` start="${order}"`, tag: 'ol' } : undefined
|
||||
}
|
||||
|
||||
function listItemsWritable(list: AdfNode): boolean {
|
||||
return nodeContent(list).every((item) => item.type === 'listItem' && holdsOnlyAttributes(item, []))
|
||||
}
|
||||
|
||||
function scheduleList(pending: Pending[], block: Block, { attributes, tag }: { attributes: string; tag: string }): Result<string | undefined> {
|
||||
const { depth, node, path } = block
|
||||
if (node.content === undefined) return success(`<${tag}${attributes}></${tag}>`)
|
||||
const items: { opening: string; rest: Pending[] }[] = []
|
||||
// The items' blocks sit one level below the list, as a markdown list's do.
|
||||
for (const [index, item] of node.content.entries()) {
|
||||
const rest: Pending[] = []
|
||||
const opening = writeItem(rest, item, [...path, 'content', index], depth + 1)
|
||||
if (!opening.ok) return opening
|
||||
items.push({ opening: `${index === 0 ? '' : '\n'}${opening.value}`, rest })
|
||||
}
|
||||
pending.push(`\n</${tag}>`)
|
||||
for (const { opening, rest } of items.reverse()) {
|
||||
for (const piece of rest) pending.push(piece)
|
||||
pending.push(opening)
|
||||
}
|
||||
pending.push(`<${tag}${attributes}>\n`)
|
||||
return success(undefined)
|
||||
}
|
||||
|
||||
// Returns the item's opening, its first paragraph written bare where it holds content, and pushes the rest; panel pick, docs/decisions.md §The HTML dialect.
|
||||
function writeItem(pending: Pending[], item: AdfNode, path: ConvertErrorPath, depth: number): Result<string> {
|
||||
if (depth > largestNesting) return tooDeep(path)
|
||||
if (item.content === undefined) return success('<li></li>')
|
||||
const [first] = item.content
|
||||
const bare = first !== undefined && first.type === 'paragraph' && holdsOnlyAttributes(first, []) && nodeContent(first).length > 0
|
||||
const rest = bare ? item.content.slice(1) : item.content
|
||||
scheduleBlocks(pending, rest, path, depth, rest.length === 0 ? '' : '\n', rest.length === 0 ? '</li>' : '\n</li>')
|
||||
if (!bare) return success('<li>')
|
||||
const inline = inlineHtml(nodeContent(first), [...path, 'content', 0])
|
||||
return inline.ok ? success(`<li>${inline.value}`) : inline
|
||||
}
|
||||
|
||||
function inlineHtml(nodes: readonly AdfNode[], path: ConvertErrorPath): Result<string> {
|
||||
let html = ''
|
||||
let afterPlainText = false
|
||||
for (const [index, node] of nodes.entries()) {
|
||||
// Two unmarked text nodes side by side read back as one, so the second rides the carry.
|
||||
const written: string | undefined = afterPlainText && isUnmarkedSpellableText(node) ? undefined : tryInlineNode(node)
|
||||
if (written === undefined) {
|
||||
const carried = carriedInline(node, [...path, 'content', index])
|
||||
if (!carried.ok) return carried
|
||||
html += carried.value
|
||||
} else html += written
|
||||
afterPlainText = written !== undefined && isUnmarkedSpellableText(node)
|
||||
}
|
||||
return success(html)
|
||||
}
|
||||
|
||||
function tryInlineNode(node: AdfNode): string | undefined {
|
||||
if (node.type === 'hardBreak') return holdsOnlyAttributes(node, []) && nodeContent(node).length === 0 ? '<br>' : undefined
|
||||
if (!isSpellableText(node) || !writableText(node)) return undefined
|
||||
const marks = nodeMarks(node)
|
||||
const openers: string[] = []
|
||||
const closers: string[] = []
|
||||
for (const mark of marks) {
|
||||
if (marks.filter(({ type }) => type === mark.type).length > 1) return undefined
|
||||
const element = markElement(mark)
|
||||
if (element === undefined) return undefined
|
||||
openers.push(element.opener)
|
||||
closers.unshift(element.closer)
|
||||
}
|
||||
return `${openers.join('')}${escapeHtml(node.text)}${closers.join('')}`
|
||||
}
|
||||
|
||||
function markElement(mark: AdfMark): { closer: string; opener: string } | undefined {
|
||||
const { type } = mark
|
||||
if (elementMarks.includes(type)) return mark.attrs === undefined ? { closer: `</${type}>`, opener: `<${type}>` } : undefined
|
||||
if (type !== 'link' || Object.keys(nodeAttrs(mark)).some((key) => key !== 'href' && key !== 'title')) return undefined
|
||||
const target = linkTarget(nodeAttrs(mark))
|
||||
const opener = target === undefined ? undefined : anchorOpener(target)
|
||||
return opener === undefined ? undefined : { closer: '</a>', opener }
|
||||
}
|
||||
|
||||
function anchorOpener({ href, title }: LinkTarget): string | undefined {
|
||||
if (!writableUrl(href) || title?.includes('\0') === true) return undefined
|
||||
return `<a href="${escapeHtml(href)}"${title === undefined ? '' : ` title="${escapeHtml(title)}"`}>`
|
||||
}
|
||||
|
||||
// HTML holds no null character, and no element holds empty text apart from no text.
|
||||
function writableText(node: AdfNode): node is AdfNode & { text: string } {
|
||||
return typeof node.text === 'string' && node.text !== '' && !node.text.includes('\0')
|
||||
}
|
||||
|
||||
// Any scheme, `javascript:` included, as the ADF holds it: docs/decisions.md §HTML writes a URL as the ADF holds it, whatever its scheme.
|
||||
function writableUrl(url: string): boolean {
|
||||
return !url.includes('\0')
|
||||
}
|
||||
|
||||
function carriedBlock(node: AdfNode, path: ConvertErrorPath, depth: number): Result<string> {
|
||||
const json = carriedJson(node, node, 'compact', path, largestNesting - depth)
|
||||
return json.ok ? success(carryElement('div', json.value.json, carriedText(node))) : json
|
||||
}
|
||||
|
||||
function carriedInline(node: AdfNode, path: ConvertErrorPath): Result<string> {
|
||||
const json = carriedJson(node, node, 'compact', path, largestNesting)
|
||||
return json.ok ? success(carryElement('span', json.value.json, carriedText(node))) : json
|
||||
}
|
||||
|
||||
function carryElement(tag: string, json: string, text: string): string {
|
||||
return `<${tag} class="adf-carry" data-adf="${escapeHtml(json)}">${escapeHtml(text.replaceAll('\0', ''))}</${tag}>`
|
||||
}
|
||||
|
||||
// The text a carried node shows, a line break between its blocks and for each hard break; a reader of the element reads the JSON alone.
|
||||
function carriedText(node: AdfNode): string {
|
||||
let text = ''
|
||||
const pending: AdfNode[] = [node]
|
||||
for (let next = pending.pop(); next !== undefined; next = pending.pop()) {
|
||||
if (text !== '' && (next.type === 'hardBreak' || blockNodeModel(next.type) !== undefined)) text += '\n'
|
||||
text += next.text ?? shownText(next) ?? ''
|
||||
for (const child of [...nodeContent(next)].reverse()) pending.push(child)
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
// A carriage return is a character reference, since an HTML parser reads a raw one as a line feed.
|
||||
function escapeHtml(text: string): string {
|
||||
return text.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll('\r', ' ')
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { AdfNode } from '../../adf/document.ts'
|
||||
import { blockNodeModel } from '../../adf/block-nodes.ts'
|
||||
import { carriedJson } from '../../adf/carried-json.ts'
|
||||
import { carriedValue } from './escaping.ts'
|
||||
import { largestNesting } from '../../nesting.ts'
|
||||
import { nodeContent } from '../../adf/document.ts'
|
||||
import { shownText } from '../../adf/shown-text.ts'
|
||||
import { success, type ConvertErrorPath, type Result } from '../../result.ts'
|
||||
|
||||
export function carriedBlock(node: AdfNode, path: ConvertErrorPath, depth: number): Result<string> {
|
||||
const json = carriedJson(node, node, 'compact', path, largestNesting - depth)
|
||||
return json.ok ? success(carryElement('div', json.value.json, carriedText(node))) : json
|
||||
}
|
||||
|
||||
export function carriedInline(node: AdfNode, path: ConvertErrorPath): Result<string> {
|
||||
const json = carriedJson(node, node, 'compact', path, largestNesting)
|
||||
return json.ok ? success(carryElement('span', json.value.json, carriedText(node))) : json
|
||||
}
|
||||
|
||||
export function carryElement(tag: string, json: string, text: string): string {
|
||||
return `<${tag} class="adf-carry" data-adf="${carriedValue(json)}">${carriedValue(text)}</${tag}>`
|
||||
}
|
||||
|
||||
// The text a carried node shows, a line break between its blocks and for each hard break; a reader of the element reads the JSON alone.
|
||||
function carriedText(node: AdfNode): string {
|
||||
let text = ''
|
||||
const pending: AdfNode[] = [node]
|
||||
for (let next = pending.pop(); next !== undefined; next = pending.pop()) {
|
||||
if (text !== '' && (next.type === 'hardBreak' || blockNodeModel(next.type) !== undefined)) text += '\n'
|
||||
text += next.text ?? shownText(next) ?? ''
|
||||
for (const child of [...nodeContent(next)].reverse()) pending.push(child)
|
||||
}
|
||||
return text
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// An HTML parser reads a null character as U+FFFD, so each function here refuses or drops one, and the writer escapes through nothing else.
|
||||
|
||||
// `undefined` where the value holds a null character, so its node rides the carry element.
|
||||
export function htmlValue(value: string): string | undefined {
|
||||
return value.includes('\0') ? undefined : escapeHtml(value)
|
||||
}
|
||||
|
||||
// ` name="value"`, `''` where the value is undefined, `undefined` where it holds a null character.
|
||||
export function optionalAttribute(name: string, value: string | undefined): string | undefined {
|
||||
if (value === undefined) return ''
|
||||
const escaped = htmlValue(value)
|
||||
return escaped === undefined ? undefined : ` ${name}="${escaped}"`
|
||||
}
|
||||
|
||||
// What the carry element holds: its JSON spells a null character `\u0000`, and the text it shows drops one.
|
||||
export function carriedValue(value: string): string {
|
||||
return escapeHtml(value.replaceAll('\0', ''))
|
||||
}
|
||||
|
||||
// A carriage return is a character reference, since an HTML parser reads a raw one as a line feed.
|
||||
function escapeHtml(text: string): string {
|
||||
return text.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll('\r', ' ')
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { AdfMark, AdfNode } from '../../adf/document.ts'
|
||||
import { carriedInline } from './carry-element.ts'
|
||||
import { holdsOnlyAttributes, isSpellableText, isUnmarkedSpellableText, nodeAttrs, nodeContent, nodeMarks } from '../../adf/document.ts'
|
||||
import { htmlValue, optionalAttribute } from './escaping.ts'
|
||||
import { linkAttrs, type LinkAttrs } from '../../adf/mark-attributes.ts'
|
||||
import { success, type ConvertErrorPath, type Result } from '../../result.ts'
|
||||
|
||||
// Each names its element.
|
||||
const elementMarks: readonly string[] = ['code', 'em', 'strong']
|
||||
|
||||
export function inlineHtml(nodes: readonly AdfNode[], path: ConvertErrorPath): Result<string> {
|
||||
let html = ''
|
||||
let afterPlainText = false
|
||||
for (const [index, node] of nodes.entries()) {
|
||||
// Two unmarked text nodes side by side read back as one, so the second rides the carry.
|
||||
const written: string | undefined = afterPlainText && isUnmarkedSpellableText(node) ? undefined : tryInlineNode(node)
|
||||
if (written === undefined) {
|
||||
const carried = carriedInline(node, [...path, 'content', index])
|
||||
if (!carried.ok) return carried
|
||||
html += carried.value
|
||||
} else html += written
|
||||
afterPlainText = written !== undefined && isUnmarkedSpellableText(node)
|
||||
}
|
||||
return success(html)
|
||||
}
|
||||
|
||||
function tryInlineNode(node: AdfNode): string | undefined {
|
||||
if (node.type === 'hardBreak') return holdsOnlyAttributes(node, []) && nodeContent(node).length === 0 ? '<br>' : undefined
|
||||
const text = isSpellableText(node) ? writableText(node.text) : undefined
|
||||
if (text === undefined) return undefined
|
||||
const marks = nodeMarks(node)
|
||||
const openers: string[] = []
|
||||
const closers: string[] = []
|
||||
for (const mark of marks) {
|
||||
if (marks.filter(({ type }) => type === mark.type).length > 1) return undefined
|
||||
const element = markElement(mark)
|
||||
if (element === undefined) return undefined
|
||||
openers.push(element.opener)
|
||||
closers.unshift(element.closer)
|
||||
}
|
||||
return `${openers.join('')}${text}${closers.join('')}`
|
||||
}
|
||||
|
||||
// No element holds empty text apart from no text.
|
||||
export function writableText(text: string | undefined): string | undefined {
|
||||
return text === undefined || text === '' ? undefined : htmlValue(text)
|
||||
}
|
||||
|
||||
function markElement(mark: AdfMark): { closer: string; opener: string } | undefined {
|
||||
const { type } = mark
|
||||
if (elementMarks.includes(type)) return mark.attrs === undefined ? { closer: `</${type}>`, opener: `<${type}>` } : undefined
|
||||
if (type !== 'link' || 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 }
|
||||
}
|
||||
|
||||
export function anchorOpener({ href, title }: LinkAttrs): string | undefined {
|
||||
const url = htmlValue(href)
|
||||
const titled = optionalAttribute('title', title)
|
||||
return url === undefined || titled === undefined ? undefined : `<a href="${url}"${titled}>`
|
||||
}
|
||||
Reference in New Issue
Block a user