3
0
mirror of https://github.com/larvit/adf-codec.git synced 2026-11-18 06:05:43 +01:00

Write the line feeds of consecutive code fragments as one text holds them

This commit is contained in:
2026-11-14 16:06:58 +01:00
committed by Lillem4n
parent d4a77ab207
commit 9080d09aac
2 changed files with 12 additions and 3 deletions
+6
View File
@@ -198,6 +198,12 @@ test('writes a code block ending in a line feed as one block, a blank line from
assert.equal(plain(adfToPlainText(document({ content: [text('a\n')], type: 'codeBlock' }, line('b')))), 'a\n\nb')
})
test('writes the line feeds of consecutive code fragments as the one fragment holding them all', () => {
const split: AdfNode = { content: [text('a\n'), text('\n'), text('b')], type: 'codeBlock' }
const whole: AdfNode = { content: [text('a\n\nb')], type: 'codeBlock' }
assert.equal(plain(adfToPlainText(document(split))), plain(adfToPlainText(document(whole))))
})
test('writes a task item holding blocks as an item', () => {
const tasks: AdfNode = { content: [{ attrs: { localId: 'a', state: 'TODO' }, content: [line('a'), line('b')], type: 'blockTaskItem' }], type: 'taskList' }
assert.equal(plain(adfToPlainText(document(tasks))), '☐ a\n b')
+6 -3
View File
@@ -32,26 +32,29 @@ export function adfToPlainText(document: AdfDocument): Result<string> {
})
}
// A stack rather than recursion (docs/decisions.md §Nothing recurses unbounded). Text is written the moment it is met: `gap` holds the line feeds it owes first, `lead` the marker of the item it opens, `indent` the margin of every line after that.
// A stack rather than recursion (docs/decisions.md §Nothing recurses unbounded). Text is written the moment it is met: `gap` holds the line feeds the layout owes first and `literal` those the text before ended in, of which the larger is written, `lead` the marker of the item it opens, `indent` the margin of every line after that.
function writeText(content: readonly AdfNode[]): Result<string> {
const pieces: string[] = []
let length = 0
let gap = 0
let indent = ''
let lead: string | undefined
let literal = 0
function emit(text: string): void {
let end = text.length
while (end > 0 && text[end - 1] === '\n') end -= 1
if (end > 0) {
const head = length === 0 || gap > 0 ? `${length === 0 ? '' : '\n'.repeat(gap)}${lead ?? indent}` : ''
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}`)
pieces.push(head, body)
length += head.length + body.length
gap = 0
lead = undefined
literal = 0
}
gap = Math.max(gap, text.length - end)
literal += text.length - end
}
const pending: Step[] = childSteps(content, { level: 1, lines: 2 }, 0, undefined, () => undefined).reverse()