Просмотр исходного кода

✨ (api-v13): {{ref}} 与 {{toc}} 一样自带标题

两个模板共用 Templates/Concerns/OwnsBlockTitle:
- 自带一行标题(不是 <h2>,不算正文的一节),文字随内容语言:labels.references(参考文献 / 參考文獻 / References)、
  labels.toc;title=… 改文字,title= 不显示
- 紧挨在前面已经有手写标题(「## 参考文献」+ {{ref}}、「## 目录」+ {{toc}})时不再显示,免得出现两个标题,旧内容不用改
- {{ref}} 没有任何引用时整块(含标题)都不输出
- dashboard-v6:reference 与 toc 一样在列表上方显示 props.title

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
visuddhinanda 7 часов назад
Родитель
Сommit
8ecce4a74d

+ 91 - 0
api-v13/app/Services/Markup/Templates/Concerns/OwnsBlockTitle.php

@@ -0,0 +1,91 @@
+<?php
+
+namespace App\Services\Markup\Templates\Concerns;
+
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Ir\Element;
+use App\Services\Markup\Ir\Node;
+use App\Services\Markup\Ir\Text;
+use App\Services\Markup\Render\RenderContext;
+
+/**
+ * 自带标题的块级模板(目录 {{toc}}、参考文献 {{ref}})的标题规则:
+ *
+ * - 标题不是 `<h2>`,不算正文的一节;文字随内容语言(labels.*)
+ * - `title=文字` 改文字,`title=`(空)不显示
+ * - 紧挨在前面已经有手写标题(如「## 参考文献」+ `{{ref}}`)时不显示,免得出现两个标题;旧写法不用改
+ */
+trait OwnsBlockTitle
+{
+    /**
+     * @param  string  $label  语言文件里的键,如 labels.toc
+     */
+    protected function blockTitle(Call $call, RenderContext $ctx, string $label): string
+    {
+        if (array_key_exists('title', $call->params->named)) {
+            return trim($call->params->named['title']);
+        }
+        if ($this->precededByHeading($call, $ctx)) {
+            return '';
+        }
+
+        // 语言目录与 channel 的语言代码同名(zh-Hans、en…),没有对应文件时回退 en
+        return (string) __($label, [], $ctx->lang($call->scope));
+    }
+
+    /**
+     * 模板是否紧跟在一个标题后面:它是所在段落的第一个内容,且这个段落(或它自己)的前一个块是标题。
+     */
+    protected function precededByHeading(Call $call, RenderContext $ctx): bool
+    {
+        return $ctx->document !== null && $this->findPreceded($ctx->document->nodes, $call) === true;
+    }
+
+    /**
+     * @param  list<Node>  $nodes
+     * @return bool|null null 表示这一层里没找到
+     */
+    private function findPreceded(array $nodes, Call $call): ?bool
+    {
+        $previous = null;
+        foreach ($nodes as $node) {
+            if ($node instanceof Text && trim($node->value) === '') {
+                continue;
+            }
+            if ($node === $call) {
+                return self::isHeading($previous);
+            }
+            if ($node instanceof Element) {
+                if ($node->tag === 'p' && self::firstContent($node->children) === $call) {
+                    return self::isHeading($previous);
+                }
+                $found = $this->findPreceded($node->children, $call);
+                if ($found !== null) {
+                    return $found;
+                }
+            }
+            $previous = $node;
+        }
+
+        return null;
+    }
+
+    /**
+     * @param  list<Node>  $nodes
+     */
+    private static function firstContent(array $nodes): ?Node
+    {
+        foreach ($nodes as $node) {
+            if (! ($node instanceof Text && trim($node->value) === '')) {
+                return $node;
+            }
+        }
+
+        return null;
+    }
+
+    private static function isHeading(?Node $node): bool
+    {
+        return $node instanceof Element && preg_match('/^h[1-6]$/', $node->tag) === 1;
+    }
+}

+ 34 - 5
api-v13/app/Services/Markup/Templates/ReferenceTemplate.php

@@ -8,6 +8,7 @@ use App\Services\Markup\Ir\Document;
 use App\Services\Markup\Ir\Element;
 use App\Services\Markup\Ir\Node;
 use App\Services\Markup\Render\RenderContext;
+use App\Services\Markup\Templates\Concerns\OwnsBlockTitle;
 
 /**
  * 参考文献:`{{ref}}`,列出本文引用到的巴利文献(按书名去重,按首次出现的顺序编号)。
@@ -16,13 +17,28 @@ use App\Services\Markup\Render\RenderContext;
  * 带 book + para 的 ql、章节 / 段落 article。遍历整篇内容而不是边渲染边记,所以 `{{ref}}` 写在哪里都能列全
  * (v2 只统计句子模板,且必须放在文末)。
  *
+ * 标题:自带一行标题,规则见 {@see OwnsBlockTitle}(labels.references;`title=` 改文字或隐藏;
+ * 紧跟在手写的「## 参考文献」后面时不显示)。没有任何引用时整块都不输出。
+ *
  * 一段引用对应的书名:`book_titles` 里同一本书、起始段号 ≤ 该段的最近一条(一个 book 里可能收了几部作品;
  * v2 把排在前面的作品全列了进来,且用 < 漏掉了恰好引用作品首段的情况)。
  */
 final class ReferenceTemplate extends Template
 {
+    use OwnsBlockTitle;
+
     protected string $component = 'reference';
 
+    public function params(): array
+    {
+        return ['title' => new ParamSpec];
+    }
+
+    private function title(Call $call, RenderContext $ctx): string
+    {
+        return $this->blockTitle($call, $ctx, 'labels.references');
+    }
+
     private const COPYRIGHT = 'CSCD V4 VRI 2008';
 
     /**
@@ -79,13 +95,21 @@ final class ReferenceTemplate extends Template
      */
     public function props(Call $call, RenderContext $ctx): array
     {
-        return ['pali' => $this->bibliography($ctx)];
+        $references = $this->bibliography($ctx);
+        $title = $references === [] ? '' : $this->title($call, $ctx);
+
+        return ($title === '' ? [] : ['title' => $title]) + ['pali' => $references];
     }
 
     public function text(Call $call, RenderContext $ctx): string
     {
-        $text = '';
-        foreach ($this->bibliography($ctx) as $reference) {
+        $references = $this->bibliography($ctx);
+        if ($references === []) {
+            return '';
+        }
+        $title = $this->title($call, $ctx);
+        $text = $title === '' ? '' : $title."\n";
+        foreach ($references as $reference) {
             $text .= '['.$reference['sn'].'] '.ucfirst($reference['title']).' '.$reference['copyright']."\n";
         }
 
@@ -94,8 +118,13 @@ final class ReferenceTemplate extends Template
 
     public function markdown(Call $call, RenderContext $ctx): string
     {
-        $markdown = '';
-        foreach ($this->bibliography($ctx) as $reference) {
+        $references = $this->bibliography($ctx);
+        if ($references === []) {
+            return '';
+        }
+        $title = $this->title($call, $ctx);
+        $markdown = $title === '' ? '' : $title."\n\n";
+        foreach ($references as $reference) {
             $markdown .= '['.$reference['sn'].'] **'.ucfirst($reference['title']).'** '.$reference['copyright']."\n\n";
         }
 

+ 6 - 11
api-v13/app/Services/Markup/Templates/TocTemplate.php

@@ -9,13 +9,14 @@ use App\Services\Markup\Ir\Element;
 use App\Services\Markup\Ir\Node;
 use App\Services\Markup\Render\HtmlRenderer;
 use App\Services\Markup\Render\RenderContext;
+use App\Services\Markup\Templates\Concerns\OwnsBlockTitle;
 
 /**
  * 目录:`{{toc}}`,从本篇内容的标题自动生成,每项链接到对应标题(`#h-…`,IR 构建时生成的稳定 id)。
  *
  * - 层级:缺省收二、三级标题;`{{toc|2-4}}`、`{{toc|2}}` 指定
- * - 标题:目录自带一行标题(不是 `<h2>`,不算正文的一节),文字随内容语言(labels.toc);
- *   `{{toc|title=本条目录}}` 改文字,`{{toc|title=}}` 不显示
+ * - 标题:目录自带一行标题,规则见 {@see OwnsBlockTitle}(labels.toc;`title=` 改文字或隐藏;
+ *   紧跟在手写标题后面时不显示)
  * - 兼容旧写法:紧挨在 `{{toc}}` 前面的标题(手写的「## 目录」)不进目录
  * - 遍历整篇内容,写在哪里都能列全;标题里的术语、格式在目录里照常显示
  *
@@ -23,6 +24,8 @@ use App\Services\Markup\Render\RenderContext;
  */
 final class TocTemplate extends Template
 {
+    use OwnsBlockTitle;
+
     protected string $component = 'toc';
 
     public function block(): bool
@@ -49,17 +52,9 @@ final class TocTemplate extends Template
         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 $this->blockTitle($call, $ctx, 'labels.toc');
     }
 
     /**

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

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

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

@@ -8,6 +8,7 @@ return [
     'commentary' => '义注',
     'similar' => '相似段落',
     'toc' => '目录',
+    'references' => '参考文献',
 
     'script_convertor' => '巴利文字转换器',
     'input_script' => '输入文字',

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

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

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

@@ -660,6 +660,9 @@ describe('toc', function () {
     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(['甲', '乙']);
+        // 已经有手写标题,不再显示第二个
+        expect($toc($tree)['props'])->toBe([]);
+        expect(markupRender("## 目录\n\n{{toc}}\n\n## 甲", Format::Html))->not->toContain('toc-title');
     });
 
     it('accepts a level range or a single level', function () use ($source, $toc, $items) {

+ 22 - 0
api-v13/tests/Feature/MarkupTemplateDataTest.php

@@ -367,6 +367,28 @@ describe('ref', function () {
         expect($titles(markupDataTree("{{ref}}\n\n{{para|id=997-5}}\n\n{{998-12-1-2}}")))->toBe(['third work', 'second work']);
     });
 
+    it('gives the list its own title, like {{toc}}', function () {
+        $ref = fn (string $source) => collect(markupDataTree($source))->firstWhere('name', 'reference')
+            ?? collect(markupDataTree($source))->pluck('children')->flatten(1)->firstWhere('name', 'reference');
+
+        expect($ref('{{para|id=997-5}}{{ref}}')['props'])->toMatchArray(['title' => '参考文献']);
+        expect($ref('{{para|id=997-5}}{{ref|title=引用书目}}')['props']['title'])->toBe('引用书目');
+        expect($ref('{{para|id=997-5}}{{ref|title=}}')['props'])->not->toHaveKey('title');
+        // 紧跟在手写的「## 参考文献」后面:不再显示第二个标题
+        expect($ref("{{para|id=997-5}}\n\n## 参考文献\n\n{{ref}}")['props'])->not->toHaveKey('title');
+        // 没有引用:整块不输出,也没有标题
+        expect($ref('{{ref}}')['props'])->toBe(['pali' => []]);
+        expect(markupDataRender('{{ref}}', Format::Html))->toBe('');
+    });
+
+    it('renders the title in html, text and markdown', function () {
+        expect(markupDataRender('{{para|id=997-5}}{{ref}}', Format::Text))->toBe("参考文献\n[1] Third work CSCD V4 VRI 2008\n");
+        expect(markupDataRender('{{para|id=997-5}}{{ref}}', Format::Markdown))->toBe("参考文献\n\n[1] **Third work** CSCD V4 VRI 2008\n\n");
+        // html 的具体结构由页面决定(百科页另有写法),这里只看标题与条目都在、标题在前
+        expect(markupDataRender('{{para|id=997-5}}{{ref}}', Format::Html))
+            ->toMatch('/参考文献.*\[1\] Third work CSCD V4 VRI 2008/s');
+    });
+
     it('counts references inside template parameters such as footnotes, once per title', function () use ($titles) {
         expect($titles(markupDataTree('{{n|见 {{quote|998-3}}}} {{para|id=998-4}} {{ref}}')))->toBe(['first work']);
     });

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

@@ -50,7 +50,15 @@ const TEMPLATES: Record<string, TemplateRenderer> = {
   grammar: (p) => (
     <GrammarTermLookupCtl {...as<typeof GrammarTermLookupCtl>(p)} />
   ),
-  reference: (p) => <ReferenceCtl {...as<typeof ReferenceCtl>(p)} />,
+  // 参考文献:与目录一样自带一行标题(紧跟在手写标题后面时后端不给 title)
+  reference: (p) => (
+    <div className="markup-references">
+      {typeof p.title === "string" && p.title !== "" ? (
+        <Text strong>{p.title}</Text>
+      ) : null}
+      <ReferenceCtl {...as<typeof ReferenceCtl>(p)} />
+    </div>
+  ),
   para: (p) => <ParaCtl {...as<typeof ParaCtl>(p)} />,
   quality: (p) => <QualityCtl {...as<typeof QualityCtl>(p)} />,
   article: (p) => <ArticleCtl {...as<typeof ArticleCtl>(p)} />,