OwnsBlockTitle.php 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. namespace App\Services\Markup\Templates\Concerns;
  3. use App\Services\Markup\Ir\Call;
  4. use App\Services\Markup\Ir\Element;
  5. use App\Services\Markup\Ir\Node;
  6. use App\Services\Markup\Ir\Text;
  7. use App\Services\Markup\Render\RenderContext;
  8. /**
  9. * 自带标题的块级模板(目录 {{toc}}、参考文献 {{ref}})的标题规则:
  10. *
  11. * - 标题不是 `<h2>`,不算正文的一节;文字随内容语言(labels.*)
  12. * - `title=文字` 改文字,`title=`(空)不显示
  13. * - 紧挨在前面已经有手写标题(如「## 参考文献」+ `{{ref}}`)时不显示,免得出现两个标题;旧写法不用改
  14. */
  15. trait OwnsBlockTitle
  16. {
  17. /**
  18. * @param string $label 语言文件里的键,如 labels.toc
  19. */
  20. protected function blockTitle(Call $call, RenderContext $ctx, string $label): string
  21. {
  22. if (array_key_exists('title', $call->params->named)) {
  23. return trim($call->params->named['title']);
  24. }
  25. if ($this->precededByHeading($call, $ctx)) {
  26. return '';
  27. }
  28. // 语言目录与 channel 的语言代码同名(zh-Hans、en…),没有对应文件时回退 en
  29. return (string) __($label, [], $ctx->lang($call->scope));
  30. }
  31. /**
  32. * 模板是否紧跟在一个标题后面:它是所在段落的第一个内容,且这个段落(或它自己)的前一个块是标题。
  33. */
  34. protected function precededByHeading(Call $call, RenderContext $ctx): bool
  35. {
  36. return $ctx->document !== null && $this->findPreceded($ctx->document->nodes, $call) === true;
  37. }
  38. /**
  39. * @param list<Node> $nodes
  40. * @return bool|null null 表示这一层里没找到
  41. */
  42. private function findPreceded(array $nodes, Call $call): ?bool
  43. {
  44. $previous = null;
  45. foreach ($nodes as $node) {
  46. if ($node instanceof Text && trim($node->value) === '') {
  47. continue;
  48. }
  49. if ($node === $call) {
  50. return self::isHeading($previous);
  51. }
  52. if ($node instanceof Element) {
  53. if ($node->tag === 'p' && self::firstContent($node->children) === $call) {
  54. return self::isHeading($previous);
  55. }
  56. $found = $this->findPreceded($node->children, $call);
  57. if ($found !== null) {
  58. return $found;
  59. }
  60. }
  61. $previous = $node;
  62. }
  63. return null;
  64. }
  65. /**
  66. * @param list<Node> $nodes
  67. */
  68. private static function firstContent(array $nodes): ?Node
  69. {
  70. foreach ($nodes as $node) {
  71. if (! ($node instanceof Text && trim($node->value) === '')) {
  72. return $node;
  73. }
  74. }
  75. return null;
  76. }
  77. private static function isHeading(?Node $node): bool
  78. {
  79. return $node instanceof Element && preg_match('/^h[1-6]$/', $node->tag) === 1;
  80. }
  81. }