Jelajahi Sumber

✨ (api-v13): 目录模板 {{toc}},从正文标题自动生成

- 收本篇内容的二、三级标题({{toc|2-4}} / {{toc|2}} 指定层级),按层级嵌套,每项链接到标题 id;
  标题里的术语、格式在目录里照常显示;遍历整篇内容,写在哪里都能列全
- 目录自带一行标题(不是 <h2>,不算正文的一节),文字随内容语言(labels.toc:目录 / 目錄 / Contents),
  {{toc|title=…}} 改文字、{{toc|title=}} 不显示;紧挨在前面的手写「## 目录」不进目录,旧写法照样可用
- 输出:tree 为 toc 节点(children 是 ul > li > a),dashboard-v6 渲染成 nav;html 为 <nav class="toc">;
  纯文本为缩进列表;markdown 为 - [标题](#id)
- html:段落里只有块级模板(目录、mermaid)时不包 <p>(模板基类加 block()),避免 <p><nav> 被浏览器提前闭合

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
visuddhinanda 7 jam lalu
induk
melakukan
67046d75ea

+ 23 - 0
api-v13/app/Services/Markup/Render/HtmlRenderer.php

@@ -93,10 +93,33 @@ final class HtmlRenderer implements Renderer
         if (in_array($element->tag, [...HtmlPolicy::VOID, 'input'], true)) {
             return "<{$element->tag}{$attrs} />";
         }
+        // 段落里只有块级模板(目录、mermaid):不包 <p>,否则 <p><nav> 会被浏览器提前闭合
+        if ($element->tag === 'p' && $this->onlyBlockTemplates($element->children)) {
+            return $this->nodes($element->children, $ctx);
+        }
 
         return "<{$element->tag}{$attrs}>".$this->nodes($element->children, $ctx)."</{$element->tag}>";
     }
 
+    /**
+     * @param  list<Node>  $nodes
+     */
+    private function onlyBlockTemplates(array $nodes): bool
+    {
+        $found = false;
+        foreach ($nodes as $node) {
+            if ($node instanceof Text && trim($node->value) === '') {
+                continue;
+            }
+            if (! $node instanceof Call || ! $node->template->block()) {
+                return false;
+            }
+            $found = true;
+        }
+
+        return $found;
+    }
+
     /**
      * 文末的脚注列表(footnote 选项打开时)。
      */

+ 5 - 0
api-v13/app/Services/Markup/Templates/MermaidTemplate.php

