mirror of
https://github.com/larvit/adf-codec.git
synced 2026-11-19 22:55:44 +01:00
Write tables, images, cards, extensions and expand titles in adfToPlainText
This commit is contained in:
@@ -229,10 +229,118 @@ test('writes a mention, an emoji, a date and a status as the text they show', ()
|
||||
assert.equal(plain(adfToPlainText(document(paragraph(...nodes.flatMap((node) => [node, text(' ')]))))), '@557058:ann 😄 2025-08-25 Done ')
|
||||
})
|
||||
|
||||
test('writes a table\'s cells as blocks, until a table has its own spelling', () => {
|
||||
const cell = (value: string): AdfNode => ({ content: [line(value)], type: 'tableCell' })
|
||||
const table: AdfNode = { content: [{ content: [cell('a'), cell('b')], type: 'tableRow' }, { content: [cell('c'), cell('d')], type: 'tableRow' }], type: 'table' }
|
||||
assert.equal(plain(adfToPlainText(document(table))), 'a\n\nb\n\nc\n\nd')
|
||||
function cell(...content: AdfNode[]): AdfNode {
|
||||
return { content: content.length === 0 ? [paragraph()] : content, type: 'tableCell' }
|
||||
}
|
||||
|
||||
function row(...cells: AdfNode[]): AdfNode {
|
||||
return { content: cells, type: 'tableRow' }
|
||||
}
|
||||
|
||||
function table(...rows: AdfNode[]): AdfNode {
|
||||
return { content: rows, type: 'table' }
|
||||
}
|
||||
|
||||
function cells(...values: string[]): AdfNode {
|
||||
return row(...values.map((value) => cell(line(value))))
|
||||
}
|
||||
|
||||
test('writes a table as one line per row, its cells apart by a bar, a header row like any other', () => {
|
||||
const header = row(...['Name', 'Role'].map((value) => ({ content: [line(value)], type: 'tableHeader' })))
|
||||
assert.equal(plain(adfToPlainText(document(table(header, cells('Ada', 'Engineer'), cells('Grace', 'Admiral'))))), 'Name | Role\nAda | Engineer\nGrace | Admiral')
|
||||
})
|
||||
|
||||
test('writes a table a blank line from the blocks around it', () => {
|
||||
assert.equal(plain(adfToPlainText(document(line('Team'), table(cells('a', 'b'), cells('c', 'd')), line('End')))), 'Team\n\na | b\nc | d\n\nEnd')
|
||||
})
|
||||
|
||||
test('writes a merged cell once, with no place for the cells it covers', () => {
|
||||
const wide: AdfNode = { attrs: { colspan: 2 }, content: [line('Wide')], type: 'tableCell' }
|
||||
const tall: AdfNode = { attrs: { rowspan: 2 }, content: [line('Tall')], type: 'tableCell' }
|
||||
assert.equal(plain(adfToPlainText(document(table(row(wide, tall), cells('x', 'y'))))), 'Wide | Tall\nx | y')
|
||||
})
|
||||
|
||||
test('writes an empty cell as an empty place between the bars, in any column', () => {
|
||||
assert.equal(plain(adfToPlainText(document(table(row(cell(line('a')), cell(), cell(line('c'))), row(cell(), cell(line('e'))))))), 'a | | c\n | e')
|
||||
})
|
||||
|
||||
test('writes the blocks of a cell on its line, a space apart, a list item behind its marker', () => {
|
||||
const nested = row(cell(line('Line one'), line('Line two')), cell(bullets(item(line('p')), item(line('q')))))
|
||||
assert.equal(plain(adfToPlainText(document(table(nested, cells('x', 'y'))))), 'Line one Line two | • p • q\nx | y')
|
||||
})
|
||||
|
||||
test('writes a hard break and the lines of a code block in a cell as spaces, so the row stays one line', () => {
|
||||
const broken = row(cell(paragraph(text('a'), { type: 'hardBreak' }, text('b'))), cell({ content: [text('c\nd\n')], type: 'codeBlock' }), cell(line('e')))
|
||||
assert.equal(plain(adfToPlainText(document(table(broken)))), 'a b | c d | e')
|
||||
})
|
||||
|
||||
test('writes a table inside a list item under the item\'s indent', () => {
|
||||
assert.equal(plain(adfToPlainText(document(bullets(item(line('t'), table(cells('a', 'b'), cells('c', 'd'))))))), '• t\n a | b\n c | d')
|
||||
})
|
||||
|
||||
const external: AdfNode = { attrs: { alt: 'Team photo', type: 'external', url: 'https://example.com/team.png' }, type: 'media' }
|
||||
const uploaded: AdfNode = { attrs: { alt: 'Quarterly chart', id: 'f', type: 'file' }, type: 'media' }
|
||||
|
||||
function shown(...nodes: AdfNode[]): string {
|
||||
return plain(adfToPlainText(document(paragraph(text('Before')), ...nodes, paragraph(text('After')))))
|
||||
}
|
||||
|
||||
function withLink(media: AdfNode, href: string): AdfNode {
|
||||
return { ...media, marks: [{ attrs: { href }, type: 'link' }] }
|
||||
}
|
||||
|
||||
test('writes an external image as its alt text then its address, the address alone with no alt text', () => {
|
||||
assert.equal(shown({ content: [external], type: 'mediaSingle' }), 'Before\n\nTeam photo (https://example.com/team.png)\n\nAfter')
|
||||
assert.equal(shown({ content: [{ attrs: { type: 'external', url: 'https://example.com/team.png' }, type: 'media' }], type: 'mediaSingle' }), 'Before\n\nhttps://example.com/team.png\n\nAfter')
|
||||
})
|
||||
|
||||
test('writes an uploaded image as its alt text, or as [image] with none', () => {
|
||||
assert.equal(shown({ content: [uploaded], type: 'mediaSingle' }), 'Before\n\nQuarterly chart\n\nAfter')
|
||||
assert.equal(shown({ content: [{ attrs: { id: 'f', type: 'file' }, type: 'media' }], type: 'mediaSingle' }), 'Before\n\n[image]\n\nAfter')
|
||||
assert.equal(shown({ content: [{ attrs: { alt: ' ', id: 'f', type: 'file' }, type: 'media' }], type: 'mediaSingle' }), 'Before\n\n[image]\n\nAfter')
|
||||
})
|
||||
|
||||
test('writes the target of a link around an image, after its alt text and before the image\'s own address', () => {
|
||||
assert.equal(shown({ content: [withLink(external, 'https://example.com/go')], type: 'mediaSingle' }), 'Before\n\nTeam photo (https://example.com/go) (https://example.com/team.png)\n\nAfter')
|
||||
assert.equal(shown({ content: [withLink(external, 'https://example.com/team.png')], type: 'mediaSingle' }), 'Before\n\nTeam photo (https://example.com/team.png)\n\nAfter')
|
||||
assert.equal(shown({ content: [withLink(uploaded, 'https://example.com/go')], type: 'mediaSingle' }), 'Before\n\nQuarterly chart (https://example.com/go)\n\nAfter')
|
||||
assert.equal(shown({ content: [withLink({ attrs: { id: 'f', type: 'file' }, type: 'media' }, 'https://example.com/go')], type: 'mediaSingle' }), 'Before\n\n[image] (https://example.com/go)\n\nAfter')
|
||||
assert.equal(shown({ content: [withLink({ attrs: { type: 'external', url: 'https://example.com/team.png' }, type: 'media' }, 'https://example.com/go')], type: 'mediaSingle' }), 'Before\n\nhttps://example.com/team.png (https://example.com/go)\n\nAfter')
|
||||
})
|
||||
|
||||
test('writes a link\'s title around an image behind its target', () => {
|
||||
const titled: AdfNode = { ...uploaded, marks: [{ attrs: { href: 'https://example.com/go', title: 'Go' }, type: 'link' }] }
|
||||
assert.equal(shown({ content: [titled], type: 'mediaSingle' }), 'Before\n\nQuarterly chart (https://example.com/go, "Go")\n\nAfter')
|
||||
})
|
||||
|
||||
test('writes the images of a group and an inline image on the line they stand in', () => {
|
||||
assert.equal(shown({ content: [external, uploaded], type: 'mediaGroup' }), 'Before\n\nTeam photo (https://example.com/team.png)\n\nQuarterly chart\n\nAfter')
|
||||
assert.equal(plain(adfToPlainText(document(paragraph(text('See '), { attrs: { alt: 'logo', type: 'file' }, type: 'mediaInline' }, text(' here'))))), 'See logo here')
|
||||
})
|
||||
|
||||
test('writes a card as its address, or as its name then its address', () => {
|
||||
const card = (attrs: Record<string, unknown>): AdfNode => ({ attrs, type: 'blockCard' })
|
||||
assert.equal(shown(card({ url: 'https://example.com/spec' })), 'Before\n\nhttps://example.com/spec\n\nAfter')
|
||||
assert.equal(shown(card({ data: { name: 'Design spec' }, url: 'https://example.com/spec' })), 'Before\n\nhttps://example.com/spec\n\nAfter')
|
||||
assert.equal(shown(card({ data: { name: 'Design spec' } })), 'Before\n\nDesign spec\n\nAfter')
|
||||
assert.equal(shown(card({ data: { name: 'Design spec', url: 'https://example.com/spec' } })), 'Before\n\nDesign spec (https://example.com/spec)\n\nAfter')
|
||||
assert.equal(shown(card({ data: { url: 'https://example.com/spec' } })), 'Before\n\nhttps://example.com/spec\n\nAfter')
|
||||
assert.equal(shown(card({})), 'Before\n\nAfter')
|
||||
assert.equal(shown({ attrs: { url: 'https://example.com/embed' }, type: 'embedCard' }), 'Before\n\nhttps://example.com/embed\n\nAfter')
|
||||
assert.equal(plain(adfToPlainText(document(paragraph(text('See '), { attrs: { data: { name: 'Spec', url: 'https://example.com/spec' } }, type: 'inlineCard' }, text('.'))))), 'See Spec (https://example.com/spec).')
|
||||
})
|
||||
|
||||
test('writes an extension as the text it carries, and as nothing with none', () => {
|
||||
assert.equal(shown({ attrs: { extensionKey: 'chart', extensionType: 'com.example', text: 'Roadmap macro output' }, type: 'extension' }), 'Before\n\nRoadmap macro output\n\nAfter')
|
||||
assert.equal(shown({ attrs: { extensionKey: 'chart', extensionType: 'com.example' }, type: 'extension' }), 'Before\n\nAfter')
|
||||
assert.equal(plain(adfToPlainText(document(paragraph(text('a '), { attrs: { extensionKey: 'k', extensionType: 't', text: 'x' }, type: 'inlineExtension' }, text(' b'))))), 'a x b')
|
||||
})
|
||||
|
||||
test('writes an expand\'s title on a line, a blank line above its body', () => {
|
||||
assert.equal(shown({ attrs: { title: 'Details' }, content: [line('Hidden body')], type: 'expand' }), 'Before\n\nDetails\n\nHidden body\n\nAfter')
|
||||
assert.equal(shown({ attrs: { title: 'Details' }, content: [line('Hidden body')], type: 'nestedExpand' }), 'Before\n\nDetails\n\nHidden body\n\nAfter')
|
||||
assert.equal(shown({ content: [line('Hidden body')], type: 'expand' }), 'Before\n\nHidden body\n\nAfter')
|
||||
assert.equal(shown({ attrs: { title: 'Details' }, content: [paragraph()], type: 'expand' }), 'Before\n\nDetails\n\nAfter')
|
||||
})
|
||||
|
||||
test('writes a node of an unknown type as the text it holds, its children a blank line apart', () => {
|
||||
|
||||
@@ -6,22 +6,31 @@ import { linkAttrs, type LinkAttrs } from '../adf/mark-attributes.ts'
|
||||
import { largestNesting } from '../nesting.ts'
|
||||
import { longestOutput, tooLong, withinEngineLimits } from '../length-bound.ts'
|
||||
import { nodeAttrs, nodeContent, nodeMarks, readAdfDocument, writableContent } from '../adf/document.ts'
|
||||
import { shownText } from '../adf/shown-text.ts'
|
||||
import { shownLink, shownText, shownUrl, visibleText } from '../adf/shown-text.ts'
|
||||
|
||||
// `gap`: the line feeds the next text needs before it at least; `leave`: the state to restore after a list item, and its `length` at the start, which shows whether it wrote anything; `marker`: the marker this node has in its list; `suffix`: text written right after this node; `depth`: the nesting level as `largestNesting` counts it; `parent`: the node holding this one, from which a refusal's path is built.
|
||||
// `gap`: the line feeds the next text needs before it at least; `leave`: the state to restore after a list item, and its `length` at the start, which shows whether it wrote anything; `leaveCell`: the cell, `gap` and `literal` to restore after a table cell; `separator`: the bar between two cells of a row; `marker`: the marker this node has in its list; `suffix`: text written right after this node; `depth`: the nesting level as `largestNesting` counts it; `parent`: the node holding this one, from which a refusal's path is built.
|
||||
type Place = { index: number; parent: Place | undefined }
|
||||
type Step =
|
||||
| { kind: 'gap'; lines: number }
|
||||
| { kind: 'leaveCell'; cell: Cell | undefined; gap: number; literal: number }
|
||||
| { kind: 'leave'; indent: string; lead: string | undefined; length: number }
|
||||
| { kind: 'separator' }
|
||||
| { depth: number; kind: 'node'; marker: string | undefined; node: AdfNode; place: Place | undefined; suffix: string | undefined }
|
||||
|
||||
// `lines`: the line feeds between a node's children; `level`: how much deeper they nest.
|
||||
type Layout = { level: number; lines: number }
|
||||
// A table cell being written: its text goes on the row's line, so `base`, the margin of the row, is not repeated; `start` is the `length` where the cell began.
|
||||
type Cell = { base: string; start: number }
|
||||
|
||||
// `lines`: the line feeds between a node's children; `level`: how much deeper they nest; `cells`: they are bar-separated cells on one line.
|
||||
type Layout = { cells?: true; level: number; lines: number }
|
||||
|
||||
const bulletLists = ['bulletList', 'decisionList', 'taskList']
|
||||
const itemTypes = ['blockTaskItem', 'listItem']
|
||||
const markedItems = ['blockTaskItem', 'decisionItem', 'listItem', 'taskItem']
|
||||
const shownTextTypes = ['date', 'emoji', 'mention', 'status']
|
||||
const cardTypes = ['blockCard', 'embedCard', 'inlineCard']
|
||||
const cellTypes = ['tableCell', 'tableHeader']
|
||||
const expandTypes = ['expand', 'nestedExpand']
|
||||
const imageTypes = ['media', 'mediaInline']
|
||||
const shownTextTypes = ['date', 'emoji', 'extension', 'inlineExtension', 'mention', 'status']
|
||||
|
||||
export function adfToPlainText(document: AdfDocument): Result<string> {
|
||||
return withinEngineLimits(() => {
|
||||
@@ -40,19 +49,25 @@ function writeText(content: readonly AdfNode[]): Result<string> {
|
||||
let indent = ''
|
||||
let lead: string | undefined
|
||||
let literal = 0
|
||||
let cell: Cell | undefined
|
||||
|
||||
// Past its first text, a cell goes on the row's line: a line feed owed becomes a space, and a marker keeps its place without the row's margin.
|
||||
function emit(text: string): void {
|
||||
const end = endBeforeLineFeeds(text)
|
||||
if (end > 0) {
|
||||
const owed = Math.max(gap, literal)
|
||||
const head = length === 0 || owed > 0 ? `${length === 0 ? '' : '\n'.repeat(owed)}${lead ?? indent}` : ''
|
||||
const body = text.slice(0, end).replaceAll(/\n(?=[^\n])/g, `\n${indent}`)
|
||||
const open = cell
|
||||
let head = ''
|
||||
if (open !== undefined && length > open.start) head = owed > 0 ? ` ${lead === undefined ? '' : lead.slice(open.base.length)}` : ''
|
||||
else if (length === 0 || owed > 0 || lead !== undefined) head = `${length === 0 ? '' : '\n'.repeat(owed)}${lead ?? indent}`
|
||||
const kept = text.slice(0, end)
|
||||
const body = open === undefined ? kept.replaceAll(/\n(?=[^\n])/g, `\n${indent}`) : kept.replaceAll(/\n+/g, ' ')
|
||||
pieces.push(head, body)
|
||||
length += head.length + body.length
|
||||
gap = 0
|
||||
lead = undefined
|
||||
}
|
||||
literal = (end > 0 ? 0 : literal) + text.length - end
|
||||
literal = (end > 0 ? 0 : literal) + (cell === undefined ? text.length - end : 0)
|
||||
}
|
||||
|
||||
const pending: Step[] = childSteps(content, { level: 1, lines: 2 }, 0, undefined, () => undefined).reverse()
|
||||
@@ -61,6 +76,17 @@ function writeText(content: readonly AdfNode[]): Result<string> {
|
||||
gap = Math.max(gap, step.lines)
|
||||
continue
|
||||
}
|
||||
if (step.kind === 'leaveCell') {
|
||||
const written = cell !== undefined && length > cell.start
|
||||
gap = written ? 0 : step.gap
|
||||
literal = written ? 0 : step.literal
|
||||
cell = step.cell
|
||||
continue
|
||||
}
|
||||
if (step.kind === 'separator') {
|
||||
emit(' | ')
|
||||
continue
|
||||
}
|
||||
if (step.kind === 'leave') {
|
||||
indent = step.indent
|
||||
lead = step.length === length ? step.lead : undefined
|
||||
@@ -68,6 +94,10 @@ function writeText(content: readonly AdfNode[]): Result<string> {
|
||||
}
|
||||
const { depth, marker, node, place, suffix } = step
|
||||
if (depth > largestNesting) return failure('unsupported-nesting-depth', `the document nests deeper than the ${largestNesting} levels the writer carries`, pathTo(place))
|
||||
if (cellTypes.includes(node.type)) {
|
||||
pending.push({ cell, gap, kind: 'leaveCell', literal })
|
||||
cell = { base: indent, start: length }
|
||||
}
|
||||
if (marker !== undefined) {
|
||||
pending.push({ indent, kind: 'leave', lead, length })
|
||||
lead = lead === undefined ? `${indent}${marker}` : `${lead}${marker}`
|
||||
@@ -75,9 +105,14 @@ function writeText(content: readonly AdfNode[]): Result<string> {
|
||||
}
|
||||
if (node.type === 'hardBreak') gap += 1
|
||||
else if (shownTextTypes.includes(node.type)) emit(shownText(node) ?? '')
|
||||
else if (cardTypes.includes(node.type)) emit(cardText(node))
|
||||
else if (imageTypes.includes(node.type)) emit(imageText(node))
|
||||
else {
|
||||
emit(`${node.text ?? ''}${suffix ?? ''}`)
|
||||
for (const child of stepsWithin(node, depth, place).reverse()) pending.push(child)
|
||||
const title = expandTypes.includes(node.type) ? shownText(node) : undefined
|
||||
emit(`${node.text ?? title ?? ''}${suffix ?? ''}`)
|
||||
const inner = stepsWithin(node, depth, place)
|
||||
if (title !== undefined) inner.unshift({ kind: 'gap', lines: 2 })
|
||||
for (const child of inner.reverse()) pending.push(child)
|
||||
}
|
||||
if (length > longestOutput) return tooLong()
|
||||
}
|
||||
@@ -101,7 +136,7 @@ function childSteps(nodes: readonly AdfNode[], layout: Layout, depth: number, pa
|
||||
const links = nodes.map(linkOf)
|
||||
let run = ''
|
||||
for (const [index, node] of nodes.entries()) {
|
||||
if (index > 0) steps.push({ kind: 'gap', lines: layout.lines })
|
||||
if (index > 0) steps.push(layout.cells === true ? { kind: 'separator' } : { kind: 'gap', lines: layout.lines })
|
||||
const link = links[index]
|
||||
const before = links[index - 1]
|
||||
run = link !== undefined && before !== undefined && sameLink(link, before) ? `${run}${node.text ?? ''}` : node.text ?? ''
|
||||
@@ -112,6 +147,24 @@ function childSteps(nodes: readonly AdfNode[], layout: Layout, depth: number, pa
|
||||
return steps
|
||||
}
|
||||
|
||||
// A card shows its address, or its name and then its address.
|
||||
function cardText(card: AdfNode): string {
|
||||
const text = shownText(card)
|
||||
const url = shownUrl(card)
|
||||
return text === undefined || url === undefined || url === text ? text ?? '' : `${text} (${url})`
|
||||
}
|
||||
|
||||
// An image shows its alt text, else its address, else `[image]`; then the target of the link around it, then its own address where the alt text stood in for it.
|
||||
function imageText(media: AdfNode): string {
|
||||
const alt = visibleText(nodeAttrs(media)['alt'])
|
||||
const link = shownLink(media)
|
||||
const url = shownUrl(media)
|
||||
const shown = alt ?? url ?? '[image]'
|
||||
const target = link === undefined ? undefined : linkSuffix(link, shown)
|
||||
const own = alt !== undefined && url !== undefined && url !== link?.href ? ` (${url})` : ''
|
||||
return `${shown}${target ?? ''}${own}`
|
||||
}
|
||||
|
||||
function linkOf(node: AdfNode): LinkAttrs | undefined {
|
||||
const mark = nodeMarks(node).find((held) => held.type === 'link')
|
||||
return node.type === 'text' && mark !== undefined ? linkAttrs(nodeAttrs(mark)) : undefined
|
||||
@@ -130,7 +183,9 @@ function linkSuffix(link: LinkAttrs, text: string): string | undefined {
|
||||
function layoutOf(node: AdfNode): Layout {
|
||||
if (bulletLists.includes(node.type) || node.type === 'orderedList') return { level: 1, lines: 1 }
|
||||
if (itemTypes.includes(node.type)) return { level: 0, lines: 1 }
|
||||
if (node.type === 'tableCell' || node.type === 'tableHeader') return { level: 0, lines: 2 }
|
||||
if (node.type === 'table') return { level: 1, lines: 1 }
|
||||
if (node.type === 'tableRow') return { cells: true, level: 1, lines: 0 }
|
||||
if (cellTypes.includes(node.type)) return { level: 0, lines: 2 }
|
||||
const model = blockNodeModel(node.type)
|
||||
if (model !== undefined) return model.contentModel === 'block' ? { level: 1, lines: 2 } : { level: 0, lines: 0 }
|
||||
return nodeContent(node).every((child) => child.type === 'text' || inlineNodeModel(child.type) !== undefined) ? { level: 0, lines: 0 } : { level: 1, lines: 2 }
|
||||
|
||||
Reference in New Issue
Block a user