Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

refactor(mcp-host): read the blocks of a PDF and a DOCX body in one place

marcotebab6365161553
diff --git a/mcp-host/src/workflow/__tests__/markdownBlocks.test.ts b/mcp-host/src/workflow/__tests__/markdownBlocks.test.ts
index 658daa43c..db267764b 100644
--- a/mcp-host/src/workflow/__tests__/markdownBlocks.test.ts
+++ b/mcp-host/src/workflow/__tests__/markdownBlocks.test.ts
@@ -8,9 +8,11 @@ import {
isListLine,
isTableSeparator,
parseColumnAlignments,
+ readBlock,
startsTable,
stripListMarker,
} from '../markdownBlocks'
+import { allText, readPdf } from './support/pdfText'
describe('delimiter rows', () => {
it('reads a delimiter row as GFM does', () => {
@@ -94,3 +96,78 @@ describe('a body with a long run of spaces after a pipe row', () => {
}, 60_000)
}
})
+
+describe('readBlock', () => {
+ const block = (body: string, at = 0) => readBlock(body.split('\n'), at)
+
+ it('runs a fence to its closing fence, with the language noted', () => {
+ expect(block('```sh\nls\n\nls -l\n```\nafter')).toEqual({
+ kind: 'code',
+ language: 'sh',
+ code: ['ls', '', 'ls -l'],
+ next: 5,
+ })
+ // An unclosed fence takes the rest of the body.
+ expect(block('```\nx')).toMatchObject({ kind: 'code', code: ['x'], next: 3 })
+ })
+
+ it('reads a heading without its closing hashes, once', () => {
+ expect(block('## Title ##')).toEqual({ kind: 'heading', level: 2, text: 'Title', next: 1 })
+ expect(block('# Title # #')).toMatchObject({ text: 'Title #' })
+ expect(block('# C#')).toMatchObject({ text: 'C#' })
+ })
+
+ it('ends a table at a blank line or at the start of another block, as GFM does', () => {
+ const table = '| A | B |\n|---|--:|\n| 1 | 2 |'
+ expect(block(`${table}\n| 3 | 4 |\n\nafter`)).toEqual({
+ kind: 'table',
+ headers: ['A', 'B'],
+ alignments: ['left', 'right'],
+ rows: [
+ ['1', '2'],
+ ['3', '4'],
+ ],
+ next: 4,
+ })
+ for (const other of ['- item | x', '# Head | x', '> quote | x', '```x|y']) {
+ expect(block(`${table}\n${other}`), other).toMatchObject({ kind: 'table', next: 3 })
+ }
+ })
+
+ it('takes "- - -" for a rule, not a list', () => {
+ expect(block('- - -')).toEqual({ kind: 'rule', next: 1 })
+ expect(block('- item')).toEqual({ kind: 'list' })
+ })
+
+ it('reads consecutive quote lines as paragraphs', () => {
+ expect(block('> one\n> two\n>\n> three\nafter')).toEqual({
+ kind: 'quote',
+ paragraphs: ['one two', 'three'],
+ next: 4,
+ })
+ })
+
+ it('leaves blank lines and text to the renderer', () => {
+ expect(block(' ')).toEqual({ kind: 'blank', next: 1 })
+ expect(block('Some *text*')).toEqual({ kind: 'text', line: 'Some *text*', next: 1 })
+ })
+})
+
+describe('a list item with a pipe right after a table', () => {
+ let outputDir: string
+ beforeEach(() => {
+ outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-md-blocks-'))
+ })
+ afterEach(() => {
+ fs.rmSync(outputDir, { recursive: true, force: true })
+ })
+
+ it('is a list item in the PDF, as in the DOCX, not one more table row', async () => {
+ const pdf = INTERNAL_TOOLS.find(t => t.name === 'clerum__generate_pdf')!
+ const body = '| A | B |\n|---|---|\n| 1 | 2 |\n- item | x'
+ const result = await pdf.execute({ filename: 'l.pdf', body }, outputDir)
+ expect(result.success, result.error).toBe(true)
+ // As a row, the pipe would split "- item" and "x" into two cells and print neither.
+ expect(allText(await readPdf(result.artifact!.path))).toMatch(/item\s+\|\s+x/)
+ })
+})
diff --git a/mcp-host/src/workflow/docxMarkdown.ts b/mcp-host/src/workflow/docxMarkdown.ts
index df5928f68..6654f8d6a 100644
--- a/mcp-host/src/workflow/docxMarkdown.ts
+++ b/mcp-host/src/workflow/docxMarkdown.ts
@@ -6,20 +6,14 @@ import { inlineRuns, textRuns } from './docxInline'
import { docxDirection, isRtlText } from './docxScript'
import { DOCX_LIST_LEVELS, type DocxListNumbering, type DocxPalette, docxHex } from './docxStyle'
import { buildDocxTable } from './docxTable'
-import {
- closesFence,
- imageTarget,
- openingFence,
- quoteParagraphs,
- withoutClosingHashes,
-} from './inlineMarkup'
+import { imageTarget } from './inlineMarkup'
import {
BULLET_RE,
+ IMAGE_LINE_RE,
ORDERED_RE,
indentOf,
isListLine,
- splitTableRow,
- startsTable,
+ readBlock,
} from './markdownBlocks'
export interface DocxBodyContext {
@@ -30,10 +24,6 @@ export interface DocxBodyContext {
image(file: string, alt: string): Paragraph | undefined
}
-const HEADING_RE = /^(#{1,6})\s+(.*)$/
-const QUOTE_RE = /^>\s?/
-const IMAGE_LINE_RE = /^!\[([^\]\n]*)\]\(((?:[^()\n]|\([^()\n]*\))*)\)$/
-
function blankParagraph(): Paragraph {
return new Paragraph({ children: [new TextRun({ text: '' })] })
}
@@ -115,22 +105,9 @@ function parseList(lines: string[], start: number, ctx: DocxBodyContext, out: Pa
return i
}
-/** Whether `line` opens a block other than a table row, which ends a table. */
-function startsOtherBlock(line: string): boolean {
- const t = line.trim()
- if (t.startsWith('|')) return false
- return (
- HEADING_RE.test(t) ||
- openingFence(t) !== undefined ||
- QUOTE_RE.test(t) ||
- IMAGE_LINE_RE.test(t) ||
- isListLine(line)
- )
-}
-
-function headingParagraph(level: number, text: string, ctx: DocxBodyContext): Paragraph {
+/** A heading; `content` is its text without the closing hashes. */
+function headingParagraph(level: number, content: string, ctx: DocxBodyContext): Paragraph {
const { palette, warnings } = ctx
- const content = withoutClosingHashes(text)
const style =
level === 1
? { heading: HeadingLevel.HEADING_1, before: 360, after: 160, size: 36, bold: true }
@@ -163,148 +140,121 @@ export function bodyToDocxChildren(body: string, ctx: DocxBodyContext): (Paragra
let i = 0
while (i < lines.length) {
- const line = lines[i]
- const trimmed = line.trim()
-
- const fence = openingFence(trimmed)
- if (fence) {
- // The language after the opening fence is noted above the block, as in the PDF.
- const { marker, language } = fence
- const code: string[] = []
- i++
- while (i < lines.length && !closesFence(lines[i], marker)) {
- code.push(lines[i])
- i++
- }
- i++
- if (language) {
+ const block = readBlock(lines, i)
+ switch (block.kind) {
+ case 'code':
+ // The language after the opening fence is noted above the block, as in the PDF.
+ if (block.language) {
+ out.push(
+ new Paragraph({
+ spacing: { before: 60, after: 0 },
+ children: textRuns(block.language, { size: 16, color: docxHex(palette.muted) }),
+ })
+ )
+ }
+ for (const codeLine of block.code) {
+ out.push(
+ new Paragraph({
+ spacing: { before: 0, after: 0 },
+ shading: { type: ShadingType.CLEAR, fill: docxHex(palette.surface) },
+ children: [
+ new TextRun({
+ text: codeLine === '' ? ' ' : codeLine,
+ font: { ascii: 'Courier New', hAnsi: 'Courier New' },
+ size: 18,
+ color: docxHex(palette.text),
+ }),
+ ],
+ })
+ )
+ }
+ out.push(new Paragraph({ children: [new TextRun({ text: '' })], spacing: { after: 80 } }))
+ break
+ case 'heading':
+ out.push(headingParagraph(block.level, block.text, ctx))
+ break
+ case 'table':
out.push(
- new Paragraph({
- spacing: { before: 60, after: 0 },
- children: textRuns(language, { size: 16, color: docxHex(palette.muted) }),
- })
+ buildDocxTable(
+ block.headers,
+ block.rows,
+ palette,
+ 'striped',
+ warnings,
+ `The body's table ${++tables}`
+ )
)
- }
- for (const codeLine of code) {
+ out.push(new Paragraph({ children: [new TextRun({ text: '' })], spacing: { before: 60 } }))
+ break
+ case 'rule':
out.push(
new Paragraph({
- spacing: { before: 0, after: 0 },
- shading: { type: ShadingType.CLEAR, fill: docxHex(palette.surface) },
- children: [
- new TextRun({
- text: codeLine === '' ? ' ' : codeLine,
- font: { ascii: 'Courier New', hAnsi: 'Courier New' },
- size: 18,
- color: docxHex(palette.text),
- }),
- ],
+ spacing: { before: 120, after: 120 },
+ border: {
+ bottom: {
+ style: BorderStyle.SINGLE,
+ color: docxHex(palette.border),
+ size: 6,
+ space: 1,
+ },
+ },
+ children: [new TextRun({ text: '' })],
})
)
+ break
+ case 'list': {
+ const items: Paragraph[] = []
+ i = parseList(lines, i, ctx, items)
+ out.push(...items)
+ continue
}
- out.push(new Paragraph({ children: [new TextRun({ text: '' })], spacing: { after: 80 } }))
- continue
- }
-
- const heading = HEADING_RE.exec(trimmed)
- if (heading) {
- out.push(headingParagraph(heading[1].length, heading[2], ctx))
- i++
- continue
- }
-
- const image = IMAGE_LINE_RE.exec(trimmed)
- if (image) {
- const paragraph = ctx.image(imageTarget(image[2]), image[1])
- if (paragraph) out.push(paragraph)
- i++
- continue
- }
-
- if (startsTable(lines, i)) {
- const headers = splitTableRow(line)
- const rows: string[][] = []
- i += 2
- while (
- i < lines.length &&
- lines[i].trim() !== '' &&
- lines[i].includes('|') &&
- !startsOtherBlock(lines[i])
- ) {
- rows.push(splitTableRow(lines[i]))
- i++
+ case 'quote': {
+ const bar = {
+ style: BorderStyle.SINGLE,
+ color: docxHex(palette.primary),
+ size: 12,
+ space: 8,
+ }
+ const paragraphs = block.paragraphs
+ // In a right-to-left paragraph Word reads the indent from the right but
+ // draws borders where they are named, so the bar moves to the right.
+ paragraphs.forEach((quote, n) =>
+ out.push(
+ new Paragraph({
+ ...docxDirection(quote),
+ spacing: {
+ before: n === 0 ? 120 : 0,
+ after: n === paragraphs.length - 1 ? 120 : 80,
+ },
+ indent: { left: 360 },
+ border: isRtlText(quote) ? { right: bar } : { left: bar },
+ children: inlineRuns(quote, { color: docxHex(palette.muted) }, warnings),
+ })
+ )
+ )
+ break
}
- out.push(
- buildDocxTable(headers, rows, palette, 'striped', warnings, `The body's table ${++tables}`)
- )
- out.push(new Paragraph({ children: [new TextRun({ text: '' })], spacing: { before: 60 } }))
- continue
- }
-
- // A rule wins over a list: "- - -" and "* * *" are rules in markdown.
- if (/^(-{3,}|\*{3,}|_{3,})$/.test(trimmed.replace(/\s+/g, ''))) {
- out.push(
- new Paragraph({
- spacing: { before: 120, after: 120 },
- border: {
- bottom: {
- style: BorderStyle.SINGLE,
- color: docxHex(palette.border),
- size: 6,
- space: 1,
- },
- },
- children: [new TextRun({ text: '' })],
- })
- )
- i++
- continue
- }
-
- if (isListLine(line)) {
- const items: Paragraph[] = []
- i = parseList(lines, i, ctx, items)
- out.push(...items)
- continue
- }
-
- if (QUOTE_RE.test(trimmed)) {
- const quoted: string[] = []
- while (i < lines.length && QUOTE_RE.test(lines[i].trimStart())) {
- quoted.push(lines[i].trimStart().replace(QUOTE_RE, ''))
- i++
+ case 'blank':
+ out.push(blankParagraph())
+ break
+ case 'text': {
+ const image = IMAGE_LINE_RE.exec(block.line.trim())
+ if (image) {
+ const paragraph = ctx.image(imageTarget(image[2]), image[1])
+ if (paragraph) out.push(paragraph)
+ } else {
+ out.push(
+ new Paragraph({
+ ...docxDirection(block.line),
+ spacing: { after: 80 },
+ children: inlineRuns(block.line, { color: docxHex(palette.text) }, warnings),
+ })
+ )
+ }
+ break
}
- const paragraphs = quoteParagraphs(quoted)
- const bar = { style: BorderStyle.SINGLE, color: docxHex(palette.primary), size: 12, space: 8 }
- // In a right-to-left paragraph Word reads the indent from the right but
- // draws borders where they are named, so the bar moves to the right.
- paragraphs.forEach((quote, n) =>
- out.push(
- new Paragraph({
- ...docxDirection(quote),
- spacing: { before: n === 0 ? 120 : 0, after: n === paragraphs.length - 1 ? 120 : 80 },
- indent: { left: 360 },
- border: isRtlText(quote) ? { right: bar } : { left: bar },
- children: inlineRuns(quote, { color: docxHex(palette.muted) }, warnings),
- })
- )
- )
- continue
- }
-
- if (trimmed === '') {
- out.push(blankParagraph())
- i++
- continue
}
-
- out.push(
- new Paragraph({
- ...docxDirection(line),
- spacing: { after: 80 },
- children: inlineRuns(line, { color: docxHex(palette.text) }, warnings),
- })
- )
- i++
+ i = block.next
}
return out
diff --git a/mcp-host/src/workflow/markdownBlocks.ts b/mcp-host/src/workflow/markdownBlocks.ts
index 5e1a1028c..8904ceb93 100644
--- a/mcp-host/src/workflow/markdownBlocks.ts
+++ b/mcp-host/src/workflow/markdownBlocks.ts
@@ -1,11 +1,19 @@
/**
- * Line-level markdown rules the PDF and DOCX body parsers share, so both read
- * a list item, a table row and a delimiter row the same way. Every rule runs
- * on text a model wrote, so none may backtrack across the line.
+ * The markdown block rules the PDF and DOCX body parsers share: which block a
+ * line starts and where it ends (readBlock), and how a list item, a table row
+ * and a delimiter row read. Each renderer only draws what this finds. Every
+ * rule runs on text a model wrote, so none may backtrack across the line.
*/
+import { closesFence, openingFence, quoteParagraphs, withoutClosingHashes } from './inlineMarkup'
export type ColumnAlignment = 'left' | 'center' | 'right'
+const HEADING_RE = /^(#{1,6})\s+(.*)$/
+const QUOTE_RE = /^>\s?/
+const RULE_RE = /^(-{3,}|\*{3,}|_{3,})$/
+/** An image on a line of its own: its alt text and its target. */
+export const IMAGE_LINE_RE = /^!\[([^\]\n]*)\]\(((?:[^()\n]|\([^()\n]*\))*)\)$/
+
export const BULLET_RE = /^[-*+]\s+/
/** CommonMark numbers a list item with one to nine digits. */
export const ORDERED_RE = /^(\d{1,9})[.)]\s+/
@@ -70,3 +78,90 @@ export function parseColumnAlignments(separator: string): ColumnAlignment[] {
return 'left'
})
}
+
+/** One block of a markdown body, with the index of the line after it. */
+export type MarkdownBlock =
+ | { kind: 'code'; language: string; code: string[]; next: number }
+ | { kind: 'heading'; level: number; text: string; next: number }
+ | { kind: 'rule'; next: number }
+ | {
+ kind: 'table'
+ headers: string[]
+ alignments: ColumnAlignment[]
+ rows: string[][]
+ next: number
+ }
+ | { kind: 'quote'; paragraphs: string[]; next: number }
+ /** A list starts here; each renderer reads its items and nesting. */
+ | { kind: 'list' }
+ | { kind: 'blank'; next: number }
+ /** A line of text: a paragraph, or an image on a line of its own. */
+ | { kind: 'text'; line: string; next: number }
+
+/** Whether `line` opens a block other than a table row, which ends a table (GFM). */
+function startsOtherBlock(line: string): boolean {
+ const t = line.trim()
+ if (t.startsWith('|')) return false
+ return (
+ HEADING_RE.test(t) ||
+ openingFence(t) !== undefined ||
+ QUOTE_RE.test(t) ||
+ IMAGE_LINE_RE.test(t) ||
+ isListLine(line)
+ )
+}
+
+/**
+ * The block that starts at line `i`. A fence runs to its closing fence, a
+ * table to the first blank line or other block, a quote over its `>` lines.
+ * A rule wins over a list: "- - -" and "* * *" are rules in markdown.
+ */
+export function readBlock(lines: string[], i: number): MarkdownBlock {
+ const line = lines[i]
+ const trimmed = line.trim()
+
+ const fence = openingFence(trimmed)
+ if (fence) {
+ const code: string[] = []
+ let next = i + 1
+ while (next < lines.length && !closesFence(lines[next], fence.marker)) code.push(lines[next++])
+ return { kind: 'code', language: fence.language, code, next: next + 1 }
+ }
+
+ const heading = HEADING_RE.exec(trimmed)
+ if (heading) {
+ const text = withoutClosingHashes(heading[2])
+ return { kind: 'heading', level: heading[1].length, text, next: i + 1 }
+ }
+
+ if (startsTable(lines, i)) {
+ const rows: string[][] = []
+ let next = i + 2
+ while (
+ next < lines.length &&
+ lines[next].trim() !== '' &&
+ lines[next].includes('|') &&
+ !startsOtherBlock(lines[next])
+ ) {
+ rows.push(splitTableRow(lines[next++]))
+ }
+ const headers = splitTableRow(line)
+ const alignments = parseColumnAlignments(lines[i + 1])
+ return { kind: 'table', headers, alignments, rows, next }
+ }
+
+ if (RULE_RE.test(trimmed.replace(/\s+/g, ''))) return { kind: 'rule', next: i + 1 }
+ if (isListLine(line)) return { kind: 'list' }
+
+ if (QUOTE_RE.test(trimmed)) {
+ const quoted: string[] = []
+ let next = i
+ while (next < lines.length && QUOTE_RE.test(lines[next].trimStart())) {
+ quoted.push(lines[next++].trimStart().replace(QUOTE_RE, ''))
+ }
+ return { kind: 'quote', paragraphs: quoteParagraphs(quoted), next }
+ }
+
+ if (trimmed === '') return { kind: 'blank', next: i + 1 }
+ return { kind: 'text', line, next: i + 1 }
+}
diff --git a/mcp-host/src/workflow/pdfGenerator.ts b/mcp-host/src/workflow/pdfGenerator.ts
index 4a5bd930d..f531b9dc2 100644
--- a/mcp-host/src/workflow/pdfGenerator.ts
+++ b/mcp-host/src/workflow/pdfGenerator.ts
@@ -26,22 +26,13 @@ import {
loadEmbeddableImage,
} from './embeddedImages'
import { PDF_FONT_FAMILY, PDF_MONO_FAMILY, pdfGlyphSource } from './fonts'
-import {
- closesFence,
- htmlToPlainText,
- inlineSpans,
- openingFence,
- quoteParagraphs,
- withoutClosingHashes,
-} from './inlineMarkup'
+import { htmlToPlainText, inlineSpans } from './inlineMarkup'
import {
type ColumnAlignment,
ORDERED_RE,
indentOf,
isListLine,
- parseColumnAlignments,
- splitTableRow,
- startsTable,
+ readBlock,
stripListMarker,
} from './markdownBlocks'
import { choose } from './ownEntry'
@@ -485,127 +476,89 @@ function bodyToContent(body: string, palette: PdfPalette, env: PdfBodyEnv): Cont
)
let i = 0
while (i < lines.length) {
- const line = lines[i]
- const trimmed = line.trimStart()
-
- // Fenced code block. Everything up to the closing fence is verbatim, so a
- // shell snippet or a config sample keeps its spacing instead of being
- // reflowed into paragraphs.
- const fence = openingFence(trimmed)
- if (fence) {
- const { marker, language } = fence
- const code: string[] = []
- i++
- while (i < lines.length && !closesFence(lines[i], marker)) {
- code.push(lines[i])
- i++
- }
- i++ // closing fence
- out.push(buildCodeBlock(code.join('\n'), language, palette))
- continue
- }
-
- // Heading levels. The deeper ones share h3's style rather than falling
- // through as literal hashes. headlineLevel marks them for the page-break
- // check that keeps a heading off the foot of a page.
- const heading = /^(#{1,6})\s+(.*)$/.exec(trimmed)
- if (heading) {
- const level = heading[1].length
- const style = level === 1 ? 'h1' : level === 2 ? 'h2' : 'h3'
- const top = level === 1 ? 16 : level === 2 ? 12 : 8
- out.push({
- ...asPieces(parseInlineMarkdown(withoutClosingHashes(heading[2]), stray)),
- style,
- headlineLevel: 1,
- margin: [0, top, 0, level === 1 ? 6 : 4],
- } as Content)
- i++
- continue
- }
-
- // Horizontal rule in any of the three markdown spellings.
- if (/^(-{3,}|\*{3,}|_{3,})$/.test(trimmed.replace(/\s+/g, ''))) {
- out.push({
- canvas: [
- {
- type: 'line',
- x1: 0,
- y1: 0,
- x2: PDF_CONTENT_WIDTH,
- y2: 0,
- lineWidth: 0.5,
- lineColor: palette.border,
- },
- ],
- margin: [0, 8, 0, 8],
- })
- i++
- continue
- }
-
- // GFM pipe table: header line, then separator, then the rows up to the
- // first line without a pipe.
- if (startsTable(lines, i)) {
- const headers = splitTableRow(line)
- const alignments = parseColumnAlignments(lines[i + 1])
- const rows: string[][] = []
- i += 2
- while (i < lines.length && lines[i].trim() !== '' && lines[i].includes('|')) {
- rows.push(splitTableRow(lines[i]))
- i++
+ const block = readBlock(lines, i)
+ switch (block.kind) {
+ case 'code':
+ // Verbatim, so a shell snippet or a config sample keeps its spacing
+ // instead of being reflowed into paragraphs.
+ out.push(buildCodeBlock(block.code.join('\n'), block.language, palette))
+ break
+ case 'heading': {
+ // The deeper levels share h3's style rather than falling through as
+ // literal hashes. headlineLevel marks them for the page-break check
+ // that keeps a heading off the foot of a page.
+ const level = block.level
+ const style = level === 1 ? 'h1' : level === 2 ? 'h2' : 'h3'
+ const top = level === 1 ? 16 : level === 2 ? 12 : 8
+ out.push({
+ ...asPieces(parseInlineMarkdown(block.text, stray)),
+ style,
+ headlineLevel: 1,
+ margin: [0, top, 0, level === 1 ? 6 : 4],
+ } as Content)
+ break
}
- const label = `The body's table ${++env.tableCount}`
- out.push(
- buildTableNode(
- { headers, rows, alignments, label, rowLabel: index => `${label}, row ${index + 1}` },
- palette,
- env,
- stray
+ case 'rule':
+ out.push({
+ canvas: [
+ {
+ type: 'line',
+ x1: 0,
+ y1: 0,
+ x2: PDF_CONTENT_WIDTH,
+ y2: 0,
+ lineWidth: 0.5,
+ lineColor: palette.border,
+ },
+ ],
+ margin: [0, 8, 0, 8],
+ })
+ break
+ case 'table': {
+ const label = `The body's table ${++env.tableCount}`
+ const { headers, rows, alignments } = block
+ out.push(
+ buildTableNode(
+ { headers, rows, alignments, label, rowLabel: index => `${label}, row ${index + 1}` },
+ palette,
+ env,
+ stray
+ )
)
- )
- continue
- }
-
- // Blockquote: consecutive `>` lines become one ruled, indented block.
- if (/^>\s?/.test(trimmed)) {
- const quoted: string[] = []
- while (i < lines.length && /^>\s?/.test(lines[i].trimStart())) {
- quoted.push(lines[i].trimStart().replace(/^>\s?/, ''))
- i++
+ break
+ }
+ case 'quote':
+ out.push(buildBlockquote(block.paragraphs, palette, stray))
+ break
+ case 'list': {
+ // Anything nested under the first item belongs to the list.
+ const built = buildList(lines, i, indentOf(lines[i]), stray)
+ out.push(built.node)
+ i = built.next
+ continue
+ }
+ case 'blank':
+ // Small vertical breathing room.
+ out.push({ text: '', margin: [0, 2, 0, 2] })
+ break
+ case 'text': {
+ // A paragraph of inline markdown, then any images it references.
+ const images: MarkdownImage[] = []
+ const paragraph = parseInlineMarkdown(block.line, image => images.push(image))
+ if (plainText(paragraph).trim() !== '') {
+ const pieces = inPieces(paragraph)
+ pieces.forEach((piece, p) =>
+ out.push({ ...piece, margin: [0, 0, 0, p === pieces.length - 1 ? 4 : 0] })
+ )
+ }
+ for (const image of images) {
+ const placed = env.image(image.src)
+ if (placed) out.push(placed)
+ }
+ break
}
- out.push(buildBlockquote(quoteParagraphs(quoted), palette, stray))
- continue
- }
-
- // Bullet or numbered list, including anything nested under it.
- if (isListLine(line)) {
- const built = buildList(lines, i, indentOf(line), stray)
- out.push(built.node)
- i = built.next
- continue
- }
-
- // Blank line: small vertical breathing room.
- if (trimmed === '') {
- out.push({ text: '', margin: [0, 2, 0, 2] })
- i++
- continue
- }
-
- // Default: paragraph with inline markdown, then any images it references.
- const images: MarkdownImage[] = []
- const paragraph = parseInlineMarkdown(line, image => images.push(image))
- if (plainText(paragraph).trim() !== '') {
- const pieces = inPieces(paragraph)
- pieces.forEach((piece, p) =>
- out.push({ ...piece, margin: [0, 0, 0, p === pieces.length - 1 ? 4 : 0] })
- )
- }
- for (const image of images) {
- const block = env.image(image.src)
- if (block) out.push(block)
}
- i++
+ i = block.next
}
return out
}