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

Move the portable flavour's reading and writing into markdown/portable/

This commit is contained in:
2026-10-22 19:35:37 +02:00
committed by Lillem4n
parent 5278f68262
commit 0c0a9e7835
24 changed files with 364 additions and 313 deletions
+1 -1
View File
@@ -10,7 +10,7 @@ import { commonMarkLink, linkHref, linkMark } from '../mark-spellings.ts'
import { decodeTextEscapes, trimTrailingSpace } from '../commonmark/grammar.ts'
import { failure, faulted, success, type ConvertErrorPath, type Result } from '../../result.ts'
import { flavourClaims } from '../flavour.ts'
import { highlightDelimiter } from '../portable/conventions.ts'
import { highlightDelimiter } from '../highlight-syntax.ts'
import { identicalMarks, mergeAdjacentText, nodeAttrs, nodeMarks } from '../../adf/document.ts'
import { inlineNodeModel, takesMark } from '../../adf/inline-nodes.ts'
import { inlineSource, readInlineToken } from '../inline-tokens.ts'
+2 -1
View File
@@ -3,8 +3,9 @@ import test from 'node:test'
import type { AdfAttributes, AdfDocument, AdfMark, AdfNode } from '../../adf/document.ts'
import type { ParseError, Result, SourcePosition } from '../../result.ts'
import { commonMarkToAdf, losslessMarkdownToAdf, portableMarkdownToAdf } from './markdown-to-adf.ts'
import { commonMarkToAdf, losslessMarkdownToAdf } from './markdown-to-adf.ts'
import { largestNesting } from '../../nesting.ts'
import { portableMarkdownToAdf } from '../portable/portable-markdown-to-adf.ts'
const em: AdfMark = { type: 'em' }
const strike: AdfMark = { type: 'strike' }
+27 -162
View File
@@ -2,70 +2,60 @@ import type { AdfDocument, AdfNode } from '../../adf/document.ts'
import type { Block, DirectiveBlock } from './blocks.ts'
import type { BlockDirectiveNode } from '../directive/node-reading.ts'
import type { ConvertFault } from '../../result.ts'
import type { Flavour } from '../flavour.ts'
import type { LineContainer } from '../line-container.ts'
import type { LinkDefinitions } from './inline-content.ts'
import { carryFenceType, readCarriedBlock } from '../opaque-carry.ts'
import { commonMarkSpelling, type SpellingMemo } from '../emit/spelling-questions.ts'
import { documentAttribute, documentName, documentSpelling } from '../directive/block.ts'
import { emptyKeys, nodeAttrs } from '../../adf/document.ts'
import { failure, faulted, positioned, success, type ConvertError, type ConvertErrorPath, type ParseError, type Result, type SourcePosition } from '../../result.ts'
import { failure, faulted, positioned, success, type ConvertErrorPath, type ParseError, type Result } from '../../result.ts'
import { flavourClaims } from '../flavour.ts'
import { languageSlot } from '../code-language.ts'
import { largestNesting } from '../../nesting.ts'
import { leadingMarker, readAlertMarker, readTaskMarker } from '../portable/conventions.ts'
import { mintTaskIds } from '../portable/task-ids.ts'
import { parseBlocks } from './blocks.ts'
import { parseInlineContent } from './inline-content.ts'
import { pathTo, splitTaskList } from '../portable/task-list.ts'
import { readBlockDirectiveNode } from '../directive/node-reading.ts'
import { spellStringAttribute, unsupportedNodeShape } from '../directive/syntax.ts'
import { spellsEmpty } from '../directive/empty-keys.ts'
import { withinEngineLimits } from '../length-bound.ts'
type Paragraph = Extract<Block, { kind: 'paragraph' }>
// A flavour's own reading of a quote and of a bullet list, which may read to several blocks.
export type FlavourBlockReaders = {
bulletList: (items: readonly Block[][], reading: Reading, path: ConvertErrorPath, depth: number, listIndex: number) => Result<AdfNode[]>
quote: (blocks: readonly Block[], reading: Reading, path: ConvertErrorPath, depth: number) => Result<AdfNode>
}
// The paragraph a task marker opens: a task item holds no image, so a lone one there reads as its linked alt text.
type TaskParagraph = { kind: 'taskParagraph'; position: SourcePosition; text: string }
export type ReadAs = { flavour: 'commonmark' | 'lossless' } | { blocks: FlavourBlockReaders; flavour: 'portable' }
type ReadBlock = Block | TaskParagraph
// `inExpand` is whether an expand holds the blocks, which makes a folded callout a nestedExpand.
type Reading = { definitions: LinkDefinitions; flavour: Flavour; inExpand: boolean; memo: SpellingMemo }
// `inExpand` is whether an expand holds the blocks, which makes a folded callout a nestedExpand. An expand directive leaves it unset, so no flavour reads both.
export type Reading = ReadAs & { definitions: LinkDefinitions; inExpand: boolean; memo: SpellingMemo }
export function commonMarkToAdf(markdown: string): Result<AdfDocument, ParseError> {
return readDocument(markdown, 'commonmark')
return readDocument(markdown, { flavour: 'commonmark' })
}
export function losslessMarkdownToAdf(markdown: string): Result<AdfDocument, ParseError> {
return readDocument(markdown, 'lossless')
return readDocument(markdown, { flavour: 'lossless' })
}
export function portableMarkdownToAdf(markdown: string): Result<AdfDocument, ParseError> {
return readDocument(markdown, 'portable')
}
function readDocument(markdown: string, flavour: Flavour): Result<AdfDocument, ParseError> {
export function readDocument(markdown: string, readAs: ReadAs): Result<AdfDocument, ParseError> {
return positioned(
withinEngineLimits(() => readMarkdown(markdown, flavour)),
withinEngineLimits(() => readMarkdown(markdown, readAs)),
{ line: 1, offset: 0 },
)
}
function readMarkdown(markdown: string, flavour: Flavour): Result<AdfDocument> {
function readMarkdown(markdown: string, readAs: ReadAs): Result<AdfDocument> {
if (typeof markdown !== 'string') return failure('not-a-string', `markdown is a string: found ${typeName(markdown)}`, [])
const parsed = parseBlocks(markdown, flavour)
const parsed = parseBlocks(markdown, readAs.flavour)
const [only] = parsed.blocks
if (parsed.blocks.length === 1 && only?.kind === 'directive' && only.name === documentName) {
const fault = documentFault(only)
return fault === undefined ? success({ type: 'doc', version: 1 }) : positioned(faulted(fault, []), only.position)
}
const reading: Reading = { definitions: parsed.definitions, flavour, inExpand: false, memo: new Map() }
const reading: Reading = { ...readAs, definitions: parsed.definitions, inExpand: false, memo: new Map() }
const content = readBlocks(parsed.blocks, reading, [], 0)
if (!content.ok) return content
const document: AdfDocument = { content: content.value, type: 'doc', version: 1 }
if (flavourClaims[flavour].taskMarkers) mintTaskIds(document, markdown)
return success(document)
return content.ok ? success({ content: content.value, type: 'doc', version: 1 }) : content
}
// `typeof` alone, since anything more throws on a revoked Proxy.
@@ -76,7 +66,7 @@ function typeName(value: unknown): string {
return type === 'object' ? 'an object' : `a ${type}`
}
function readBlocks(blocks: readonly ReadBlock[], reading: Reading, path: ConvertErrorPath, depth: number): Result<AdfNode[]> {
export function readBlocks(blocks: readonly Block[], reading: Reading, path: ConvertErrorPath, depth: number): Result<AdfNode[]> {
if (depth > largestNesting) return tooDeep(path)
const content: AdfNode[] = []
for (const block of blocks) {
@@ -85,8 +75,8 @@ function readBlocks(blocks: readonly ReadBlock[], reading: Reading, path: Conver
const fault = documentFault(block) ?? unsupportedNodeShape(`delete the ${documentSpelling} line to give the document content: it stands only as the whole document`)
return positioned(faulted(fault, nodePath), block.position)
}
if (block.kind === 'bulletList' && flavourClaims[reading.flavour].taskMarkers) {
const listed = positioned(bulletBlocks(block.items, reading, nodePath, depth, content.length), block.position)
if (block.kind === 'bulletList' && reading.flavour === 'portable') {
const listed = positioned(reading.blocks.bulletList(block.items, reading, nodePath, depth, content.length), block.position)
if (!listed.ok) return listed
for (const node of listed.value) content.push(node)
continue
@@ -98,7 +88,7 @@ function readBlocks(blocks: readonly ReadBlock[], reading: Reading, path: Conver
return success(content)
}
function tooDeep<T>(path: ConvertErrorPath): Result<T> {
export function tooDeep<T>(path: ConvertErrorPath): Result<T> {
return failure('unsupported-nesting-depth', `the input nests deeper than the ${largestNesting} levels the parser carries`, path)
}
@@ -111,12 +101,12 @@ function documentFault(block: DirectiveBlock): ConvertFault | undefined {
return unsupportedNodeShape(`${documentName} spells the one form ${documentSpelling}: this one spells another`)
}
function readBlock(block: ReadBlock, reading: Reading, path: ConvertErrorPath, depth: number): Result<AdfNode> {
function readBlock(block: Block, reading: Reading, path: ConvertErrorPath, depth: number): Result<AdfNode> {
switch (block.kind) {
case 'blockquote':
return flavourClaims[reading.flavour].alerts ? quoteNode(block.blocks, reading, path, depth) : containerNode({ type: 'blockquote' }, block.blocks, reading, path, depth)
return reading.flavour === 'portable' ? reading.blocks.quote(block.blocks, reading, path, depth) : containerNode({ type: 'blockquote' }, block.blocks, reading, path, depth)
case 'bulletList':
// readBlocks reads a portable task list before it reaches here.
// readBlocks reads a portable bullet list before it reaches here.
return listNode({ type: 'bulletList' }, block.items, reading, path, depth)
case 'code':
return codeBlockNode(block.language, block.text, reading, path, depth)
@@ -136,134 +126,9 @@ function readBlock(block: ReadBlock, reading: Reading, path: ConvertErrorPath, d
return success({ type: 'rule' })
case 'table':
return tableNode(block.rows, reading, path)
case 'taskParagraph':
return contentNode({ type: 'paragraph' }, block.text, reading, path, 'paragraph')
}
}
function markerLed<T extends { length: number }>(block: Block | undefined, read: (text: string) => T | undefined): { marker: T; position: SourcePosition; text: string } | undefined {
if (block?.kind !== 'paragraph') return undefined
const marker = leadingMarker(block.text, read)
return marker === undefined ? undefined : { marker, position: block.position, text: block.text.slice(marker.length) }
}
function markerLine(text: string): { line: string; rest: string } {
const lineEnd = text.indexOf('\n')
const line = lineEnd === -1 ? text : text.slice(0, lineEnd)
const hardBreak = lineEnd !== -1 && /(?:^|[^\\])(?:\\\\)*\\$/.test(line)
return { line: (hardBreak ? line.slice(0, -1) : line).replace(/^[ \t]+/, ''), rest: lineEnd === -1 ? '' : text.slice(lineEnd + 1) }
}
// docs/decisions.md, An image reads as an image only alone in its paragraph: a marker or title line stands apart from the lines after it.
function paragraphsOf(position: SourcePosition, ...texts: string[]): Paragraph[] {
return texts.filter((text) => text !== '').map((text) => ({ kind: 'paragraph', position, text }))
}
function quoteNode(blocks: readonly Block[], reading: Reading, path: ConvertErrorPath, depth: number): Result<AdfNode> {
const [first, ...body] = blocks
const led = markerLed(first, readAlertMarker)
if (led === undefined) return containerNode({ type: 'blockquote' }, blocks, reading, path, depth)
const { folded, panelType } = led.marker
const { line, rest } = markerLine(led.text)
if (!folded) return filledNode({ attrs: { panelType }, type: 'panel' }, readBlocks([...paragraphsOf(led.position, line, rest), ...body], reading, path, depth + 1))
const title = parseInlineContent(line, reading.definitions, path, 'paragraph', reading.flavour)
if (!title.ok) return title
const text = titleText(title.value.nodes)
const type = reading.inExpand ? 'nestedExpand' : 'expand'
return filledNode(text === '' ? { type } : { attrs: { title: text }, type }, readBlocks([...paragraphsOf(led.position, rest), ...body], { ...reading, inExpand: true }, path, depth + 1))
}
// docs/decisions.md, A callout title keeps its link targets.
function titleText(nodes: readonly AdfNode[]): string {
let text = ''
let linked = ''
for (const [index, node] of nodes.entries()) {
const href = linkTarget(node)
text += node.text ?? ''
linked += href === undefined ? '' : node.text ?? ''
if (href === undefined || linkTarget(nodes[index + 1]) === href) continue
if (href !== linked && href !== `mailto:${linked}`) text += ` (${href})`
linked = ''
}
return text
}
function linkTarget(node: AdfNode | undefined): string | undefined {
const href = node?.marks?.find((mark) => mark.type === 'link')?.attrs?.href
return typeof href === 'string' ? href : undefined
}
// Atlassian's schema requires a panel and an expand to hold a block.
function filledNode(node: AdfNode, content: Result<AdfNode[]>): Result<AdfNode> {
if (!content.ok) return content
return success({ ...node, content: content.value.length === 0 ? [{ type: 'paragraph' }] : content.value })
}
function taskItems(items: readonly Block[][]) {
const led = []
for (const [first, ...others] of items) {
const marked = markerLed(first, readTaskMarker)
if (marked === undefined) return undefined
led.push({ ...marked, others })
}
return led
}
function bulletBlocks(items: readonly Block[][], reading: Reading, path: ConvertErrorPath, depth: number, listIndex: number): Result<AdfNode[]> {
const tasks = taskBlocks(items, reading, path, depth)
if (tasks === undefined) {
const list = listNode({ type: 'bulletList' }, items, reading, path, depth)
return list.ok ? success([list.value]) : list
}
if (!tasks.ok) return tasks
const { nodes: blocks, refusal } = tasks.value
if (refusal === undefined) return success(blocks)
const place = pathTo(blocks, refusal.marker)
// task-list.test.ts pins that the split keeps the marker; were it lost, the error keeps its pre-split path, since nothing here throws.
if (place === undefined) return { error: refusal.error, ok: false }
const [blockIndex, ...steps] = place
return { error: { ...refusal.error, path: [...path.slice(0, -1), listIndex + blockIndex, ...steps.slice(0, -2), ...refusal.within] }, ok: false }
}
// A block a task list refused. Its placeholder holds `marker` as its one child and stands where the block's node would, so the one split that builds the list places it; `within` is the error's path below that node.
type Refusal = { error: ConvertError; marker: AdfNode; within: ConvertErrorPath }
// Nodes read from task blocks and the first refusal among them; a list is read up to the task holding its refusal.
type TaskNodes = { nodes: AdfNode[]; refusal: Refusal | undefined }
function taskBlocks(items: readonly Block[][], reading: Reading, path: ConvertErrorPath, depth: number): Result<TaskNodes> | undefined {
const led = taskItems(items)
if (led === undefined) return undefined
if (depth + 1 > largestNesting) return tooDeep([...path, 'content', 0])
const tasks: AdfNode[] = []
let refusal: Refusal | undefined
for (const [index, { marker, others, position, text }] of led.entries()) {
const body = text.replace(/^(?:[ \t\n]|\\\n)+/, '')
const marked: TaskParagraph[] = body === '' ? [] : [{ kind: 'taskParagraph', position, text: body }]
const task: AdfNode & { content: AdfNode[] } = { attrs: { state: marker.state }, content: [], type: 'blockTaskItem' }
for (const block of [...marked, ...others]) {
const read = readTaskBlock(block, reading, [...path, 'content', index], depth + 1)
for (const node of read.nodes) task.content.push(node)
refusal ??= read.refusal
}
tasks.push(task)
if (refusal !== undefined) break
}
return success({ nodes: splitTaskList({ content: tasks, type: 'taskList' }), refusal })
}
// A refused block reads to a placeholder. The split tells only paragraphs and task lists from other blocks, so a paragraph that failed to read stays a paragraph.
function readTaskBlock(block: ReadBlock, reading: Reading, path: ConvertErrorPath, depth: number): TaskNodes {
const nodePath = [...path, 'content', 0]
const nested = block.kind === 'bulletList' ? taskBlocks(block.items, reading, nodePath, depth) : undefined
if (nested?.ok) return nested.value
const read = positioned(nested ?? readBlocks([block], reading, path, depth), block.position)
if (read.ok) return { nodes: read.value, refusal: undefined }
const marker: AdfNode = { text: '', type: 'text' }
const type = block.kind === 'taskParagraph' ? 'paragraph' : nested === undefined ? block.kind : 'taskList'
return { nodes: [{ content: [marker], type }], refusal: { error: read.error, marker, within: read.error.path.slice(nodePath.length) } }
}
function directiveNode(block: DirectiveBlock, reading: Reading, path: ConvertErrorPath, depth: number): Result<AdfNode> {
const read = readBlockDirectiveNode(block.name, block.argument, block.attributes, path)
if (!read.ok) return read
@@ -355,7 +220,7 @@ function inlineBodyNode(node: AdfNode, blocks: readonly Block[], reading: Readin
return positioned(contentNode(node, only.text, reading, path, 'paragraph'), only.position)
}
function containerNode(node: AdfNode, blocks: readonly Block[], reading: Reading, path: ConvertErrorPath, depth: number): Result<AdfNode> {
export function containerNode(node: AdfNode, blocks: readonly Block[], reading: Reading, path: ConvertErrorPath, depth: number): Result<AdfNode> {
const content = readBlocks(blocks, reading, path, depth + 1)
if (!content.ok) return content
return success(withContent(node, content.value))
@@ -365,7 +230,7 @@ function withContent(node: AdfNode, content: readonly AdfNode[]): AdfNode {
return content.length === 0 ? node : { ...node, content: [...content] }
}
function listNode(node: AdfNode, items: readonly Block[][], reading: Reading, path: ConvertErrorPath, depth: number): Result<AdfNode> {
export function listNode(node: AdfNode, items: readonly Block[][], reading: Reading, path: ConvertErrorPath, depth: number): Result<AdfNode> {
const content: AdfNode[] = []
for (const [index, blocks] of items.entries()) {
const item = containerNode({ type: 'listItem' }, blocks, reading, [...path, 'content', index], depth)
@@ -393,7 +258,7 @@ function paragraphNode(text: string, reading: Reading, path: ConvertErrorPath):
return success(image === undefined ? withContent({ type: 'paragraph' }, content.value.nodes) : image)
}
function contentNode(node: AdfNode, text: string, reading: Reading, path: ConvertErrorPath, container: LineContainer): Result<AdfNode> {
export function contentNode(node: AdfNode, text: string, reading: Reading, path: ConvertErrorPath, container: LineContainer): Result<AdfNode> {
const content = parseInlineContent(text, reading.definitions, path, container, reading.flavour)
if (!content.ok) return content
return success(withContent(node, content.value.nodes))
@@ -1,341 +0,0 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import type { AdfAttributes, AdfDocument, AdfMark, AdfNode } from '../../adf/document.ts'
import { adfToPortableMarkdown } from '../portable/adf-to-portable-markdown.ts'
import { largestNesting } from '../../nesting.ts'
import { portableMarkdownToAdf } from './markdown-to-adf.ts'
const code: AdfMark = { type: 'code' }
const em: AdfMark = { type: 'em' }
const highlight: AdfMark = { attrs: { color: '#f8e6a0' }, type: 'backgroundColor' }
const strong: AdfMark = { type: 'strong' }
const taskTypes = ['blockTaskItem', 'taskItem', 'taskList']
function read(markdown: string): readonly AdfNode[] | string {
const parsed = portableMarkdownToAdf(markdown)
if (!parsed.ok) return parsed.error.code
const blocks = parsed.value.content ?? []
const pending = [...blocks]
for (let block = pending.pop(); block !== undefined; block = pending.pop()) {
for (const child of block.content ?? []) pending.push(child)
if (!taskTypes.includes(block.type)) continue
const { localId, ...attrs } = block.attrs ?? {}
assert.equal(typeof localId, 'string', `${block.type} in ${JSON.stringify(markdown)}`)
if (Object.keys(attrs).length === 0) delete block.attrs
else block.attrs = attrs
}
return blocks
}
function document(...content: AdfNode[]): AdfDocument {
return { content, type: 'doc', version: 1 }
}
function roundTripped(...content: AdfNode[]): readonly AdfNode[] | string {
const markdown = adfToPortableMarkdown(document(...content))
return markdown.ok ? read(markdown.value) : markdown.error.code
}
function text(value: string, ...marks: AdfMark[]): AdfNode {
return marks.length === 0 ? { text: value, type: 'text' } : { marks, text: value, type: 'text' }
}
function node(type: string, attrs: AdfAttributes, ...content: AdfNode[]): AdfNode {
return { attrs, content, type }
}
function bare(type: string, ...content: AdfNode[]): AdfNode {
return { content, type }
}
function paragraph(...content: AdfNode[]): AdfNode {
return content.length === 0 ? { type: 'paragraph' } : bare('paragraph', ...content)
}
function said(value: string): AdfNode {
return paragraph(text(value))
}
function panel(panelType: string, ...content: AdfNode[]): AdfNode {
return node('panel', { panelType }, ...content)
}
function task(state: string, ...content: AdfNode[]): AdfNode {
return node('taskItem', { state }, ...content)
}
test('reads an alert to a panel by its GitHub word, in any case', () => {
const alert = (word: string): readonly AdfNode[] | string => read(`> [!${word}]\n>\n> Check it.\n`)
assert.deepEqual(alert('NOTE'), [panel('info', said('Check it.'))])
assert.deepEqual(alert('IMPORTANT'), [panel('note', said('Check it.'))])
assert.deepEqual(alert('TIP'), [panel('tip', said('Check it.'))])
assert.deepEqual(alert('WARNING'), [panel('warning', said('Check it.'))])
assert.deepEqual(alert('CAUTION'), [panel('error', said('Check it.'))])
assert.deepEqual(alert('Warning'), [panel('warning', said('Check it.'))])
assert.deepEqual(alert('caution'), [panel('error', said('Check it.'))])
})
test('reads an Obsidian callout to a panel by what its word means, any other word info', () => {
const alert = (word: string): unknown => {
const blocks = read(`> [!${word}]\n> Body.\n`)
return typeof blocks === 'string' ? blocks : blocks[0]?.attrs
}
assert.deepEqual(alert('hint'), { panelType: 'tip' })
for (const word of ['success', 'check', 'Done']) assert.deepEqual(alert(word), { panelType: 'success' }, word)
assert.deepEqual(alert('attention'), { panelType: 'warning' })
for (const word of ['danger', 'error', 'failure', 'fail', 'missing', 'BUG']) assert.deepEqual(alert(word), { panelType: 'error' }, word)
for (const word of ['info', 'note', 'question', 'my-type']) assert.deepEqual(alert(word), { panelType: 'info' }, word)
})
test('reads the rest of an alert marker line as the panel first body paragraph, the lines after as the next', () => {
assert.deepEqual(read('> [!NOTE]\n> Line **one**.\n>\n> Two.\n'), [panel('info', paragraph(text('Line '), text('one', strong), text('.')), said('Two.'))])
assert.deepEqual(read('> [!tip] Title\n'), [panel('tip', said('Title'))])
assert.deepEqual(read('> [!tip] Title\n> body\n'), [panel('tip', said('Title'), said('body'))])
assert.deepEqual(read('> [!tip] Title\\\n> body\n'), [panel('tip', said('Title'), said('body'))])
assert.deepEqual(read('> [!NOTE]\\\n> Broken.\n'), [panel('info', said('Broken.'))])
assert.deepEqual(read('> [!NOTE]\n'), [panel('info', paragraph())])
assert.deepEqual(read('> > [!WARNING]\n> > Inner.\n'), [bare('blockquote', panel('warning', said('Inner.')))])
})
test('leaves a quote plain where its first line is no alert marker', () => {
for (const markdown of ['> \\[!NOTE]\n> x\n', '> [!NOTE]x\n', '> **[!NOTE]**\n', '> See [!NOTE]\n', '> [!NOTE]**x**\n', '> [!]\n', '> ```\n> [!NOTE]\n> ```\n']) {
const blocks = read(markdown)
assert.equal(typeof blocks !== 'string' && blocks[0]?.type, 'blockquote', markdown)
}
})
test('reads a folded callout to an expand titled by the rest of its marker line, whatever the word', () => {
assert.deepEqual(read('> [!NOTE]- Build log\n>\n> Line.\n'), [node('expand', { title: 'Build log' }, said('Line.'))])
assert.deepEqual(read('> [!bug]+ Open **by** default\n> body\n>\n> Line.\n'), [node('expand', { title: 'Open by default' }, said('body'), said('Line.'))])
const link: AdfMark = { attrs: { href: 'https://example.com' }, type: 'link' }
assert.deepEqual(read('> [!faq]- Why?\n> See [the docs](https://example.com), **now**.\n'), [
node('expand', { title: 'Why?' }, paragraph(text('See '), text('the docs', link), text(', '), text('now', strong), text('.'))),
])
assert.deepEqual(read('> [!NOTE]- Two\\\n> lines\n'), [node('expand', { title: 'Two' }, said('lines'))])
assert.deepEqual(read('> [!faq]- See [x](http://y)\n'), [node('expand', { title: 'See x (http://y)' }, paragraph())])
assert.deepEqual(read('> [!faq]- [a **b**](u "t")[c](u) and [d](v)\n'), [node('expand', { title: 'a bc (u) and d (v)' }, paragraph())])
assert.deepEqual(read('> [!faq]- <http://y> or <a@b.c> or <http://a\\b>\n'), [node('expand', { title: 'http://y or a@b.c or http://a\\b' }, paragraph())])
assert.deepEqual(read('> [!faq]- [a&#10;b](u)\n'), [node('expand', { title: 'a\nb (u)' }, paragraph())])
assert.deepEqual(read('> [!faq]- !adf:status[x]{color=red} ~~y~~\n'), [node('expand', { title: '!adf:status[x]{color=red} y' }, paragraph())])
assert.deepEqual(read('> [!NOTE]- Set ==x== here\n'), [node('expand', { title: 'Set x here' }, paragraph())])
assert.deepEqual(read('> [!NOTE]-\n>\n> Line.\n'), [bare('expand', said('Line.'))])
})
test('reads a folded callout inside an expand to a nested expand', () => {
const markdown = '> [!NOTE]- Outer\n>\n> > [!NOTE]- Inner\n> >\n> > Deep.\n>\n> > [!TIP]\n> >\n> > > [!NOTE]-\n'
assert.deepEqual(read(markdown), [node('expand', { title: 'Outer' }, node('nestedExpand', { title: 'Inner' }, said('Deep.')), panel('tip', bare('nestedExpand', paragraph())))])
assert.deepEqual(read('- > [!NOTE]-\n'), [bare('bulletList', bare('listItem', bare('expand', paragraph())))])
})
test('reads a bullet list whose every item leads with a task marker to a task list', () => {
assert.deepEqual(read('- [x] Write the spec\n- [ ] Ship **it**\n- [X] Tell\n'), [
bare('taskList', task('DONE', text('Write the spec')), task('TODO', text('Ship '), text('it', strong)), task('DONE', text('Tell'))),
])
assert.deepEqual(read('- [x]\n- [ ]\\\n after\n'), [bare('taskList', task('DONE'), task('TODO', text('after')))])
const minted = portableMarkdownToAdf('- [x] Parent\n - [ ] Child\n')
assert.deepEqual(minted.ok ? minted.value.content : minted.error.code, [
node(
'taskList',
{ localId: '51470556-7c91-46cb-b140-16e225a9b1f2' },
node('taskItem', { localId: 'e04cbd87-eb04-4737-ae72-6d56d7799874', state: 'DONE' }, text('Parent')),
node('taskList', { localId: '9ab33f3f-8c58-428f-b4eb-343a32a177d6' }, node('taskItem', { localId: 'b16a2f09-9543-499b-8a97-b88fc342b918', state: 'TODO' }, text('Child'))),
),
])
})
test('moves a nested task list beside its item and makes an item holding more than one paragraph a block task item', () => {
assert.deepEqual(read('- [x] Parent\n - [ ] Child\n- [ ] Next\n'), [bare('taskList', task('DONE', text('Parent')), bare('taskList', task('TODO', text('Child'))), task('TODO', text('Next')))])
assert.deepEqual(read('- [x] First.\n\n Second.\n- [ ] Next\n'), [bare('taskList', node('blockTaskItem', { state: 'DONE' }, said('First.'), said('Second.')), task('TODO', text('Next')))])
const nested = bare('taskList', node('blockTaskItem', { state: 'DONE' }, said('p1'), said('p2')), bare('taskList', task('TODO', text('n'))), task('TODO', text('B')))
assert.deepEqual(read('- [x] p1\n\n p2\n - [ ] n\n- [ ] B\n'), [nested])
assert.deepEqual(roundTripped(nested), [nested])
})
test('stands a block a task item cannot hold, and what follows it in the item, after the task list, which resumes at the next task', () => {
assert.deepEqual(read('- [x] Deploy\n\n ![a](u)\n- [ ] Tell\n'), [
bare('taskList', task('DONE', text('Deploy'))),
node('mediaSingle', { layout: 'center' }, { attrs: { alt: 'a', type: 'external', url: 'u' }, type: 'media' }),
bare('taskList', task('TODO', text('Tell'))),
])
assert.deepEqual(read('- [x] First.\n\n Second.\n\n > q\n\n Third.\n- [ ]\n\n ```\n x\n ```\n'), [
bare('taskList', node('blockTaskItem', { state: 'DONE' }, said('First.'), said('Second.'))),
bare('blockquote', said('q')),
said('Third.'),
bare('taskList', task('TODO')),
bare('codeBlock', text('x')),
])
assert.deepEqual(read('- [x] A\n - plain\n- [ ] B\n'), [bare('taskList', task('DONE', text('A'))), bare('bulletList', bare('listItem', said('plain'))), bare('taskList', task('TODO', text('B')))])
assert.deepEqual(read('- [ ] A\n - [ ] Child\n\n # h\n- [ ] B\n'), [
bare('taskList', task('TODO', text('A')), bare('taskList', task('TODO', text('Child')))),
node('heading', { level: 1 }, text('h')),
bare('taskList', task('TODO', text('B'))),
])
assert.deepEqual(read('- [ ] A\n\n # h\n - [ ] Child\n- [ ] B\n'), [
bare('taskList', task('TODO', text('A'))),
node('heading', { level: 1 }, text('h')),
bare('taskList', task('TODO', text('Child'))),
bare('taskList', task('TODO', text('B'))),
])
})
test('names where a refused block stands after the task list splits', () => {
const refused = (markdown: string): string => {
const parsed = portableMarkdownToAdf(markdown)
return parsed.ok ? 'read' : parsed.error.path.map((step) => '/' + step).join('')
}
assert.equal(refused('- [x] A\n\n ```\n x\n ```\n\n <div>x</div>\n'), '/content/2')
assert.equal(refused('- [ ] a <b>x</b>\n'), '/content/0/content/0')
assert.equal(refused('- [ ] a <b>x</b>\n\n more\n'), '/content/0/content/0/content/0')
assert.equal(refused('- [ ] a <b>x</b>\n\n ![i](u)\n'), '/content/0/content/0')
assert.equal(refused('- [ ] A\n\n b <b>x</b>\n'), '/content/0/content/0/content/1')
assert.equal(refused('- [ ] A\n\n # h\n\n b <b>x</b>\n'), '/content/2')
assert.equal(refused('- [ ] A\n\n # h\n- [ ] B <b>x</b>\n'), '/content/2/content/0')
assert.equal(refused('- [ ] A\n- [ ] B\n\n # h\n- [ ] C <b>x</b>\n'), '/content/2/content/0')
assert.equal(refused('- [ ] A\n - [ ] C <b>x</b>\n'), '/content/0/content/1/content/0')
assert.equal(refused('- [ ] A\n\n # h\n - [ ] C <b>x</b>\n'), '/content/2/content/0')
assert.equal(refused('- [ ] A\n - [ ] C\n\n # h\n\n <div>x</div>\n'), '/content/2')
assert.equal(refused('> q\n>\n> - [ ] A\n>\n> # h\n>\n> <div>x</div>\n'), '/content/0/content/3')
assert.equal(refused('- [ ] a <b>x</b>\n\n # h\n'), '/content/0/content/0')
assert.equal(refused('- [ ] A\n - [ ] B\n\n # h\n - [ ] C <b>x</b>\n'), '/content/2/content/0')
assert.equal(refused('- [ ] A\n - [ ] B\n\n # h\n - [ ] C\n\n <div>x</div>\n'), '/content/3')
assert.equal(refused('- [ ] A\n - [ ] B\n - [ ] C <b>x</b>\n'), '/content/0/content/1/content/1/content/0')
assert.equal(refused('- [ ] A\n - [ ] B <b>x</b>\n - [ ] C <i>y</i>\n'), '/content/0/content/1/content/0')
assert.equal(refused('- [ ] a\n\n <div>x</div>\n\n tail <b>y</b>\n'), '/content/1')
})
test('refuses a task list nested one level past the 500 the parser carries, at its deepest item', () => {
const nested = (levels: number): string => Array.from({ length: levels }, (_, level) => `${' '.repeat(level)}- [ ] a\n`).join('')
assert.ok(portableMarkdownToAdf(nested(largestNesting)).ok)
const refused = portableMarkdownToAdf(nested(largestNesting + 1))
assert.deepEqual(refused.ok ? undefined : [refused.error.code, refused.error.path], [
'unsupported-nesting-depth',
['content', 0, ...Array.from({ length: largestNesting }, () => ['content', 1]).flat(), 'content', 0],
])
assert.ok(portableMarkdownToAdf(`${'> '.repeat(largestNesting - 1)}- [ ] a\n`).ok)
const quoted = portableMarkdownToAdf(`${'> '.repeat(largestNesting)}- [ ] a\n`)
assert.equal(quoted.ok ? undefined : quoted.error.code, 'unsupported-nesting-depth')
})
test('reads a task list beside a list of another bullet character as two lists', () => {
const tasks = (state: string, value: string): AdfNode => bare('taskList', node('taskItem', { state }, text(value)))
assert.deepEqual(read('- [x] a\n* b\n'), [tasks('DONE', 'a'), bare('bulletList', bare('listItem', bare('paragraph', text('b'))))])
assert.deepEqual(read('- [x] a\n* [ ] b\n'), [tasks('DONE', 'a'), tasks('TODO', 'b')])
})
test('leaves mixed, ordered and unmarked lists plain', () => {
for (const markdown of ['- \\[x] a\n', '- [x] a\n- \\[ ] b\n', '- [x] a\n- b\n', '1. [x] a\n', '- [x]a\n', '- **[x]** a\n', '- [x]**a**\n', '- [-] a\n', '- > [x] a\n']) {
const blocks = read(markdown)
assert.notEqual(typeof blocks !== 'string' && blocks[0]?.type, 'taskList', markdown)
assert.equal(JSON.stringify(blocks).includes('taskItem'), false, markdown)
}
assert.deepEqual(read('- plain\n - [ ] nested\n'), [bare('bulletList', bare('listItem', said('plain'), bare('taskList', task('TODO', text('nested')))))])
})
test('reads a == pair to the editor default highlight, Yellow200 #f8e6a0 in @atlaskit/adf-schema 57.6.8', () => {
assert.deepEqual(read('a ==hi there== b\n'), [paragraph(text('a '), text('hi there', highlight), text(' b'))])
assert.deepEqual(read('**==hi==** b\n'), [paragraph(text('hi', highlight, strong), text(' b'))])
assert.deepEqual(read('==**a**_b_ `c`==\n'), [paragraph(text('a', highlight, strong), text('b', highlight, em), text(' ', highlight), text('c', code))])
assert.deepEqual(read('==`a`==\n'), [paragraph(text('a', code))])
assert.deepEqual(read('==[==a==](/u) b==\n'), [paragraph(text('a', { attrs: { href: '/u' }, type: 'link' }, highlight), text(' b', highlight))])
assert.deepEqual(read('x==y==z ==a == b==, (==c==) _d_==e==\n'), [paragraph(text('x==y==z '), text('a == b', highlight), text(', ('), text('c', highlight), text(') '), text('d', em), text('e', highlight))])
assert.deepEqual(read('😀==b== ==c==😀 é==d==\n'), [paragraph(text('😀'), text('b', highlight), text(' '), text('c', highlight), text('😀 é==d=='))])
assert.deepEqual(read('この機能は==日本語==でのみ、中文==重点==内容、ภาษา==ไทย==ดี 𠀀==𠀁==𠀂 이 기능은 ==한국어==에서만 サーバー==停止==中 このiPhone==専用==アプリ\n'), [
paragraph(
text('この機能は'), text('日本語', highlight), text('でのみ、中文'), text('重点', highlight), text('内容、ภาษา'), text('ไทย', highlight), text('ดี 𠀀'), text('𠀁', highlight),
text('𠀂 이 기능은 '), text('한국어', highlight), text('에서만 サーバー'), text('停止', highlight), text('中 このiPhone'), text('専用', highlight), text('アプリ'),
),
])
assert.deepEqual(read('# ==h==\n\n| ==c== |\n| --- |\n'), [
node('heading', { level: 1 }, text('h', highlight)),
bare('table', bare('tableRow', bare('tableHeader', paragraph(text('c', highlight))))),
])
assert.deepEqual(read('> [!NOTE]\n> ==x==\n'), [panel('info', paragraph(text('x', highlight)))])
assert.deepEqual(read('==a==\\\n==b==\n'), [paragraph(text('a', highlight), { type: 'hardBreak' }, text('b', highlight))])
})
test('leaves a == no pair flanks as text', () => {
for (const markdown of ['\\==x==\n', '==x\\==\n', 'a == b == c\n', 'if a==b and c==d then\n', 'a==b== c\n', '==a==b\n', '====\n', '`==x==`\n', '==a\\\nb==\n', '**==a**==\n', '==a', '== a==\n', '==a ==\n']) {
assert.equal(JSON.stringify(read(markdown)).includes('backgroundColor'), false, markdown)
}
})
test('reads what the reduction wrote back to the node it reduced, less the attributes it drops', () => {
const localId = '01a0d99b-1f59-7e2c-a3d4-62c1f0b8e7a1'
for (const panelType of ['info', 'note', 'tip', 'warning', 'error']) {
assert.deepEqual(roundTripped(node('panel', { localId, panelType }, said('Check.'))), [panel(panelType, said('Check.'))], panelType)
}
const expand = node('expand', { localId, title: 'Log' }, said('Line.'), node('nestedExpand', { title: 'Inner' }, said('Deep.')))
assert.deepEqual(roundTripped(node('panel', { panelType: 'tip' }, paragraph()), node('expand', { title: 'Empty' }, paragraph())), [panel('tip', paragraph()), node('expand', { title: 'Empty' }, paragraph())])
assert.deepEqual(roundTripped(expand), [node('expand', { title: 'Log' }, said('Line.'), node('nestedExpand', { title: 'Inner' }, said('Deep.')))])
const tasks = bare(
'taskList',
node('taskItem', { localId, state: 'DONE' }, text('Write')),
bare('taskList', task('TODO', text('Review'))),
node('blockTaskItem', { state: 'TODO' }, said('First.'), said('Second.')),
node('blockTaskItem', { state: 'DONE' }, bare('codeBlock', text('x'))),
)
const plainTasks = bare(
'taskList',
task('DONE', text('Write')),
bare('taskList', task('TODO', text('Review'))),
node('blockTaskItem', { state: 'TODO' }, said('First.'), said('Second.')),
task('DONE'),
)
assert.deepEqual(roundTripped(tasks), [plainTasks, bare('codeBlock', text('x'))])
const colour: AdfMark = { attrs: { color: '#c6edfb' }, type: 'backgroundColor' }
assert.deepEqual(roundTripped(paragraph(text('a '), text('hi', colour, strong), text(' b'))), [paragraph(text('a '), text('hi', highlight, strong), text(' b'))])
assert.deepEqual(roundTripped(paragraph(text('=', colour), text(' '), text('a==b', colour))), [paragraph(text('=', highlight), text(' '), text('a==b', highlight))])
assert.deepEqual(roundTripped(paragraph(text('x'), text('y', colour))), [said('xy')])
assert.deepEqual(roundTripped(node('expand', { title: '**x** [y](z)' }, said('b'))), [node('expand', { title: '**x** [y](z)' }, said('b'))])
})
test('reads text the writer kept from reading as a marker back as text', () => {
const quote = bare('blockquote', said('[!NOTE] x'))
const list = bare('bulletList', bare('listItem', said('[x] a')), bare('listItem', said('[ ] b')))
assert.deepEqual(roundTripped(said('==x== a==b 日==本==語'), quote, list), [said('==x== a==b 日==本==語'), quote, list])
assert.deepEqual(roundTripped(bare('taskList', task('DONE', text('[x] ==a==')))), [bare('taskList', task('DONE', text('[x] ==a==')))])
})
test('reads GFM\'s pipe table without its leading pipes or with alignment colons, dropping the alignment', () => {
const cell = (type: string, value: string): AdfNode => bare(type, said(value))
const table = bare('table', bare('tableRow', cell('tableHeader', 'a'), cell('tableHeader', 'b')), bare('tableRow', cell('tableCell', 'c'), cell('tableCell', 'd')))
assert.deepEqual(read('a | b\n--- | ---\nc | d\n'), [table])
assert.deepEqual(read('| a | b |\n| :--- | ---: |\n| c | d |\n'), [table])
assert.deepEqual(read('a | b\n:---: | ---:\n| c | d |\n'), [table])
assert.deepEqual(read('| a | b |\n--- | ---\nc | d |\n'), [table])
assert.deepEqual(read('a | b\n| --- | --- |\nc | d\n'), [table])
assert.deepEqual(read('Intro.\na | b\n--- | ---\nc | d\n\nAfter.\n'), [said('Intro.'), table, said('After.')])
assert.deepEqual(read('> a | b\n> --- | ---\n> c | d\n'), [bare('blockquote', table)])
assert.deepEqual(read('a | b\n--- | ---\nc | d\nAfter.\n'), [table, said('After.')])
assert.deepEqual(read('a | b\n--- | ---\nc | d\n# h | i\n'), [table, { attrs: { level: 1 }, content: [text('h | i')], type: 'heading' }])
assert.deepEqual(read('a | b\n--- | --- | ---\n'), [said('a | b --- | --- | ---')])
assert.deepEqual(read('- a | b\n--- | ---\n'), [bare('bulletList', bare('listItem', said('a | b --- | ---')))])
assert.deepEqual(read('a | b\n--- | ---\nc\n'), [bare('table', table.content?.[0] ?? said('')), said('c')])
assert.deepEqual(read('a | b\nc | d\n'), [said('a | b c | d')])
assert.deepEqual(read('| a | b |\n| --- | --- |\n | c | d |\n'), [bare('table', table.content?.[0] ?? said('')), bare('codeBlock', text('| c | d |'))])
assert.deepEqual(read('a | b\n--- | ---\n c | d\n'), [bare('table', table.content?.[0] ?? said('')), bare('codeBlock', text('c | d'))])
assert.deepEqual(read('a | b\n --- | ---\nc | d\n'), [said('a | b --- | --- c | d')])
const ragged = portableMarkdownToAdf('Intro.\na | b\n--- | ---\nc | d | e\n')
assert.deepEqual(ragged.ok ? undefined : [ragged.error.code, ragged.error.position], ['malformed-pipe-table', { line: 2, offset: 7 }])
})
test('reads what CommonMark reads where no row reads, a directive and a carry fence among it, an image sharing its paragraph with a marker among it', () => {
assert.deepEqual(read('!adf:panel\n'), [said('!adf:panel')])
assert.deepEqual(read('a !adf:carry{json="{}"} \\!adf:x\n'), [said('a !adf:carry{json="{}"} !adf:x')])
assert.deepEqual(read('```adf:blockCard\n{}\n```\n'), [node('codeBlock', { language: 'adf:blockCard' }, text('{}'))])
const linked = paragraph(text('a', { attrs: { href: 'u' }, type: 'link' }))
const image = node('mediaSingle', { layout: 'center' }, { attrs: { alt: 'a', type: 'external', url: 'u' }, type: 'media' })
assert.deepEqual(read('> [!tip] ![a](u)\n'), [panel('tip', image)])
assert.deepEqual(read('> [!tip]\n> ![a](u)\n'), [panel('tip', image)])
assert.deepEqual(read('> [!tip]\n>\n> ![a](u)\n'), [panel('tip', image)])
assert.deepEqual(read('> [!tip]\n> ![a](u) b\n'), [panel('tip', paragraph(...(linked.content ?? []), text(' b')))])
assert.deepEqual(read('> [!NOTE]- t\n> ![a](u)\n'), [node('expand', { title: 't' }, image)])
assert.deepEqual(read('> [!NOTE]- ![a](u)\n'), [node('expand', { title: 'a (u)' }, paragraph())])
assert.deepEqual(read('- [x] ![a](u)\n'), [bare('taskList', task('DONE', ...(linked.content ?? [])))])
assert.deepEqual(read('- [x]\n ![a](u)\n'), [bare('taskList', task('DONE', ...(linked.content ?? [])))])
let deep = 'x\n'
for (let level = 0; level < largestNesting; level += 1) deep = `> ${deep}`
assert.equal(typeof read(deep), 'object')
})