Carry the fence depth through blockquotes and lists, and split the block spelling from it
This commit is contained in:
+70
-70
@@ -2,21 +2,21 @@ import type { AdfDocument, AdfNode } from './adf-document.ts'
|
||||
import type { BlockDirective } from './block-directives.ts'
|
||||
import type { JsonValue } from './json-value.ts'
|
||||
import { blockDirective, spellDirectiveHeader } from './block-directives.ts'
|
||||
import { emitImageLine, emitInlineLine } from './markdown-inline.ts'
|
||||
import { emitPipeTable } from './markdown-tables.ts'
|
||||
import { emitImage } from './markdown-image.ts'
|
||||
import { emitInlineLine } from './markdown-inline.ts'
|
||||
import { emitPipeTable } from './markdown-pipe-table.ts'
|
||||
import { failure, success, type ConvertErrorPath, type Result } from './result.ts'
|
||||
import { holdsNullCharacter, isThematicBreak } from './commonmark-grammar.ts'
|
||||
import { isAdfDocument } from './adf-document.ts'
|
||||
import { largestNesting } from './nesting.ts'
|
||||
import { longestBacktickRun } from './backtick-runs.ts'
|
||||
import { serializeCanonicalJson } from './canonical-json.ts'
|
||||
|
||||
type BlockContainer = 'directive' | 'document' | 'list-item'
|
||||
type BlockSpelling = 'commonmark' | 'directive'
|
||||
type EmittedBody = { fenceColons: number; text: string }
|
||||
type EmittedBlock = EmittedBody & { node: AdfNode; path: ConvertErrorPath }
|
||||
type EmittedBlock = EmittedBody & { spelling: BlockSpelling }
|
||||
type PlacedBlock = EmittedBlock & { node: AdfNode; path: ConvertErrorPath }
|
||||
|
||||
const centeredMediaSingle = '{"layout":"center"}'
|
||||
const imageAttributes = ['alt', 'type', 'url']
|
||||
const largestListMarker = 999999999
|
||||
const listTypes = ['bulletList', 'orderedList']
|
||||
|
||||
@@ -30,7 +30,7 @@ export function adfToMarkdown(document: AdfDocument): Result<string> {
|
||||
|
||||
function emitBlocks(nodes: readonly AdfNode[], container: BlockContainer, path: ConvertErrorPath, depth: number): Result<EmittedBody> {
|
||||
if (depth > largestNesting) return failure('unsupported-node-shape', `the document nests deeper than the ${largestNesting} levels the emitter carries`, path)
|
||||
const blocks: EmittedBlock[] = []
|
||||
const blocks: PlacedBlock[] = []
|
||||
for (const [index, node] of nodes.entries()) {
|
||||
const nodePath = [...path, 'content', index]
|
||||
const block = emitBlock(node, nodePath, depth)
|
||||
@@ -52,7 +52,7 @@ function emitBlocks(nodes: readonly AdfNode[], container: BlockContainer, path:
|
||||
return success({ fenceColons, text })
|
||||
}
|
||||
|
||||
function separationBetween(previous: EmittedBlock, next: EmittedBlock, container: BlockContainer): Result<string> {
|
||||
function separationBetween(previous: PlacedBlock, next: PlacedBlock, container: BlockContainer): Result<string> {
|
||||
if (listTypes.includes(next.node.type) && previous.node.type === next.node.type) {
|
||||
return failure('unspellable-adjacent-lists', `two adjacent ${next.node.type} nodes read back as one list`, next.path)
|
||||
}
|
||||
@@ -63,8 +63,8 @@ function separationBetween(previous: EmittedBlock, next: EmittedBlock, container
|
||||
return success('\n')
|
||||
}
|
||||
if (container !== 'directive') return success('\n\n')
|
||||
if (previous.fenceColons === 0 && next.fenceColons === 0) return success('\n\n')
|
||||
if (previous.fenceColons > 0 && next.fenceColons > 0) return success('\n')
|
||||
if (previous.spelling === 'commonmark' && next.spelling === 'commonmark') return success('\n\n')
|
||||
if (previous.spelling === 'directive' && next.spelling === 'directive') return success('\n')
|
||||
return failure(
|
||||
'unspelled-block-separation',
|
||||
`the canonical form leaves the separation between a ${previous.node.type} and a ${next.node.type} in a container body unspelled`,
|
||||
@@ -77,13 +77,13 @@ function interruptsParagraph(node: AdfNode): boolean {
|
||||
return ((node.content ?? [])[0]?.content ?? []).length > 0
|
||||
}
|
||||
|
||||
function emitBlock(node: AdfNode, path: ConvertErrorPath, depth: number): Result<EmittedBody> {
|
||||
if (node.type === 'blockquote') return plainBlock(emitBlockquote(node, path, depth))
|
||||
if (node.type === 'bulletList' || node.type === 'orderedList') return plainBlock(emitList(node, path, depth))
|
||||
if (node.type === 'codeBlock') return plainBlock(emitCodeBlock(node, path))
|
||||
if (node.type === 'heading') return plainBlock(emitHeading(node, path))
|
||||
function emitBlock(node: AdfNode, path: ConvertErrorPath, depth: number): Result<EmittedBlock> {
|
||||
if (node.type === 'blockquote') return commonMarkContainer(emitBlockquote(node, path, depth))
|
||||
if (node.type === 'bulletList' || node.type === 'orderedList') return commonMarkContainer(emitList(node, path, depth))
|
||||
if (node.type === 'codeBlock') return commonMarkLine(emitCodeBlock(node, path))
|
||||
if (node.type === 'heading') return commonMarkLine(emitHeading(node, path))
|
||||
if (node.type === 'paragraph') return emitParagraph(node, path)
|
||||
if (node.type === 'rule') return plainBlock(emitRule(node, path))
|
||||
if (node.type === 'rule') return commonMarkLine(emitRule(node, path))
|
||||
const directive = blockDirective(node.type)
|
||||
if (directive !== undefined) {
|
||||
if (node.type === 'mediaSingle') return emitMediaSingle(node, directive, path, depth)
|
||||
@@ -96,71 +96,62 @@ function emitBlock(node: AdfNode, path: ConvertErrorPath, depth: number): Result
|
||||
return failure('unsupported-node-type', `the canonical form spells no block node of type ${node.type}`, path)
|
||||
}
|
||||
|
||||
function plainBlock(text: Result<string>): Result<EmittedBody> {
|
||||
function commonMarkLine(text: Result<string>): Result<EmittedBlock> {
|
||||
if (!text.ok) return text
|
||||
return success({ fenceColons: 0, text: text.value })
|
||||
return success({ fenceColons: 0, spelling: 'commonmark', text: text.value })
|
||||
}
|
||||
|
||||
function emitDirectiveBlock(node: AdfNode, directive: BlockDirective, path: ConvertErrorPath, depth: number): Result<EmittedBody> {
|
||||
function commonMarkContainer(body: Result<EmittedBody>): Result<EmittedBlock> {
|
||||
if (!body.ok) return body
|
||||
return success({ ...body.value, spelling: 'commonmark' })
|
||||
}
|
||||
|
||||
function emitDirectiveBlock(node: AdfNode, directive: BlockDirective, path: ConvertErrorPath, depth: number): Result<EmittedBlock> {
|
||||
if (node.text !== undefined) return failure('unsupported-node-shape', `a ${node.type} carries no text`, path)
|
||||
const header = spellDirectiveHeader(node, directive, path)
|
||||
if (!header.ok) return header
|
||||
const content = node.content ?? []
|
||||
if (directive.body === 'none') {
|
||||
if (content.length > 0) return failure('unsupported-node-shape', `a ${node.type} holds no content`, path)
|
||||
return success({ fenceColons: 2, text: `::${header.value}` })
|
||||
return success({ fenceColons: 2, spelling: 'directive', text: `::${header.value}` })
|
||||
}
|
||||
const body = directive.body === 'inline' ? emitInlineBody(content, path) : emitBlocks(content, 'directive', path, depth + 1)
|
||||
if (!body.ok) return body
|
||||
const fenceColons = Math.max(3, body.value.fenceColons + 1)
|
||||
const fence = ':'.repeat(fenceColons)
|
||||
const lines = body.value.text === '' ? '' : `${body.value.text}\n`
|
||||
return success({ fenceColons, text: `${fence}${header.value}\n${lines}${fence}` })
|
||||
return success({ fenceColons, spelling: 'directive', text: `${fence}${header.value}\n${lines}${fence}` })
|
||||
}
|
||||
|
||||
function emitInlineBody(content: readonly AdfNode[], path: ConvertErrorPath): Result<EmittedBody> {
|
||||
if (content.length === 0) return success({ fenceColons: 0, text: '' })
|
||||
return plainBlock(emitInlineLine(content, 'paragraph', path))
|
||||
const line = emitInlineLine(content, 'paragraph', path)
|
||||
if (!line.ok) return line
|
||||
return success({ fenceColons: 0, text: line.value })
|
||||
}
|
||||
|
||||
function emitMediaSingle(node: AdfNode, directive: BlockDirective, path: ConvertErrorPath, depth: number): Result<EmittedBody> {
|
||||
const image = imageShape(node)
|
||||
function emitMediaSingle(node: AdfNode, directive: BlockDirective, path: ConvertErrorPath, depth: number): Result<EmittedBlock> {
|
||||
const image = emitImage(node, path)
|
||||
if (image === undefined) return emitDirectiveBlock(node, directive, path, depth)
|
||||
const mediaPath = [...path, 'content', 0]
|
||||
if (image.alt === '') return failure('ambiguous-empty-media-alt', 'an empty media alt and an absent one share one image spelling', mediaPath)
|
||||
return plainBlock(emitImageLine(image.alt, image.url, mediaPath))
|
||||
return commonMarkLine(image)
|
||||
}
|
||||
|
||||
function imageShape(node: AdfNode): { alt: string | undefined; url: string } | undefined {
|
||||
const content = node.content ?? []
|
||||
const media = content[0]
|
||||
if (serializeCanonicalJson(node.attrs ?? {}, 'compact') !== centeredMediaSingle || (node.marks ?? []).length > 0) return undefined
|
||||
if (media === undefined || content.length !== 1 || media.type !== 'media' || (media.marks ?? []).length > 0 || (media.content ?? []).length > 0) return undefined
|
||||
const attrs = media.attrs ?? {}
|
||||
const alt = attrs['alt']
|
||||
const url = attrs['url']
|
||||
if (Object.keys(attrs).some((key) => !imageAttributes.includes(key)) || attrs['type'] !== 'external') return undefined
|
||||
if (typeof url !== 'string' || (alt !== undefined && typeof alt !== 'string')) return undefined
|
||||
return { alt, url }
|
||||
}
|
||||
|
||||
function emitTable(node: AdfNode, directive: BlockDirective, path: ConvertErrorPath, depth: number): Result<EmittedBody> {
|
||||
function emitTable(node: AdfNode, directive: BlockDirective, path: ConvertErrorPath, depth: number): Result<EmittedBlock> {
|
||||
const pipe = emitPipeTable(node, path)
|
||||
if (pipe === undefined) return emitDirectiveBlock(node, directive, path, depth)
|
||||
return plainBlock(pipe)
|
||||
return commonMarkLine(pipe)
|
||||
}
|
||||
|
||||
function emitBlockquote(node: AdfNode, path: ConvertErrorPath, depth: number): Result<string> {
|
||||
function emitBlockquote(node: AdfNode, path: ConvertErrorPath, depth: number): Result<EmittedBody> {
|
||||
const validation = validateBlockNode(node, [], path)
|
||||
if (!validation.ok) return validation
|
||||
const inner = emitBlocks(node.content ?? [], 'document', path, depth + 1)
|
||||
if (!inner.ok) return inner
|
||||
return success(
|
||||
inner.value.text
|
||||
.split('\n')
|
||||
.map((line) => (line === '' ? '>' : `> ${line}`))
|
||||
.join('\n'),
|
||||
)
|
||||
const text = inner.value.text
|
||||
.split('\n')
|
||||
.map((line) => (line === '' ? '>' : `> ${line}`))
|
||||
.join('\n')
|
||||
return success({ fenceColons: inner.value.fenceColons, text })
|
||||
}
|
||||
|
||||
function emitCodeBlock(node: AdfNode, path: ConvertErrorPath): Result<string> {
|
||||
@@ -211,54 +202,63 @@ function emitHeading(node: AdfNode, path: ConvertErrorPath): Result<string> {
|
||||
return success(`${hashes} ${line.value}`)
|
||||
}
|
||||
|
||||
function emitList(node: AdfNode, path: ConvertErrorPath, depth: number): Result<string> {
|
||||
function emitList(node: AdfNode, path: ConvertErrorPath, depth: number): Result<EmittedBody> {
|
||||
const ordered = node.type === 'orderedList'
|
||||
const validation = validateBlockNode(node, ordered ? ['order'] : [], path)
|
||||
if (!validation.ok) return validation
|
||||
const items = node.content ?? []
|
||||
if (items.length === 0) return failure('unsupported-node-shape', `a ${node.type} holds at least one listItem`, path)
|
||||
const start = ordered ? node.attrs?.['order'] : 0
|
||||
if (ordered && (start === undefined || start === 1)) {
|
||||
return failure('ambiguous-ordered-list-start', 'an orderedList starting at 1 and one with no order share one markdown spelling', path)
|
||||
}
|
||||
if (typeof start !== 'number' || !Number.isInteger(start) || start < 0 || start > largestListMarker) {
|
||||
return failure('unsupported-node-shape', `no list marker spells the order ${JSON.stringify(start ?? null)}`, path)
|
||||
}
|
||||
if (start + items.length - 1 > largestListMarker) {
|
||||
return failure('unspellable-list-marker', `no list marker spells the ${items.length} items a list starting at ${start} needs`, path)
|
||||
}
|
||||
const start = listStart(node, items.length, path)
|
||||
if (!start.ok) return start
|
||||
const lines: string[] = []
|
||||
let fenceColons = 0
|
||||
for (const [offset, item] of items.entries()) {
|
||||
const itemPath = [...path, 'content', offset]
|
||||
if (item.type !== 'listItem') return failure('unsupported-node-shape', `a ${node.type} holds listItem nodes only`, itemPath)
|
||||
const emitted = emitListItem(item, ordered ? `${start + offset}. ` : '- ', itemPath, depth)
|
||||
const emitted = emitListItem(item, ordered ? `${start.value + offset}. ` : '- ', itemPath, depth)
|
||||
if (!emitted.ok) return emitted
|
||||
lines.push(emitted.value)
|
||||
fenceColons = Math.max(fenceColons, emitted.value.fenceColons)
|
||||
lines.push(emitted.value.text)
|
||||
}
|
||||
return success(lines.join('\n'))
|
||||
return success({ fenceColons, text: lines.join('\n') })
|
||||
}
|
||||
|
||||
function emitListItem(item: AdfNode, marker: string, path: ConvertErrorPath, depth: number): Result<string> {
|
||||
function listStart(node: AdfNode, items: number, path: ConvertErrorPath): Result<number> {
|
||||
if (items === 0) return failure('unsupported-node-shape', `a ${node.type} holds at least one listItem`, path)
|
||||
if (node.type !== 'orderedList') return success(0)
|
||||
const start = node.attrs?.['order']
|
||||
if (start === undefined || start === 1) {
|
||||
return failure('ambiguous-ordered-list-start', 'an orderedList starting at 1 and one with no order share one markdown spelling', path)
|
||||
}
|
||||
if (typeof start !== 'number' || !Number.isInteger(start) || start < 0 || start > largestListMarker) {
|
||||
return failure('unsupported-node-shape', `no list marker spells the order ${JSON.stringify(start)}`, path)
|
||||
}
|
||||
if (start + items - 1 > largestListMarker) {
|
||||
return failure('unspellable-list-marker', `no list marker spells the ${items} items a list starting at ${start} needs`, path)
|
||||
}
|
||||
return success(start)
|
||||
}
|
||||
|
||||
function emitListItem(item: AdfNode, marker: string, path: ConvertErrorPath, depth: number): Result<EmittedBody> {
|
||||
const validation = validateBlockNode(item, [], path)
|
||||
if (!validation.ok) return validation
|
||||
const inner = emitBlocks(item.content ?? [], 'list-item', path, depth + 1)
|
||||
if (!inner.ok) return inner
|
||||
if (inner.value.text === '') return success(marker.trimEnd())
|
||||
if (inner.value.text === '') return success({ fenceColons: 0, text: marker.trimEnd() })
|
||||
const indent = ' '.repeat(marker.length)
|
||||
const lines = inner.value.text.split('\n').map((line, index) => (index === 0 ? `${marker}${line}` : line === '' ? '' : `${indent}${line}`))
|
||||
const first = lines[0] ?? ''
|
||||
if (isThematicBreak(first)) {
|
||||
return failure('unspellable-line-start', `block parsing would claim the emitted line ${JSON.stringify(first)}`, path)
|
||||
}
|
||||
return success(lines.join('\n'))
|
||||
return success({ fenceColons: inner.value.fenceColons, text: lines.join('\n') })
|
||||
}
|
||||
|
||||
function emitParagraph(node: AdfNode, path: ConvertErrorPath): Result<EmittedBody> {
|
||||
function emitParagraph(node: AdfNode, path: ConvertErrorPath): Result<EmittedBlock> {
|
||||
const validation = validateBlockNode(node, [], path)
|
||||
if (!validation.ok) return validation
|
||||
const content = node.content ?? []
|
||||
if (content.length === 0) return success({ fenceColons: 2, text: '::paragraph' })
|
||||
return plainBlock(emitInlineLine(content, 'paragraph', path))
|
||||
if (content.length === 0) return success({ fenceColons: 2, spelling: 'directive', text: '::paragraph' })
|
||||
return commonMarkLine(emitInlineLine(content, 'paragraph', path))
|
||||
}
|
||||
|
||||
function emitRule(node: AdfNode, path: ConvertErrorPath): Result<string> {
|
||||
|
||||
Reference in New Issue
Block a user