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

✨ (api-v13): 参考文献 {{ref}} 统计 para、quote、ql、章节,写在哪里都能列全

- 引用来源:模板基类加 references(),各模板只从参数解析 [book, para](不查库):
  句子、para、quote、带 book + para 的 ql、type=chapter|para 的 article;脚注等参数里的也算。
  v2 只统计句子模板
- {{ref}} 遍历整篇内容收集,不再边渲染边记,所以不必放在文末
- 书名:book_titles 里同一本书、起始段号 ≤ 该段的最近一条。v2 把 book 里排在前面的作品全列进来,
  且用 < 漏掉了恰好引用作品首段的情况
- 按首次出现的顺序编号,同一作品只列一次
- dashboard-v6:ReferenceCtl 列表补 key

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

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

@@ -109,6 +109,7 @@ final class MarkupService
         foreach ($documents as $key => $document) {
             $idPrefix = $idPrefixes[$key] ?? substr(md5($key.'|'.$document->source), 0, 8);
             $ctx = new RenderContext($options, $resolver, $renderer, $idPrefix);
+            $ctx->document = $document;
             $rendered = $renderer->document($document, $ctx);
             if (is_string($rendered) && $options->footnote) {
                 $rendered .= match (true) {

+ 2 - 2
api-v13/app/Services/Markup/Render/RenderContext.php

@@ -21,8 +21,8 @@ final class RenderContext
     /** @var list<array{sn: int, trigger: string, content: string}> 脚注(html / markdown 输出末尾的列表) */
     public array $footnotes = [];
 
-    /** @var array<int, array{0: int, 1: int}> 句子模板引用到的 [book, para](按调用去重),ref 模板据此列参考文献 */
-    public array $sentenceRefs = [];
+    /** 正在渲染的顶层内容(ref 模板遍历它收集引用的经文段落) */
+    public ?Document $document = null;
 
     /** @var array<string, int> 术语出现次数(markdown 输出只有第一次带巴利原词与脚注) */
     public array $termSeen = [];

+ 17 - 0
api-v13/app/Services/Markup/Templates/ArticleTemplate.php

@@ -59,6 +59,23 @@ final class ArticleTemplate extends Template
         return $props;
     }
 
+    /**
+     * 章节 / 段落(type=chapter|para)引用了经文段落;文章、文集不算。
+     */
+    public function references(Call $call): array
+    {
+        $type = (string) $call->param('type');
+        if (! in_array($type, ['chapter', 'para'], true)) {
+            return [];
+        }
+        $id = (string) $call->param('id');
+        if ($id === '') {
+            $id = $call->param('book').'-'.$call->param('paragraphs');
+        }
+
+        return self::paragraphRef($id);
+    }
+
     public function plain(Call $call, RenderContext $ctx, Format $format): string
     {
         return $format === Format::Prompt ? '' : (string) $call->param('title');

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

@@ -34,6 +34,11 @@ final class ParaTemplate extends Template
         return $props;
     }
 
+    public function references(Call $call): array
+    {
+        return self::paragraphRef((string) $call->param('id'));
+    }
+
     public function text(Call $call, RenderContext $ctx): string
     {
         return (string) $call->param('title');

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

@@ -28,6 +28,14 @@ final class QuoteLinkTemplate extends Template
         ];
     }
 
+    /**
+     * 只有给了 book + para 的才算引用了经文段落(按书名册页引用的不知道是哪一段)。
+     */
+    public function references(Call $call): array
+    {
+        return self::paragraphRef($call->param('book').'-'.$call->param('para'));
+    }
+
     public function collect(Call $call, Resolver $resolver): void
     {
         $call->data['quoteLink'] = $resolver->loader(QuoteLinkLoader::class)->request($call);

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

@@ -19,6 +19,11 @@ final class QuoteTemplate extends Template
         return ['para' => ParamSpec::at(1)];
     }
 
+    public function references(Call $call): array
+    {
+        return self::paragraphRef((string) $call->param('para'));
+    }
+
     public function collect(Call $call, Resolver $resolver): void
     {
         $resolver->loader(QuoteLoader::class)->request((string) $call->param('para'));

+ 49 - 14
api-v13/app/Services/Markup/Templates/ReferenceTemplate.php

@@ -4,10 +4,20 @@ namespace App\Services\Markup\Templates;
 
 use App\Models\BookTitle;
 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\RenderContext;
 
 /**
- * 参考文献:`{{ref}}`,列出本文前面句子模板引用到的巴利文献(按书名去重)。要放在文末。
+ * 参考文献:`{{ref}}`,列出本文引用到的巴利文献(按书名去重,按首次出现的顺序编号)。
+ *
+ * 引用来自整篇内容里各模板的 {@see Template::references()}:句子、para、quote、
+ * 带 book + para 的 ql、章节 / 段落 article。遍历整篇内容而不是边渲染边记,所以 `{{ref}}` 写在哪里都能列全
+ * (v2 只统计句子模板,且必须放在文末)。
+ *
+ * 一段引用对应的书名:`book_titles` 里同一本书、起始段号 ≤ 该段的最近一条(一个 book 里可能收了几部作品;
+ * v2 把排在前面的作品全列了进来,且用 < 漏掉了恰好引用作品首段的情况)。
  */
 final class ReferenceTemplate extends Template
 {
@@ -18,39 +28,64 @@ final class ReferenceTemplate extends Template
     /**
      * @return list<array{sn: int, title: string, copyright: string}>
      */
-    private function references(RenderContext $ctx): array
+    private function bibliography(RenderContext $ctx): array
     {
-        if ($ctx->sentenceRefs === []) {
+        $refs = $ctx->document === null ? [] : $this->gather($ctx->document->nodes);
+        if ($refs === []) {
             return [];
         }
-        $books = BookTitle::orderByDesc('sn')->get(['book', 'paragraph', 'title']);
+        $books = array_values(array_unique(array_map(fn (array $ref) => $ref[0], $refs)));
+        $titles = BookTitle::whereIn('book', $books)->orderByDesc('paragraph')->get(['book', 'paragraph', 'title']);
+
         $seen = [];
         $references = [];
-        foreach ($ctx->sentenceRefs as [$book, $para]) {
-            foreach ($books as $title) {
-                if ((int) $title->book !== $book || (int) $title->paragraph >= $para || isset($seen[$title->title])) {
-                    continue;
-                }
-                $seen[$title->title] = true;
-                $references[] = ['sn' => count($references) + 1, 'title' => (string) $title->title, 'copyright' => self::COPYRIGHT];
+        foreach ($refs as [$book, $para]) {
+            $title = $titles->first(fn (BookTitle $row) => (int) $row->book === $book && (int) $row->paragraph <= $para);
+            if ($title === null || isset($seen[$title->title])) {
+                continue;
             }
+            $seen[$title->title] = true;
+            $references[] = ['sn' => count($references) + 1, 'title' => (string) $title->title, 'copyright' => self::COPYRIGHT];
         }
 
         return $references;
     }
 
+    /**
+     * 按文档顺序收集引用的 [book, para](含模板参数里的内容,如脚注正文)。
+     *
+     * @param  list<Node>  $nodes
+     * @return list<array{0: int, 1: int}>
+     */
+    private function gather(array $nodes): array
+    {
+        $refs = [];
+        foreach ($nodes as $node) {
+            if ($node instanceof Element) {
+                array_push($refs, ...$this->gather($node->children));
+            } elseif ($node instanceof Call) {
+                array_push($refs, ...$node->template->references($node));
+                foreach ($node->slots as $slot) {
+                    array_push($refs, ...$this->gather($slot instanceof Document ? $slot->nodes : []));
+                }
+            }
+        }
+
+        return $refs;
+    }
+
     /**
      * @return array<string, mixed>
      */
     public function props(Call $call, RenderContext $ctx): array
     {
-        return ['pali' => $this->references($ctx)];
+        return ['pali' => $this->bibliography($ctx)];
     }
 
     public function text(Call $call, RenderContext $ctx): string
     {
         $text = '';
-        foreach ($this->references($ctx) as $reference) {
+        foreach ($this->bibliography($ctx) as $reference) {
             $text .= '['.$reference['sn'].'] '.ucfirst($reference['title']).' '.$reference['copyright']."\n";
         }
 
@@ -60,7 +95,7 @@ final class ReferenceTemplate extends Template
     public function markdown(Call $call, RenderContext $ctx): string
     {
         $markdown = '';
-        foreach ($this->references($ctx) as $reference) {
+        foreach ($this->bibliography($ctx) as $reference) {
             $markdown .= '['.$reference['sn'].'] **'.ucfirst($reference['title']).'** '.$reference['copyright']."\n\n";
         }
 

+ 8 - 7
api-v13/app/Services/Markup/Templates/SentTemplate.php

@@ -59,6 +59,13 @@ final class SentTemplate extends Template
         return in_array($show, ['origin', 'translation'], true) ? $show : 'both';
     }
 
+    public function references(Call $call): array
+    {
+        [$id] = $this->target($call);
+
+        return self::paragraphRef($id);
+    }
+
     public function collect(Call $call, Resolver $resolver): void
     {
         [$id, $channels] = $this->target($call);
@@ -71,13 +78,7 @@ final class SentTemplate extends Template
      */
     private function sentence(Call $call, RenderContext $ctx): ?array
     {
-        $sentence = $ctx->loader(SentenceLoader::class)->result((string) ($call->data['sentence'] ?? ''));
-        if ($sentence !== null) {
-            // 以调用为键:同一个调用在一次渲染里可能被取多次(props、纯文本…),只记一次
-            $ctx->sentenceRefs[spl_object_id($call)] = [$sentence['book'], $sentence['para']];
-        }
-
-        return $sentence;
+        return $ctx->loader(SentenceLoader::class)->result((string) ($call->data['sentence'] ?? ''));
     }
 
     public function component(Call $call, RenderContext $ctx): string

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

@@ -69,6 +69,31 @@ abstract class Template
 
     public function collect(Call $call, Resolver $resolver): void {}
 
+    /**
+     * 这次调用引用到的经文段落(`{{ref}}` 据此列参考文献)。只从参数里解析,不查库。
+     *
+     * @return list<array{0: int, 1: int}> [book, para]
+     */
+    public function references(Call $call): array
+    {
+        return [];
+    }
+
+    /**
+     * `book-para` 或 `book-para-start-end` 形式的坐标 → [[book, para]];不合法返回 []。
+     *
+     * @return list<array{0: int, 1: int}>
+     */
+    protected static function paragraphRef(string $id): array
+    {
+        $parts = explode('-', trim($id));
+        if (count($parts) < 2 || ! ctype_digit($parts[0]) || ! ctype_digit($parts[1])) {
+            return [];
+        }
+
+        return [[(int) $parts[0], (int) $parts[1]]];
+    }
+
     public function component(Call $call, RenderContext $ctx): string
     {
         return $this->component;

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

@@ -324,3 +324,50 @@ describe('templates reading other tables', function () {
             ->toBe('<span><span lang="pi-Mymr">evaṃ</span>၊ <span lang="my">ဤသို့</span></span>');
     });
 });
+
+describe('ref', function () {
+    beforeEach(function () {
+        // book 998 收了两部作品:第 1 段起是 first work,第 10 段起是 second work;book 997 一部
+        BookTitle::forceCreate(['book' => 998, 'paragraph' => 1, 'title' => 'first work', 'sn' => 1]);
+        BookTitle::forceCreate(['book' => 998, 'paragraph' => 10, 'title' => 'second work', 'sn' => 2]);
+        BookTitle::forceCreate(['book' => 997, 'paragraph' => 1, 'title' => 'third work', 'sn' => 3]);
+    });
+
+    $titles = function (array $tree): array {
+        $find = function (array $nodes) use (&$find): ?array {
+            foreach ($nodes as $node) {
+                if (($node['name'] ?? null) === 'reference') {
+                    return $node;
+                }
+                if (($found = $find($node['children'] ?? [])) !== null) {
+                    return $found;
+                }
+            }
+
+            return null;
+        };
+
+        return array_column($find($tree)['props']['pali'] ?? [], 'title');
+    };
+
+    it('collects references from para, quote, ql with book and para, and chapter articles', function () use ($titles) {
+        $source = '{{para|id=998-12|title=t}} {{quote|997-3}} {{ql|type=m|book=998|para=2}} '
+            .'{{article|type=chapter|book=998|paragraphs=15}} {{ql|type=m|bookname=x|volume=1|page=2}}{{ref}}';
+
+        expect($titles(markupDataTree($source)))->toBe(['second work', 'third work', 'first work']);
+    });
+
+    it('picks the nearest title, counting a reference to the first paragraph of a work', function () use ($titles) {
+        expect($titles(markupDataTree('{{para|id=998-10}}{{ref}}')))->toBe(['second work']);
+        expect($titles(markupDataTree('{{para|id=998-9}}{{ref}}')))->toBe(['first work']);
+        expect($titles(markupDataTree('{{para|id=998-0}}{{ref}}')))->toBe([]);
+    });
+
+    it('lists every reference wherever {{ref}} is placed', function () use ($titles) {
+        expect($titles(markupDataTree("{{ref}}\n\n{{para|id=997-5}}\n\n{{998-12-1-2}}")))->toBe(['third work', 'second work']);
+    });
+
+    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']);
+    });
+});

+ 1 - 1
dashboard-v6/src/components/template/Reference.tsx

@@ -21,7 +21,7 @@ interface IReferenceCtl {
 export const ReferenceCtl = ({ pali }: IReferenceCtl) => {
   const Reference = (ref: IReference) => {
     return (
-      <Paragraph>{`[${ref.sn}] ${ucFirst(ref.title)} ${
+      <Paragraph key={ref.sn}>{`[${ref.sn}] ${ucFirst(ref.title)} ${
         ref.copyright
       }`}</Paragraph>
     );