Skip to content

Plain text

phil/ujo

PlainText::convert($document) gives the text of a document — for a search index, an excerpt, an e-mail, a summary read aloud —: each block's text without HTML, decoded, blocks separated by a blank line, empty ones left out.

TypeText
paragraph, header, alert, runningFooter, footnote, rawthe text
banner, watermark, code, mermaid, maththe plain value
quote, credit, personalitythe parts joined by —
warningtitle and message
delimiter***
listone item per line, -, 1. or [x]/[ ], two spaces per level
definitionListeach term, then its definitions indented
tableone row per line, cells separated by `
indexthe title, then term, pages, two spaces per level
image, embed, gallerythe captions; an image without one, its alt
linkToolthe title and the address
attachesthe title, or the file's name
buttonthe text and the address in parentheses
toggle, note, descriptivethe title, then the nested blocks
wide, columnFlow, container, columnsthe nested blocks
statblockname, subtitle, then each section: title, label: value, abilities, nested blocks
page markers, decorations, chart, qrCode, toc, and any unknown typenothing

with() replaces the conversion of a type, or adds one:

$text = new PlainText()->with('callout', static fn (Block $block, PlainText $text): string => $text->text($block->data['text'] ?? null));

passages($document, $language) gives the text by language, for a search index that reads each passage with the analyser of its language: each block at the top of the document goes to the language its language tune names, in lower case, or to the language given for the document; inline passages (<span lang>) stay with their block. The languages come in the order of their first block, and a language whose blocks give no text is left out.

foreach (new PlainText()->passages($document, 'fr') as $language => $text) {
    $fields['body_'.str_replace('-', '_', $language)] = $text; // body_fr, body_en_ca…
}

The conversion receives the converter, whose text() strips HTML and whose blocks() converts nested blocks. Ujo::toText() normalizes the document first.