MarkdownRenderer.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace App\Services\Markup\Render;
  3. use App\Services\Markup\Annotation\AnnotationToken;
  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. use App\Services\Markup\Parsing\Placeholder;
  10. /**
  11. * 展开模板后的 markdown(导出用)。
  12. *
  13. * markdown 本身原样保留:拿预扫描后的源码,把每个占位符换成模板的 markdown() 输出;
  14. * 脚注变成 `[^n]`,脚注正文在文末(footnote 选项打开时)。站内附件地址补上站点地址。
  15. */
  16. final class MarkdownRenderer implements Renderer
  17. {
  18. public function document(Document $document, RenderContext $ctx): string
  19. {
  20. if ($document->source === '') {
  21. return $this->fromNodes($document->nodes, $ctx);
  22. }
  23. $markdown = (string) preg_replace_callback(
  24. Placeholder::PATTERN,
  25. function (array $m) use ($document, $ctx) {
  26. $call = $document->calls[(int) $m[1]] ?? null;
  27. return $call === null ? '' : $call->template->markdown($call, $ctx);
  28. },
  29. $document->source,
  30. );
  31. // 批注占位符:点标记换成模板的 markdown(脚注 → [^n]),区间边界去掉
  32. $markdown = (string) preg_replace_callback(
  33. AnnotationToken::PATTERN,
  34. function (array $m) use ($document, $ctx) {
  35. $call = $document->annotationCalls[(int) $m[1]] ?? null;
  36. return $call === null ? '' : $call->template->markdown($call, $ctx);
  37. },
  38. $markdown,
  39. );
  40. return str_replace('](/attachments/', ']('.rtrim((string) config('app.url'), '/').'/attachments/', $markdown);
  41. }
  42. /**
  43. * 没有源码的内容(IR 构建时生成的,如 toggle 的内容):只取文字与模板。
  44. *
  45. * @param list<Node> $nodes
  46. */
  47. private function fromNodes(array $nodes, RenderContext $ctx): string
  48. {
  49. $markdown = '';
  50. foreach ($nodes as $node) {
  51. $markdown .= match (true) {
  52. $node instanceof Text => $node->value,
  53. $node instanceof Call => $node->template->markdown($node, $ctx),
  54. $node instanceof Element => $this->fromNodes($node->children, $ctx),
  55. default => '',
  56. };
  57. }
  58. return $markdown;
  59. }
  60. public function footnotes(RenderContext $ctx): string
  61. {
  62. if ($ctx->footnotes === []) {
  63. return '';
  64. }
  65. $lines = array_map(fn (array $note) => '[^'.$note['sn'].']: '.$note['content'], $ctx->footnotes);
  66. return "\n\n".implode("\n\n", $lines);
  67. }
  68. }