MermaidTemplate.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace App\Services\Markup\Templates;
  3. use App\Services\Markup\Format;
  4. use App\Services\Markup\Ir\Call;
  5. use App\Services\Markup\Render\RenderContext;
  6. /**
  7. * 图表:```mermaid 围栏(解析时转成本模板)。源码原样,不做 markdown 解析、不再 base64。
  8. *
  9. * html 输出 `<pre class="mermaid">`,由 library 页面按需加载 mermaid.js 渲染;没有 JS 时显示源码。
  10. */
  11. final class MermaidTemplate extends Template
  12. {
  13. protected string $component = 'mermaid';
  14. public function block(): bool
  15. {
  16. return true;
  17. }
  18. public function params(): array
  19. {
  20. return ['text' => ParamSpec::at(1)];
  21. }
  22. private function source(Call $call): string
  23. {
  24. return (string) $call->params->raw('text', 1);
  25. }
  26. /**
  27. * @return array<string, mixed>
  28. */
  29. public function props(Call $call, RenderContext $ctx): array
  30. {
  31. return ['text' => $this->source($call)];
  32. }
  33. public function text(Call $call, RenderContext $ctx): string
  34. {
  35. return 'mermaid';
  36. }
  37. /**
  38. * prompt 给 LLM 原文:它读得懂 mermaid,只给「mermaid」一词会丢掉图里的信息。
  39. */
  40. public function plain(Call $call, RenderContext $ctx, Format $format): string
  41. {
  42. return $format === Format::Prompt ? $this->markdown($call, $ctx) : 'mermaid';
  43. }
  44. public function html(Call $call, RenderContext $ctx): string
  45. {
  46. return '<pre class="mermaid">'.e($this->source($call)).'</pre>';
  47. }
  48. public function markdown(Call $call, RenderContext $ctx): string
  49. {
  50. return "```mermaid\n".$this->source($call)."\n```";
  51. }
  52. }