Something went wrong. Try again.
A monorepo for writing specs and other serious text on the AT Protocol.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199// Reading the document: blocks by id, defined terms, cited references,// and the empty section a host starts with. Works on ProseMirror nodes, so// it runs headless too (tests, servers).import type { Node as PMNode } from '@tiptap/pm/model';import { slugify } from './text.ts';import type { PMJson } from './types.ts';
/** A block (or section) as ops and assistants address it. */export type BlockInfo = { id: string; /** paragraph, codeBlock, blockMath, bulletList, orderedList, definitionList, figure, section */ type: string; node: PMNode; pos: number; /** Nesting depth of sections (0 for a top-level section's blocks). */ depth: number; /** The text as the assistant sees it: a section's title, a block's content. */ text: string; /** A section's number as the page shows it ("2.1"). */ number?: string;};
const BLOCK_TYPES = new Set(['paragraph', 'codeBlock', 'blockMath', 'bulletList', 'orderedList', 'definitionList', 'figure', 'section']);
export function isBlockType(name: string): boolean { return BLOCK_TYPES.has(name);}
/** Every addressable block and section, in document order (list items are part of their list). */export function blocksOf(doc: PMNode): BlockInfo[] { const out: BlockInfo[] = []; const walk = (node: PMNode, base: number, depth: number, path: string) => { let n = 0; node.forEach((child, offset) => { const pos = base + offset; if (child.type.name === 'section') { const number = `${path}${++n}`; out.push({ id: String(child.attrs.id ?? ''), type: 'section', node: child, pos, depth, text: child.firstChild?.textContent ?? '', number }); walk(child, pos + 1, depth + 1, `${number}.`); } else if (BLOCK_TYPES.has(child.type.name)) { out.push({ id: String(child.attrs.id ?? ''), type: child.type.name, node: child, pos, depth, text: blockText(child) }); } }); }; walk(doc, 0, 0, ''); return out;}
export function findBlock(doc: PMNode, id: string): BlockInfo | undefined { return blocksOf(doc).find((b) => b.id === id);}
/** A section around a position: the node, where it starts, its number and its word target. */export type SectionAt = { id: string; node: PMNode; pos: number; depth: number; number: string; title: string; target: number | null };
/** The sections a position sits in, outermost first (none when it is not inside any). */export function sectionsAround(doc: PMNode, pos: number): SectionAt[] { const $pos = doc.resolve(Math.max(0, Math.min(pos, doc.content.size))); const out: SectionAt[] = []; const path: number[] = []; for (let d = 1; d <= $pos.depth; d++) { const node = $pos.node(d); if (node.type.name !== 'section') continue; const parent = $pos.node(d - 1); const idx = $pos.index(d - 1); let n = 0; for (let i = 0; i < idx; i++) if (parent.child(i).type.name === 'section') n++; path.push(n + 1); const target = Number(node.attrs.target); out.push({ id: String(node.attrs.id ?? ''), node, pos: $pos.before(d), depth: path.length - 1, number: path.join('.'), title: node.firstChild?.textContent ?? '', target: target > 0 ? target : null }); } return out;}
/** The innermost section around a position that has a word target, if any. */export function targetedSectionAt(doc: PMNode, pos: number): SectionAt | null { const around = sectionsAround(doc, pos); for (let i = around.length - 1; i >= 0; i--) if (around[i]!.target) return around[i]!; return null;}
/** A block's text the way a reader would say it. *//** An outline note: a paragraph on what will be said, or a list of the points a paragraph will make. A plan, not prose. */export function isOutlineNote(node: PMNode): boolean { return (node.type.name === 'paragraph' || node.type.name === 'bulletList' || node.type.name === 'orderedList') && !!node.attrs.outline;}
export function blockText(node: PMNode): string { switch (node.type.name) { case 'blockMath': return String(node.attrs.latex ?? ''); case 'bulletList': case 'orderedList': return listLines(node, 0).join('\n'); case 'definitionList': { const lines: string[] = []; node.forEach((item) => lines.push(`${item.child(0).textContent}: ${item.child(1).textContent}`)); return lines.join('\n'); } default: return node.textContent; }}
function listLines(list: PMNode, indent: number): string[] { const lines: string[] = []; const ordered = list.type.name === 'orderedList'; list.forEach((item, _o, i) => { const bullet = ordered ? `${i + 1}.` : '-'; lines.push(`${' '.repeat(indent)}${bullet} ${item.firstChild?.textContent ?? ''}`); item.forEach((c) => { if (c.type.name === 'bulletList' || c.type.name === 'orderedList') lines.push(...listLines(c, indent + 1)); }); }); return lines;}
/** Terms defined in the document (dfn marks), for the "@" menu. */export function dfnsIn(doc: PMNode): { id: string; text: string }[] { const out = new Map<string, { id: string; text: string }>(); let run = ''; let runId: string | null | undefined; const flush = () => { if (run.trim()) { const id = runId ?? `dfn-${slugify(run.trim())}`; if (!out.has(id)) out.set(id, { id, text: run.trim() }); } run = ''; runId = undefined; }; doc.descendants((node) => { if (!node.isText) { flush(); return true; } const m = node.marks.find((x) => x.type.name === 'dfn'); if (m) { const id = (m.attrs.id as string | null) ?? null; if (run && runId !== id) flush(); runId = id; run += node.text ?? ''; } else flush(); return true; }); flush(); return [...out.values()];}
/** References cited in the document (ref marks), for the "[" menu. */export function refsIn(doc: PMNode): { key: string; title?: string; uri?: string }[] { const out = new Map<string, { key: string; title?: string; uri?: string }>(); doc.descendants((node) => { if (!node.isText) return true; const m = node.marks.find((x) => x.type.name === 'ref'); if (m && typeof m.attrs.key === 'string' && m.attrs.key && !out.has(m.attrs.key)) { const r: { key: string; title?: string; uri?: string } = { key: m.attrs.key }; if (m.attrs.title) r.title = String(m.attrs.title); if (m.attrs.uri) r.uri = String(m.attrs.uri); out.set(r.key, r); } return true; }); return [...out.values()];}
/** A section with an empty title and one empty, untyped block. */export function emptySectionNode(id: string, blockId: string, title = ''): PMJson { return { type: 'section', attrs: { id, anchor: slugify(title, 'section'), anchorTouched: false }, content: [ { type: 'sectionTitle', ...(title ? { content: [{ type: 'text', text: title }] } : {}) }, { type: 'paragraph', attrs: { id: blockId } }, ], };}
/** * A section holds at least one block before its subsections (see the * schema). A document made elsewhere may not: left as it is, the editor * mangles it the first time it reads its DOM back (an empty paragraph and an * empty section appear). Such a section gets an empty paragraph after its * title instead. The same object comes back when nothing needed doing. */export function repairBody(json: PMJson, newId: () => string): PMJson { let changed = false; const fix = (n: PMJson): PMJson => { if (!Array.isArray(n.content)) return n; const content = n.content.map(fix); if (n.type === 'section' && (content.length < 2 || content[1]!.type === 'section')) { content.splice(1, 0, { type: 'paragraph', attrs: { id: newId() } }); changed = true; } return changed ? { ...n, content } : n; }; const out = fix(json); return changed ? out : json;}