TextRenderer.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace App\Services\Markup\Render;
  3. use App\Services\Markup\Format;
  4. use App\Services\Markup\Ir\Call;
  5. use App\Services\Markup\Ir\Document;
  6. use App\Services\Markup\Ir\Element;
  7. use App\Services\Markup\Ir\Node;
  8. use App\Services\Markup\Ir\Text;
  9. /**
  10. * IR → 纯文本(text / simple / prompt)。块与块之间换行,模板由各模板的 plain() 给出。
  11. */
  12. final class TextRenderer implements Renderer
  13. {
  14. private const BLOCKS = [
  15. 'p', 'div', 'blockquote', 'pre', 'ul', 'ol', 'li', 'table', 'thead', 'tbody', 'tr',
  16. 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'dl', 'dt', 'dd', 'figure', 'details', 'summary',
  17. ];
  18. public function __construct(private readonly Format $format) {}
  19. public function document(Document $document, RenderContext $ctx): string
  20. {
  21. if ($document->inline) {
  22. return $this->nodes($document->nodes, $ctx);
  23. }
  24. // 块级内容逐块换行(块级模板如 mermaid 自己不带换行)
  25. $text = '';
  26. foreach ($document->nodes as $node) {
  27. $text .= rtrim($this->nodes([$node], $ctx), "\n")."\n";
  28. }
  29. return rtrim($text, "\n");
  30. }
  31. /**
  32. * @param list<Node> $nodes
  33. */
  34. private function nodes(array $nodes, RenderContext $ctx): string
  35. {
  36. $text = '';
  37. foreach ($nodes as $node) {
  38. if ($node instanceof Text) {
  39. $text .= $node->value;
  40. } elseif ($node instanceof Call) {
  41. $text .= $node->template->plain($node, $ctx, $this->format);
  42. } elseif ($node instanceof Element) {
  43. $text .= $this->element($node, $ctx);
  44. }
  45. }
  46. return $text;
  47. }
  48. private function element(Element $element, RenderContext $ctx): string
  49. {
  50. if ($element->tag === 'br') {
  51. return "\n";
  52. }
  53. if ($element->tag === 'img') {
  54. return $element->attrs['alt'] ?? '';
  55. }
  56. $inner = $this->nodes($element->children, $ctx);
  57. if ($element->tag === 'td' || $element->tag === 'th') {
  58. return $inner."\t";
  59. }
  60. return in_array($element->tag, self::BLOCKS, true) ? rtrim($inner, "\n")."\n" : $inner;
  61. }
  62. }