@@ -15,6 +15,11 @@ final class MermaidTemplate extends Template
 {
     protected string $component = 'mermaid';
 
+    public function block(): bool
+    {
+        return true;
+    }
+
     public function params(): array
     {
         return ['text' => ParamSpec::at(1)];

+ 8 - 0
api-v13/app/Services/Markup/Templates/Template.php

@@ -69,6 +69,14 @@ abstract class Template
 
     public function collect(Call $call, Resolver $resolver): void {}
 
+    /**
+     * html 输出是块级元素(目录的 nav、mermaid 的 pre):段落里只有它时不包 `<p>`。
+     */
+    public function block(): bool
+    {
+        return false;
+    }
+
     /**
      * 这次调用引用到的经文段落(`{{ref}}` 据此列参考文献)。只从参数里解析,不查库。
      *

+ 1 - 0
api-v13/app/Services/Markup/Templates/TemplateRegistry.php

@@ -31,6 +31,7 @@ final class TemplateRegistry
         'category' => CategoryTemplate::class,
         'quality' => QualityTemplate::class,
         'toggle' => ToggleTemplate::class,
+        'toc' => TocTemplate::class,
     ];
 
     /**

+ 219 - 0
api-v13/app/Services/Markup/Templates/TocTemplate.php

@@ -0,0 +1,219 @@
+<?php
+
+namespace App\Services\Markup\Templates;
+
+use App\Services\Markup\Format;
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Ir\Document;
+use App\Services\Markup\Ir\Element;
+use App\Services\Markup\Ir\Node;
+use App\Services\Markup\Render\HtmlRenderer;
+use App\Services\Markup\Render\RenderContext;
+
+/**
+ * 目录:`{{toc}}`,从本篇内容的标题自动生成,每项链接到对应标题(`#h-…`,IR 构建时生成的稳定 id)。
+ *
+ * - 层级:缺省收二、三级标题;`{{toc|2-4}}`、`{{toc|2}}` 指定
+ * - 标题:目录自带一行标题(不是 `<h2>`,不算正文的一节),文字随内容语言(labels.toc);
+ *   `{{toc|title=本条目录}}` 改文字,`{{toc|title=}}` 不显示
+ * - 兼容旧写法:紧挨在 `{{toc}}` 前面的标题(手写的「## 目录」)不进目录
+ * - 遍历整篇内容,写在哪里都能列全;标题里的术语、格式在目录里照常显示
+ *
+ * tree:`{name: 'toc', props: {title}, children: [ul]}`;html:`<nav class="toc">`。
+ */
+final class TocTemplate extends Template
+{
+    protected string $component = 'toc';
+
+    public function block(): bool
+    {
+        return true;
+    }
+
+    public function params(): array
+    {
+        return ['levels' => ParamSpec::at(1, '2-3'), 'title' => new ParamSpec];
+    }
+
+    /**
+     * @return array{0: int, 1: int}
+     */
+    private function levels(Call $call): array
+    {
+        if (preg_match('/^\s*([1-6])\s*(?:-\s*([1-6]))?\s*$/', (string) $call->param('levels'), $m) !== 1) {
+            return [2, 3];
+        }
+        $from = (int) $m[1];
+        $to = isset($m[2]) && $m[2] !== '' ? (int) $m[2] : $from;
+
+        return [min($from, $to), max($from, $to)];
+    }
+
+    /**
+     * 目录标题;写了 `title=`(哪怕为空)就用写的,否则按内容语言取默认文字。
+     */
+    private function title(Call $call, RenderContext $ctx): string
+    {
+        if (array_key_exists('title', $call->params->named)) {
+            return trim($call->params->named['title']);
+        }
+
+        // 语言目录与 channel 的语言代码同名(zh-Hans、en…),没有对应文件时回退 en
+        return (string) __('labels.toc', [], $ctx->lang($call->scope));
+    }
+
+    /**
+     * 本篇内容里要进目录的标题(文档顺序)。
+     *
+     * @return list<array{level: int, id: string, nodes: list<Node>}>
+     */
+    private function headings(Call $call, RenderContext $ctx): array
+    {
+        if ($ctx->document === null) {
+            return [];
+        }
+        [$from, $to] = $this->levels($call);
+        $all = [];
+        $skip = null;
+        $this->walk($ctx->document->nodes, $call, $all, $skip);
+
+        return array_values(array_filter(
+            $all,
+            fn (array $heading, int $index) => $index !== $skip && $heading['level'] >= $from && $heading['level'] <= $to,
+            ARRAY_FILTER_USE_BOTH,
+        ));
+    }
+
+    /**
+     * @param  list<Node>  $nodes
+     * @param  list<array{level: int, id: string, nodes: list<Node>}>  $all
+     */
+    private function walk(array $nodes, Call $self, array &$all, ?int &$skip): void
+    {
+        foreach ($nodes as $node) {
+            if ($node === $self) {
+                // 紧挨在目录前面的标题(手写的「## 目录」)不进目录
+                $skip = $all === [] ? null : count($all) - 1;
+
+                continue;
+            }
+            if (! $node instanceof Element) {
+                continue;
+            }
+            if (preg_match('/^h([1-6])$/', $node->tag, $m) === 1 && isset($node->attrs['id'])) {
+                $all[] = ['level' => (int) $m[1], 'id' => $node->attrs['id'], 'nodes' => $node->children];
+
+                continue;
+            }
+            $this->walk($node->children, $self, $all, $skip);
+        }
+    }
+
+    /**
+     * 按层级嵌套的 `ul > li > a`。
+     *
+     * @param  list<array{level: int, id: string, nodes: list<Node>}>  $headings
+     */
+    private function tree(array $headings): ?Element
+    {
+        if ($headings === []) {
+            return null;
+        }
+        $root = new Element('ul');
+        /** @var list<array{level: int, list: Element}> $stack */
+        $stack = [['level' => min(array_column($headings, 'level')), 'list' => $root]];
+        foreach ($headings as $heading) {
+            while ($heading['level'] < end($stack)['level'] && count($stack) > 1) {
+                array_pop($stack);
+            }
+            while ($heading['level'] > end($stack)['level']) {
+                $list = end($stack)['list'];
+                $parent = end($list->children);
+                if (! $parent instanceof Element) {
+                    $parent = new Element('li');
+                    $list->children[] = $parent;
+                }
+                $nested = new Element('ul');
+                $parent->children[] = $nested;
+                $stack[] = ['level' => end($stack)['level'] + 1, 'list' => $nested];
+            }
+            end($stack)['list']->children[] = new Element('li', [], [
+                new Element('a', ['href' => '#'.$heading['id']], $heading['nodes']),
+            ]);
+        }
+
+        return $root;
+    }
+
+    /**
+     * @return array<string, mixed>
+     */
+    public function props(Call $call, RenderContext $ctx): array
+    {
+        $title = $this->title($call, $ctx);
+
+        return $title === '' ? [] : ['title' => $title];
+    }
+
+    public function children(Call $call, RenderContext $ctx): ?Document
+    {
+        $list = $this->tree($this->headings($call, $ctx));
+
+        return $list === null ? null : new Document([$list], false, '', [], $call->scope);
+    }
+
+    public function html(Call $call, RenderContext $ctx): string
+    {
+        $list = $this->tree($this->headings($call, $ctx));
+        if ($list === null || ! $ctx->renderer instanceof HtmlRenderer) {
+            return '';
+        }
+        $title = $this->title($call, $ctx);
+
+        return '<nav class="toc">'
+            .($title === '' ? '' : '<div class="toc-title">'.e($title).'</div>')
+            .$ctx->renderer->nodes([$list], $ctx)
+            .'</nav>';
+    }
+
+    /**
+     * 纯文本:标题一行,下面按层级缩进列出。
+     */
+    public function plain(Call $call, RenderContext $ctx, Format $format): string
+    {
+        return $this->lines($call, $ctx, fn (string $text, string $id) => $text);
+    }
+
+    public function text(Call $call, RenderContext $ctx): string
+    {
+        return $this->plain($call, $ctx, Format::Text);
+    }
+
+    /**
+     * markdown:`- [标题](#id)` 列表。
+     */
+    public function markdown(Call $call, RenderContext $ctx): string
+    {
+        return $this->lines($call, $ctx, fn (string $text, string $id) => "- [{$text}](#{$id})");
+    }
+
+    /**
+     * @param  callable(string, string): string  $line
+     */
+    private function lines(Call $call, RenderContext $ctx, callable $line): string
+    {
+        $headings = $this->headings($call, $ctx);
+        if ($headings === []) {
+            return '';
+        }
+        $top = min(array_column($headings, 'level'));
+        $title = $this->title($call, $ctx);
+        $out = $title === '' ? [] : [$title];
+        foreach ($headings as $heading) {
+            $text = trim($ctx->renderString(new Document($heading['nodes'], true, '', [], $call->scope, fragment: true)));
+            $out[] = str_repeat('  ', $heading['level'] - $top).$line($text, $heading['id']);
+        }
+
+        return implode("\n", $out)."\n";
+    }
+}

+ 1 - 0
api-v13/resources/lang/en/labels.php

@@ -7,6 +7,7 @@ return [
     'nissaya' => 'Nissaya',
     'commentary' => 'Commentary',
     'similar' => 'Parallels',
+    'toc' => 'Contents',
 
     'script_convertor' => 'Pāli Script Converter',
     'input_script' => 'Input Script',

+ 1 - 0
api-v13/resources/lang/zh-Hans/labels.php

@@ -7,6 +7,7 @@ return [
     'nissaya' => '缅文逐词',
     'commentary' => '义注',
     'similar' => '相似段落',
+    'toc' => '目录',
 
     'script_convertor' => '巴利文字转换器',
     'input_script' => '输入文字',

+ 1 - 0
api-v13/resources/lang/zh-Hant/labels.php

@@ -1,5 +1,6 @@
 <?php
 return [
+    'toc' => '目錄',
     'home' => '首页',
     'translation' => '譯文',
     'original' => '原文',

+ 83 - 0
api-v13/tests/Feature/MarkupSyntaxTest.php

@@ -603,3 +603,86 @@ describe('emphasis next to CJK punctuation (markdown-cjk-friendly)', function ()
         }
     });
 });
+
+describe('toc', function () {
+    $source = "{{toc}}\n\n# 一级\n\n## 甲 [[dhamma]]\n\n### 甲一\n\n#### 甲一a\n\n## 乙\n\n正文";
+
+    /** 树里的目录节点 */
+    $toc = function (array $tree): array {
+        foreach ($tree as $node) {
+            if (($node['name'] ?? null) === 'toc') {
+                return $node;
+            }
+            foreach ($node['children'] ?? [] as $child) {
+                if (($child['name'] ?? null) === 'toc') {
+                    return $child;
+                }
+            }
+        }
+
+        return [];
+    };
+
+    /** 列表 → [[层级, 链接 href, 文字], …] */
+    $items = function (array $list, int $depth = 1) use (&$items): array {
+        $out = [];
+        foreach ($list['children'] as $li) {
+            foreach ($li['children'] as $child) {
+                if ($child['tag'] === 'a') {
+                    $out[] = [$depth, $child['attrs']['href'], markupText($child['children'])];
+                } elseif ($child['tag'] === 'ul') {
+                    array_push($out, ...$items($child, $depth + 1));
+                }
+            }
+        }
+
+        return $out;
+    };
+
+    it('lists h2 and h3 by default, nested, linking to the heading ids', function () use ($source, $toc, $items) {
+        $tree = markupTree($source);
+        $node = $toc($tree);
+        expect($node['props'])->toBe(['title' => '目录']);
+
+        $h2 = collect($tree)->where('tag', 'h2')->values();
+        expect($items($node['children'][0]))->toBe([
+            [1, '#'.$h2[0]['attrs']['id'], '甲 dhamma'],
+            [2, '#'.collect($tree)->firstWhere('tag', 'h3')['attrs']['id'], '甲一'],
+            [1, '#'.$h2[1]['attrs']['id'], '乙'],
+        ]);
+    });
+
+    it('keeps templates inside heading text', function () use ($source, $toc) {
+        $link = $toc(markupTree($source))['children'][0]['children'][0]['children'][0];
+        expect(collect($link['children'])->firstWhere('name', 'term')['props']['word'])->toBe('dhamma');
+    });
+
+    it('skips a hand-written heading right before it', function () use ($toc, $items) {
+        $tree = markupTree("## 目录\n\n{{toc}}\n\n## 甲\n\n## 乙");
+        expect(array_column($items($toc($tree)['children'][0]), 2))->toBe(['甲', '乙']);
+    });
+
+    it('accepts a level range or a single level', function () use ($source, $toc, $items) {
+        expect(array_column($items($toc(markupTree(str_replace('{{toc}}', '{{toc|2-4}}', $source)))['children'][0]), 2))
+            ->toBe(['甲 dhamma', '甲一', '甲一a', '乙']);
+        expect(array_column($items($toc(markupTree(str_replace('{{toc}}', '{{toc|2}}', $source)))['children'][0]), 2))
+            ->toBe(['甲 dhamma', '乙']);
+    });
+
+    it('takes a custom title, or none', function () use ($source, $toc) {
+        expect($toc(markupTree(str_replace('{{toc}}', '{{toc|title=本条目录}}', $source)))['props'])->toBe(['title' => '本条目录']);
+        expect($toc(markupTree(str_replace('{{toc}}', '{{toc|title=}}', $source)))['props'])->toBe([]);
+    });
+
+    it('renders html, text and markdown', function () use ($source) {
+        expect(markupRender($source, Format::Html))
+            ->toMatch('/^<nav class="toc"><div class="toc-title">目录<\/div><ul><li><a href="#(h-[0-9a-f]{8}-2)">甲 .*<\/a><ul><li><a href="#h-[0-9a-f]{8}-3">甲一<\/a><\/li><\/ul><\/li><li><a href="#h-[0-9a-f]{8}-5">乙<\/a><\/li><\/ul><\/nav><h1 id="h-[0-9a-f]{8}-1">一级<\/h1><h2 id="\1">/');
+        expect(markupRender($source, Format::Text))->toStartWith("目录\n甲 dhamma\n  甲一\n乙\n");
+        expect(markupRender($source, Format::Markdown))->toMatch('/^目录\n- \[甲 dhamma\]\(#h-[0-9a-f]{8}-2\)\n  - \[甲一\]\(#h-[0-9a-f]{8}-3\)\n- \[乙\]\(#h-[0-9a-f]{8}-5\)\n/');
+    });
+
+    it('renders nothing when there are no headings', function () {
+        expect(markupTree('{{toc}} 正文')[0])->toMatchArray(['name' => 'toc', 'children' => []]);
+        expect(markupRender('{{toc}}', Format::Html))->toBe('');
+    });
+});

+ 9 - 0
dashboard-v6/src/components/markup/MarkupTemplate.tsx

@@ -56,6 +56,15 @@ const TEMPLATES: Record<string, TemplateRenderer> = {
   article: (p) => <ArticleCtl {...as<typeof ArticleCtl>(p)} />,
   category: (p) => <Tag>{p.name as string}</Tag>,
   toggle: (_, children) => <ToggleCtl>{children}</ToggleCtl>,
+  // 目录:自带一行标题(不是正文的一节),children 是链到各标题的嵌套列表
+  toc: (p, children) => (
+    <nav className="markup-toc">
+      {typeof p.title === "string" && p.title !== "" ? (
+        <Text strong>{p.title}</Text>
+      ) : null}
+      {children}
+    </nav>
+  ),
   // 用户自定义模板:正文已由后端渲染成 children
   tpl: (_, children) => <>{children}</>,
 };

+ 1 - 0
dashboard-v6/src/components/markup/render.tsx

@@ -121,6 +121,7 @@ const BLOCK_TEMPLATES = new Set([
   "reference",
   // VideoCtl 外层是 antd Space(div)
   "video",
+  "toc",
 ]);
 
 const hasBlockTemplate = (node: MarkupElementNode) =>