TocTemplate.php 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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\Ir\Document;
  6. use App\Services\Markup\Ir\Element;
  7. use App\Services\Markup\Ir\Node;
  8. use App\Services\Markup\Render\HtmlRenderer;
  9. use App\Services\Markup\Render\RenderContext;
  10. use App\Services\Markup\Templates\Concerns\OwnsBlockTitle;
  11. /**
  12. * 目录:`{{toc}}`,从本篇内容的标题自动生成,每项链接到对应标题(`#h-…`,IR 构建时生成的稳定 id)。
  13. *
  14. * - 层级:缺省收二、三级标题;`{{toc|2-4}}`、`{{toc|2}}` 指定
  15. * - 标题:目录自带一行标题,规则见 {@see OwnsBlockTitle}(labels.toc;`title=` 改文字或隐藏;
  16. * 紧跟在手写标题后面时不显示)
  17. * - 兼容旧写法:紧挨在 `{{toc}}` 前面的标题(手写的「## 目录」)不进目录
  18. * - 遍历整篇内容,写在哪里都能列全;标题里的术语、格式在目录里照常显示
  19. *
  20. * tree:`{name: 'toc', props: {title}, children: [ul]}`;html:`<nav class="toc">`。
  21. */
  22. final class TocTemplate extends Template
  23. {
  24. use OwnsBlockTitle;
  25. protected string $component = 'toc';
  26. public function block(): bool
  27. {
  28. return true;
  29. }
  30. public function params(): array
  31. {
  32. return ['levels' => ParamSpec::at(1, '2-3'), 'title' => new ParamSpec];
  33. }
  34. /**
  35. * @return array{0: int, 1: int}
  36. */
  37. private function levels(Call $call): array
  38. {
  39. if (preg_match('/^\s*([1-6])\s*(?:-\s*([1-6]))?\s*$/', (string) $call->param('levels'), $m) !== 1) {
  40. return [2, 3];
  41. }
  42. $from = (int) $m[1];
  43. $to = isset($m[2]) && $m[2] !== '' ? (int) $m[2] : $from;
  44. return [min($from, $to), max($from, $to)];
  45. }
  46. private function title(Call $call, RenderContext $ctx): string
  47. {
  48. return $this->blockTitle($call, $ctx, 'labels.toc');
  49. }
  50. /**
  51. * 本篇内容里要进目录的标题(文档顺序)。
  52. *
  53. * @return list<array{level: int, id: string, nodes: list<Node>}>
  54. */
  55. private function headings(Call $call, RenderContext $ctx): array
  56. {
  57. if ($ctx->document === null) {
  58. return [];
  59. }
  60. [$from, $to] = $this->levels($call);
  61. $all = [];
  62. $skip = null;
  63. $this->walk($ctx->document->nodes, $call, $all, $skip);
  64. return array_values(array_filter(
  65. $all,
  66. fn (array $heading, int $index) => $index !== $skip && $heading['level'] >= $from && $heading['level'] <= $to,
  67. ARRAY_FILTER_USE_BOTH,
  68. ));
  69. }
  70. /**
  71. * @param list<Node> $nodes
  72. * @param list<array{level: int, id: string, nodes: list<Node>}> $all
  73. */
  74. private function walk(array $nodes, Call $self, array &$all, ?int &$skip): void
  75. {
  76. foreach ($nodes as $node) {
  77. if ($node === $self) {
  78. // 紧挨在目录前面的标题(手写的「## 目录」)不进目录
  79. $skip = $all === [] ? null : count($all) - 1;
  80. continue;
  81. }
  82. if (! $node instanceof Element) {
  83. continue;
  84. }
  85. if (preg_match('/^h([1-6])$/', $node->tag, $m) === 1 && isset($node->attrs['id'])) {
  86. $all[] = ['level' => (int) $m[1], 'id' => $node->attrs['id'], 'nodes' => $node->children];
  87. continue;
  88. }
  89. $this->walk($node->children, $self, $all, $skip);
  90. }
  91. }
  92. /**
  93. * 按层级嵌套的 `ul > li > a`。
  94. *
  95. * @param list<array{level: int, id: string, nodes: list<Node>}> $headings
  96. */
  97. private function tree(array $headings): ?Element
  98. {
  99. if ($headings === []) {
  100. return null;
  101. }
  102. $root = new Element('ul');
  103. /** @var list<array{level: int, list: Element}> $stack */
  104. $stack = [['level' => min(array_column($headings, 'level')), 'list' => $root]];
  105. foreach ($headings as $heading) {
  106. while ($heading['level'] < end($stack)['level'] && count($stack) > 1) {
  107. array_pop($stack);
  108. }
  109. while ($heading['level'] > end($stack)['level']) {
  110. $list = end($stack)['list'];
  111. $parent = end($list->children);
  112. if (! $parent instanceof Element) {
  113. $parent = new Element('li');
  114. $list->children[] = $parent;
  115. }
  116. $nested = new Element('ul');
  117. $parent->children[] = $nested;
  118. $stack[] = ['level' => end($stack)['level'] + 1, 'list' => $nested];
  119. }
  120. end($stack)['list']->children[] = new Element('li', [], [
  121. new Element('a', ['href' => '#'.$heading['id']], $heading['nodes']),
  122. ]);
  123. }
  124. return $root;
  125. }
  126. /**
  127. * @return array<string, mixed>
  128. */
  129. public function props(Call $call, RenderContext $ctx): array
  130. {
  131. $title = $this->title($call, $ctx);
  132. return $title === '' ? [] : ['title' => $title];
  133. }
  134. public function children(Call $call, RenderContext $ctx): ?Document
  135. {
  136. $list = $this->tree($this->headings($call, $ctx));
  137. return $list === null ? null : new Document([$list], false, '', [], $call->scope);
  138. }
  139. public function html(Call $call, RenderContext $ctx): string
  140. {
  141. $list = $this->tree($this->headings($call, $ctx));
  142. if ($list === null || ! $ctx->renderer instanceof HtmlRenderer) {
  143. return '';
  144. }
  145. $title = $this->title($call, $ctx);
  146. return '<nav class="toc">'
  147. .($title === '' ? '' : '<div class="toc-title">'.e($title).'</div>')
  148. .$ctx->renderer->nodes([$list], $ctx)
  149. .'</nav>';
  150. }
  151. /**
  152. * 纯文本:标题一行,下面按层级缩进列出。
  153. */
  154. public function plain(Call $call, RenderContext $ctx, Format $format): string
  155. {
  156. return $this->lines($call, $ctx, fn (string $text, string $id) => $text);
  157. }
  158. public function text(Call $call, RenderContext $ctx): string
  159. {
  160. return $this->plain($call, $ctx, Format::Text);
  161. }
  162. /**
  163. * markdown:`- [标题](#id)` 列表。
  164. */
  165. public function markdown(Call $call, RenderContext $ctx): string
  166. {
  167. return $this->lines($call, $ctx, fn (string $text, string $id) => "- [{$text}](#{$id})");
  168. }
  169. /**
  170. * @param callable(string, string): string $line
  171. */
  172. private function lines(Call $call, RenderContext $ctx, callable $line): string
  173. {
  174. $headings = $this->headings($call, $ctx);
  175. if ($headings === []) {
  176. return '';
  177. }
  178. $top = min(array_column($headings, 'level'));
  179. $title = $this->title($call, $ctx);
  180. $out = $title === '' ? [] : [$title];
  181. foreach ($headings as $heading) {
  182. $text = trim($ctx->renderString(new Document($heading['nodes'], true, '', [], $call->scope, fragment: true)));
  183. $out[] = str_repeat(' ', $heading['level'] - $top).$line($text, $heading['id']);
  184. }
  185. return implode("\n", $out)."\n";
  186. }
  187. }