TocTemplate.php 7.9 KB

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