Something went wrong. Try again.
A monorepo for writing specs and other serious text on the AT Protocol.
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768// A few blocks of rich text (a brief, a plan) as plain text and back: what// goes to a model as prose, and what a host stores when it only has text.import type { PMJson } from './types.ts';
/** The text of inline content, with **bold**, _italic_ and `code` as Markdown and math as $…$. */export function inlineText(nodes: PMJson[] | undefined): string { return (nodes ?? []) .map((n) => { if (n.type === 'inlineMath') return `$${String(n.attrs?.latex ?? '')}$`; if (n.type === 'hardBreak') return '\n'; let t = n.text ?? ''; if (!t) return ''; const marks = new Set((n.marks ?? []).map((m) => m.type)); if (marks.has('code')) t = `\`${t}\``; if (marks.has('bold')) t = `**${t}**`; if (marks.has('italic')) t = `_${t}_`; return t; }) .join('');}
function listLines(list: PMJson, indent: number): string[] { const ordered = list.type === 'orderedList'; const out: string[] = []; (list.content ?? []).forEach((item, i) => { const [first, ...rest] = item.content ?? []; out.push(`${' '.repeat(indent)}${ordered ? `${i + 1}.` : '-'} ${first?.type === 'paragraph' ? inlineText(first.content) : ''}`.trimEnd()); for (const c of rest) if (c.type === 'bulletList' || c.type === 'orderedList') out.push(...listLines(c, indent + 1)); }); return out;}
/** Blocks as plain text: paragraphs a blank line apart, lists one item per line. */export function textOfBlocks(blocks: PMJson[] | undefined): string { const parts: string[] = []; for (const b of blocks ?? []) { if (b.type === 'paragraph') { const t = inlineText(b.content).trim(); if (t) parts.push(t); } else if (b.type === 'bulletList' || b.type === 'orderedList') parts.push(listLines(b, 0).join('\n')); else if (b.content) { const t = inlineText(b.content).trim(); if (t) parts.push(t); } } return parts.join('\n\n');}
/** Plain text as blocks: a paragraph per blank-line-separated run, a list where lines start with "- " or "1. ". */export function blocksFromText(text: string): PMJson[] { const out: PMJson[] = []; for (const run of text.split(/\n\s*\n/)) { const lines = run.split('\n').map((l) => l.trim()).filter(Boolean); if (!lines.length) continue; const bullets = lines.every((l) => /^[-*] /.test(l)); const numbers = lines.every((l) => /^\d+[.)] /.test(l)); if (bullets || numbers) { out.push({ type: bullets ? 'bulletList' : 'orderedList', content: lines.map((l) => ({ type: 'listItem', content: [{ type: 'paragraph', content: [{ type: 'text', text: l.replace(/^(?:[-*]|\d+[.)]) /, '') }] }] })) }); } else out.push({ type: 'paragraph', content: [{ type: 'text', text: lines.join(' ') }] }); } return out;}
/** True when the blocks hold no text at all. */export function blocksEmpty(blocks: PMJson[] | undefined): boolean { return !textOfBlocks(blocks).trim();}