MermaidTemplate.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 params(): array
  15. {
  16. return ['text' => ParamSpec::at(1)];
  17. }
  18. private function source(Call $call): string
  19. {
  20. return (string) $call->params->raw('text', 1);
  21. }
  22. /**
  23. * @return array<string, mixed>
  24. */
  25. public function props(Call $call, RenderContext $ctx): array
  26. {
  27. return ['text' => $this->source($call)];
  28. }
  29. public function text(Call $call, RenderContext $ctx): string
  30. {
  31. return 'mermaid';
  32. }
  33. /**
  34. * prompt 给 LLM 原文:它读得懂 mermaid,只给「mermaid」一词会丢掉图里的信息。
  35. */
  36. public function plain(Call $call, RenderContext $ctx, Format $format): string
  37. {
  38. return $format === Format::Prompt ? $this->markdown($call, $ctx) : 'mermaid';
  39. }
  40. public function html(Call $call, RenderContext $ctx): string
  41. {
  42. return '<pre class="mermaid">'.e($this->source($call)).'</pre>';
  43. }
  44. public function markdown(Call $call, RenderContext $ctx): string
  45. {
  46. return "```mermaid\n".$this->source($call)."\n```";
  47. }
  48. }